2
0

code.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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. cmdstring = button.attributes.cmdname.value;
  940. fields=document.getElementById("flds-"+cmdstring);
  941. cmdstring+=' ';
  942. if(fields){
  943. hint = pardiv.hint;
  944. allfields=fields.querySelectorAll("select,input");
  945. for (i = 0; i < allfields.length; i++) {
  946. attr=allfields[i].attributes;
  947. qts='';
  948. opt='';
  949. optspacer=' ';
  950. isSelect=allfields[i].attributes?.class?.value=="custom-select";
  951. if(( isSelect && allfields[i].selectedIndex != 0 )|| !isSelect ){
  952. if (attr.longopts.value!== "undefined"){
  953. opt+= '--' + attr.longopts.value;
  954. optspacer='=';
  955. }
  956. else if(attr.shortopts.value!== "undefined"){
  957. opt= '-' + attr.shortopts.value;
  958. }
  959. if(attr.hasvalue.value== "true" ){
  960. if(allfields[i].value!=''){
  961. qts = (/\s/.test(allfields[i].value))?'"':'';
  962. cmdstring+=opt+optspacer+qts +allfields[i].value +qts+ ' ';
  963. }
  964. }
  965. else {
  966. // this is a checkbox
  967. if(allfields[i].checked) cmdstring+=opt+ ' ';
  968. }
  969. }
  970. }
  971. }
  972. console.log(cmdstring);
  973. var data = { 'timestamp': Date.now() };
  974. data['command'] = cmdstring;
  975. $.ajax({
  976. url: '/commands.json',
  977. dataType: 'text',
  978. method: 'POST',
  979. cache: false,
  980. contentType: 'application/json; charset=utf-8',
  981. data: JSON.stringify(data),
  982. error: function (xhr, ajaxOptions, thrownError) {
  983. console.log(xhr.status);
  984. console.log(thrownError);
  985. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  986. },
  987. complete: function(response) {
  988. //var returnedResponse = JSON.parse(response.responseText);
  989. console.log(response.responseText);
  990. if(reboot){
  991. showMessage('Applying. Please wait for the ESP32 to reboot', 'MESSAGING_WARNING');
  992. console.log('now triggering reboot');
  993. $.ajax({
  994. url: '/reboot.json',
  995. dataType: 'text',
  996. method: 'POST',
  997. cache: false,
  998. contentType: 'application/json; charset=utf-8',
  999. data: JSON.stringify({ 'timestamp': Date.now()}),
  1000. error: function (xhr, ajaxOptions, thrownError) {
  1001. console.log(xhr.status);
  1002. console.log(thrownError);
  1003. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  1004. },
  1005. complete: function(response) {
  1006. console.log('reboot call completed');
  1007. getCommands();
  1008. }
  1009. });
  1010. }
  1011. }
  1012. });
  1013. enableStatusTimer = true;
  1014. }
  1015. function getCommands() {
  1016. $.getJSON("/commands.json", function(data) {
  1017. console.log(data);
  1018. var advancedtabhtml='';
  1019. data.commands.forEach(function(command) {
  1020. if($("#flds-"+command.name).length == 0){
  1021. isConfig=($('#'+command.name+'-list').length>0);
  1022. innerhtml='';
  1023. innerhtml+='<tr><td>'+(isConfig?'<h1>':'');
  1024. innerhtml+=escapeHTML(command.help).replace(/\n/g, '<br />')+(isConfig?'</h1>':'<br>');
  1025. innerhtml+='<div >';
  1026. if(command.hasOwnProperty("argtable")){
  1027. innerhtml+='<table class="table table-hover" id="flds-'+command.name+'"><tbody>';
  1028. command.argtable.forEach(function (arg){
  1029. placeholder=arg?.datatype || '';
  1030. ctrlname=command.name+'-'+arg.longopts;
  1031. curvalue=data.values?.[command.name]?.[arg.longopts] || '';
  1032. innerhtml+="<tr>";
  1033. var attributes ='datatype="'+arg.datatype+'" ';
  1034. attributes+='hasvalue='+arg.hasvalue+' ';
  1035. attributes+='longopts="'+arg.longopts+'" ';
  1036. attributes+='shortopts="'+arg.shortopts+'" ';
  1037. attributes+='checkbox='+arg.checkbox+' ';
  1038. attributes+='cmdname="'+command.name+'" ';
  1039. attributes+= 'id="'+ctrlname+'" name="'+ctrlname+'" placeholder="'+placeholder+'" hasvalue="'+arg.hasvalue+'" ';
  1040. if(placeholder.includes('|')){
  1041. placeholder = placeholder.replace('<','').replace('>','');
  1042. innerhtml+='<td><select ';
  1043. innerhtml+=attributes;
  1044. innerhtml+=' class="custom-select">';
  1045. innerhtml+='<option '+(curvalue.length>0?'value':'selected')+'>'+arg.glossary+'</option>'
  1046. placeholder.split('|').forEach(function(choice){
  1047. innerhtml+='<option '+(curvalue.length>0&&curvalue==choice?'selected':'value')+'="'+choice+'">'+choice+'</option>';
  1048. });
  1049. innerhtml+='</select></td>';
  1050. }
  1051. else {
  1052. ctrltype="text";
  1053. if(arg.checkbox){
  1054. ctrltype="checkbox";
  1055. }
  1056. innerhtml+='<td><label for="'+ctrlname+'">'+ arg.glossary+'</label></td>';
  1057. innerhtml+='<td><input type="'+ctrltype+'"';
  1058. innerhtml+=attributes;
  1059. if(arg.checkbox){
  1060. if(data.values?.[command.name]?.[arg.longopts] ){
  1061. innerhtml+='checked ';
  1062. }
  1063. innerhtml+='></input></td>';
  1064. }
  1065. else {
  1066. innerhtml+='value="'+curvalue+'" ';
  1067. innerhtml+='></input></td>'+ curvalue.length>0?'<td>last: '+curvalue+'</td>':'';
  1068. }
  1069. }
  1070. innerhtml+="</tr>";
  1071. });
  1072. innerhtml+='</tbody></table>';
  1073. }
  1074. if(isConfig){
  1075. innerhtml+='<div class="buttons"><input id="btn-'+ command.name + '" type="button" class="btn btn-success" cmdname="'+command.name+'" value="Save" onclick="runCommand(this,false);">';
  1076. innerhtml+='<input id="btn-'+ command.name + '-apply" type="button" class="btn btn-success" cmdname="'+command.name+'" value="Apply" onclick="runCommand(this,true);"></div></div><td></tr>';
  1077. $('#'+command.name+'-list').append(innerhtml);
  1078. }
  1079. else {
  1080. advancedtabhtml+='<br>'+innerhtml;
  1081. advancedtabhtml+='<div class="buttons"><input id="btn-'+ command.name + '" type="button" class="btn btn-danger btn-sm" cmdname="'+command.name+'" value="'+command.name+'" onclick="runCommand(this);"></div></div><td></tr>';
  1082. }
  1083. }
  1084. });
  1085. $("#commands-list").append(advancedtabhtml);
  1086. data.commands.forEach(function(command) {
  1087. if(command.hasOwnProperty("argtable")){
  1088. command.argtable.forEach(function (arg){
  1089. ctrlselector='#'+command.name+'-'+arg.longopts;
  1090. if(arg.checkbox){
  1091. $(ctrlselector)[0].checked=data.values?.[command.name]?.[arg.longopts];
  1092. }
  1093. else {
  1094. $(ctrlselector)[0].value=data.values?.[command.name]?.[arg.longopts] || '';
  1095. }
  1096. });
  1097. }
  1098. });
  1099. })
  1100. .fail(function(xhr, ajaxOptions, thrownError) {
  1101. console.log(xhr.status);
  1102. console.log(thrownError);
  1103. $("#commands-list").empty();
  1104. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  1105. blockAjax = false;
  1106. });
  1107. }
  1108. function getConfig() {
  1109. $.getJSON("/config.json", function(data) {
  1110. Object.keys(data).sort().forEach(function(key, i) {
  1111. if (data.hasOwnProperty(key)) {
  1112. if (key == 'autoexec') {
  1113. if (data["autoexec"].value === "1") {
  1114. $("#autoexec-cb")[0].checked=true;
  1115. } else {
  1116. $("#autoexec-cb")[0].checked=false;
  1117. }
  1118. } else if (key == 'autoexec1') {
  1119. $("textarea#autoexec1").val(data[key].value);
  1120. var re = / -o "?(\S+)\b/g;
  1121. var m = re.exec(data[key].value);
  1122. if (m[1] =='I2S') {
  1123. o_i2s.setAttribute("display","inline");
  1124. } else if (m[1] =='SPDIF') {
  1125. o_spdif.setAttribute("display","inline");
  1126. } else if (m[1] =='BT') {
  1127. o_bt.setAttribute("display","inline");
  1128. }
  1129. } else if (key == 'host_name') {
  1130. $("input#dhcp-name1").val(data[key].value);
  1131. $("input#dhcp-name2").val(data[key].value);
  1132. }
  1133. $("tbody#nvsTable").append(
  1134. "<tr>"+
  1135. "<td>"+key+"</td>"+
  1136. "<td class='value'>"+
  1137. "<input type='text' class='form-control nvs' id='"+key+"' nvs_type="+data[key].type+" >"+
  1138. "</td>"+
  1139. "</tr>"
  1140. );
  1141. $("input#"+key).val(data[key].value);
  1142. }
  1143. });
  1144. $("tbody#nvsTable").append(
  1145. "<tr>"+
  1146. "<td>"+
  1147. "<input type='text' class='form-control' id='nvs-new-key' placeholder='new key'>"+
  1148. "</td>"+
  1149. "<td>"+
  1150. "<input type='text' class='form-control' id='nvs-new-value' placeholder='new value' nvs_type=33 >"+ // todo: provide a way to choose field type
  1151. "</td>"+
  1152. "</tr>"
  1153. );
  1154. })
  1155. .fail(function(xhr, ajaxOptions, thrownError) {
  1156. console.log(xhr.status);
  1157. console.log(thrownError);
  1158. if (thrownError != '') showMessage(thrownError, 'MESSAGING_ERROR');
  1159. blockAjax = false;
  1160. });
  1161. }
  1162. function showMessage(message, severity, age=0) {
  1163. if (severity == 'MESSAGING_INFO') {
  1164. $('#message').css('background', '#6af');
  1165. } else if (severity == 'MESSAGING_WARNING') {
  1166. $('#message').css('background', '#ff0');
  1167. } else if (severity == 'MESSAGING_ERROR' ) {
  1168. $('#message').css('background', '#f00');
  1169. } else {
  1170. $('#message').css('background', '#f00');
  1171. }
  1172. $('#message').html(message);
  1173. return new Promise(function(resolve, reject) {
  1174. $("#content").fadeTo("slow", 0.3, function() {
  1175. $("#message").show(500).delay(5000).hide(500, function() {
  1176. $("#content").fadeTo("slow", 1.0, function() {
  1177. resolve(true);
  1178. });
  1179. });
  1180. });
  1181. });
  1182. }
  1183. function inRange(x, min, max) {
  1184. return ((x-min)*(x-max) <= 0);
  1185. }
  1186. function sleep(ms) {
  1187. return new Promise(resolve => setTimeout(resolve, ms));
  1188. }