code.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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 dblclickCounter=0;
  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. getCommands();
  489. //start timers
  490. startCheckStatusInterval();
  491. //startRefreshAPInterval();
  492. $('[data-toggle="tooltip"]').tooltip({
  493. html: true,
  494. placement : 'right',
  495. });
  496. $('a[href^="#tab-firmware"]').dblclick(function () {
  497. dblclickCounter++;
  498. if(dblclickCounter>=2)
  499. {
  500. dblclickCounter=0;
  501. blockFlashButton=false;
  502. alert("Unocking flash button!");
  503. }
  504. });
  505. $('a[href^="#tab-firmware"]').click(function () {
  506. // when navigating back to this table, reset the counter
  507. if(!this.classList.contains("active")) dblclickCounter=0;
  508. });
  509. });
  510. function setURL(button) {
  511. var url = button.dataset.url;
  512. $("#fwurl").val(url);
  513. $('[data-url^="http"]').addClass("btn-success").removeClass("btn-danger");
  514. $('[data-url="'+url+'"]').addClass("btn-danger").removeClass("btn-success");
  515. }
  516. function performConnect(conntype){
  517. //stop the status refresh. This prevents a race condition where a status
  518. //request would be refreshed with wrong ip info from a previous connection
  519. //and the request would automatically shows as succesful.
  520. stopCheckStatusInterval();
  521. //stop refreshing wifi list
  522. stopRefreshAPInterval();
  523. var pwd;
  524. var dhcpname;
  525. if (conntype == 'manual') {
  526. //Grab the manual SSID and PWD
  527. selectedSSID=$('#manual_ssid').val();
  528. pwd = $("#manual_pwd").val();
  529. dhcpname= $("#dhcp-name2").val();;
  530. }else{
  531. pwd = $("#pwd").val();
  532. dhcpname= $("#dhcp-name1").val();;
  533. }
  534. //reset connection
  535. $( "#loading" ).show();
  536. $( "#connect-success" ).hide();
  537. $( "#connect-fail" ).hide();
  538. $( "#ok-connect" ).prop("disabled",true);
  539. $( "#ssid-wait" ).text(selectedSSID);
  540. $( "#connect" ).slideUp( "fast", function() {});
  541. $( "#connect_manual" ).slideUp( "fast", function() {});
  542. $( "#connect-wait" ).slideDown( "fast", function() {});
  543. $.ajax({
  544. url: '/connect.json',
  545. dataType: 'text',
  546. method: 'POST',
  547. cache: false,
  548. // headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd, 'X-Custom-host_name': dhcpname },
  549. contentType: 'application/json; charset=utf-8',
  550. data: JSON.stringify({ 'timestamp': Date.now(),
  551. 'ssid' : selectedSSID,
  552. 'pwd' : pwd,
  553. 'host_name' : dhcpname
  554. }),
  555. error: function (xhr, ajaxOptions, thrownError) {
  556. console.log(xhr.status);
  557. console.log(thrownError);
  558. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  559. }
  560. });
  561. //now we can re-set the intervals regardless of result
  562. startCheckStatusInterval();
  563. startRefreshAPInterval();
  564. }
  565. function rssiToIcon(rssi){
  566. if(rssi >= -60){
  567. return 'w0';
  568. }
  569. else if(rssi >= -67){
  570. return 'w1';
  571. }
  572. else if(rssi >= -75){
  573. return 'w2';
  574. }
  575. else{
  576. return 'w3';
  577. }
  578. }
  579. function refreshAP(force){
  580. if (!enableAPTimer && !force) return;
  581. $.getJSON( "/scan.json", async function( data ) {
  582. await sleep(2000);
  583. $.getJSON( "/ap.json", function( data ) {
  584. if(data.length > 0){
  585. //sort by signal strength
  586. data.sort(function (a, b) {
  587. var x = a["rssi"]; var y = b["rssi"];
  588. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  589. });
  590. apList = data;
  591. refreshAPHTML(apList);
  592. }
  593. });
  594. });
  595. }
  596. function refreshAPHTML(data){
  597. var h = "";
  598. data.forEach(function(e, idx, array) {
  599. 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);
  600. h += "\n";
  601. });
  602. $( "#wifi-list" ).html(h)
  603. }
  604. function getMessages() {
  605. $.getJSON("/messages.json?1", async function(data) {
  606. for (const msg of data) {
  607. var msg_age = msg["current_time"] - msg["sent_time"];
  608. var msg_time = new Date();
  609. msg_time.setTime( msg_time.getTime() - msg_age );
  610. switch (msg["class"]) {
  611. case "MESSAGING_CLASS_OTA":
  612. //message: "{"ota_dsc":"Erasing flash complete","ota_pct":0}"
  613. var ota_data = JSON.parse(msg["message"]);
  614. if (ota_data.hasOwnProperty('ota_pct') && ota_data['ota_pct'] != 0){
  615. otapct = ota_data['ota_pct'];
  616. $('.progress-bar').css('width', otapct+'%').attr('aria-valuenow', otapct);
  617. $('.progress-bar').html(otapct+'%');
  618. }
  619. if (ota_data.hasOwnProperty('ota_dsc') && ota_data['ota_dsc'] != ''){
  620. otadsc = ota_data['ota_dsc'];
  621. $("span#flash-status").html(otadsc);
  622. if (msg.type =="MESSAGING_ERROR" || otapct > 95) {
  623. blockFlashButton = false;
  624. enableStatusTimer = true;
  625. }
  626. }
  627. break;
  628. case "MESSAGING_CLASS_STATS":
  629. // for task states, check structure : task_state_t
  630. var stats_data = JSON.parse(msg["message"]);
  631. console.log(msg_time.toLocaleString() + " - Number of tasks on the ESP32: " + stats_data["ntasks"]);
  632. var stats_tasks = stats_data["tasks"];
  633. console.log(msg_time.toLocaleString() + '\tname' + '\tcpu' + '\tstate'+ '\tminstk'+ '\tbprio'+ '\tcprio'+ '\tnum' );
  634. stats_tasks.forEach(function(task) {
  635. 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"]);
  636. });
  637. break;
  638. case "MESSAGING_CLASS_SYSTEM":
  639. var r = await showMessage(msg["message"], msg["type"],msg_age);
  640. $("#syslogTable").append(
  641. "<tr class='"+msg["type"]+"'>"+
  642. "<td>"+msg_time.toLocaleString()+"</td>"+
  643. "<td>"+msg["message"]+"</td>"+
  644. "</tr>"
  645. );
  646. break;
  647. default:
  648. break;
  649. }
  650. }
  651. })
  652. .fail(function(xhr, ajaxOptions, thrownError) {
  653. console.log(xhr.status);
  654. console.log(thrownError);
  655. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  656. });
  657. /*
  658. Minstk is minimum stack space left
  659. Bprio is base priority
  660. cprio is current priority
  661. nme is name
  662. st is task state. I provided a "typedef" that you can use to convert to text
  663. cpu is cpu percent used
  664. */
  665. }
  666. function checkStatus(){
  667. RepeatCheckStatusInterval();
  668. if (!enableStatusTimer) return;
  669. if (blockAjax) return;
  670. blockAjax = true;
  671. getMessages();
  672. $.getJSON( "/status.json", function( data ) {
  673. if (data.hasOwnProperty('ssid') && data['ssid'] != ""){
  674. if (data["ssid"] === selectedSSID){
  675. //that's a connection attempt
  676. if (data["urc"] === 0){
  677. //got connection
  678. $("#connected-to span").text(data["ssid"]);
  679. $("#connect-details h1").text(data["ssid"]);
  680. $("#ip").text(data["ip"]);
  681. $("#netmask").text(data["netmask"]);
  682. $("#gw").text(data["gw"]);
  683. $("#wifi-status").slideDown( "fast", function() {});
  684. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  685. //unlock the wait screen if needed
  686. $( "#ok-connect" ).prop("disabled",false);
  687. //update wait screen
  688. $( "#loading" ).hide();
  689. $( "#connect-success" ).text("Your IP address now is: " + data["ip"] );
  690. $( "#connect-success" ).show();
  691. $( "#connect-fail" ).hide();
  692. enableAPTimer = false;
  693. if (!recovery) enableStatusTimer = false;
  694. }
  695. else if (data["urc"] === 1){
  696. //failed attempt
  697. $("#connected-to span").text('');
  698. $("#connect-details h1").text('');
  699. $("#ip").text('0.0.0.0');
  700. $("#netmask").text('0.0.0.0');
  701. $("#gw").text('0.0.0.0');
  702. $("span#foot-wifi").html("");
  703. //don't show any connection
  704. $("#wifi-status").slideUp( "fast", function() {});
  705. //unlock the wait screen
  706. $( "#ok-connect" ).prop("disabled",false);
  707. //update wait screen
  708. $( "#loading" ).hide();
  709. $( "#connect-fail" ).show();
  710. $( "#connect-success" ).hide();
  711. enableAPTimer = true;
  712. enableStatusTimer = true;
  713. }
  714. }
  715. else if (data.hasOwnProperty('urc') && data['urc'] === 0){
  716. //ESP32 is already connected to a wifi without having the user do anything
  717. if( !($("#wifi-status").is(":visible")) ){
  718. $("#connected-to span").text(data["ssid"]);
  719. $("#connect-details h1").text(data["ssid"]);
  720. $("#ip").text(data["ip"]);
  721. $("#netmask").text(data["netmask"]);
  722. $("#gw").text(data["gw"]);
  723. $("#wifi-status").slideDown( "fast", function() {});
  724. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  725. }
  726. enableAPTimer = false;
  727. if (!recovery) enableStatusTimer = false;
  728. }
  729. }
  730. else if (data.hasOwnProperty('urc') && data['urc'] === 2){
  731. //that's a manual disconnect
  732. if($("#wifi-status").is(":visible")){
  733. $("#wifi-status").slideUp( "fast", function() {});
  734. $("span#foot-wifi").html("");
  735. }
  736. enableAPTimer = true;
  737. enableStatusTimer = true;
  738. }
  739. if (data.hasOwnProperty('recovery')) {
  740. if(LastRecoveryState != data["recovery"]){
  741. LastRecoveryState = data["recovery"];
  742. $("input#show-nvs")[0].checked=LastRecoveryState==1?true:false;
  743. }
  744. if($("input#show-nvs")[0].checked){
  745. $('a[href^="#tab-nvs"]').show();
  746. } else{
  747. $('a[href^="#tab-nvs"]').hide();
  748. }
  749. if (data["recovery"] === 1) {
  750. recovery = true;
  751. $("#otadiv").show();
  752. $('a[href^="#tab-audio"]').hide();
  753. $('a[href^="#tab-gpio"]').show();
  754. $('#uploaddiv').show();
  755. $("footer.footer").removeClass('sl');
  756. $("footer.footer").addClass('recovery');
  757. $("#boot-button").html('Reboot');
  758. $("#boot-form").attr('action', '/reboot_ota.json');
  759. enableStatusTimer = true;
  760. } else {
  761. recovery = false;
  762. $("#otadiv").hide();
  763. $('a[href^="#tab-audio"]').show();
  764. $('a[href^="#tab-gpio"]').hide();
  765. $('#uploaddiv').hide();
  766. $("footer.footer").removeClass('recovery');
  767. $("footer.footer").addClass('sl');
  768. $("#boot-button").html('Recovery');
  769. $("#boot-form").attr('action', '/recovery.json');
  770. enableStatusTimer = false;
  771. }
  772. }
  773. if (data.hasOwnProperty('project_name') && data['project_name'] != ''){
  774. pname = data['project_name'];
  775. }
  776. if (data.hasOwnProperty('version') && data['version'] != ''){
  777. ver = data['version'];
  778. $("span#foot-fw").html("fw: <strong>"+ver+"</strong>, mode: <strong>"+pname+"</strong>");
  779. }
  780. else {
  781. $("span#flash-status").html('');
  782. }
  783. if (data.hasOwnProperty('Voltage')) {
  784. var voltage = data['Voltage'];
  785. var layer;
  786. if (voltage > 0) {
  787. if (inRange(voltage, 5.8, 6.2) || inRange(voltage, 8.8, 9.2)) {
  788. layer = bat0;
  789. } else if (inRange(voltage, 6.2, 6.8) || inRange(voltage, 9.2, 10.0)) {
  790. layer = bat1;
  791. } else if (inRange(voltage, 6.8, 7.1) || inRange(voltage, 10.0, 10.5)) {
  792. layer = bat2;
  793. } else if (inRange(voltage, 7.1, 7.5) || inRange(voltage, 10.5, 11.0)) {
  794. layer = bat3;
  795. } else {
  796. layer = bat4;
  797. }
  798. layer.setAttribute("display","inline");
  799. }
  800. }
  801. if (data.hasOwnProperty('Jack')) {
  802. var jack = data['Jack'];
  803. if (jack == '1') {
  804. o_jack.setAttribute("display","inline");
  805. }
  806. }
  807. blockAjax = false;
  808. })
  809. .fail(function(xhr, ajaxOptions, thrownError) {
  810. console.log(xhr.status);
  811. console.log(thrownError);
  812. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  813. blockAjax = false;
  814. });
  815. }
  816. function getCommands() {
  817. $.getJSON("/commands.json", function(data) {
  818. console.log(data);
  819. })
  820. .fail(function(xhr, ajaxOptions, thrownError) {
  821. console.log(xhr.status);
  822. console.log(thrownError);
  823. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  824. blockAjax = false;
  825. });
  826. }
  827. function getConfig() {
  828. $.getJSON("/config.json", function(data) {
  829. Object.keys(data).sort().forEach(function(key, i) {
  830. if (data.hasOwnProperty(key)) {
  831. if (key == 'autoexec') {
  832. if (data["autoexec"].value === "1") {
  833. $("#autoexec-cb")[0].checked=true;
  834. } else {
  835. $("#autoexec-cb")[0].checked=false;
  836. }
  837. } else if (key == 'autoexec1') {
  838. $("textarea#autoexec1").val(data[key].value);
  839. var re = / -o "?(\S+)\b/g;
  840. var m = re.exec(data[key].value);
  841. if (m[1] =='I2S') {
  842. o_i2s.setAttribute("display","inline");
  843. } else if (m[1] =='SPDIF') {
  844. o_spdif.setAttribute("display","inline");
  845. } else if (m[1] =='BT') {
  846. o_bt.setAttribute("display","inline");
  847. }
  848. } else if (key == 'host_name') {
  849. $("input#dhcp-name1").val(data[key].value);
  850. $("input#dhcp-name2").val(data[key].value);
  851. }
  852. $("tbody#nvsTable").append(
  853. "<tr>"+
  854. "<td>"+key+"</td>"+
  855. "<td class='value'>"+
  856. "<input type='text' class='form-control nvs' id='"+key+"' nvs_type="+data[key].type+" >"+
  857. "</td>"+
  858. "</tr>"
  859. );
  860. $("input#"+key).val(data[key].value);
  861. }
  862. });
  863. $("tbody#nvsTable").append(
  864. "<tr>"+
  865. "<td>"+
  866. "<input type='text' class='form-control' id='nvs-new-key' placeholder='new key'>"+
  867. "</td>"+
  868. "<td>"+
  869. "<input type='text' class='form-control' id='nvs-new-value' placeholder='new value' nvs_type=33 >"+ // todo: provide a way to choose field type
  870. "</td>"+
  871. "</tr>"
  872. );
  873. })
  874. .fail(function(xhr, ajaxOptions, thrownError) {
  875. console.log(xhr.status);
  876. console.log(thrownError);
  877. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  878. blockAjax = false;
  879. });
  880. }
  881. function showMessage(message, severity, age=0) {
  882. if (severity == 'MESSAGING_INFO') {
  883. $('#message').css('background', '#6af');
  884. } else if (severity == 'MESSAGING_WARNING') {
  885. $('#message').css('background', '#ff0');
  886. } else if (severity == 'MESSAGING_ERROR' ) {
  887. $('#message').css('background', '#f00');
  888. } else {
  889. $('#message').css('background', '#f00');
  890. }
  891. $('#message').html(message);
  892. return new Promise(function(resolve, reject) {
  893. $("#content").fadeTo("slow", 0.3, function() {
  894. $("#message").show(500).delay(5000).hide(500, function() {
  895. $("#content").fadeTo("slow", 1.0, function() {
  896. resolve(true);
  897. });
  898. });
  899. });
  900. });
  901. }
  902. function inRange(x, min, max) {
  903. return ((x-min)*(x-max) <= 0);
  904. }
  905. function sleep(ms) {
  906. return new Promise(resolve => setTimeout(resolve, ms));
  907. }