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