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