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.

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