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.

1045 lines
31 KiB

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