code.js 14 KB

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