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.

1033 lines
31 KiB

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