2
0

code.js 44 KB

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