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.

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