code.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // First, checks if it isn't implemented yet.
  2. if (!String.prototype.format) {
  3. String.prototype.format = function() {
  4. var args = arguments;
  5. return this.replace(/{(\d+)}/g, function(match, number) {
  6. return typeof args[number] != 'undefined'
  7. ? args[number]
  8. : match
  9. ;
  10. });
  11. };
  12. }
  13. var releaseURL = 'https://api.github.com/repos/sle118/squeezelite-esp32/releases';
  14. var recovery = false;
  15. var enableAPTimer = true;
  16. var enableStatusTimer = true;
  17. var commandHeader = 'squeezelite -b 500:2000 -d all=info ';
  18. var pname, ver, otapct, otadsc;
  19. var blockAjax = false;
  20. var blockFlashButton = false;
  21. var apList = null;
  22. var selectedSSID = "";
  23. var refreshAPInterval = null;
  24. var checkStatusInterval = null;
  25. var StatusIntervalActive = false;
  26. var RefreshAPIIntervalActive = false;
  27. var output = '';
  28. function stopCheckStatusInterval(){
  29. if(checkStatusInterval != null){
  30. clearTimeout(checkStatusInterval);
  31. checkStatusInterval = null;
  32. }
  33. StatusIntervalActive = false;
  34. }
  35. function stopRefreshAPInterval(){
  36. if(refreshAPInterval != null){
  37. clearTimeout(refreshAPInterval);
  38. refreshAPInterval = null;
  39. }
  40. RefreshAPIIntervalActive = false;
  41. }
  42. function startCheckStatusInterval(){
  43. StatusIntervalActive = true;
  44. checkStatusInterval = setTimeout(checkStatus, 3000);
  45. }
  46. function startRefreshAPInterval(){
  47. RefreshAPIIntervalActive = true;
  48. refreshAPInterval = setTimeout(refreshAP, 2800);
  49. }
  50. function RepeatCheckStatusInterval(){
  51. if(StatusIntervalActive)
  52. startCheckStatusInterval();
  53. }
  54. function RepeatRefreshAPInterval(){
  55. if(RefreshAPIIntervalActive)
  56. startRefreshAPInterval();
  57. }
  58. $(document).ready(function(){
  59. $("#wifi-status").on("click", ".ape", function() {
  60. $( "#wifi" ).slideUp( "fast", function() {});
  61. $( "#connect-details" ).slideDown( "fast", function() {});
  62. });
  63. $("#manual_add").on("click", ".ape", function() {
  64. selectedSSID = $(this).text();
  65. $( "#ssid-pwd" ).text(selectedSSID);
  66. $( "#wifi" ).slideUp( "fast", function() {});
  67. $( "#connect_manual" ).slideDown( "fast", function() {});
  68. $( "#connect" ).slideUp( "fast", function() {});
  69. //update wait screen
  70. $( "#loading" ).show();
  71. $( "#connect-success" ).hide();
  72. $( "#connect-fail" ).hide();
  73. });
  74. $("#wifi-list").on("click", ".ape", function() {
  75. selectedSSID = $(this).text();
  76. $( "#ssid-pwd" ).text(selectedSSID);
  77. $( "#wifi" ).slideUp( "fast", function() {});
  78. $( "#connect_manual" ).slideUp( "fast", function() {});
  79. $( "#connect" ).slideDown( "fast", function() {});
  80. //update wait screen
  81. $( "#loading" ).show();
  82. $( "#connect-success" ).hide();
  83. $( "#connect-fail" ).hide();
  84. });
  85. $("#cancel").on("click", function() {
  86. selectedSSID = "";
  87. $( "#connect" ).slideUp( "fast", function() {});
  88. $( "#connect_manual" ).slideUp( "fast", function() {});
  89. $( "#wifi" ).slideDown( "fast", function() {});
  90. });
  91. $("#manual_cancel").on("click", function() {
  92. selectedSSID = "";
  93. $( "#connect" ).slideUp( "fast", function() {});
  94. $( "#connect_manual" ).slideUp( "fast", function() {});
  95. $( "#wifi" ).slideDown( "fast", function() {});
  96. });
  97. $("#join").on("click", function() {
  98. performConnect();
  99. });
  100. $("#manual_join").on("click", function() {
  101. performConnect($(this).data('connect'));
  102. });
  103. $("#ok-details").on("click", function() {
  104. $( "#connect-details" ).slideUp( "fast", function() {});
  105. $( "#wifi" ).slideDown( "fast", function() {});
  106. });
  107. $("#ok-credits").on("click", function() {
  108. $( "#credits" ).slideUp( "fast", function() {});
  109. $( "#app" ).slideDown( "fast", function() {});
  110. });
  111. $("#acredits").on("click", function(event) {
  112. event.preventDefault();
  113. $( "#app" ).slideUp( "fast", function() {});
  114. $( "#credits" ).slideDown( "fast", function() {});
  115. });
  116. $("#ok-connect").on("click", function() {
  117. $( "#connect-wait" ).slideUp( "fast", function() {});
  118. $( "#wifi" ).slideDown( "fast", function() {});
  119. });
  120. $("#disconnect").on("click", function() {
  121. $( "#connect-details-wrap" ).addClass('blur');
  122. $( "#diag-disconnect" ).slideDown( "fast", function() {});
  123. });
  124. $("#no-disconnect").on("click", function() {
  125. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  126. $( "#connect-details-wrap" ).removeClass('blur');
  127. });
  128. $("#yes-disconnect").on("click", function() {
  129. stopCheckStatusInterval();
  130. selectedSSID = "";
  131. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  132. $( "#connect-details-wrap" ).removeClass('blur');
  133. $.ajax({
  134. url: '/connect.json',
  135. dataType: 'json',
  136. method: 'DELETE',
  137. cache: false,
  138. data: { 'timestamp': Date.now()}
  139. });
  140. startCheckStatusInterval();
  141. $( "#connect-details" ).slideUp( "fast", function() {});
  142. $( "#wifi" ).slideDown( "fast", function() {})
  143. });
  144. $("#autoexec-cb").on("click", function() {
  145. autoexec = (this.checked)?1:0;
  146. $.ajax({
  147. url: '/config.json',
  148. dataType: 'json',
  149. method: 'POST',
  150. cache: false,
  151. headers: { "X-Custom-autoexec": autoexec },
  152. data: { 'timestamp': Date.now() }
  153. });
  154. console.log('sent config JSON with headers:', autoexec);
  155. console.log('now triggering reboot');
  156. $.ajax({
  157. url: '/reboot.json',
  158. dataType: 'json',
  159. method: 'POST',
  160. cache: false,
  161. data: { 'timestamp': Date.now()}
  162. });
  163. });
  164. $("#save-autoexec1").on("click", function() {
  165. autoexec1 = $("#autoexec1").val();
  166. $.ajax({
  167. url: '/config.json',
  168. dataType: 'json',
  169. method: 'POST',
  170. cache: false,
  171. headers: { "X-Custom-autoexec1": autoexec1 },
  172. data: { 'timestamp': Date.now() }
  173. });
  174. console.log('sent config JSON with headers:', autoexec1);
  175. });
  176. $("#save-gpio").on("click", function() {
  177. var headers = {};
  178. $("input.gpio").each(function() {
  179. var id = $(this)[0].id;
  180. var pin = $(this).val();
  181. if (pin != '') {
  182. headers[id] = pin;
  183. }
  184. });
  185. $.ajax({
  186. url: '/config.json',
  187. dataType: 'json',
  188. method: 'POST',
  189. cache: false,
  190. headers: JSON.stringify(headers),
  191. data: { 'timestamp': Date.now() }
  192. });
  193. console.log('sent config JSON with headers:', JSON.stringify(headers));
  194. });
  195. $("#flash").on("click", function() {
  196. if (blockFlashButton) return;
  197. blockFlashButton = true;
  198. var url = $("#fwurl").val();
  199. $.ajax({
  200. url: '/config.json',
  201. dataType: 'json',
  202. method: 'POST',
  203. cache: false,
  204. headers: { "X-Custom-fwurl": url },
  205. data: { 'timestamp': Date.now() }
  206. });
  207. enableStatusTimer = true;
  208. });
  209. $("#generate-command").on("click", function() {
  210. var commandLine = commandHeader + '-n ' + $("#player").val();
  211. if (output == 'bt') {
  212. commandLine += ' -o "BT -n \'' + $("#btsink").val() + '\'" -R -Z 192000';
  213. } else if (output == 'spdif') {
  214. commandLine += ' -o SPDIF -R -Z 192000';
  215. } else {
  216. commandLine += ' -o I2S';
  217. }
  218. if ($("#optional").val() != '') {
  219. commandLine += ' ' + $("#optional").val();
  220. }
  221. $("#autoexec1").val(commandLine);
  222. });
  223. $('[name=audio]').on("click", function(){
  224. if (this.id == 'bt') {
  225. $("#btsinkdiv").show(200);
  226. output = 'bt';
  227. } else if (this.id == 'spdif') {
  228. $("#btsinkdiv").hide(200);
  229. output = 'spdif';
  230. } else {
  231. $("#btsinkdiv").hide(200);
  232. output = 'i2s';
  233. }
  234. });
  235. $('#fwcheck').on("click", function(){
  236. $("#releaseTable").html("");
  237. $.getJSON(releaseURL, function(data) {
  238. data.forEach(function(release) {
  239. var url = '';
  240. release.assets.forEach(function(asset) {
  241. if (asset.name.match(/\.bin$/)) {
  242. url = asset.browser_download_url;
  243. }
  244. });
  245. var [ver, idf, cfg, branch] = release.name.split('#');
  246. var body = release.body;
  247. body = body.replace(/\'/ig, "\"");
  248. body = body.replace(/[\s\S]+(### Revision Log[\s\S]+)### ESP-IDF Version Used[\s\S]+/, "$1");
  249. body = body.replace(/- \(.+?\) /g, "- ");
  250. var [date, time] = release.created_at.split('T');
  251. $("#releaseTable").append(
  252. "<tr>"+
  253. "<td data-toggle='tooltip' title='"+body+"'>"+ver+"</td>"+
  254. "<td>"+idf+"</td>"+
  255. "<td>"+date+"</td>"+
  256. "<td>"+cfg+"</td>"+
  257. "<td>"+branch+"</td>"+
  258. "<td><input id='generate-command' type='button' class='btn btn-success' value='Select' data-url='"+url+"' onclick='setURL(this);' /></td>"+
  259. "</tr>"
  260. );
  261. });
  262. })
  263. .fail(function() {
  264. alert("failed to fetch release history!");
  265. });
  266. });
  267. //first time the page loads: attempt to get the connection status and start the wifi scan
  268. refreshAP();
  269. getConfig();
  270. //start timers
  271. startCheckStatusInterval();
  272. startRefreshAPInterval();
  273. $('[data-toggle="tooltip"]').tooltip({
  274. html: true,
  275. placement : 'right',
  276. });
  277. });
  278. function setURL(button) {
  279. var url = button.dataset.url;
  280. $("#fwurl").val(url);
  281. $('[data-url^="http"]').addClass("btn-success").removeClass("btn-danger");
  282. $('[data-url="'+url+'"]').addClass("btn-danger").removeClass("btn-success");
  283. }
  284. function performConnect(conntype){
  285. //stop the status refresh. This prevents a race condition where a status
  286. //request would be refreshed with wrong ip info from a previous connection
  287. //and the request would automatically shows as succesful.
  288. stopCheckStatusInterval();
  289. //stop refreshing wifi list
  290. stopRefreshAPInterval();
  291. var pwd;
  292. if (conntype == 'manual') {
  293. //Grab the manual SSID and PWD
  294. selectedSSID=$('#manual_ssid').val();
  295. pwd = $("#manual_pwd").val();
  296. }else{
  297. pwd = $("#pwd").val();
  298. }
  299. //reset connection
  300. $( "#loading" ).show();
  301. $( "#connect-success" ).hide();
  302. $( "#connect-fail" ).hide();
  303. $( "#ok-connect" ).prop("disabled",true);
  304. $( "#ssid-wait" ).text(selectedSSID);
  305. $( "#connect" ).slideUp( "fast", function() {});
  306. $( "#connect_manual" ).slideUp( "fast", function() {});
  307. $( "#connect-wait" ).slideDown( "fast", function() {});
  308. $.ajax({
  309. url: '/connect.json',
  310. dataType: 'json',
  311. method: 'POST',
  312. cache: false,
  313. headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd },
  314. data: { 'timestamp': Date.now()}
  315. });
  316. //now we can re-set the intervals regardless of result
  317. startCheckStatusInterval();
  318. startRefreshAPInterval();
  319. }
  320. function rssiToIcon(rssi){
  321. if(rssi >= -60){
  322. return 'w0';
  323. }
  324. else if(rssi >= -67){
  325. return 'w1';
  326. }
  327. else if(rssi >= -75){
  328. return 'w2';
  329. }
  330. else{
  331. return 'w3';
  332. }
  333. }
  334. function refreshAP(){
  335. if (!enableAPTimer) return;
  336. $.getJSON( "/ap.json", function( data ) {
  337. if(data.length > 0){
  338. //sort by signal strength
  339. data.sort(function (a, b) {
  340. var x = a["rssi"]; var y = b["rssi"];
  341. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  342. });
  343. apList = data;
  344. refreshAPHTML(apList);
  345. }
  346. });
  347. }
  348. function refreshAPHTML(data){
  349. var h = "";
  350. data.forEach(function(e, idx, array) {
  351. h += '<div class="ape{0}"><div class="{1}"><div class="{2}">{3}</div></div></div>'.format(idx === array.length - 1?'':' brdb', rssiToIcon(e.rssi), e.auth==0?'':'pw',e.ssid);
  352. h += "\n";
  353. });
  354. $( "#wifi-list" ).html(h)
  355. }
  356. function checkStatus(){
  357. RepeatCheckStatusInterval();
  358. if (!enableStatusTimer) return;
  359. if (blockAjax) return;
  360. blockAjax = true;
  361. $.getJSON( "/status.json", function( data ) {
  362. if(data.hasOwnProperty('ssid') && data['ssid'] != ""){
  363. if(data["ssid"] === selectedSSID){
  364. //that's a connection attempt
  365. if(data["urc"] === 0){
  366. //got connection
  367. $("#connected-to span").text(data["ssid"]);
  368. $("#connect-details h1").text(data["ssid"]);
  369. $("#ip").text(data["ip"]);
  370. $("#netmask").text(data["netmask"]);
  371. $("#gw").text(data["gw"]);
  372. $("#wifi-status").slideDown( "fast", function() {});
  373. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  374. //unlock the wait screen if needed
  375. $( "#ok-connect" ).prop("disabled",false);
  376. //update wait screen
  377. $( "#loading" ).hide();
  378. $( "#connect-success" ).append("<p>Your IP address now is: " + text(data["ip"]) + "</p>");
  379. $( "#connect-success" ).show();
  380. $( "#connect-fail" ).hide();
  381. enableAPTimer = false;
  382. if (!recovery) enableStatusTimer = false;
  383. }
  384. else if(data["urc"] === 1){
  385. //failed attempt
  386. $("#connected-to span").text('');
  387. $("#connect-details h1").text('');
  388. $("#ip").text('0.0.0.0');
  389. $("#netmask").text('0.0.0.0');
  390. $("#gw").text('0.0.0.0');
  391. $("span#foot-wifi").html("");
  392. //don't show any connection
  393. $("#wifi-status").slideUp( "fast", function() {});
  394. //unlock the wait screen
  395. $( "#ok-connect" ).prop("disabled",false);
  396. //update wait screen
  397. $( "#loading" ).hide();
  398. $( "#connect-fail" ).show();
  399. $( "#connect-success" ).hide();
  400. enableAPTimer = true;
  401. enableStatusTimer = true;
  402. }
  403. }
  404. else if(data.hasOwnProperty('urc') && data['urc'] === 0){
  405. //ESP32 is already connected to a wifi without having the user do anything
  406. if( !($("#wifi-status").is(":visible")) ){
  407. $("#connected-to span").text(data["ssid"]);
  408. $("#connect-details h1").text(data["ssid"]);
  409. $("#ip").text(data["ip"]);
  410. $("#netmask").text(data["netmask"]);
  411. $("#gw").text(data["gw"]);
  412. $("#wifi-status").slideDown( "fast", function() {});
  413. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  414. }
  415. enableAPTimer = false;
  416. if (!recovery) enableStatusTimer = false;
  417. }
  418. }
  419. else if(data.hasOwnProperty('urc') && data['urc'] === 2){
  420. //that's a manual disconnect
  421. if($("#wifi-status").is(":visible")){
  422. $("#wifi-status").slideUp( "fast", function() {});
  423. $("span#foot-wifi").html("");
  424. }
  425. enableAPTimer = true;
  426. enableStatusTimer = true;
  427. }
  428. if (data.hasOwnProperty('recovery')) {
  429. if (data["recovery"] === 1) {
  430. recovery = true;
  431. $("#otadiv").show();
  432. $('a[href^="#tab-audio"]').hide();
  433. $('a[href^="#tab-gpio"]').hide();
  434. $('a[href^="#tab-nvs"]').show();
  435. $( "footer.footer" ).removeClass('sl');
  436. $( "footer.footer" ).addClass('recovery');
  437. enableStatusTimer = true;
  438. } else {
  439. recovery = false;
  440. $("#otadiv").hide();
  441. $('a[href^="#tab-audio"]').show();
  442. $('a[href^="#tab-gpio"]').show();
  443. //$('a[href^="#tab-nvs"]').hide(); //TODO
  444. $( "footer.footer" ).removeClass('recovery');
  445. $( "footer.footer" ).addClass('sl');
  446. enableStatusTimer = false;
  447. }
  448. }
  449. if(data.hasOwnProperty('project_name') && data['project_name'] != ''){
  450. pname = data['project_name'];
  451. }
  452. if(data.hasOwnProperty('version') && data['version'] != ''){
  453. ver = data['version'];
  454. $("span#foot-fw").html("fw: <strong>"+ver+"</strong>, mode: <strong>"+pname+"</strong>");
  455. }
  456. if(data.hasOwnProperty('ota_pct') && data['ota_pct'] != 0){
  457. otapct = data['ota_pct'];
  458. $('.progress-bar').css('width', otapct+'%').attr('aria-valuenow', otapct);
  459. $('.progress-bar').html(otapct+'%');
  460. }
  461. if(data.hasOwnProperty('ota_dsc') && data['ota_dsc'] != ''){
  462. otadsc = data['ota_dsc'];
  463. $("span#flash-status").html(otadsc);
  464. if (otadsc.match(/Error:/) || otapct > 95) {
  465. blockFlashButton = false;
  466. enableStatusTimer = true;
  467. }
  468. } else {
  469. $("span#flash-status").html('');
  470. }
  471. blockAjax = false;
  472. })
  473. .fail(function() {
  474. //don't do anything, the server might be down while esp32 recalibrates radio
  475. });
  476. }
  477. function getConfig() {
  478. $.getJSON("/config.json", function(data) {
  479. for (var key in data) {
  480. if (data.hasOwnProperty(key)) {
  481. if (key == 'autoexec') {
  482. if (data["autoexec"] === "1") {
  483. $("#autoexec-cb")[0].checked=true;
  484. } else {
  485. $("#autoexec-cb")[0].checked=false;
  486. }
  487. } else if (key == 'autoexec1') {
  488. $("#autoexec1").val(data["autoexec1"]);
  489. }
  490. if (recovery) {
  491. $("tbody#nvsTable").append(
  492. "<tr>"+
  493. "<td>"+key+"</td>"+
  494. "<td>"+
  495. "<input type='text' class='form-control' id='nvs'+key value='"+data[key]+"'>"+
  496. "</td>"+
  497. "</tr>"
  498. );
  499. //TODO append empty line
  500. }
  501. }
  502. }
  503. /*
  504. if (data.hasOwnProperty('autoexec')) {
  505. if (data["autoexec"] === 1) {
  506. $("#autoexec-cb")[0].checked=true;
  507. } else {
  508. $("#autoexec-cb")[0].checked=false;
  509. }
  510. }
  511. if (data.hasOwnProperty('autoexec')) {
  512. $("#autoexec1").val(data["autoexec1"]);
  513. }
  514. */
  515. })
  516. .fail(function() {
  517. console.log("failed to fetch config!");
  518. });
  519. }