Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1012 lines
30 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var messages = [];
  5. var webhost;
  6. var numChanged = 0;
  7. var numReboot = 0;
  8. var numReconnect = 0;
  9. var numReload = 0;
  10. var useWhite = false;
  11. // -----------------------------------------------------------------------------
  12. // Messages
  13. // -----------------------------------------------------------------------------
  14. function initMessages() {
  15. messages[ 1] = "Remote update started";
  16. messages[ 2] = "OTA update started";
  17. messages[ 3] = "Error parsing data!";
  18. messages[ 4] = "The file does not look like a valid configuration backup or is corrupted";
  19. messages[ 5] = "Changes saved. You should reboot your board now";
  20. messages[ 7] = "Passwords do not match!";
  21. messages[ 8] = "Changes saved";
  22. messages[ 9] = "No changes detected";
  23. messages[10] = "Session expired, please reload page...";
  24. }
  25. function sensorType(type) {
  26. if (type == 1) return "Temperature";
  27. if (type == 2) return "Humidity";
  28. if (type == 11) return "Analog";
  29. if (type == 12) return "Events";
  30. return null;
  31. }
  32. // -----------------------------------------------------------------------------
  33. // Utils
  34. // -----------------------------------------------------------------------------
  35. // http://www.the-art-of-web.com/javascript/validate-password/
  36. function checkPassword(str) {
  37. // at least one lowercase and one uppercase letter or number
  38. // at least five characters (letters, numbers or special characters)
  39. var re = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{5,}$/;
  40. return re.test(str);
  41. }
  42. function zeroPad(number, positions) {
  43. return ("0".repeat(positions) + number).slice(-positions);
  44. }
  45. function validateForm(form) {
  46. // password
  47. var adminPass1 = $("input[name='adminPass1']", form).val();
  48. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  49. alert("The password you have entered is not valid, it must have at least 5 characters, 1 lowercase and 1 uppercase or number!");
  50. return false;
  51. }
  52. var adminPass2 = $("input[name='adminPass2']", form).val();
  53. if (adminPass1 != adminPass2) {
  54. alert("Passwords are different!");
  55. return false;
  56. }
  57. return true;
  58. }
  59. function valueSet(data, name, value) {
  60. for (var i in data) {
  61. if (data[i]['name'] == name) {
  62. data[i]['value'] = value;
  63. return;
  64. }
  65. }
  66. data.push({'name': name, 'value': value});
  67. }
  68. function randomString(length, chars) {
  69. var mask = '';
  70. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  71. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  72. if (chars.indexOf('#') > -1) mask += '0123456789';
  73. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  74. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  75. var result = '';
  76. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  77. return result;
  78. }
  79. function generateAPIKey() {
  80. var apikey = randomString(16, '@#');
  81. $("input[name=\"apiKey\"]").val(apikey);
  82. return false;
  83. }
  84. function getJson(str) {
  85. try {
  86. return JSON.parse(str);
  87. } catch (e) {
  88. return false;
  89. }
  90. }
  91. // -----------------------------------------------------------------------------
  92. // Actions
  93. // -----------------------------------------------------------------------------
  94. function doReload(milliseconds) {
  95. milliseconds = (typeof milliseconds == 'undefined') ? 0 : parseInt(milliseconds);
  96. setTimeout(function() {
  97. window.location.reload();
  98. }, milliseconds);
  99. }
  100. function doUpdate() {
  101. var form = $("#formSave");
  102. if (validateForm(form)) {
  103. // Get data
  104. var data = form.serializeArray();
  105. // Post-process
  106. delete(data['filename']);
  107. $("input[type='checkbox']").each(function() {
  108. var name = $(this).attr("name");
  109. if (name) {
  110. valueSet(data, name, $(this).is(':checked') ? 1 : 0);
  111. }
  112. });
  113. websock.send(JSON.stringify({'config': data}));
  114. $(".pwrExpected").val(0);
  115. $("input[name='pwrResetCalibration']")
  116. .prop("checked", false)
  117. .iphoneStyle("refresh");
  118. numChanged = 0;
  119. setTimeout(function() {
  120. if (numReboot > 0) {
  121. var response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  122. if (response == true) doReboot(false);
  123. } else if (numReconnect > 0) {
  124. var response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  125. if (response == true) doReconnect(false);
  126. } else if (numReload > 0) {
  127. var response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  128. if (response == true) doReload();
  129. }
  130. resetOriginals();
  131. }, 1000);
  132. }
  133. return false;
  134. }
  135. function doUpgrade() {
  136. var contents = $("input[name='upgrade']")[0].files[0];
  137. if (typeof contents == 'undefined') {
  138. alert("First you have to select a file from your computer.");
  139. return false;
  140. }
  141. var filename = $("input[name='upgrade']").val().split('\\').pop();
  142. var data = new FormData();
  143. data.append('upgrade', contents, filename);
  144. $.ajax({
  145. // Your server script to process the upload
  146. url: webhost + 'upgrade',
  147. type: 'POST',
  148. // Form data
  149. data: data,
  150. // Tell jQuery not to process data or worry about content-type
  151. // You *must* include these options!
  152. cache: false,
  153. contentType: false,
  154. processData: false,
  155. success: function(data, text) {
  156. $("#upgrade-progress").hide();
  157. if (data == 'OK') {
  158. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  159. doReload(5000);
  160. } else {
  161. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  162. }
  163. },
  164. // Custom XMLHttpRequest
  165. xhr: function() {
  166. $("#upgrade-progress").show();
  167. var myXhr = $.ajaxSettings.xhr();
  168. if (myXhr.upload) {
  169. // For handling the progress of the upload
  170. myXhr.upload.addEventListener('progress', function(e) {
  171. if (e.lengthComputable) {
  172. $('progress').attr({ value: e.loaded, max: e.total });
  173. }
  174. } , false);
  175. }
  176. return myXhr;
  177. },
  178. });
  179. return false;
  180. }
  181. function doUpdatePassword() {
  182. var form = $("#formPassword");
  183. if (validateForm(form)) {
  184. var data = form.serializeArray();
  185. websock.send(JSON.stringify({'config': data}));
  186. }
  187. return false;
  188. }
  189. function doReboot(ask) {
  190. ask = (typeof ask == 'undefined') ? true : ask;
  191. if (numChanged > 0) {
  192. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  193. if (response == true) return doUpdate();
  194. }
  195. if (ask) {
  196. var response = window.confirm("Are you sure you want to reboot the device?");
  197. if (response == false) return false;
  198. }
  199. websock.send(JSON.stringify({'action': 'reboot'}));
  200. doReload(5000);
  201. return false;
  202. }
  203. function doReconnect(ask) {
  204. ask = (typeof ask == 'undefined') ? true : ask;
  205. if (numChanged > 0) {
  206. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  207. if (response == true) return doUpdate();
  208. }
  209. if (ask) {
  210. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  211. if (response == false) return false;
  212. }
  213. websock.send(JSON.stringify({'action': 'reconnect'}));
  214. doReload(5000);
  215. return false;
  216. }
  217. function doBackup() {
  218. document.getElementById('downloader').src = webhost + 'config';
  219. return false;
  220. }
  221. function onFileUpload(event) {
  222. var inputFiles = this.files;
  223. if (inputFiles == undefined || inputFiles.length == 0) return false;
  224. var inputFile = inputFiles[0];
  225. this.value = "";
  226. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  227. if (response == false) return false;
  228. var reader = new FileReader();
  229. reader.onload = function(e) {
  230. var data = getJson(e.target.result);
  231. if (data) {
  232. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  233. } else {
  234. alert(messages[4]);
  235. }
  236. };
  237. reader.readAsText(inputFile);
  238. return false;
  239. }
  240. function doRestore() {
  241. if (typeof window.FileReader !== 'function') {
  242. alert("The file API isn't supported on this browser yet.");
  243. } else {
  244. $("#uploader").click();
  245. }
  246. return false;
  247. }
  248. function doToggle(element, value) {
  249. var relayID = parseInt(element.attr("data"));
  250. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  251. return false;
  252. }
  253. // -----------------------------------------------------------------------------
  254. // Visualization
  255. // -----------------------------------------------------------------------------
  256. function showPanel() {
  257. $(".panel").hide();
  258. $("#" + $(this).attr("data")).show();
  259. if ($("#layout").hasClass('active')) toggleMenu();
  260. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  261. };
  262. function toggleMenu() {
  263. $("#layout").toggleClass('active');
  264. $("#menu").toggleClass('active');
  265. $("#menuLink").toggleClass('active');
  266. }
  267. // -----------------------------------------------------------------------------
  268. // Domoticz
  269. // -----------------------------------------------------------------------------
  270. function createRelayIdxs(data) {
  271. var current = $("#domoticzRelays > div").length;
  272. if (current > 0) return;
  273. var template = $("#relayIdxTemplate .pure-g")[0];
  274. for (var i=0; i<data.length; i++) {
  275. var line = $(template).clone();
  276. if (data.length > 1) $("label", line).html("Switch #" + i);
  277. $("input", line).attr("name", "dczRelayIdx" + i).attr("tabindex", 40 + i).val(data[i]);
  278. line.appendTo("#domoticzRelays");
  279. }
  280. }
  281. function createSensorIdxs(data) {
  282. var current = $("#domoticzSensors > div").length;
  283. if (current > 0) return;
  284. var template = $("#sensorIdxTemplate .pure-g")[0];
  285. for (var i=0; i<data.length; i++) {
  286. var line = $(template).clone();
  287. $("label", line).html(sensorType(data[i].type));
  288. $("div.hint", line).html(data[i].name);
  289. $("input", line).attr("name", "dczSensor" + i).attr("tabindex", 40 + i).val(data[i].idx);
  290. line.appendTo("#domoticzSensors");
  291. }
  292. }
  293. // -----------------------------------------------------------------------------
  294. // Wifi
  295. // -----------------------------------------------------------------------------
  296. function addNetwork() {
  297. var numNetworks = $("#networks > div").length;
  298. if (numNetworks >= maxNetworks) {
  299. alert("Max number of networks reached");
  300. return;
  301. }
  302. var tabindex = 200 + numNetworks * 10;
  303. var template = $("#networkTemplate").children();
  304. var line = $(template).clone();
  305. $(line).find("input").each(function() {
  306. $(this).attr("tabindex", tabindex++);
  307. });
  308. $(line).find(".button-del-network").on('click', delNetwork);
  309. $(line).find(".button-more-network").on('click', moreNetwork);
  310. line.appendTo("#networks");
  311. return line;
  312. }
  313. function delNetwork() {
  314. var parent = $(this).parents(".pure-g");
  315. $(parent).remove();
  316. }
  317. function moreNetwork() {
  318. var parent = $(this).parents(".pure-g");
  319. $("div.more", parent).toggle();
  320. }
  321. // -----------------------------------------------------------------------------
  322. // Relays
  323. // -----------------------------------------------------------------------------
  324. function initRelays(data) {
  325. var current = $("#relays > div").length;
  326. if (current > 0) return;
  327. var template = $("#relayTemplate .pure-g")[0];
  328. for (var i=0; i<data.length; i++) {
  329. var line = $(template).clone();
  330. if (data.length > 1) $(".relay_id", line).html(" " + (i+1));
  331. $("input", line).attr("data", i).prop("checked", data[i]);
  332. line.appendTo("#relays");
  333. $(":checkbox", line).iphoneStyle({
  334. onChange: doToggle,
  335. resizeContainer: true,
  336. resizeHandle: true,
  337. checkedLabel: 'ON',
  338. uncheckedLabel: 'OFF'
  339. }).iphoneStyle("refresh");
  340. }
  341. }
  342. function addRelayGroup() {
  343. var numGroups = $("#relayGroups > div").length;
  344. var tabindex = 200 + numGroups * 2;
  345. var template = $("#relayGroupTemplate").children();
  346. var line = $(template).clone();
  347. var element = $("span.relay_id", line);
  348. if (element.length) element.html(numGroups+1);
  349. $(line).find("input").each(function() {
  350. $(this).attr("tabindex", tabindex++);
  351. });
  352. line.appendTo("#relayGroups");
  353. return line;
  354. }
  355. // -----------------------------------------------------------------------------
  356. // Sensors
  357. // -----------------------------------------------------------------------------
  358. function initSensors(data) {
  359. // check if already initialized
  360. var done = $("#sensors > div").length;
  361. if (done > 0) return;
  362. // add templates
  363. var template = $("#sensorTemplate").children();
  364. for (var i=0; i<data.length; i++) {
  365. var line = $(template).clone();
  366. $("label", line).html(sensorType(data[i].type));
  367. $("div.hint", line).html(data[i].description);
  368. $("input", line).attr("data", i);
  369. line.appendTo("#sensors");
  370. }
  371. }
  372. // -----------------------------------------------------------------------------
  373. // Lights
  374. // -----------------------------------------------------------------------------
  375. function initColorRGB() {
  376. // check if already initialized
  377. var done = $("#colors > div").length;
  378. if (done > 0) return;
  379. // add template
  380. var template = $("#colorRGBTemplate").children();
  381. var line = $(template).clone();
  382. line.appendTo("#colors");
  383. // init color wheel
  384. $('input[name="color"]').wheelColorPicker({
  385. sliders: 'wrgbp'
  386. }).on('sliderup', function() {
  387. var value = $(this).wheelColorPicker('getValue', 'css');
  388. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  389. });
  390. // init bright slider
  391. $('#brightness').on("change", function() {
  392. var value = $(this).val();
  393. var parent = $(this).parents(".pure-g");
  394. $("span", parent).html(value);
  395. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  396. });
  397. }
  398. function initColorHSV() {
  399. // check if already initialized
  400. var done = $("#colors > div").length;
  401. if (done > 0) return;
  402. // add template
  403. var template = $("#colorHSVTemplate").children();
  404. var line = $(template).clone();
  405. line.appendTo("#colors");
  406. // init color wheel
  407. $('input[name="color"]').wheelColorPicker({
  408. sliders: 'whsvp'
  409. }).on('sliderup', function() {
  410. var color = $(this).wheelColorPicker('getColor');
  411. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  412. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  413. });
  414. }
  415. function initChannels(num) {
  416. // check if already initialized
  417. var done = $("#channels > div").length > 0;
  418. if (done) return;
  419. // does it have color channels?
  420. var colors = $("#colors > div").length > 0;
  421. // calculate channels to create
  422. var max = num;
  423. if (colors) {
  424. max = num % 3;
  425. if ((max > 0) & useWhite) max--;
  426. }
  427. var start = num - max;
  428. // add templates
  429. var template = $("#channelTemplate").children();
  430. for (var i=0; i<max; i++) {
  431. var channel_id = start + i;
  432. var line = $(template).clone();
  433. $("span.slider", line).attr("data", channel_id);
  434. $("input.slider", line).attr("data", channel_id).on("change", function() {
  435. var id = $(this).attr("data");
  436. var value = $(this).val();
  437. var parent = $(this).parents(".pure-g");
  438. $("span", parent).html(value);
  439. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  440. });
  441. $("label", line).html("Channel " + (channel_id + 1));
  442. line.appendTo("#channels");
  443. }
  444. }
  445. // -----------------------------------------------------------------------------
  446. // RFBridge
  447. // -----------------------------------------------------------------------------
  448. function addRfbNode() {
  449. var numNodes = $("#rfbNodes > fieldset").length;
  450. var template = $("#rfbNodeTemplate").children();
  451. var line = $(template).clone();
  452. var status = true;
  453. $("span", line).html(numNodes+1);
  454. $(line).find("input").each(function() {
  455. $(this).attr("data-id", numNodes);
  456. $(this).attr("data-status", status ? 1 : 0);
  457. status = !status;
  458. });
  459. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  460. $(line).find(".button-rfb-forget").on('click', rfbForget);
  461. $(line).find(".button-rfb-send").on('click', rfbSend);
  462. line.appendTo("#rfbNodes");
  463. return line;
  464. }
  465. function rfbLearn() {
  466. var parent = $(this).parents(".pure-g");
  467. var input = $("input", parent);
  468. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  469. }
  470. function rfbForget() {
  471. var parent = $(this).parents(".pure-g");
  472. var input = $("input", parent);
  473. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  474. }
  475. function rfbSend() {
  476. var parent = $(this).parents(".pure-g");
  477. var input = $("input", parent);
  478. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  479. }
  480. // -----------------------------------------------------------------------------
  481. // Processing
  482. // -----------------------------------------------------------------------------
  483. function processData(data) {
  484. // title
  485. if ("app_name" in data) {
  486. var title = data.app_name;
  487. if ("app_version" in data) {
  488. title = title + " " + data.app_version;
  489. }
  490. $(".pure-menu-heading").html(title);
  491. if ("hostname" in data) {
  492. title = data.hostname + " - " + title;
  493. }
  494. document.title = title;
  495. }
  496. Object.keys(data).forEach(function(key) {
  497. // ---------------------------------------------------------------------
  498. // ---------------------------------------------------------------------
  499. // Web mode
  500. // ---------------------------------------------------------------------
  501. if (key == "webMode") {
  502. password = data.webMode == 1;
  503. $("#layout").toggle(data.webMode == 0);
  504. $("#password").toggle(data.webMode == 1);
  505. }
  506. // ---------------------------------------------------------------------
  507. // Actions
  508. // ---------------------------------------------------------------------
  509. if (key == "action") {
  510. if (data.action == "reload") doReload(1000);
  511. return;
  512. }
  513. // ---------------------------------------------------------------------
  514. // RFBridge
  515. // ---------------------------------------------------------------------
  516. if (key == "rfbCount") {
  517. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  518. return;
  519. }
  520. if (key == "rfb") {
  521. var nodes = data.rfb;
  522. for (var i in nodes) {
  523. var node = nodes[i];
  524. var element = $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]");
  525. if (element.length) element.val(node["data"]);
  526. }
  527. return;
  528. }
  529. // ---------------------------------------------------------------------
  530. // Lights
  531. // ---------------------------------------------------------------------
  532. if (key == "rgb") {
  533. initColorRGB();
  534. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  535. return;
  536. }
  537. if (key == "hsv") {
  538. initColorHSV();
  539. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  540. var chunks = data[key].split(",");
  541. var obj = {};
  542. obj.h = chunks[0] / 360;
  543. obj.s = chunks[1] / 100;
  544. obj.v = chunks[2] / 100;
  545. $("input[name='color']").wheelColorPicker('setColor', obj);
  546. return;
  547. }
  548. if (key == "brightness") {
  549. var slider = $("#brightness");
  550. if (slider.length) slider.val(data[key]);
  551. var span = $("span.brightness");
  552. if (span.length) span.html(data[key]);
  553. return;
  554. }
  555. if (key == "channels") {
  556. var len = data[key].length;
  557. initChannels(len);
  558. for (var i=0; i<len; i++) {
  559. var slider = $("input.slider[data=" + i + "]");
  560. if (slider.length) slider.val(data[key][i]);
  561. var span = $("span.slider[data=" + i + "]");
  562. if (span.length) span.html(data[key][i]);
  563. }
  564. return;
  565. }
  566. if (key == "useWhite") {
  567. useWhite = data[key];
  568. }
  569. // ---------------------------------------------------------------------
  570. // Sensors
  571. // ---------------------------------------------------------------------
  572. if (key == "sensors") {
  573. initSensors(data[key]);
  574. for (var i=0; i<data[key].length; i++) {
  575. var element = $("input[name=sensor][data=" + i + "]");
  576. if (element.length) element.val(data[key][i].value + data[key][i].units);
  577. }
  578. return;
  579. }
  580. // ---------------------------------------------------------------------
  581. // WiFi
  582. // ---------------------------------------------------------------------
  583. if (key == "maxNetworks") {
  584. maxNetworks = parseInt(data.maxNetworks);
  585. return;
  586. }
  587. if (key == "wifi") {
  588. var networks = data.wifi;
  589. for (var i in networks) {
  590. // add a new row
  591. var line = addNetwork();
  592. // fill in the blanks
  593. var wifi = data.wifi[i];
  594. Object.keys(wifi).forEach(function(key) {
  595. var element = $("input[name=" + key + "]", line);
  596. if (element.length) element.val(wifi[key]);
  597. });
  598. }
  599. return;
  600. }
  601. // ---------------------------------------------------------------------
  602. // Relays
  603. // ---------------------------------------------------------------------
  604. if (key == "relayStatus") {
  605. initRelays(data[key]);
  606. return;
  607. }
  608. // Relay groups
  609. if (key == "relayGroups") {
  610. var groups = data.relayGroups;
  611. for (var i in groups) {
  612. // add a new row
  613. var line = addRelayGroup();
  614. // fill in the blanks
  615. var group = data.relayGroups[i];
  616. Object.keys(group).forEach(function(key) {
  617. var element = $("input[name=" + key + "]", line);
  618. if (element.length) element.val(group[key]);
  619. });
  620. }
  621. return;
  622. }
  623. // ---------------------------------------------------------------------
  624. // Domoticz
  625. // ---------------------------------------------------------------------
  626. // Domoticz - Relays
  627. if (key == "dczRelayIdx") {
  628. createRelayIdxs(data[key]);
  629. return;
  630. }
  631. // Domoticz - Sensors
  632. if (key == "dczSensors") {
  633. createSensorIdxs(data[key]);
  634. return;
  635. }
  636. // ---------------------------------------------------------------------
  637. // General
  638. // ---------------------------------------------------------------------
  639. // Messages
  640. if (key == "message") {
  641. window.alert(messages[data.message]);
  642. return;
  643. }
  644. // Enable options
  645. if (key.endsWith("Visible")) {
  646. var module = key.slice(0,-7);
  647. $(".module-" + module).show();
  648. return;
  649. }
  650. // Pre-process
  651. if (key == "network") {
  652. data.network = data.network.toUpperCase();
  653. }
  654. if (key == "mqttStatus") {
  655. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  656. }
  657. if (key == "ntpStatus") {
  658. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  659. }
  660. if (key == "uptime") {
  661. var uptime = parseInt(data[key]);
  662. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  663. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  664. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  665. var days = uptime;
  666. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  667. }
  668. // ---------------------------------------------------------------------
  669. // Matching
  670. // ---------------------------------------------------------------------
  671. // Look for INPUTs
  672. var element = $("input[name=" + key + "]");
  673. if (element.length > 0) {
  674. if (element.attr('type') == 'checkbox') {
  675. element
  676. .prop("checked", data[key])
  677. .iphoneStyle("refresh");
  678. } else if (element.attr('type') == 'radio') {
  679. element.val([data[key]]);
  680. } else {
  681. var pre = element.attr("pre") || "";
  682. var post = element.attr("post") || "";
  683. element.val(pre + data[key] + post);
  684. }
  685. return;
  686. }
  687. // Look for SPANs
  688. var element = $("span[name=" + key + "]");
  689. if (element.length > 0) {
  690. var pre = element.attr("pre") || "";
  691. var post = element.attr("post") || "";
  692. element.html(pre + data[key] + post);
  693. return;
  694. }
  695. // Look for SELECTs
  696. var element = $("select[name=" + key + "]");
  697. if (element.length > 0) {
  698. element.val(data[key]);
  699. return;
  700. }
  701. });
  702. // Auto generate an APIKey if none defined yet
  703. if ($("input[name='apiKey']").val() == "") {
  704. generateAPIKey();
  705. }
  706. resetOriginals();
  707. }
  708. function hasChanged() {
  709. var newValue, originalValue;
  710. if ($(this).attr('type') == 'checkbox') {
  711. newValue = $(this).prop("checked")
  712. originalValue = $(this).attr("original") == "true";
  713. } else {
  714. newValue = $(this).val();
  715. originalValue = $(this).attr("original");
  716. }
  717. var hasChanged = $(this).attr("hasChanged") || 0;
  718. var action = $(this).attr("action");
  719. if (typeof originalValue == 'undefined') return;
  720. if (action == 'none') return;
  721. if (newValue != originalValue) {
  722. if (hasChanged == 0) {
  723. ++numChanged;
  724. if (action == "reconnect") ++numReconnect;
  725. if (action == "reboot") ++numReboot;
  726. if (action == "reload") ++numReload;
  727. $(this).attr("hasChanged", 1);
  728. }
  729. } else {
  730. if (hasChanged == 1) {
  731. --numChanged;
  732. if (action == "reconnect") --numReconnect;
  733. if (action == "reboot") --numReboot;
  734. if (action == "reload") --numReload;
  735. $(this).attr("hasChanged", 0);
  736. }
  737. }
  738. }
  739. function resetOriginals() {
  740. $("input").each(function() {
  741. $(this).attr("original", $(this).val());
  742. })
  743. $("select").each(function() {
  744. $(this).attr("original", $(this).val());
  745. })
  746. numReboot = numReconnect = numReload = 0;
  747. }
  748. // -----------------------------------------------------------------------------
  749. // Init & connect
  750. // -----------------------------------------------------------------------------
  751. function connect(host) {
  752. if (typeof host === 'undefined') {
  753. host = window.location.href.replace('#', '');
  754. } else {
  755. if (!host.startsWith("http")) {
  756. host = 'http://' + host + '/';
  757. }
  758. }
  759. if (!host.startsWith("http")) return;
  760. webhost = host;
  761. wshost = host.replace('http', 'ws') + 'ws';
  762. if (websock) websock.close();
  763. websock = new WebSocket(wshost);
  764. websock.onopen = function(evt) {
  765. console.log("Connected");
  766. };
  767. websock.onclose = function(evt) {
  768. console.log("Disconnected");
  769. };
  770. websock.onerror = function(evt) {
  771. console.log("Error: ", evt);
  772. };
  773. websock.onmessage = function(evt) {
  774. var data = getJson(evt.data);
  775. if (data) processData(data);
  776. };
  777. }
  778. function init() {
  779. initMessages();
  780. $("#menuLink").on('click', toggleMenu);
  781. $(".pure-menu-link").on('click', showPanel);
  782. $('progress').attr({ value: 0, max: 100 });
  783. $(".button-update").on('click', doUpdate);
  784. $(".button-update-password").on('click', doUpdatePassword);
  785. $(".button-reboot").on('click', doReboot);
  786. $(".button-reconnect").on('click', doReconnect);
  787. $(".button-settings-backup").on('click', doBackup);
  788. $(".button-settings-restore").on('click', doRestore);
  789. $('#uploader').on('change', onFileUpload);
  790. $(".button-upgrade").on('click', doUpgrade);
  791. $(".button-apikey").on('click', generateAPIKey);
  792. $(".button-upgrade-browse").on('click', function() {
  793. $("input[name='upgrade']")[0].click();
  794. return false;
  795. });
  796. $("input[name='upgrade']").change(function (){
  797. var fileName = $(this).val();
  798. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  799. });
  800. $(".button-add-network").on('click', function() {
  801. $("div.more", addNetwork()).toggle();
  802. });
  803. $(document).on('change', 'input', hasChanged);
  804. $(document).on('change', 'select', hasChanged);
  805. connect();
  806. }
  807. $(init);