code.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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 releaseURL = 'https://api.github.com/repos/sle118/squeezelite-esp32/releases';
  27. var recovery = false;
  28. var enableAPTimer = true;
  29. var enableStatusTimer = true;
  30. var commandHeader = 'squeezelite -b 500:2000 -d all=info ';
  31. var pname, ver, otapct, otadsc;
  32. var blockAjax = false;
  33. var blockFlashButton = false;
  34. var lastMsg = '';
  35. var apList = null;
  36. var selectedSSID = "";
  37. var refreshAPInterval = null;
  38. var checkStatusInterval = null;
  39. var StatusIntervalActive = false;
  40. var RefreshAPIIntervalActive = false;
  41. var LastRecoveryState=null;
  42. var output = '';
  43. function stopCheckStatusInterval(){
  44. if(checkStatusInterval != null){
  45. clearTimeout(checkStatusInterval);
  46. checkStatusInterval = null;
  47. }
  48. StatusIntervalActive = false;
  49. }
  50. function stopRefreshAPInterval(){
  51. if(refreshAPInterval != null){
  52. clearTimeout(refreshAPInterval);
  53. refreshAPInterval = null;
  54. }
  55. RefreshAPIIntervalActive = false;
  56. }
  57. function startCheckStatusInterval(){
  58. StatusIntervalActive = true;
  59. checkStatusInterval = setTimeout(checkStatus, 3000);
  60. }
  61. function startRefreshAPInterval(){
  62. RefreshAPIIntervalActive = true;
  63. refreshAPInterval = setTimeout(refreshAP(false), 4500); // leave enough time for the initial scan
  64. }
  65. function RepeatCheckStatusInterval(){
  66. if(StatusIntervalActive)
  67. startCheckStatusInterval();
  68. }
  69. function RepeatRefreshAPInterval(){
  70. if(RefreshAPIIntervalActive)
  71. startRefreshAPInterval();
  72. }
  73. $(document).ready(function(){
  74. $("#wifi-status").on("click", ".ape", function() {
  75. $( "#wifi" ).slideUp( "fast", function() {});
  76. $( "#connect-details" ).slideDown( "fast", function() {});
  77. });
  78. $("#manual_add").on("click", ".ape", function() {
  79. selectedSSID = $(this).text();
  80. $( "#ssid-pwd" ).text(selectedSSID);
  81. $( "#wifi" ).slideUp( "fast", function() {});
  82. $( "#connect_manual" ).slideDown( "fast", function() {});
  83. $( "#connect" ).slideUp( "fast", function() {});
  84. //update wait screen
  85. $( "#loading" ).show();
  86. $( "#connect-success" ).hide();
  87. $( "#connect-fail" ).hide();
  88. });
  89. $("#wifi-list").on("click", ".ape", function() {
  90. selectedSSID = $(this).text();
  91. $( "#ssid-pwd" ).text(selectedSSID);
  92. $( "#wifi" ).slideUp( "fast", function() {});
  93. $( "#connect_manual" ).slideUp( "fast", function() {});
  94. $( "#connect" ).slideDown( "fast", function() {});
  95. //update wait screen
  96. $( "#loading" ).show();
  97. $( "#connect-success" ).hide();
  98. $( "#connect-fail" ).hide();
  99. });
  100. $("#cancel").on("click", function() {
  101. selectedSSID = "";
  102. $( "#connect" ).slideUp( "fast", function() {});
  103. $( "#connect_manual" ).slideUp( "fast", function() {});
  104. $( "#wifi" ).slideDown( "fast", function() {});
  105. });
  106. $("#manual_cancel").on("click", function() {
  107. selectedSSID = "";
  108. $( "#connect" ).slideUp( "fast", function() {});
  109. $( "#connect_manual" ).slideUp( "fast", function() {});
  110. $( "#wifi" ).slideDown( "fast", function() {});
  111. });
  112. $("#join").on("click", function() {
  113. performConnect();
  114. });
  115. $("#manual_join").on("click", function() {
  116. performConnect($(this).data('connect'));
  117. });
  118. $("#ok-details").on("click", function() {
  119. $( "#connect-details" ).slideUp( "fast", function() {});
  120. $( "#wifi" ).slideDown( "fast", function() {});
  121. });
  122. $("#ok-credits").on("click", function() {
  123. $( "#credits" ).slideUp( "fast", function() {});
  124. $( "#app" ).slideDown( "fast", function() {});
  125. });
  126. $("#acredits").on("click", function(event) {
  127. event.preventDefault();
  128. $( "#app" ).slideUp( "fast", function() {});
  129. $( "#credits" ).slideDown( "fast", function() {});
  130. });
  131. $("#ok-connect").on("click", function() {
  132. $( "#connect-wait" ).slideUp( "fast", function() {});
  133. $( "#wifi" ).slideDown( "fast", function() {});
  134. });
  135. $("#disconnect").on("click", function() {
  136. $( "#connect-details-wrap" ).addClass('blur');
  137. $( "#diag-disconnect" ).slideDown( "fast", function() {});
  138. });
  139. $("#no-disconnect").on("click", function() {
  140. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  141. $( "#connect-details-wrap" ).removeClass('blur');
  142. });
  143. $("#yes-disconnect").on("click", function() {
  144. stopCheckStatusInterval();
  145. selectedSSID = "";
  146. $( "#diag-disconnect" ).slideUp( "fast", function() {});
  147. $( "#connect-details-wrap" ).removeClass('blur');
  148. $.ajax({
  149. url: '/connect.json',
  150. dataType: 'text',
  151. method: 'DELETE',
  152. cache: false,
  153. contentType: 'application/json; charset=utf-8',
  154. data: JSON.stringify({ 'timestamp': Date.now()})
  155. });
  156. startCheckStatusInterval();
  157. $( "#connect-details" ).slideUp( "fast", function() {});
  158. $( "#wifi" ).slideDown( "fast", function() {})
  159. });
  160. $("input#show-nvs").on("click", function() {
  161. this.checked=this.checked?1:0;
  162. if(this.checked){
  163. $('a[href^="#tab-nvs"]').show();
  164. } else {
  165. $('a[href^="#tab-nvs"]').hide();
  166. }
  167. });
  168. $("input#autoexec-cb").on("click", function() {
  169. var data = { 'timestamp': Date.now() };
  170. autoexec = (this.checked)?1:0;
  171. data['config'] = {};
  172. data['config'] = {
  173. autoexec : {
  174. value : autoexec,
  175. type : 33
  176. }
  177. }
  178. showMessage('please wait for the ESP32 to reboot', 'WARNING');
  179. $.ajax({
  180. url: '/config.json',
  181. dataType: 'text',
  182. method: 'POST',
  183. cache: false,
  184. // headers: { "X-Custom-autoexec": autoexec },
  185. contentType: 'application/json; charset=utf-8',
  186. data: JSON.stringify(data),
  187. error: function (xhr, ajaxOptions, thrownError) {
  188. console.log(xhr.status);
  189. console.log(thrownError);
  190. if (thrownError != '') showMessage(thrownError, 'ERROR');
  191. },
  192. complete: function(response) {
  193. //var returnedResponse = JSON.parse(response.responseText);
  194. console.log(response.responseText);
  195. console.log('sent config JSON with headers:', autoexec);
  196. console.log('now triggering reboot');
  197. $.ajax({
  198. url: '/reboot_ota.json',
  199. dataType: 'text',
  200. method: 'POST',
  201. cache: false,
  202. contentType: 'application/json; charset=utf-8',
  203. data: JSON.stringify({ 'timestamp': Date.now()}),
  204. error: function (xhr, ajaxOptions, thrownError) {
  205. console.log(xhr.status);
  206. console.log(thrownError);
  207. if (thrownError != '') showMessage(thrownError, 'ERROR');
  208. },
  209. complete: function(response) {
  210. console.log('reboot call completed');
  211. }
  212. });
  213. }
  214. });
  215. });
  216. $("input#save-autoexec1").on("click", function() {
  217. var data = { 'timestamp': Date.now() };
  218. autoexec1 = $("#autoexec1").val();
  219. data['config'] = {};
  220. data['config'] = {
  221. autoexec1 : {
  222. value : autoexec1,
  223. type : 33
  224. }
  225. }
  226. $.ajax({
  227. url: '/config.json',
  228. dataType: 'text',
  229. method: 'POST',
  230. cache: false,
  231. // headers: { "X-Custom-autoexec1": autoexec1 },
  232. contentType: 'application/json; charset=utf-8',
  233. data: JSON.stringify(data),
  234. error: function (xhr, ajaxOptions, thrownError) {
  235. console.log(xhr.status);
  236. console.log(thrownError);
  237. if (thrownError != '') showMessage(thrownError, 'ERROR');
  238. }
  239. });
  240. console.log('sent config JSON with headers:', autoexec1);
  241. console.log('sent data:', JSON.stringify(data));
  242. });
  243. $("input#save-gpio").on("click", function() {
  244. var data = { 'timestamp': Date.now() };
  245. var config = {};
  246. var headers = {};
  247. $("input.gpio").each(function() {
  248. var id = $(this)[0].id;
  249. var pin = $(this).val();
  250. if (pin != '') {
  251. config[id] = {};
  252. config[id].value = pin;
  253. config[id].type = nvs_type_t.NVS_TYPE_STR;
  254. }
  255. });
  256. data['config'] = config;
  257. $.ajax({
  258. url: '/config.json',
  259. dataType: 'text',
  260. method: 'POST',
  261. cache: false,
  262. headers: headers,
  263. contentType: 'application/json; charset=utf-8',
  264. data: JSON.stringify(data),
  265. error: function (xhr, ajaxOptions, thrownError) {
  266. console.log(xhr.status);
  267. console.log(thrownError);
  268. if (thrownError != '') showMessage(thrownError, 'ERROR');
  269. }
  270. });
  271. console.log('sent config JSON with headers:', JSON.stringify(headers));
  272. console.log('sent config JSON with data:', JSON.stringify(data));
  273. });
  274. $("#save-nvs").on("click", function() {
  275. var headers = {};
  276. var data = { 'timestamp': Date.now() };
  277. var config = {};
  278. $("input.nvs").each(function() {
  279. var key = $(this)[0].id;
  280. var val = $(this).val();
  281. var nvs_type = parseInt($(this)[0].attributes.nvs_type.nodeValue,10);
  282. if (key != '') {
  283. config[key] = {};
  284. if(nvs_type == nvs_type_t.NVS_TYPE_U8
  285. || nvs_type == nvs_type_t.NVS_TYPE_I8
  286. || nvs_type == nvs_type_t.NVS_TYPE_U16
  287. || nvs_type == nvs_type_t.NVS_TYPE_I16
  288. || nvs_type == nvs_type_t.NVS_TYPE_U32
  289. || nvs_type == nvs_type_t.NVS_TYPE_I32
  290. || nvs_type == nvs_type_t.NVS_TYPE_U64
  291. || nvs_type == nvs_type_t.NVS_TYPE_I64) {
  292. config[key].value = parseInt(val);
  293. }
  294. else {
  295. config[key].value = val;
  296. }
  297. config[key].type = nvs_type;
  298. }
  299. });
  300. var key = $("#nvs-new-key").val();
  301. var val = $("#nvs-new-value").val();
  302. if (key != '') {
  303. // headers["X-Custom-" +key] = val;
  304. config[key] = {};
  305. config[key].value = val;
  306. config[key].type = 33;
  307. }
  308. data['config'] = config;
  309. $.ajax({
  310. url: '/config.json',
  311. dataType: 'text',
  312. method: 'POST',
  313. cache: false,
  314. headers: headers,
  315. contentType: 'application/json; charset=utf-8',
  316. data : JSON.stringify(data),
  317. error: function (xhr, ajaxOptions, thrownError) {
  318. console.log(xhr.status);
  319. console.log(thrownError);
  320. if (thrownError != '') showMessage(thrownError, 'ERROR');
  321. }
  322. });
  323. console.log('sent config JSON with headers:', JSON.stringify(headers));
  324. console.log('sent config JSON with data:', JSON.stringify(data));
  325. });
  326. $("#flash").on("click", function() {
  327. var data = { 'timestamp': Date.now() };
  328. if (blockFlashButton) return;
  329. blockFlashButton = true;
  330. var url = $("#fwurl").val();
  331. data['config'] = {
  332. fwurl : {
  333. value : url,
  334. type : 33
  335. }
  336. };
  337. $.ajax({
  338. url: '/config.json',
  339. dataType: 'text',
  340. method: 'POST',
  341. cache: false,
  342. contentType: 'application/json; charset=utf-8',
  343. data: JSON.stringify(data),
  344. error: function (xhr, ajaxOptions, thrownError) {
  345. console.log(xhr.status);
  346. console.log(thrownError);
  347. if (thrownError != '') showMessage(thrownError, 'ERROR');
  348. }
  349. });
  350. enableStatusTimer = true;
  351. });
  352. $("#generate-command").on("click", function() {
  353. var commandLine = commandHeader + '-n "' + $("#player").val() + '"';
  354. if (output == 'bt') {
  355. commandLine += ' -o "BT -n \'' + $("#btsink").val() + '\'" -R -Z 192000';
  356. } else if (output == 'spdif') {
  357. commandLine += ' -o SPDIF -R -Z 192000';
  358. } else {
  359. commandLine += ' -o I2S';
  360. }
  361. if ($("#optional").val() != '') {
  362. commandLine += ' ' + $("#optional").val();
  363. }
  364. $("#autoexec1").val(commandLine);
  365. });
  366. $('[name=audio]').on("click", function(){
  367. if (this.id == 'bt') {
  368. $("#btsinkdiv").show(200);
  369. output = 'bt';
  370. } else if (this.id == 'spdif') {
  371. $("#btsinkdiv").hide(200);
  372. output = 'spdif';
  373. } else {
  374. $("#btsinkdiv").hide(200);
  375. output = 'i2s';
  376. }
  377. });
  378. $('#fwcheck').on("click", function(){
  379. $("#releaseTable").html("");
  380. $.getJSON(releaseURL, function(data) {
  381. var i=0;
  382. data.forEach(function(release) {
  383. var url = '';
  384. release.assets.forEach(function(asset) {
  385. if (asset.name.match(/\.bin$/)) {
  386. url = asset.browser_download_url;
  387. }
  388. });
  389. var [ver, idf, cfg, branch] = release.name.split('#');
  390. var body = release.body;
  391. body = body.replace(/\'/ig, "\"");
  392. body = body.replace(/[\s\S]+(### Revision Log[\s\S]+)### ESP-IDF Version Used[\s\S]+/, "$1");
  393. body = body.replace(/- \(.+?\) /g, "- ");
  394. var [date, time] = release.created_at.split('T');
  395. var trclass = (i++ > 6)?' hide':'';
  396. $("#releaseTable").append(
  397. "<tr class='release"+trclass+"'>"+
  398. "<td data-toggle='tooltip' title='"+body+"'>"+ver+"</td>"+
  399. "<td>"+date+"</td>"+
  400. "<td>"+cfg+"</td>"+
  401. "<td>"+idf+"</td>"+
  402. "<td>"+branch+"</td>"+
  403. "<td><input id='generate-command' type='button' class='btn btn-success' value='Select' data-url='"+url+"' onclick='setURL(this);' /></td>"+
  404. "</tr>"
  405. );
  406. });
  407. if (i > 7) {
  408. $("#releaseTable").append(
  409. "<tr id='showall'>"+
  410. "<td colspan='6'>"+
  411. "<input type='button' id='showallbutton' class='btn btn-info' value='Show older releases' />"+
  412. "</td>"+
  413. "</tr>"
  414. );
  415. $('#showallbutton').on("click", function(){
  416. $("tr.hide").removeClass("hide");
  417. $("tr#showall").addClass("hide");
  418. });
  419. }
  420. $("#searchfw").css("display", "inline");
  421. })
  422. .fail(function() {
  423. alert("failed to fetch release history!");
  424. });
  425. });
  426. $('input#searchinput').on("input", function(){
  427. var s = $('input#searchinput').val();
  428. var re = new RegExp(s, "gi");
  429. if (s.length == 0) {
  430. $("tr.release").removeClass("hide");
  431. } else if (s.length < 3) {
  432. $("tr.release").addClass("hide");
  433. } else {
  434. $("tr.release").addClass("hide");
  435. $("tr.release").each(function(tr){
  436. $(this).find('td').each (function() {
  437. if ($(this).html().match(re)) {
  438. $(this).parent().removeClass('hide');
  439. }
  440. });
  441. });
  442. }
  443. });
  444. $('#boot-button').on("click", function(){
  445. enableStatusTimer = true;
  446. });
  447. $('#reboot-button').on("click", function(){
  448. enableStatusTimer = true;
  449. });
  450. $('#updateAP').on("click", function(){
  451. refreshAP(true);
  452. console.log("refresh AP");
  453. });
  454. //first time the page loads: attempt to get the connection status and start the wifi scan
  455. refreshAP(false);
  456. getConfig();
  457. //start timers
  458. startCheckStatusInterval();
  459. //startRefreshAPInterval();
  460. $('[data-toggle="tooltip"]').tooltip({
  461. html: true,
  462. placement : 'right',
  463. });
  464. });
  465. function setURL(button) {
  466. var url = button.dataset.url;
  467. $("#fwurl").val(url);
  468. $('[data-url^="http"]').addClass("btn-success").removeClass("btn-danger");
  469. $('[data-url="'+url+'"]').addClass("btn-danger").removeClass("btn-success");
  470. }
  471. function performConnect(conntype){
  472. //stop the status refresh. This prevents a race condition where a status
  473. //request would be refreshed with wrong ip info from a previous connection
  474. //and the request would automatically shows as succesful.
  475. stopCheckStatusInterval();
  476. //stop refreshing wifi list
  477. stopRefreshAPInterval();
  478. var pwd;
  479. var dhcpname;
  480. if (conntype == 'manual') {
  481. //Grab the manual SSID and PWD
  482. selectedSSID=$('#manual_ssid').val();
  483. pwd = $("#manual_pwd").val();
  484. dhcpname= $("#dhcp-name2").val();;
  485. }else{
  486. pwd = $("#pwd").val();
  487. dhcpname= $("#dhcp-name1").val();;
  488. }
  489. //reset connection
  490. $( "#loading" ).show();
  491. $( "#connect-success" ).hide();
  492. $( "#connect-fail" ).hide();
  493. $( "#ok-connect" ).prop("disabled",true);
  494. $( "#ssid-wait" ).text(selectedSSID);
  495. $( "#connect" ).slideUp( "fast", function() {});
  496. $( "#connect_manual" ).slideUp( "fast", function() {});
  497. $( "#connect-wait" ).slideDown( "fast", function() {});
  498. $.ajax({
  499. url: '/connect.json',
  500. dataType: 'text',
  501. method: 'POST',
  502. cache: false,
  503. // headers: { 'X-Custom-ssid': selectedSSID, 'X-Custom-pwd': pwd, 'X-Custom-host_name': dhcpname },
  504. contentType: 'application/json; charset=utf-8',
  505. data: JSON.stringify({ 'timestamp': Date.now(),
  506. 'ssid' : selectedSSID,
  507. 'pwd' : pwd,
  508. 'host_name' : dhcpname
  509. }),
  510. error: function (xhr, ajaxOptions, thrownError) {
  511. console.log(xhr.status);
  512. console.log(thrownError);
  513. if (thrownError != '') showMessage(thrownError, 'ERROR');
  514. }
  515. });
  516. //now we can re-set the intervals regardless of result
  517. startCheckStatusInterval();
  518. startRefreshAPInterval();
  519. }
  520. function rssiToIcon(rssi){
  521. if(rssi >= -60){
  522. return 'w0';
  523. }
  524. else if(rssi >= -67){
  525. return 'w1';
  526. }
  527. else if(rssi >= -75){
  528. return 'w2';
  529. }
  530. else{
  531. return 'w3';
  532. }
  533. }
  534. function refreshAP(force){
  535. if (!enableAPTimer && !force) return;
  536. $.getJSON( "/ap.json", function( data ) {
  537. if(data.length > 0){
  538. //sort by signal strength
  539. data.sort(function (a, b) {
  540. var x = a["rssi"]; var y = b["rssi"];
  541. return ((x < y) ? 1 : ((x > y) ? -1 : 0));
  542. });
  543. apList = data;
  544. refreshAPHTML(apList);
  545. }
  546. });
  547. }
  548. function refreshAPHTML(data){
  549. var h = "";
  550. data.forEach(function(e, idx, array) {
  551. 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);
  552. h += "\n";
  553. });
  554. $( "#wifi-list" ).html(h)
  555. }
  556. function checkStatus(){
  557. RepeatCheckStatusInterval();
  558. if (!enableStatusTimer) return;
  559. if (blockAjax) return;
  560. blockAjax = true;
  561. $.getJSON( "/status.json", function( data ) {
  562. if (data.hasOwnProperty('ssid') && data['ssid'] != ""){
  563. if (data["ssid"] === selectedSSID){
  564. //that's a connection attempt
  565. if (data["urc"] === 0){
  566. //got connection
  567. $("#connected-to span").text(data["ssid"]);
  568. $("#connect-details h1").text(data["ssid"]);
  569. $("#ip").text(data["ip"]);
  570. $("#netmask").text(data["netmask"]);
  571. $("#gw").text(data["gw"]);
  572. $("#wifi-status").slideDown( "fast", function() {});
  573. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  574. //unlock the wait screen if needed
  575. $( "#ok-connect" ).prop("disabled",false);
  576. //update wait screen
  577. $( "#loading" ).hide();
  578. $( "#connect-success" ).text("Your IP address now is: " + data["ip"] );
  579. $( "#connect-success" ).show();
  580. $( "#connect-fail" ).hide();
  581. enableAPTimer = false;
  582. if (!recovery) enableStatusTimer = false;
  583. }
  584. else if (data["urc"] === 1){
  585. //failed attempt
  586. $("#connected-to span").text('');
  587. $("#connect-details h1").text('');
  588. $("#ip").text('0.0.0.0');
  589. $("#netmask").text('0.0.0.0');
  590. $("#gw").text('0.0.0.0');
  591. $("span#foot-wifi").html("");
  592. //don't show any connection
  593. $("#wifi-status").slideUp( "fast", function() {});
  594. //unlock the wait screen
  595. $( "#ok-connect" ).prop("disabled",false);
  596. //update wait screen
  597. $( "#loading" ).hide();
  598. $( "#connect-fail" ).show();
  599. $( "#connect-success" ).hide();
  600. enableAPTimer = true;
  601. enableStatusTimer = true;
  602. }
  603. }
  604. else if (data.hasOwnProperty('urc') && data['urc'] === 0){
  605. //ESP32 is already connected to a wifi without having the user do anything
  606. if( !($("#wifi-status").is(":visible")) ){
  607. $("#connected-to span").text(data["ssid"]);
  608. $("#connect-details h1").text(data["ssid"]);
  609. $("#ip").text(data["ip"]);
  610. $("#netmask").text(data["netmask"]);
  611. $("#gw").text(data["gw"]);
  612. $("#wifi-status").slideDown( "fast", function() {});
  613. $("span#foot-wifi").html(", SSID: <strong>"+data["ssid"]+"</strong>, IP: <strong>"+data["ip"]+"</strong>");
  614. }
  615. enableAPTimer = false;
  616. if (!recovery) enableStatusTimer = false;
  617. }
  618. }
  619. else if (data.hasOwnProperty('urc') && data['urc'] === 2){
  620. //that's a manual disconnect
  621. if($("#wifi-status").is(":visible")){
  622. $("#wifi-status").slideUp( "fast", function() {});
  623. $("span#foot-wifi").html("");
  624. }
  625. enableAPTimer = true;
  626. enableStatusTimer = true;
  627. }
  628. if (data.hasOwnProperty('recovery')) {
  629. if(LastRecoveryState != data["recovery"]){
  630. LastRecoveryState = data["recovery"];
  631. $("input#show-nvs")[0].checked=LastRecoveryState==1?true:false;
  632. }
  633. if($("input#show-nvs")[0].checked){
  634. $('a[href^="#tab-nvs"]').show();
  635. } else{
  636. $('a[href^="#tab-nvs"]').hide();
  637. }
  638. if (data["recovery"] === 1) {
  639. recovery = true;
  640. $("#otadiv").show();
  641. $('a[href^="#tab-audio"]').hide();
  642. $('a[href^="#tab-gpio"]').show();
  643. $("footer.footer").removeClass('sl');
  644. $("footer.footer").addClass('recovery');
  645. $("#boot-button").html('Reboot');
  646. $("#boot-form").attr('action', '/reboot_ota.json');
  647. enableStatusTimer = true;
  648. } else {
  649. recovery = false;
  650. $("#otadiv").hide();
  651. $('a[href^="#tab-audio"]').show();
  652. $('a[href^="#tab-gpio"]').hide();
  653. $("footer.footer").removeClass('recovery');
  654. $("footer.footer").addClass('sl');
  655. $("#boot-button").html('Recovery');
  656. $("#boot-form").attr('action', '/recovery.json');
  657. enableStatusTimer = false;
  658. }
  659. }
  660. if (data.hasOwnProperty('project_name') && data['project_name'] != ''){
  661. pname = data['project_name'];
  662. }
  663. if (data.hasOwnProperty('version') && data['version'] != ''){
  664. ver = data['version'];
  665. $("span#foot-fw").html("fw: <strong>"+ver+"</strong>, mode: <strong>"+pname+"</strong>");
  666. }
  667. if (data.hasOwnProperty('ota_pct') && data['ota_pct'] != 0){
  668. otapct = data['ota_pct'];
  669. $('.progress-bar').css('width', otapct+'%').attr('aria-valuenow', otapct);
  670. $('.progress-bar').html(otapct+'%');
  671. }
  672. if (data.hasOwnProperty('ota_dsc') && data['ota_dsc'] != ''){
  673. otadsc = data['ota_dsc'];
  674. $("span#flash-status").html(otadsc);
  675. if (otadsc.match(/Error:/) || otapct > 95) {
  676. blockFlashButton = false;
  677. enableStatusTimer = true;
  678. }
  679. } else {
  680. $("span#flash-status").html('');
  681. }
  682. if (data.hasOwnProperty('message') && data['message'] != ''){
  683. var msg = data['message'].text;
  684. var severity = data['message'].severity;
  685. if (msg != lastMsg) {
  686. showMessage(msg, severity);
  687. lastMsg = msg;
  688. }
  689. }
  690. blockAjax = false;
  691. })
  692. .fail(function(xhr, ajaxOptions, thrownError) {
  693. console.log(xhr.status);
  694. console.log(thrownError);
  695. if (thrownError != '') showMessage(thrownError, 'ERROR');
  696. blockAjax = false;
  697. });
  698. }
  699. function getConfig() {
  700. $.getJSON("/config.json", function(data) {
  701. Object.keys(data).sort().forEach(function(key, i) {
  702. if (data.hasOwnProperty(key)) {
  703. if (key == 'autoexec') {
  704. if (data["autoexec"].value === "1") {
  705. $("#autoexec-cb")[0].checked=true;
  706. } else {
  707. $("#autoexec-cb")[0].checked=false;
  708. }
  709. } else if (key == 'autoexec1') {
  710. $("textarea#autoexec1").val(data[key].value);
  711. } else if (key == 'host_name') {
  712. $("input#dhcp-name1").val(data[key].value);
  713. $("input#dhcp-name2").val(data[key].value);
  714. }
  715. $("tbody#nvsTable").append(
  716. "<tr>"+
  717. "<td>"+key+"</td>"+
  718. "<td class='value'>"+
  719. "<input type='text' class='form-control nvs' id='"+key+"' nvs_type="+data[key].type+" >"+
  720. "</td>"+
  721. "</tr>"
  722. );
  723. $("input#"+key).val(data[key].value);
  724. }
  725. });
  726. $("tbody#nvsTable").append(
  727. "<tr>"+
  728. "<td>"+
  729. "<input type='text' class='form-control' id='nvs-new-key' placeholder='new key'>"+
  730. "</td>"+
  731. "<td>"+
  732. "<input type='text' class='form-control' id='nvs-new-value' placeholder='new value' nvs_type=33 >"+ // todo: provide a way to choose field type
  733. "</td>"+
  734. "</tr>"
  735. );
  736. })
  737. .fail(function(xhr, ajaxOptions, thrownError) {
  738. console.log(xhr.status);
  739. console.log(thrownError);
  740. if (thrownError != '') showMessage(thrownError, 'ERROR');
  741. blockAjax = false;
  742. });
  743. }
  744. function showMessage(message, severity) {
  745. if (severity == 'INFO') {
  746. $('#message').css('background', '#6af');
  747. } else if (severity == 'WARNING') {
  748. $('#message').css('background', '#ff0');
  749. } else {
  750. $('#message').css('background', '#f00');
  751. }
  752. $('#message').html(message);
  753. $("#content").fadeTo("slow", 0.3, function() {
  754. $("#message").show(500).delay(5000).hide(500, function() {
  755. $("#content").fadeTo("slow", 1.0);
  756. });
  757. });
  758. }