code.js 14 KB

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