code.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. console.log(this);
  205. if (this.id == 'bt') {
  206. $("#btsinkdiv").show(200);
  207. output = 'bt';
  208. } else if (this.id == 'spdif') {
  209. $("#btsinkdiv").hide(200);
  210. output = 'spdif';
  211. } else {
  212. $("#btsinkdiv").hide(200);
  213. output = 'i2s';
  214. }
  215. });
  216. $('#fwcheck').on("click", function(){
  217. $("#releaseTable").html("");
  218. $.getJSON(releaseURL, function(data) {
  219. console.log(data);
  220. data.forEach(function(release) {
  221. var url = '';
  222. release.assets.forEach(function(asset) {
  223. if (asset.name.match(/\.bin$/)) {
  224. url = asset.browser_download_url;
  225. }
  226. });
  227. var [ver, idf, cfg, branch] = release.name.split('-');
  228. $("#releaseTable").append(
  229. "<tr>"+
  230. "<td>"+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. console.log(release.assets);
  238. });
  239. })
  240. .fail(function() {
  241. alert("failed to fetch release history!");
  242. });
  243. });
  244. //first time the page loads: attempt to get the connection status and start the wifi scan
  245. refreshAP();
  246. getConfig();
  247. //start timers
  248. startCheckStatusInterval();
  249. startRefreshAPInterval();
  250. });
  251. function setURL(button) {
  252. var url = button.dataset.url;
  253. $.ajax({
  254. url: '/config.json',
  255. dataType: 'json',
  256. method: 'POST',
  257. cache: false,
  258. headers: { "X-Custom-fwurl": url },
  259. data: { 'timestamp': Date.now() }
  260. });
  261. }
  262. function performConnect(conntype){
  263. //stop the status refresh. This prevents a race condition where a status
  264. //request would be refreshed with wrong ip info from a previous connection
  265. //and the request would automatically shows as succesful.
  266. stopCheckStatusInterval();
  267. //stop refreshing wifi list
  268. stopRefreshAPInterval();
  269. var pwd;
  270. if (conntype == 'manual') {
  271. //Grab the manual SSID and PWD
  272. selectedSSID=$('#manual_ssid').val();
  273. pwd = $("#manual_pwd").val();
  274. }else{
  275. pwd = $("#pwd").val();
  276. }
  277. //reset connection
  278. $( "#loading" ).show();
  279. $( "#connect-success" ).hide();
  280. $( "#connect-fail" ).hide();
  281. $( "#ok-connect" ).prop("disabled",true);
  282. $( "#ssid-wait" ).text(selectedSSID);
  283. $( "#connect" ).slideUp( "fast", function() {});
  284. $( "#connect_manual" ).slideUp( "fast", function() {});
  285. $( "#connect-wait" ).slideDown( "fast", function() {});
  286. $.ajax({
  287. url: '/connect.json',
  288. dataType: 'json',
  289. method: 'POST',
  290. cache: false,
  291. headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd },
  292. data: { 'timestamp': Date.now()}
  293. });
  294. //now we can re-set the intervals regardless of result
  295. startCheckStatusInterval();
  296. startRefreshAPInterval();
  297. }
  298. function rssiToIcon(rssi){
  299. if(rssi >= -60){
  300. return 'w0';
  301. }
  302. else if(rssi >= -67){
  303. return 'w1';
  304. }
  305. else if(rssi >= -75){
  306. return 'w2';
  307. }
  308. else{
  309. return 'w3';
  310. }
  311. }
  312. function refreshAP(){
  313. if (!enableTimers) return;
  314. $.getJSON( "/ap.json", function( data ) {
  315. if(data.length > 0){
  316. //sort by signal strength
  317. data.sort(function (a, b) {
  318. var x = a["rssi"]; var y = b["rssi"];
  319. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  320. });
  321. apList = data;
  322. refreshAPHTML(apList);
  323. }
  324. });
  325. }
  326. function refreshAPHTML(data){
  327. var h = "";
  328. data.forEach(function(e, idx, array) {
  329. 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);
  330. h += "\n";
  331. });
  332. $( "#wifi-list" ).html(h)
  333. }
  334. function checkStatus(){
  335. if (!enableTimers) return;
  336. $.getJSON( "/status.json", function( data ) {
  337. if(data.hasOwnProperty('ssid') && data['ssid'] != ""){
  338. if(data["ssid"] === selectedSSID){
  339. //that's a connection attempt
  340. if(data["urc"] === 0){
  341. //got connection
  342. $("#connected-to span").text(data["ssid"]);
  343. $("#connect-details h1").text(data["ssid"]);
  344. $("#ip").text(data["ip"]);
  345. $("#netmask").text(data["netmask"]);
  346. $("#gw").text(data["gw"]);
  347. $("#wifi-status").slideDown( "fast", function() {});
  348. //unlock the wait screen if needed
  349. $( "#ok-connect" ).prop("disabled",false);
  350. //update wait screen
  351. $( "#loading" ).hide();
  352. $( "#connect-success" ).append("<p>Your IP address now is: " + text(data["ip"]) + "</p>");
  353. $( "#connect-success" ).show();
  354. $( "#connect-fail" ).hide();
  355. enableTimers = false;
  356. }
  357. else if(data["urc"] === 1){
  358. //failed attempt
  359. $("#connected-to span").text('');
  360. $("#connect-details h1").text('');
  361. $("#ip").text('0.0.0.0');
  362. $("#netmask").text('0.0.0.0');
  363. $("#gw").text('0.0.0.0');
  364. //don't show any connection
  365. $("#wifi-status").slideUp( "fast", function() {});
  366. //unlock the wait screen
  367. $( "#ok-connect" ).prop("disabled",false);
  368. //update wait screen
  369. $( "#loading" ).hide();
  370. $( "#connect-fail" ).show();
  371. $( "#connect-success" ).hide();
  372. enableTimers = true;
  373. }
  374. }
  375. else if(data.hasOwnProperty('urc') && data['urc'] === 0){
  376. //ESP32 is already connected to a wifi without having the user do anything
  377. if( !($("#wifi-status").is(":visible")) ){
  378. $("#connected-to span").text(data["ssid"]);
  379. $("#connect-details h1").text(data["ssid"]);
  380. $("#ip").text(data["ip"]);
  381. $("#netmask").text(data["netmask"]);
  382. $("#gw").text(data["gw"]);
  383. $("#wifi-status").slideDown( "fast", function() {});
  384. }
  385. enableTimers = false;
  386. }
  387. }
  388. else if(data.hasOwnProperty('urc') && data['urc'] === 2){
  389. //that's a manual disconnect
  390. if($("#wifi-status").is(":visible")){
  391. $("#wifi-status").slideUp( "fast", function() {});
  392. }
  393. enableTimers = true;
  394. }
  395. })
  396. .fail(function() {
  397. //don't do anything, the server might be down while esp32 recalibrates radio
  398. });
  399. RepeatCheckStatusInterval();
  400. }
  401. function getConfig() {
  402. $.getJSON("/config.json", function(data) {
  403. if (data.hasOwnProperty('autoexec')) {
  404. if (data["autoexec"] === 1) {
  405. console.log('turn on autoexec');
  406. $("#autoexec-cb")[0].checked=true;
  407. } else {
  408. console.log('turn off autoexec');
  409. $("#autoexec-cb")[0].checked=false;
  410. }
  411. }
  412. if (data.hasOwnProperty('recovery')) {
  413. if (data["recovery"] === 1) {
  414. recovery = true;
  415. $("#recoverydiv").hide();
  416. $("#otadiv").show();
  417. $("#command_line").hide();
  418. $("#wifi").hide();
  419. } else {
  420. recovery = false;
  421. $("#recoverydiv").show();
  422. $("#otadiv").hide();
  423. }
  424. }
  425. if (data.hasOwnProperty('list')) {
  426. data.list.forEach(function(line) {
  427. let key = Object.keys(line)[0];
  428. let val = Object.values(line)[0];
  429. console.log(key, val);
  430. if (key == 'autoexec1') {
  431. $("#autoexec1").val(val);
  432. }
  433. });
  434. }
  435. })
  436. .fail(function() {
  437. console.log("failed to fetch config!");
  438. });
  439. }
  440. //TODO daduke check
  441. function file_change() {
  442. document.getElementById('update').disabled = 0;
  443. }
  444. function do_upload(f) {
  445. var xhr = new XMLHttpRequest();
  446. document.getElementById('update').disabled = 1;
  447. //ws.close();
  448. document.getElementById("progr").class = "progr-ok";
  449. xhr.upload.addEventListener("progress", function(e) {
  450. document.getElementById("progr").value = parseInt(e.loaded / e.total * 100);
  451. if (e.loaded == e.total) {
  452. // document.getElementById("realpage").style.display = "none";
  453. // document.getElementById("waiting").style.display = "block";
  454. }
  455. }, false);
  456. xhr.onreadystatechange = function(e) {
  457. console.log("rs" + xhr.readyState + " status " + xhr.status);
  458. if (xhr.readyState == 4) {
  459. /* it completed, for good or for ill */
  460. // document.getElementById("realpage").style.display = "none";
  461. // document.getElementById("waiting").style.display = "block";
  462. document.getElementById("progr").class = "progr-ok";
  463. console.log("upload reached state 4: xhr status " + xhr.status);
  464. setTimeout(function() { window.location.href = location.origin + "/"; }, 9000 );
  465. }
  466. };
  467. /* kill the heart timer */
  468. clearInterval(set_int);
  469. xhr.open("POST", f.action, true);
  470. xhr.send(new FormData(f));
  471. return false;
  472. }
  473. function heart_timer() {
  474. var s;
  475. s = Math.round((95 * to) / (40 * 10)) / 100;
  476. if (s < 0) {
  477. clearInterval(set_int);
  478. set_int = 0;
  479. ws.close();
  480. document.getElementById("realpage").style.opacity = "0.3";
  481. }
  482. to--;
  483. document.getElementById("heart").style.opacity = s;
  484. }
  485. function heartbeat()
  486. {
  487. to = 40 * 10;
  488. if (!set_int) {
  489. set_int = setInterval(heart_timer, 100);
  490. }
  491. }