code.js 16 KB

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