2
0

code.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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 nvs_type_t = {
  14. NVS_TYPE_U8 : 0x01, /*!< Type uint8_t */
  15. NVS_TYPE_I8 : 0x11, /*!< Type int8_t */
  16. NVS_TYPE_U16 : 0x02, /*!< Type uint16_t */
  17. NVS_TYPE_I16 : 0x12, /*!< Type int16_t */
  18. NVS_TYPE_U32 : 0x04, /*!< Type uint32_t */
  19. NVS_TYPE_I32 : 0x14, /*!< Type int32_t */
  20. NVS_TYPE_U64 : 0x08, /*!< Type uint64_t */
  21. NVS_TYPE_I64 : 0x18, /*!< Type int64_t */
  22. NVS_TYPE_STR : 0x21, /*!< Type string */
  23. NVS_TYPE_BLOB : 0x42, /*!< Type blob */
  24. NVS_TYPE_ANY : 0xff /*!< Must be last */
  25. } ;
  26. var releaseURL = 'https://api.github.com/repos/sle118/squeezelite-esp32/releases';
  27. var recovery = false;
  28. var enableAPTimer = true;
  29. var enableStatusTimer = true;
  30. var commandHeader = 'squeezelite -b 500:2000 -d all=info ';
  31. var pname, ver, otapct, otadsc;
  32. var blockAjax = false;
  33. var blockFlashButton = false;
  34. var lastMsg = '';
  35. var apList = null;
  36. var selectedSSID = "";
  37. var refreshAPInterval = null;
  38. var checkStatusInterval = null;
  39. var StatusIntervalActive = false;
  40. var RefreshAPIIntervalActive = false;
  41. var LastRecoveryState=null;
  42. var output = '';
  43. function stopCheckStatusInterval(){
  44. if(checkStatusInterval != null){
  45. clearTimeout(checkStatusInterval);
  46. checkStatusInterval = null;
  47. }
  48. StatusIntervalActive = false;
  49. }
  50. function stopRefreshAPInterval(){
  51. if(refreshAPInterval != null){
  52. clearTimeout(refreshAPInterval);
  53. refreshAPInterval = null;
  54. }
  55. RefreshAPIIntervalActive = false;
  56. }
  57. function startCheckStatusInterval(){
  58. StatusIntervalActive = true;
  59. checkStatusInterval = setTimeout(checkStatus, 3000);
  60. }
  61. function startRefreshAPInterval(){
  62. RefreshAPIIntervalActive = true;
  63. refreshAPInterval = setTimeout(refreshAP(false), 4500); // leave enough time for the initial scan
  64. }
  65. function RepeatCheckStatusInterval(){
  66. if(StatusIntervalActive)
  67. startCheckStatusInterval();
  68. }
  69. function RepeatRefreshAPInterval(){
  70. if(RefreshAPIIntervalActive)
  71. startRefreshAPInterval();
  72. }
  73. $(document).ready(function(){
  74. $("#wifi-status").on("click", ".ape", function() {
  75. $( "#wifi" ).slideUp( "fast", function() {});
  76. $( "#connect-details" ).slideDown( "fast", function() {});
  77. });
  78. $("#manual_add").on("click", ".ape", function() {
  79. selectedSSID = $(this).text();
  80. $( "#ssid-pwd" ).text(selectedSSID);
  81. $( "#wifi" ).slideUp( "fast", function() {});
  82. $( "#connect_manual" ).slideDown( "fast", function() {});
  83. $( "#connect" ).slideUp( "fast", function() {});
  84. //update wait screen
  85. $( "#loading" ).show();
  86. $( "#connect-success" ).hide();
  87. $( "#connect-fail" ).hide();
  88. });
  89. $("#wifi-list").on("click", ".ape", function() {
  90. selectedSSID = $(this).text();
  91. $( "#ssid-pwd" ).text(selectedSSID);
  92. $( "#wifi" ).slideUp( "fast", function() {});
  93. $( "#connect_manual" ).slideUp( "fast", function() {});
  94. $( "#connect" ).slideDown( "fast", function() {});
  95. //update wait screen
  96. $( "#loading" ).show();
  97. $( "#connect-success" ).hide();
  98. $( "#connect-fail" ).hide();
  99. });
  100. $("#cancel").on("click", function() {
  101. selectedSSID = "";
  102. $( "#connect" ).slideUp( "fast", function() {});
  103. $( "#connect_manual" ).slideUp( "fast", function() {});
  104. $( "#wifi" ).slideDown( "fast", function() {});
  105. });
  106. $("#manual_cancel").on("click", function() {
  107. selectedSSID = "";
  108. $( "#connect" ).slideUp( "fast", function() {});
  109. $( "#connect_manual" ).slideUp( "fast", function() {});
  110. $( "#wifi" ).slideDown( "fast", function() {});
  111. });
  112. $("#join").on("click", function() {
  113. performConnect();
  114. });
  115. $("#manual_join").on("click", function() {
  116. performConnect($(this).data('connect'));
  117. });
  118. $("#ok-details").on("click", function() {
  119. $( "#connect-details" ).slideUp( "fast", function() {});
  120. $( "#wifi" ).slideDown( "fast", function() {});
  121. });
  122. $("#ok-credits").on("click", function() {
  123. $( "#credits" ).slideUp( "fast", function() {});
  124. $( "#app" ).slideDown( "fast", function() {});
  125. });
  126. $("#acredits").on("click", function(event) {
  127. event.preventDefault();
  128. $( "#app" ).slideUp( "fast", function() {});
  129. $( "#credits" ).slideDown( "fast", function() {});
  130. });
  131. $("#ok-connect").on("click", function() {
  132. $( "#connect-wait" ).slideUp( "fast", function() {});
  133. $( "#wifi" ).slideDown( "fast", function() {});
  134. });
  135. $("#disconnect").on("click", function() {
  136. $( "#connect-details-wrap" ).addClass('blur');
  137. $( "#diag-disconnect" ).slideDown( "fast", function() {});
  138. });
  139. $("#no-disconnect").on("click", function() {
  140. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  141. $( "#connect-details-wrap" ).removeClass('blur');
  142. });
  143. $("#yes-disconnect").on("click", function() {
  144. stopCheckStatusInterval();
  145. selectedSSID = "";
  146. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  147. $( "#connect-details-wrap" ).removeClass('blur');
  148. $.ajax({
  149. url: '/connect.json',
  150. dataType: 'text',
  151. method: 'DELETE',
  152. cache: false,
  153. contentType: 'application/json; charset=utf-8',
  154. data: JSON.stringify({ 'timestamp': Date.now()})
  155. });
  156. startCheckStatusInterval();
  157. $( "#connect-details" ).slideUp( "fast", function() {});
  158. $( "#wifi" ).slideDown( "fast", function() {})
  159. });
  160. $("input#show-nvs").on("click", function() {
  161. this.checked=this.checked?1:0;
  162. if(this.checked){
  163. $('a[href^="#tab-nvs"]').show();
  164. } else {
  165. $('a[href^="#tab-nvs"]').hide();
  166. }
  167. });
  168. $("input#autoexec-cb").on("click", function() {
  169. var data = { 'timestamp': Date.now() };
  170. autoexec = (this.checked)?1:0;
  171. data['config'] = {};
  172. data['config'] = {
  173. autoexec : {
  174. value : autoexec,
  175. type : 33
  176. }
  177. }
  178. showMessage('please wait for the ESP32 to reboot', 'MESSAGING_WARNING');
  179. $.ajax({
  180. url: '/config.json',
  181. dataType: 'text',
  182. method: 'POST',
  183. cache: false,
  184. // headers: { "X-Custom-autoexec": autoexec },
  185. contentType: 'application/json; charset=utf-8',
  186. data: JSON.stringify(data),
  187. error: function (xhr, ajaxOptions, thrownError) {
  188. console.log(xhr.status);
  189. console.log(thrownError);
  190. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  191. },
  192. complete: function(response) {
  193. //var returnedResponse = JSON.parse(response.responseText);
  194. console.log(response.responseText);
  195. console.log('sent config JSON with headers:', autoexec);
  196. console.log('now triggering reboot');
  197. $.ajax({
  198. url: '/reboot_ota.json',
  199. dataType: 'text',
  200. method: 'POST',
  201. cache: false,
  202. contentType: 'application/json; charset=utf-8',
  203. data: JSON.stringify({ 'timestamp': Date.now()}),
  204. error: function (xhr, ajaxOptions, thrownError) {
  205. console.log(xhr.status);
  206. console.log(thrownError);
  207. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  208. },
  209. complete: function(response) {
  210. console.log('reboot call completed');
  211. }
  212. });
  213. }
  214. });
  215. });
  216. $("input#save-autoexec1").on("click", function() {
  217. var data = { 'timestamp': Date.now() };
  218. autoexec1 = $("#autoexec1").val();
  219. data['config'] = {};
  220. data['config'] = {
  221. autoexec1 : {
  222. value : autoexec1,
  223. type : 33
  224. }
  225. }
  226. $.ajax({
  227. url: '/config.json',
  228. dataType: 'text',
  229. method: 'POST',
  230. cache: false,
  231. // headers: { "X-Custom-autoexec1": autoexec1 },
  232. contentType: 'application/json; charset=utf-8',
  233. data: JSON.stringify(data),
  234. error: function (xhr, ajaxOptions, thrownError) {
  235. console.log(xhr.status);
  236. console.log(thrownError);
  237. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  238. }
  239. });
  240. console.log('sent config JSON with headers:', autoexec1);
  241. console.log('sent data:', JSON.stringify(data));
  242. });
  243. $("input#save-gpio").on("click", function() {
  244. var data = { 'timestamp': Date.now() };
  245. var config = {};
  246. var headers = {};
  247. $("input.gpio").each(function() {
  248. var id = $(this)[0].id;
  249. var pin = $(this).val();
  250. if (pin != '') {
  251. config[id] = {};
  252. config[id].value = pin;
  253. config[id].type = nvs_type_t.NVS_TYPE_STR;
  254. }
  255. });
  256. data['config'] = config;
  257. $.ajax({
  258. url: '/config.json',
  259. dataType: 'text',
  260. method: 'POST',
  261. cache: false,
  262. headers: headers,
  263. contentType: 'application/json; charset=utf-8',
  264. data: JSON.stringify(data),
  265. error: function (xhr, ajaxOptions, thrownError) {
  266. console.log(xhr.status);
  267. console.log(thrownError);
  268. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  269. }
  270. });
  271. console.log('sent config JSON with headers:', JSON.stringify(headers));
  272. console.log('sent config JSON with data:', JSON.stringify(data));
  273. });
  274. $("#save-nvs").on("click", function() {
  275. var headers = {};
  276. var data = { 'timestamp': Date.now() };
  277. var config = {};
  278. $("input.nvs").each(function() {
  279. var key = $(this)[0].id;
  280. var val = $(this).val();
  281. var nvs_type = parseInt($(this)[0].attributes.nvs_type.nodeValue,10);
  282. if (key != '') {
  283. config[key] = {};
  284. if(nvs_type == nvs_type_t.NVS_TYPE_U8
  285. || nvs_type == nvs_type_t.NVS_TYPE_I8
  286. || nvs_type == nvs_type_t.NVS_TYPE_U16
  287. || nvs_type == nvs_type_t.NVS_TYPE_I16
  288. || nvs_type == nvs_type_t.NVS_TYPE_U32
  289. || nvs_type == nvs_type_t.NVS_TYPE_I32
  290. || nvs_type == nvs_type_t.NVS_TYPE_U64
  291. || nvs_type == nvs_type_t.NVS_TYPE_I64) {
  292. config[key].value = parseInt(val);
  293. }
  294. else {
  295. config[key].value = val;
  296. }
  297. config[key].type = nvs_type;
  298. }
  299. });
  300. var key = $("#nvs-new-key").val();
  301. var val = $("#nvs-new-value").val();
  302. if (key != '') {
  303. // headers["X-Custom-" +key] = val;
  304. config[key] = {};
  305. config[key].value = val;
  306. config[key].type = 33;
  307. }
  308. data['config'] = config;
  309. $.ajax({
  310. url: '/config.json',
  311. dataType: 'text',
  312. method: 'POST',
  313. cache: false,
  314. headers: headers,
  315. contentType: 'application/json; charset=utf-8',
  316. data : JSON.stringify(data),
  317. error: function (xhr, ajaxOptions, thrownError) {
  318. console.log(xhr.status);
  319. console.log(thrownError);
  320. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  321. }
  322. });
  323. console.log('sent config JSON with headers:', JSON.stringify(headers));
  324. console.log('sent config JSON with data:', JSON.stringify(data));
  325. });
  326. $("#fwUpload").on("click", function() {
  327. var upload_path = "/flash.json";
  328. var fileInput = document.getElementById("flashfilename").files;
  329. if (fileInput.length == 0) {
  330. alert("No file selected!");
  331. } else {
  332. var file = fileInput[0];
  333. var xhttp = new XMLHttpRequest();
  334. xhttp.onreadystatechange = function() {
  335. if (xhttp.readyState == 4) {
  336. if (xhttp.status == 200) {
  337. showMessage(xhttp.responseText, 'MESSAGING_INFO')
  338. } else if (xhttp.status == 0) {
  339. showMessage("Upload connection was closed abruptly!", 'MESSAGING_ERROR');
  340. } else {
  341. showMessage(xhttp.status + " Error!\n" + xhttp.responseText, 'MESSAGING_ERROR');
  342. }
  343. }
  344. };
  345. xhttp.open("POST", upload_path, true);
  346. xhttp.send(file);
  347. }
  348. enableStatusTimer = true;
  349. });
  350. $("#flash").on("click", function() {
  351. var data = { 'timestamp': Date.now() };
  352. if (blockFlashButton) return;
  353. blockFlashButton = true;
  354. var url = $("#fwurl").val();
  355. data['config'] = {
  356. fwurl : {
  357. value : url,
  358. type : 33
  359. }
  360. };
  361. $.ajax({
  362. url: '/config.json',
  363. dataType: 'text',
  364. method: 'POST',
  365. cache: false,
  366. contentType: 'application/json; charset=utf-8',
  367. data: JSON.stringify(data),
  368. error: function (xhr, ajaxOptions, thrownError) {
  369. console.log(xhr.status);
  370. console.log(thrownError);
  371. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  372. }
  373. });
  374. enableStatusTimer = true;
  375. });
  376. $("#generate-command").on("click", function() {
  377. var commandLine = commandHeader + '-n "' + $("#player").val() + '"';
  378. if (output == 'bt') {
  379. commandLine += ' -o "BT -n \'' + $("#btsink").val() + '\'" -R -Z 192000';
  380. } else if (output == 'spdif') {
  381. commandLine += ' -o SPDIF -R -Z 192000';
  382. } else {
  383. commandLine += ' -o I2S';
  384. }
  385. if ($("#optional").val() != '') {
  386. commandLine += ' ' + $("#optional").val();
  387. }
  388. $("#autoexec1").val(commandLine);
  389. });
  390. $('[name=audio]').on("click", function(){
  391. if (this.id == 'bt') {
  392. $("#btsinkdiv").show(200);
  393. output = 'bt';
  394. } else if (this.id == 'spdif') {
  395. $("#btsinkdiv").hide(200);
  396. output = 'spdif';
  397. } else {
  398. $("#btsinkdiv").hide(200);
  399. output = 'i2s';
  400. }
  401. });
  402. $('#fwcheck').on("click", function(){
  403. $("#releaseTable").html("");
  404. $.getJSON(releaseURL, function(data) {
  405. var i=0;
  406. data.forEach(function(release) {
  407. var url = '';
  408. release.assets.forEach(function(asset) {
  409. if (asset.name.match(/\.bin$/)) {
  410. url = asset.browser_download_url;
  411. }
  412. });
  413. var [ver, idf, cfg, branch] = release.name.split('#');
  414. var body = release.body;
  415. body = body.replace(/\'/ig, "\"");
  416. body = body.replace(/[\s\S]+(### Revision Log[\s\S]+)### ESP-IDF Version Used[\s\S]+/, "$1");
  417. body = body.replace(/- \(.+?\) /g, "- ");
  418. var [date, time] = release.created_at.split('T');
  419. var trclass = (i++ > 6)?' hide':'';
  420. $("#releaseTable").append(
  421. "<tr class='release"+trclass+"'>"+
  422. "<td data-toggle='tooltip' title='"+body+"'>"+ver+"</td>"+
  423. "<td>"+date+"</td>"+
  424. "<td>"+cfg+"</td>"+
  425. "<td>"+idf+"</td>"+
  426. "<td>"+branch+"</td>"+
  427. "<td><input id='generate-command' type='button' class='btn btn-success' value='Select' data-url='"+url+"' onclick='setURL(this);' /></td>"+
  428. "</tr>"
  429. );
  430. });
  431. if (i > 7) {
  432. $("#releaseTable").append(
  433. "<tr id='showall'>"+
  434. "<td colspan='6'>"+
  435. "<input type='button' id='showallbutton' class='btn btn-info' value='Show older releases' />"+
  436. "</td>"+
  437. "</tr>"
  438. );
  439. $('#showallbutton').on("click", function(){
  440. $("tr.hide").removeClass("hide");
  441. $("tr#showall").addClass("hide");
  442. });
  443. }
  444. $("#searchfw").css("display", "inline");
  445. })
  446. .fail(function() {
  447. alert("failed to fetch release history!");
  448. });
  449. });
  450. $('input#searchinput').on("input", function(){
  451. var s = $('input#searchinput').val();
  452. var re = new RegExp(s, "gi");
  453. if (s.length == 0) {
  454. $("tr.release").removeClass("hide");
  455. } else if (s.length < 3) {
  456. $("tr.release").addClass("hide");
  457. } else {
  458. $("tr.release").addClass("hide");
  459. $("tr.release").each(function(tr){
  460. $(this).find('td').each (function() {
  461. if ($(this).html().match(re)) {
  462. $(this).parent().removeClass('hide');
  463. }
  464. });
  465. });
  466. }
  467. });
  468. $('#boot-button').on("click", function(){
  469. enableStatusTimer = true;
  470. });
  471. $('#reboot-button').on("click", function(){
  472. enableStatusTimer = true;
  473. });
  474. $('#updateAP').on("click", function(){
  475. refreshAP(true);
  476. console.log("refresh AP");
  477. });
  478. //first time the page loads: attempt to get the connection status and start the wifi scan
  479. refreshAP(false);
  480. getConfig();
  481. //start timers
  482. startCheckStatusInterval();
  483. //startRefreshAPInterval();
  484. $('[data-toggle="tooltip"]').tooltip({
  485. html: true,
  486. placement : 'right',
  487. });
  488. });
  489. function setURL(button) {
  490. var url = button.dataset.url;
  491. $("#fwurl").val(url);
  492. $('[data-url^="http"]').addClass("btn-success").removeClass("btn-danger");
  493. $('[data-url="'+url+'"]').addClass("btn-danger").removeClass("btn-success");
  494. }
  495. function performConnect(conntype){
  496. //stop the status refresh. This prevents a race condition where a status
  497. //request would be refreshed with wrong ip info from a previous connection
  498. //and the request would automatically shows as succesful.
  499. stopCheckStatusInterval();
  500. //stop refreshing wifi list
  501. stopRefreshAPInterval();
  502. var pwd;
  503. var dhcpname;
  504. if (conntype == 'manual') {
  505. //Grab the manual SSID and PWD
  506. selectedSSID=$('#manual_ssid').val();
  507. pwd = $("#manual_pwd").val();
  508. dhcpname= $("#dhcp-name2").val();;
  509. }else{
  510. pwd = $("#pwd").val();
  511. dhcpname= $("#dhcp-name1").val();;
  512. }
  513. //reset connection
  514. $( "#loading" ).show();
  515. $( "#connect-success" ).hide();
  516. $( "#connect-fail" ).hide();
  517. $( "#ok-connect" ).prop("disabled",true);
  518. $( "#ssid-wait" ).text(selectedSSID);
  519. $( "#connect" ).slideUp( "fast", function() {});
  520. $( "#connect_manual" ).slideUp( "fast", function() {});
  521. $( "#connect-wait" ).slideDown( "fast", function() {});
  522. $.ajax({
  523. url: '/connect.json',
  524. dataType: 'text',
  525. method: 'POST',
  526. cache: false,
  527. // headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd, 'X-Custom-host_name': dhcpname },
  528. contentType: 'application/json; charset=utf-8',
  529. data: JSON.stringify({ 'timestamp': Date.now(),
  530. 'ssid' : selectedSSID,
  531. 'pwd' : pwd,
  532. 'host_name' : dhcpname
  533. }),
  534. error: function (xhr, ajaxOptions, thrownError) {
  535. console.log(xhr.status);
  536. console.log(thrownError);
  537. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  538. }
  539. });
  540. //now we can re-set the intervals regardless of result
  541. startCheckStatusInterval();
  542. startRefreshAPInterval();
  543. }
  544. function rssiToIcon(rssi){
  545. if(rssi >= -60){
  546. return 'w0';
  547. }
  548. else if(rssi >= -67){
  549. return 'w1';
  550. }
  551. else if(rssi >= -75){
  552. return 'w2';
  553. }
  554. else{
  555. return 'w3';
  556. }
  557. }
  558. function refreshAP(force){
  559. if (!enableAPTimer && !force) return;
  560. $.getJSON( "/ap.json", function( data ) {
  561. if(data.length > 0){
  562. //sort by signal strength
  563. data.sort(function (a, b) {
  564. var x = a["rssi"]; var y = b["rssi"];
  565. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  566. });
  567. apList = data;
  568. refreshAPHTML(apList);
  569. }
  570. });
  571. }
  572. function refreshAPHTML(data){
  573. var h = "";
  574. data.forEach(function(e, idx, array) {
  575. 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);
  576. h += "\n";
  577. });
  578. $( "#wifi-list" ).html(h)
  579. }
  580. function getMessages() {
  581. $.getJSON("/messages.json", function(data) {
  582. data.forEach(function(msg) {
  583. var msg_age = msg["current_time"] - msg["sent_time"];
  584. switch (msg["class"]) {
  585. case "MESSAGING_CLASS_OTA":
  586. //message: "{"ota_dsc":"Erasing flash complete","ota_pct":0}"
  587. var ota_data = JSON.parse(msg["message"]);
  588. if (ota_data.hasOwnProperty('ota_pct') && ota_data['ota_pct'] != 0){
  589. otapct = ota_data['ota_pct'];
  590. $('.progress-bar').css('width', otapct+'%').attr('aria-valuenow', otapct);
  591. $('.progress-bar').html(otapct+'%');
  592. }
  593. if (ota_data.hasOwnProperty('ota_dsc') && ota_data['ota_dsc'] != ''){
  594. otadsc = ota_data['ota_dsc'];
  595. $("span#flash-status").html(otadsc);
  596. if (otadsc.match(/Error:/) || otapct > 95) {
  597. blockFlashButton = false;
  598. enableStatusTimer = true;
  599. }
  600. }
  601. break;
  602. case "MESSAGING_CLASS_SYSTEM":
  603. showMessage(msg["message"], msg["type"],msg_age);
  604. lastMsg = msg;
  605. break;
  606. default:
  607. break;
  608. }
  609. });
  610. })
  611. .fail(function(xhr, ajaxOptions, thrownError) {
  612. console.log(xhr.status);
  613. console.log(thrownError);
  614. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  615. });
  616. }
  617. function checkStatus(){
  618. RepeatCheckStatusInterval();
  619. if (!enableStatusTimer) return;
  620. if (blockAjax) return;
  621. blockAjax = true;
  622. getMessages();
  623. $.getJSON( "/status.json", function( data ) {
  624. if (data.hasOwnProperty('ssid') && data['ssid'] != ""){
  625. if (data["ssid"] === selectedSSID){
  626. //that's a connection attempt
  627. if (data["urc"] === 0){
  628. //got connection
  629. $("#connected-to span").text(data["ssid"]);
  630. $("#connect-details h1").text(data["ssid"]);
  631. $("#ip").text(data["ip"]);
  632. $("#netmask").text(data["netmask"]);
  633. $("#gw").text(data["gw"]);
  634. $("#wifi-status").slideDown( "fast", function() {});
  635. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  636. //unlock the wait screen if needed
  637. $( "#ok-connect" ).prop("disabled",false);
  638. //update wait screen
  639. $( "#loading" ).hide();
  640. $( "#connect-success" ).text("Your IP address now is: " + data["ip"] );
  641. $( "#connect-success" ).show();
  642. $( "#connect-fail" ).hide();
  643. enableAPTimer = false;
  644. if (!recovery) enableStatusTimer = false;
  645. }
  646. else if (data["urc"] === 1){
  647. //failed attempt
  648. $("#connected-to span").text('');
  649. $("#connect-details h1").text('');
  650. $("#ip").text('0.0.0.0');
  651. $("#netmask").text('0.0.0.0');
  652. $("#gw").text('0.0.0.0');
  653. $("span#foot-wifi").html("");
  654. //don't show any connection
  655. $("#wifi-status").slideUp( "fast", function() {});
  656. //unlock the wait screen
  657. $( "#ok-connect" ).prop("disabled",false);
  658. //update wait screen
  659. $( "#loading" ).hide();
  660. $( "#connect-fail" ).show();
  661. $( "#connect-success" ).hide();
  662. enableAPTimer = true;
  663. enableStatusTimer = true;
  664. }
  665. }
  666. else if (data.hasOwnProperty('urc') && data['urc'] === 0){
  667. //ESP32 is already connected to a wifi without having the user do anything
  668. if( !($("#wifi-status").is(":visible")) ){
  669. $("#connected-to span").text(data["ssid"]);
  670. $("#connect-details h1").text(data["ssid"]);
  671. $("#ip").text(data["ip"]);
  672. $("#netmask").text(data["netmask"]);
  673. $("#gw").text(data["gw"]);
  674. $("#wifi-status").slideDown( "fast", function() {});
  675. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  676. }
  677. enableAPTimer = false;
  678. if (!recovery) enableStatusTimer = false;
  679. }
  680. }
  681. else if (data.hasOwnProperty('urc') && data['urc'] === 2){
  682. //that's a manual disconnect
  683. if($("#wifi-status").is(":visible")){
  684. $("#wifi-status").slideUp( "fast", function() {});
  685. $("span#foot-wifi").html("");
  686. }
  687. enableAPTimer = true;
  688. enableStatusTimer = true;
  689. }
  690. if (data.hasOwnProperty('recovery')) {
  691. if(LastRecoveryState != data["recovery"]){
  692. LastRecoveryState = data["recovery"];
  693. $("input#show-nvs")[0].checked=LastRecoveryState==1?true:false;
  694. }
  695. if($("input#show-nvs")[0].checked){
  696. $('a[href^="#tab-nvs"]').show();
  697. } else{
  698. $('a[href^="#tab-nvs"]').hide();
  699. }
  700. if (data["recovery"] === 1) {
  701. recovery = true;
  702. $("#otadiv").show();
  703. $('a[href^="#tab-audio"]').hide();
  704. $('a[href^="#tab-gpio"]').show();
  705. $("footer.footer").removeClass('sl');
  706. $("footer.footer").addClass('recovery');
  707. $("#boot-button").html('Reboot');
  708. $("#boot-form").attr('action', '/reboot_ota.json');
  709. enableStatusTimer = true;
  710. } else {
  711. recovery = false;
  712. $("#otadiv").hide();
  713. $('a[href^="#tab-audio"]').show();
  714. $('a[href^="#tab-gpio"]').hide();
  715. $("footer.footer").removeClass('recovery');
  716. $("footer.footer").addClass('sl');
  717. $("#boot-button").html('Recovery');
  718. $("#boot-form").attr('action', '/recovery.json');
  719. $('#uploaddiv"]').hide();
  720. enableStatusTimer = false;
  721. }
  722. }
  723. if (data.hasOwnProperty('project_name') && data['project_name'] != ''){
  724. pname = data['project_name'];
  725. }
  726. if (data.hasOwnProperty('version') && data['version'] != ''){
  727. ver = data['version'];
  728. $("span#foot-fw").html("fw: <strong>"+ver+"</strong>, mode: <strong>"+pname+"</strong>");
  729. }
  730. else {
  731. $("span#flash-status").html('');
  732. }
  733. if (data.hasOwnProperty('Voltage')) {
  734. var voltage = data['Voltage'];
  735. var layer;
  736. if (voltage > 0) {
  737. if (inRange(voltage, 5.8, 6.2) || inRange(voltage, 8.8, 9.2)) {
  738. layer = bat0;
  739. } else if (inRange(voltage, 6.2, 6.8) || inRange(voltage, 9.2, 10.0)) {
  740. layer = bat1;
  741. } else if (inRange(voltage, 6.8, 7.1) || inRange(voltage, 10.0, 10.5)) {
  742. layer = bat2;
  743. } else if (inRange(voltage, 7.1, 7.5) || inRange(voltage, 10.5, 11.0)) {
  744. layer = bat3;
  745. } else {
  746. layer = bat4;
  747. }
  748. layer.setAttribute("display","inline");
  749. }
  750. }
  751. if (data.hasOwnProperty('Jack')) {
  752. var jack = data['Jack'];
  753. if (jack == '1') {
  754. o_jack.setAttribute("display","inline");
  755. }
  756. }
  757. blockAjax = false;
  758. })
  759. .fail(function(xhr, ajaxOptions, thrownError) {
  760. console.log(xhr.status);
  761. console.log(thrownError);
  762. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  763. blockAjax = false;
  764. });
  765. }
  766. function getConfig() {
  767. $.getJSON("/config.json", function(data) {
  768. Object.keys(data).sort().forEach(function(key, i) {
  769. if (data.hasOwnProperty(key)) {
  770. if (key == 'autoexec') {
  771. if (data["autoexec"].value === "1") {
  772. $("#autoexec-cb")[0].checked=true;
  773. } else {
  774. $("#autoexec-cb")[0].checked=false;
  775. }
  776. } else if (key == 'autoexec1') {
  777. $("textarea#autoexec1").val(data[key].value);
  778. var re = / -o "?(\S+)\b/g;
  779. var m = re.exec(data[key].value);
  780. if (m[1] =='I2S') {
  781. o_i2s.setAttribute("display","inline");
  782. } else if (m[1] =='SPDIF') {
  783. o_spdif.setAttribute("display","inline");
  784. } else if (m[1] =='BT') {
  785. o_bt.setAttribute("display","inline");
  786. }
  787. } else if (key == 'host_name') {
  788. $("input#dhcp-name1").val(data[key].value);
  789. $("input#dhcp-name2").val(data[key].value);
  790. }
  791. $("tbody#nvsTable").append(
  792. "<tr>"+
  793. "<td>"+key+"</td>"+
  794. "<td class='value'>"+
  795. "<input type='text' class='form-control nvs' id='"+key+"' nvs_type="+data[key].type+" >"+
  796. "</td>"+
  797. "</tr>"
  798. );
  799. $("input#"+key).val(data[key].value);
  800. }
  801. });
  802. $("tbody#nvsTable").append(
  803. "<tr>"+
  804. "<td>"+
  805. "<input type='text' class='form-control' id='nvs-new-key' placeholder='new key'>"+
  806. "</td>"+
  807. "<td>"+
  808. "<input type='text' class='form-control' id='nvs-new-value' placeholder='new value' nvs_type=33 >"+ // todo: provide a way to choose field type
  809. "</td>"+
  810. "</tr>"
  811. );
  812. })
  813. .fail(function(xhr, ajaxOptions, thrownError) {
  814. console.log(xhr.status);
  815. console.log(thrownError);
  816. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  817. blockAjax = false;
  818. });
  819. }
  820. function showMessage(message, severity, age=0) {
  821. if (severity == 'MESSAGING_INFO') {
  822. $('#message').css('background', '#6af');
  823. } else if (severity == 'MESSAGING_WARNING') {
  824. $('#message').css('background', '#ff0');
  825. } else if (severity == 'MESSAGING_ERROR' ) {
  826. $('#message').css('background', '#f00');
  827. } else {
  828. $('#message').css('background', '#f00');
  829. }
  830. $('#message').html(message);
  831. $("#content").fadeTo("slow", 0.3, function() {
  832. $("#message").show(500).delay(5000).hide(500, function() {
  833. $("#content").fadeTo("slow", 1.0);
  834. });
  835. });
  836. }
  837. function inRange(x, min, max) {
  838. return ((x-min)*(x-max) <= 0);
  839. }