code.js 34 KB

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