code.js 40 KB

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