code.js 34 KB

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