code.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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', '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, '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, '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, '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, '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, '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, 'INFO')
  338. } else if (xhttp.status == 0) {
  339. showMessage("Upload connection was closed abruptly!", 'ERROR');
  340. } else {
  341. showMessage(xhttp.status + " Error!\n" + xhttp.responseText, '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, '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, '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. });
  584. })
  585. .fail(function(xhr, ajaxOptions, thrownError) {
  586. console.log(xhr.status);
  587. console.log(thrownError);
  588. if (thrownError != '') showMessage(thrownError, 'ERROR');
  589. });
  590. }
  591. function checkStatus(){
  592. RepeatCheckStatusInterval();
  593. if (!enableStatusTimer) return;
  594. if (blockAjax) return;
  595. blockAjax = true;
  596. getMessages();
  597. $.getJSON( "/status.json", function( data ) {
  598. if (data.hasOwnProperty('ssid') && data['ssid'] != ""){
  599. if (data["ssid"] === selectedSSID){
  600. //that's a connection attempt
  601. if (data["urc"] === 0){
  602. //got connection
  603. $("#connected-to span").text(data["ssid"]);
  604. $("#connect-details h1").text(data["ssid"]);
  605. $("#ip").text(data["ip"]);
  606. $("#netmask").text(data["netmask"]);
  607. $("#gw").text(data["gw"]);
  608. $("#wifi-status").slideDown( "fast", function() {});
  609. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  610. //unlock the wait screen if needed
  611. $( "#ok-connect" ).prop("disabled",false);
  612. //update wait screen
  613. $( "#loading" ).hide();
  614. $( "#connect-success" ).text("Your IP address now is: " + data["ip"] );
  615. $( "#connect-success" ).show();
  616. $( "#connect-fail" ).hide();
  617. enableAPTimer = false;
  618. if (!recovery) enableStatusTimer = false;
  619. }
  620. else if (data["urc"] === 1){
  621. //failed attempt
  622. $("#connected-to span").text('');
  623. $("#connect-details h1").text('');
  624. $("#ip").text('0.0.0.0');
  625. $("#netmask").text('0.0.0.0');
  626. $("#gw").text('0.0.0.0');
  627. $("span#foot-wifi").html("");
  628. //don't show any connection
  629. $("#wifi-status").slideUp( "fast", function() {});
  630. //unlock the wait screen
  631. $( "#ok-connect" ).prop("disabled",false);
  632. //update wait screen
  633. $( "#loading" ).hide();
  634. $( "#connect-fail" ).show();
  635. $( "#connect-success" ).hide();
  636. enableAPTimer = true;
  637. enableStatusTimer = true;
  638. }
  639. }
  640. else if (data.hasOwnProperty('urc') && data['urc'] === 0){
  641. //ESP32 is already connected to a wifi without having the user do anything
  642. if( !($("#wifi-status").is(":visible")) ){
  643. $("#connected-to span").text(data["ssid"]);
  644. $("#connect-details h1").text(data["ssid"]);
  645. $("#ip").text(data["ip"]);
  646. $("#netmask").text(data["netmask"]);
  647. $("#gw").text(data["gw"]);
  648. $("#wifi-status").slideDown( "fast", function() {});
  649. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  650. }
  651. enableAPTimer = false;
  652. if (!recovery) enableStatusTimer = false;
  653. }
  654. }
  655. else if (data.hasOwnProperty('urc') && data['urc'] === 2){
  656. //that's a manual disconnect
  657. if($("#wifi-status").is(":visible")){
  658. $("#wifi-status").slideUp( "fast", function() {});
  659. $("span#foot-wifi").html("");
  660. }
  661. enableAPTimer = true;
  662. enableStatusTimer = true;
  663. }
  664. if (data.hasOwnProperty('recovery')) {
  665. if(LastRecoveryState != data["recovery"]){
  666. LastRecoveryState = data["recovery"];
  667. $("input#show-nvs")[0].checked=LastRecoveryState==1?true:false;
  668. }
  669. if($("input#show-nvs")[0].checked){
  670. $('a[href^="#tab-nvs"]').show();
  671. } else{
  672. $('a[href^="#tab-nvs"]').hide();
  673. }
  674. if (data["recovery"] === 1) {
  675. recovery = true;
  676. $("#otadiv").show();
  677. $('a[href^="#tab-audio"]').hide();
  678. $('a[href^="#tab-gpio"]').show();
  679. $("footer.footer").removeClass('sl');
  680. $("footer.footer").addClass('recovery');
  681. $("#boot-button").html('Reboot');
  682. $("#boot-form").attr('action', '/reboot_ota.json');
  683. enableStatusTimer = true;
  684. } else {
  685. recovery = false;
  686. $("#otadiv").hide();
  687. $('a[href^="#tab-audio"]').show();
  688. $('a[href^="#tab-gpio"]').hide();
  689. $("footer.footer").removeClass('recovery');
  690. $("footer.footer").addClass('sl');
  691. $("#boot-button").html('Recovery');
  692. $("#boot-form").attr('action', '/recovery.json');
  693. $('#uploaddiv"]').hide();
  694. enableStatusTimer = false;
  695. }
  696. }
  697. if (data.hasOwnProperty('project_name') && data['project_name'] != ''){
  698. pname = data['project_name'];
  699. }
  700. if (data.hasOwnProperty('version') && data['version'] != ''){
  701. ver = data['version'];
  702. $("span#foot-fw").html("fw: <strong>"+ver+"</strong>, mode: <strong>"+pname+"</strong>");
  703. }
  704. if (data.hasOwnProperty('ota_pct') && data['ota_pct'] != 0){
  705. otapct = data['ota_pct'];
  706. $('.progress-bar').css('width', otapct+'%').attr('aria-valuenow', otapct);
  707. $('.progress-bar').html(otapct+'%');
  708. }
  709. if (data.hasOwnProperty('ota_dsc') && data['ota_dsc'] != ''){
  710. otadsc = data['ota_dsc'];
  711. $("span#flash-status").html(otadsc);
  712. if (otadsc.match(/Error:/) || otapct > 95) {
  713. blockFlashButton = false;
  714. enableStatusTimer = true;
  715. }
  716. } else {
  717. $("span#flash-status").html('');
  718. }
  719. if (data.hasOwnProperty('message') && data['message'] != ''){
  720. var msg = data['message'].text;
  721. var severity = data['message'].severity;
  722. if (msg != lastMsg) {
  723. showMessage(msg, severity);
  724. lastMsg = msg;
  725. }
  726. }
  727. if (data.hasOwnProperty('Voltage')) {
  728. var voltage = data['Voltage'];
  729. var layer;
  730. if (voltage > 0) {
  731. if (inRange(voltage, 5.8, 6.2) || inRange(voltage, 8.8, 9.2)) {
  732. layer = bat0;
  733. } else if (inRange(voltage, 6.2, 6.8) || inRange(voltage, 9.2, 10.0)) {
  734. layer = bat1;
  735. } else if (inRange(voltage, 6.8, 7.1) || inRange(voltage, 10.0, 10.5)) {
  736. layer = bat2;
  737. } else if (inRange(voltage, 7.1, 7.5) || inRange(voltage, 10.5, 11.0)) {
  738. layer = bat3;
  739. } else {
  740. layer = bat4;
  741. }
  742. layer.setAttribute("display","inline");
  743. }
  744. }
  745. if (data.hasOwnProperty('Jack')) {
  746. var jack = data['Jack'];
  747. if (jack == '1') {
  748. o_jack.setAttribute("display","inline");
  749. }
  750. }
  751. blockAjax = false;
  752. })
  753. .fail(function(xhr, ajaxOptions, thrownError) {
  754. console.log(xhr.status);
  755. console.log(thrownError);
  756. if (thrownError != '') showMessage(thrownError, 'ERROR');
  757. blockAjax = false;
  758. });
  759. }
  760. function getConfig() {
  761. $.getJSON("/config.json", function(data) {
  762. Object.keys(data).sort().forEach(function(key, i) {
  763. if (data.hasOwnProperty(key)) {
  764. if (key == 'autoexec') {
  765. if (data["autoexec"].value === "1") {
  766. $("#autoexec-cb")[0].checked=true;
  767. } else {
  768. $("#autoexec-cb")[0].checked=false;
  769. }
  770. } else if (key == 'autoexec1') {
  771. $("textarea#autoexec1").val(data[key].value);
  772. var re = / -o "?(\S+)\b/g;
  773. var m = re.exec(data[key].value);
  774. if (m[1] =='I2S') {
  775. o_i2s.setAttribute("display","inline");
  776. } else if (m[1] =='SPDIF') {
  777. o_spdif.setAttribute("display","inline");
  778. } else if (m[1] =='BT') {
  779. o_bt.setAttribute("display","inline");
  780. }
  781. } else if (key == 'host_name') {
  782. $("input#dhcp-name1").val(data[key].value);
  783. $("input#dhcp-name2").val(data[key].value);
  784. }
  785. $("tbody#nvsTable").append(
  786. "<tr>"+
  787. "<td>"+key+"</td>"+
  788. "<td class='value'>"+
  789. "<input type='text' class='form-control nvs' id='"+key+"' nvs_type="+data[key].type+" >"+
  790. "</td>"+
  791. "</tr>"
  792. );
  793. $("input#"+key).val(data[key].value);
  794. }
  795. });
  796. $("tbody#nvsTable").append(
  797. "<tr>"+
  798. "<td>"+
  799. "<input type='text' class='form-control' id='nvs-new-key' placeholder='new key'>"+
  800. "</td>"+
  801. "<td>"+
  802. "<input type='text' class='form-control' id='nvs-new-value' placeholder='new value' nvs_type=33 >"+ // todo: provide a way to choose field type
  803. "</td>"+
  804. "</tr>"
  805. );
  806. })
  807. .fail(function(xhr, ajaxOptions, thrownError) {
  808. console.log(xhr.status);
  809. console.log(thrownError);
  810. if (thrownError != '') showMessage(thrownError, 'ERROR');
  811. blockAjax = false;
  812. });
  813. }
  814. function showMessage(message, severity) {
  815. if (severity == 'INFO') {
  816. $('#message').css('background', '#6af');
  817. } else if (severity == 'WARNING') {
  818. $('#message').css('background', '#ff0');
  819. } else {
  820. $('#message').css('background', '#f00');
  821. }
  822. $('#message').html(message);
  823. $("#content").fadeTo("slow", 0.3, function() {
  824. $("#message").show(500).delay(5000).hide(500, function() {
  825. $("#content").fadeTo("slow", 1.0);
  826. });
  827. });
  828. }
  829. function inRange(x, min, max) {
  830. return ((x-min)*(x-max) <= 0);
  831. }