2
0

code.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. //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. //first time the page loads: attempt to get the connection status and start the wifi scan
  155. refreshAP();
  156. getConfig();
  157. //start timers
  158. startCheckStatusInterval();
  159. startRefreshAPInterval();
  160. });
  161. function performConnect(conntype){
  162. //stop the status refresh. This prevents a race condition where a status
  163. //request would be refreshed with wrong ip info from a previous connection
  164. //and the request would automatically shows as succesful.
  165. stopCheckStatusInterval();
  166. //stop refreshing wifi list
  167. stopRefreshAPInterval();
  168. var pwd;
  169. if (conntype == 'manual') {
  170. //Grab the manual SSID and PWD
  171. selectedSSID=$('#manual_ssid').val();
  172. pwd = $("#manual_pwd").val();
  173. }else{
  174. pwd = $("#pwd").val();
  175. }
  176. //reset connection
  177. $( "#loading" ).show();
  178. $( "#connect-success" ).hide();
  179. $( "#connect-fail" ).hide();
  180. $( "#ok-connect" ).prop("disabled",true);
  181. $( "#ssid-wait" ).text(selectedSSID);
  182. $( "#connect" ).slideUp( "fast", function() {});
  183. $( "#connect_manual" ).slideUp( "fast", function() {});
  184. $( "#connect-wait" ).slideDown( "fast", function() {});
  185. $.ajax({
  186. url: '/connect.json',
  187. dataType: 'json',
  188. method: 'POST',
  189. cache: false,
  190. headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd },
  191. data: { 'timestamp': Date.now()}
  192. });
  193. //now we can re-set the intervals regardless of result
  194. startCheckStatusInterval();
  195. startRefreshAPInterval();
  196. }
  197. function rssiToIcon(rssi){
  198. if(rssi >= -60){
  199. return 'w0';
  200. }
  201. else if(rssi >= -67){
  202. return 'w1';
  203. }
  204. else if(rssi >= -75){
  205. return 'w2';
  206. }
  207. else{
  208. return 'w3';
  209. }
  210. }
  211. function refreshAP(){
  212. if (!enableTimers) return;
  213. $.getJSON( "/ap.json", function( data ) {
  214. if(data.length > 0){
  215. //sort by signal strength
  216. data.sort(function (a, b) {
  217. var x = a["rssi"]; var y = b["rssi"];
  218. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  219. });
  220. apList = data;
  221. refreshAPHTML(apList);
  222. }
  223. });
  224. }
  225. function refreshAPHTML(data){
  226. var h = "";
  227. data.forEach(function(e, idx, array) {
  228. 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);
  229. h += "\n";
  230. });
  231. $( "#wifi-list" ).html(h)
  232. }
  233. function checkStatus(){
  234. if (!enableTimers) return;
  235. $.getJSON( "/status.json", function( data ) {
  236. if(data.hasOwnProperty('ssid') && data['ssid'] != ""){
  237. if(data["ssid"] === selectedSSID){
  238. //that's a connection attempt
  239. if(data["urc"] === 0){
  240. //got connection
  241. $("#connected-to span").text(data["ssid"]);
  242. $("#connect-details h1").text(data["ssid"]);
  243. $("#ip").text(data["ip"]);
  244. $("#netmask").text(data["netmask"]);
  245. $("#gw").text(data["gw"]);
  246. $("#wifi-status").slideDown( "fast", function() {});
  247. //unlock the wait screen if needed
  248. $( "#ok-connect" ).prop("disabled",false);
  249. //update wait screen
  250. $( "#loading" ).hide();
  251. $( "#connect-success" ).append("<p>Your IP address now is: " + text(data["ip"]) + "</p>");
  252. $( "#connect-success" ).show();
  253. $( "#connect-fail" ).hide();
  254. enableTimers = false;
  255. }
  256. else if(data["urc"] === 1){
  257. //failed attempt
  258. $("#connected-to span").text('');
  259. $("#connect-details h1").text('');
  260. $("#ip").text('0.0.0.0');
  261. $("#netmask").text('0.0.0.0');
  262. $("#gw").text('0.0.0.0');
  263. //don't show any connection
  264. $("#wifi-status").slideUp( "fast", function() {});
  265. //unlock the wait screen
  266. $( "#ok-connect" ).prop("disabled",false);
  267. //update wait screen
  268. $( "#loading" ).hide();
  269. $( "#connect-fail" ).show();
  270. $( "#connect-success" ).hide();
  271. enableTimers = true;
  272. }
  273. }
  274. else if(data.hasOwnProperty('urc') && data['urc'] === 0){
  275. //ESP32 is already connected to a wifi without having the user do anything
  276. if( !($("#wifi-status").is(":visible")) ){
  277. $("#connected-to span").text(data["ssid"]);
  278. $("#connect-details h1").text(data["ssid"]);
  279. $("#ip").text(data["ip"]);
  280. $("#netmask").text(data["netmask"]);
  281. $("#gw").text(data["gw"]);
  282. $("#wifi-status").slideDown( "fast", function() {});
  283. }
  284. enableTimers = false;
  285. }
  286. }
  287. else if(data.hasOwnProperty('urc') && data['urc'] === 2){
  288. //that's a manual disconnect
  289. if($("#wifi-status").is(":visible")){
  290. $("#wifi-status").slideUp( "fast", function() {});
  291. }
  292. enableTimers = true;
  293. }
  294. })
  295. .fail(function() {
  296. //don't do anything, the server might be down while esp32 recalibrates radio
  297. });
  298. RepeatCheckStatusInterval();
  299. }
  300. function getConfig() {
  301. $.getJSON("/config.json", function(data) {
  302. if (data.hasOwnProperty('autoexec')) {
  303. if (data["autoexec"] === 1) {
  304. console.log('turn on autoexec');
  305. $("#autoexec-cb")[0].checked=true;
  306. } else {
  307. console.log('turn off autoexec');
  308. $("#autoexec-cb")[0].checked=false;
  309. $("#autoexec-command").hide(200);
  310. }
  311. }
  312. if (data.hasOwnProperty('recovery')) {
  313. if (data["recovery"] === 1) {
  314. recovery = true;
  315. $("#recoverydiv").hide();
  316. $("#otadiv").show();
  317. $("#command_line").hide();
  318. $("#wifi").hide();
  319. } else {
  320. recovery = false;
  321. $("#recoverydiv").show();
  322. $("#otadiv").hide();
  323. }
  324. }
  325. if (data.hasOwnProperty('list')) {
  326. data.list.forEach(function(line) {
  327. let key = Object.keys(line)[0];
  328. let val = Object.values(line)[0];
  329. console.log(key, val);
  330. if (key == 'autoexec1') {
  331. $("#autoexec1").val(val);
  332. }
  333. });
  334. }
  335. })
  336. .fail(function() {
  337. console.log("failed to fetch config!");
  338. });
  339. }
  340. function updateAutoexec(){
  341. autoexec = ($("#autoexec-cb")[0].checked)?1:0;
  342. autoexec1 = $("#autoexec1").val();
  343. $.ajax({
  344. url: '/config.json',
  345. dataType: 'json',
  346. method: 'POST',
  347. cache: false,
  348. headers: { "X-Custom-autoexec": autoexec, "X-Custom-autoexec1": autoexec1 },
  349. data: { 'timestamp': Date.now() }
  350. });
  351. console.log('sent config JSON with headers:', autoexec, autoexec1);
  352. }
  353. var output = '';
  354. function selectOutput(el) {
  355. if ($(el).attr('id') == 'bt') {
  356. $("#btsinkdiv").show(200);
  357. output = 'bt';
  358. } else if ($(el).attr('id') == 'spdif') {
  359. $("#btsinkdiv").hide(200);
  360. output = 'spdif';
  361. } else {
  362. $("#btsinkdiv").hide(200);
  363. output = 'i2s';
  364. }
  365. }
  366. function generateCommand() {
  367. var commandLine = commandHeader + '-n ' + $("#player").val();
  368. if (output == 'bt') {
  369. commandLine += ' -o "BT -n \'' + $("#btsink").val() + '\'" -R -Z 192000';
  370. } else if (output == 'spdif') {
  371. commandLine += ' -o SPDIF -R -Z 192000';
  372. } else {
  373. commandLine += ' -o I2S';
  374. }
  375. if ($("#optional").val() != '') {
  376. commandLine += ' ' + $("#optional").val();
  377. }
  378. $("#autoexec1").val(commandLine);
  379. }
  380. function handleClick(item) {
  381. console.log(item);
  382. if (item.id == 'autoexec-cb') {
  383. if (item.checked) {
  384. $("#autoexec-command").show(200);
  385. } else {
  386. $("#autoexec-command").hide(200);
  387. }
  388. } else if (item.id == 'recovery') {
  389. $.ajax({
  390. url: '/recovery.json',
  391. dataType: 'json',
  392. method: 'POST',
  393. cache: false,
  394. data: { 'timestamp': Date.now()}
  395. });
  396. } else if (item.id == 'reboot') {
  397. $.ajax({
  398. url: '/reboot.json',
  399. dataType: 'json',
  400. method: 'POST',
  401. cache: false,
  402. data: { 'timestamp': Date.now()}
  403. });
  404. }
  405. }
  406. //TODO daduke check
  407. function file_change() {
  408. document.getElementById('update').disabled = 0;
  409. }
  410. function do_upload(f) {
  411. var xhr = new XMLHttpRequest();
  412. document.getElementById('update').disabled = 1;
  413. //ws.close();
  414. document.getElementById("progr").class = "progr-ok";
  415. xhr.upload.addEventListener("progress", function(e) {
  416. document.getElementById("progr").value = parseInt(e.loaded / e.total * 100);
  417. if (e.loaded == e.total) {
  418. // document.getElementById("realpage").style.display = "none";
  419. // document.getElementById("waiting").style.display = "block";
  420. }
  421. }, false);
  422. xhr.onreadystatechange = function(e) {
  423. console.log("rs" + xhr.readyState + " status " + xhr.status);
  424. if (xhr.readyState == 4) {
  425. /* it completed, for good or for ill */
  426. // document.getElementById("realpage").style.display = "none";
  427. // document.getElementById("waiting").style.display = "block";
  428. document.getElementById("progr").class = "progr-ok";
  429. console.log("upload reached state 4: xhr status " + xhr.status);
  430. setTimeout(function() { window.location.href = location.origin + "/"; }, 9000 );
  431. }
  432. };
  433. /* kill the heart timer */
  434. clearInterval(set_int);
  435. xhr.open("POST", f.action, true);
  436. xhr.send(new FormData(f));
  437. return false;
  438. }
  439. function heart_timer() {
  440. var s;
  441. s = Math.round((95 * to) / (40 * 10)) / 100;
  442. if (s < 0) {
  443. clearInterval(set_int);
  444. set_int = 0;
  445. ws.close();
  446. document.getElementById("realpage").style.opacity = "0.3";
  447. }
  448. to--;
  449. document.getElementById("heart").style.opacity = s;
  450. }
  451. function heartbeat()
  452. {
  453. to = 40 * 10;
  454. if (!set_int) {
  455. set_int = setInterval(heart_timer, 100);
  456. }
  457. }