code.js 36 KB

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