2
0

code.js 34 KB

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