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.

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