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.

1024 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. // -----------------------------------------------------------------------------
  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 sensorType(type) {
  26. if (type == 1) return "Temperature";
  27. if (type == 2) return "Humidity";
  28. if (type == 3) return "Pressure";
  29. if (type == 4) return "Current";
  30. if (type == 5) return "Voltage";
  31. if (type == 6) return "Active Power";
  32. if (type == 7) return "Apparent Power";
  33. if (type == 8) return "Reactive Power";
  34. if (type == 9) return "Energy";
  35. if (type == 10) return "Energy (delta)";
  36. if (type == 11) return "Power Factor";
  37. if (type == 12) return "Analog";
  38. if (type == 13) return "Events";
  39. if (type == 14) return "PM1.0"
  40. if (type == 15) return "PM2.5"
  41. if (type == 16) return "PM10"
  42. return null;
  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 createSensorIdxs(data) {
  294. var current = $("#domoticzSensors > div").length;
  295. if (current > 0) return;
  296. var template = $("#sensorIdxTemplate .pure-g")[0];
  297. for (var i=0; i<data.length; i++) {
  298. var line = $(template).clone();
  299. $("label", line).html(sensorType(data[i].type));
  300. $("div.hint", line).html(data[i].name);
  301. $("input", line).attr("name", "dczSensor" + i).attr("tabindex", 40 + i).val(data[i].idx);
  302. line.appendTo("#domoticzSensors");
  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
  369. // -----------------------------------------------------------------------------
  370. function initSensors(data) {
  371. // check if already initialized
  372. var done = $("#sensors > div").length;
  373. if (done > 0) return;
  374. // add templates
  375. var template = $("#sensorTemplate").children();
  376. for (var i=0; i<data.length; i++) {
  377. var line = $(template).clone();
  378. $("label", line).html(sensorType(data[i].type));
  379. $("div.hint", line).html(data[i].description);
  380. $("input", line).attr("data", i);
  381. line.appendTo("#sensors");
  382. }
  383. }
  384. // -----------------------------------------------------------------------------
  385. // Lights
  386. // -----------------------------------------------------------------------------
  387. function initColorRGB() {
  388. // check if already initialized
  389. var done = $("#colors > div").length;
  390. if (done > 0) return;
  391. // add template
  392. var template = $("#colorRGBTemplate").children();
  393. var line = $(template).clone();
  394. line.appendTo("#colors");
  395. // init color wheel
  396. $('input[name="color"]').wheelColorPicker({
  397. sliders: 'wrgbp'
  398. }).on('sliderup', function() {
  399. var value = $(this).wheelColorPicker('getValue', 'css');
  400. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  401. });
  402. // init bright slider
  403. $('#brightness').on("change", function() {
  404. var value = $(this).val();
  405. var parent = $(this).parents(".pure-g");
  406. $("span", parent).html(value);
  407. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  408. });
  409. }
  410. function initColorHSV() {
  411. // check if already initialized
  412. var done = $("#colors > div").length;
  413. if (done > 0) return;
  414. // add template
  415. var template = $("#colorHSVTemplate").children();
  416. var line = $(template).clone();
  417. line.appendTo("#colors");
  418. // init color wheel
  419. $('input[name="color"]').wheelColorPicker({
  420. sliders: 'whsvp'
  421. }).on('sliderup', function() {
  422. var color = $(this).wheelColorPicker('getColor');
  423. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  424. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  425. });
  426. }
  427. function initChannels(num) {
  428. // check if already initialized
  429. var done = $("#channels > div").length > 0;
  430. if (done) return;
  431. // does it have color channels?
  432. var colors = $("#colors > div").length > 0;
  433. // calculate channels to create
  434. var max = num;
  435. if (colors) {
  436. max = num % 3;
  437. if ((max > 0) & useWhite) max--;
  438. }
  439. var start = num - max;
  440. // add templates
  441. var template = $("#channelTemplate").children();
  442. for (var i=0; i<max; i++) {
  443. var channel_id = start + i;
  444. var line = $(template).clone();
  445. $("span.slider", line).attr("data", channel_id);
  446. $("input.slider", line).attr("data", channel_id).on("change", function() {
  447. var id = $(this).attr("data");
  448. var value = $(this).val();
  449. var parent = $(this).parents(".pure-g");
  450. $("span", parent).html(value);
  451. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  452. });
  453. $("label", line).html("Channel " + (channel_id + 1));
  454. line.appendTo("#channels");
  455. }
  456. }
  457. // -----------------------------------------------------------------------------
  458. // RFBridge
  459. // -----------------------------------------------------------------------------
  460. function addRfbNode() {
  461. var numNodes = $("#rfbNodes > fieldset").length;
  462. var template = $("#rfbNodeTemplate").children();
  463. var line = $(template).clone();
  464. var status = true;
  465. $("span", line).html(numNodes+1);
  466. $(line).find("input").each(function() {
  467. $(this).attr("data-id", numNodes);
  468. $(this).attr("data-status", status ? 1 : 0);
  469. status = !status;
  470. });
  471. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  472. $(line).find(".button-rfb-forget").on('click', rfbForget);
  473. $(line).find(".button-rfb-send").on('click', rfbSend);
  474. line.appendTo("#rfbNodes");
  475. return line;
  476. }
  477. function rfbLearn() {
  478. var parent = $(this).parents(".pure-g");
  479. var input = $("input", parent);
  480. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  481. }
  482. function rfbForget() {
  483. var parent = $(this).parents(".pure-g");
  484. var input = $("input", parent);
  485. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  486. }
  487. function rfbSend() {
  488. var parent = $(this).parents(".pure-g");
  489. var input = $("input", parent);
  490. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  491. }
  492. // -----------------------------------------------------------------------------
  493. // Processing
  494. // -----------------------------------------------------------------------------
  495. function processData(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
  583. // ---------------------------------------------------------------------
  584. if (key == "sensors") {
  585. initSensors(data[key]);
  586. for (var i=0; i<data[key].length; i++) {
  587. var element = $("input[name=sensor][data=" + i + "]");
  588. if (element.length) element.val(data[key][i].value + data[key][i].units);
  589. }
  590. return;
  591. }
  592. // ---------------------------------------------------------------------
  593. // WiFi
  594. // ---------------------------------------------------------------------
  595. if (key == "maxNetworks") {
  596. maxNetworks = parseInt(data.maxNetworks);
  597. return;
  598. }
  599. if (key == "wifi") {
  600. var networks = data.wifi;
  601. for (var i in networks) {
  602. // add a new row
  603. var line = addNetwork();
  604. // fill in the blanks
  605. var wifi = data.wifi[i];
  606. Object.keys(wifi).forEach(function(key) {
  607. var element = $("input[name=" + key + "]", line);
  608. if (element.length) element.val(wifi[key]);
  609. });
  610. }
  611. return;
  612. }
  613. // ---------------------------------------------------------------------
  614. // Relays
  615. // ---------------------------------------------------------------------
  616. if (key == "relayStatus") {
  617. initRelays(data[key]);
  618. return;
  619. }
  620. // Relay groups
  621. if (key == "relayGroups") {
  622. var groups = data.relayGroups;
  623. for (var i in groups) {
  624. // add a new row
  625. var line = addRelayGroup();
  626. // fill in the blanks
  627. var group = data.relayGroups[i];
  628. Object.keys(group).forEach(function(key) {
  629. var element = $("input[name=" + key + "]", line);
  630. if (element.length) element.val(group[key]);
  631. });
  632. }
  633. return;
  634. }
  635. // ---------------------------------------------------------------------
  636. // Domoticz
  637. // ---------------------------------------------------------------------
  638. // Domoticz - Relays
  639. if (key == "dczRelayIdx") {
  640. createRelayIdxs(data[key]);
  641. return;
  642. }
  643. // Domoticz - Sensors
  644. if (key == "dczSensors") {
  645. createSensorIdxs(data[key]);
  646. return;
  647. }
  648. // ---------------------------------------------------------------------
  649. // General
  650. // ---------------------------------------------------------------------
  651. // Messages
  652. if (key == "message") {
  653. window.alert(messages[data.message]);
  654. return;
  655. }
  656. // Enable options
  657. if (key.endsWith("Visible")) {
  658. var module = key.slice(0,-7);
  659. $(".module-" + module).show();
  660. return;
  661. }
  662. // Pre-process
  663. if (key == "network") {
  664. data.network = data.network.toUpperCase();
  665. }
  666. if (key == "mqttStatus") {
  667. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  668. }
  669. if (key == "ntpStatus") {
  670. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  671. }
  672. if (key == "uptime") {
  673. var uptime = parseInt(data[key]);
  674. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  675. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  676. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  677. var days = uptime;
  678. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  679. }
  680. // ---------------------------------------------------------------------
  681. // Matching
  682. // ---------------------------------------------------------------------
  683. // Look for INPUTs
  684. var element = $("input[name=" + key + "]");
  685. if (element.length > 0) {
  686. if (element.attr('type') == 'checkbox') {
  687. element
  688. .prop("checked", data[key])
  689. .iphoneStyle("refresh");
  690. } else if (element.attr('type') == 'radio') {
  691. element.val([data[key]]);
  692. } else {
  693. var pre = element.attr("pre") || "";
  694. var post = element.attr("post") || "";
  695. element.val(pre + data[key] + post);
  696. }
  697. return;
  698. }
  699. // Look for SPANs
  700. var element = $("span[name=" + key + "]");
  701. if (element.length > 0) {
  702. var pre = element.attr("pre") || "";
  703. var post = element.attr("post") || "";
  704. element.html(pre + data[key] + post);
  705. return;
  706. }
  707. // Look for SELECTs
  708. var element = $("select[name=" + key + "]");
  709. if (element.length > 0) {
  710. element.val(data[key]);
  711. return;
  712. }
  713. });
  714. // Auto generate an APIKey if none defined yet
  715. if ($("input[name='apiKey']").val() == "") {
  716. generateAPIKey();
  717. }
  718. resetOriginals();
  719. }
  720. function hasChanged() {
  721. var newValue, originalValue;
  722. if ($(this).attr('type') == 'checkbox') {
  723. newValue = $(this).prop("checked")
  724. originalValue = $(this).attr("original") == "true";
  725. } else {
  726. newValue = $(this).val();
  727. originalValue = $(this).attr("original");
  728. }
  729. var hasChanged = $(this).attr("hasChanged") || 0;
  730. var action = $(this).attr("action");
  731. if (typeof originalValue == 'undefined') return;
  732. if (action == 'none') return;
  733. if (newValue != originalValue) {
  734. if (hasChanged == 0) {
  735. ++numChanged;
  736. if (action == "reconnect") ++numReconnect;
  737. if (action == "reboot") ++numReboot;
  738. if (action == "reload") ++numReload;
  739. $(this).attr("hasChanged", 1);
  740. }
  741. } else {
  742. if (hasChanged == 1) {
  743. --numChanged;
  744. if (action == "reconnect") --numReconnect;
  745. if (action == "reboot") --numReboot;
  746. if (action == "reload") --numReload;
  747. $(this).attr("hasChanged", 0);
  748. }
  749. }
  750. }
  751. function resetOriginals() {
  752. $("input").each(function() {
  753. $(this).attr("original", $(this).val());
  754. })
  755. $("select").each(function() {
  756. $(this).attr("original", $(this).val());
  757. })
  758. numReboot = numReconnect = numReload = 0;
  759. }
  760. // -----------------------------------------------------------------------------
  761. // Init & connect
  762. // -----------------------------------------------------------------------------
  763. function connect(host) {
  764. if (typeof host === 'undefined') {
  765. host = window.location.href.replace('#', '');
  766. } else {
  767. if (!host.startsWith("http")) {
  768. host = 'http://' + host + '/';
  769. }
  770. }
  771. if (!host.startsWith("http")) return;
  772. webhost = host;
  773. wshost = host.replace('http', 'ws') + 'ws';
  774. if (websock) websock.close();
  775. websock = new WebSocket(wshost);
  776. websock.onopen = function(evt) {
  777. console.log("Connected");
  778. };
  779. websock.onclose = function(evt) {
  780. console.log("Disconnected");
  781. };
  782. websock.onerror = function(evt) {
  783. console.log("Error: ", evt);
  784. };
  785. websock.onmessage = function(evt) {
  786. var data = getJson(evt.data);
  787. if (data) processData(data);
  788. };
  789. }
  790. function init() {
  791. initMessages();
  792. $("#menuLink").on('click', toggleMenu);
  793. $(".pure-menu-link").on('click', showPanel);
  794. $('progress').attr({ value: 0, max: 100 });
  795. $(".button-update").on('click', doUpdate);
  796. $(".button-update-password").on('click', doUpdatePassword);
  797. $(".button-reboot").on('click', doReboot);
  798. $(".button-reconnect").on('click', doReconnect);
  799. $(".button-settings-backup").on('click', doBackup);
  800. $(".button-settings-restore").on('click', doRestore);
  801. $('#uploader').on('change', onFileUpload);
  802. $(".button-upgrade").on('click', doUpgrade);
  803. $(".button-apikey").on('click', generateAPIKey);
  804. $(".button-upgrade-browse").on('click', function() {
  805. $("input[name='upgrade']")[0].click();
  806. return false;
  807. });
  808. $("input[name='upgrade']").change(function (){
  809. var fileName = $(this).val();
  810. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  811. });
  812. $(".button-add-network").on('click', function() {
  813. $("div.more", addNetwork()).toggle();
  814. });
  815. $(document).on('change', 'input', hasChanged);
  816. $(document).on('change', 'select', hasChanged);
  817. connect();
  818. }
  819. $(init);