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.

1043 lines
31 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var messages = [];
  5. var webhost;
  6. var numChanged = 0;
  7. var numReboot = 0;
  8. var numReconnect = 0;
  9. var numReload = 0;
  10. var useWhite = false;
  11. 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 (row of manifest) if (row.sensor_id == sensor_id) return row;
  386. return null;
  387. }
  388. // -----------------------------------------------------------------------------
  389. // Lights
  390. // -----------------------------------------------------------------------------
  391. function initColorRGB() {
  392. // check if already initialized
  393. var done = $("#colors > div").length;
  394. if (done > 0) return;
  395. // add template
  396. var template = $("#colorRGBTemplate").children();
  397. var line = $(template).clone();
  398. line.appendTo("#colors");
  399. // init color wheel
  400. $('input[name="color"]').wheelColorPicker({
  401. sliders: 'wrgbp'
  402. }).on('sliderup', function() {
  403. var value = $(this).wheelColorPicker('getValue', 'css');
  404. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  405. });
  406. // init bright slider
  407. $('#brightness').on("change", function() {
  408. var value = $(this).val();
  409. var parent = $(this).parents(".pure-g");
  410. $("span", parent).html(value);
  411. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  412. });
  413. }
  414. function initColorHSV() {
  415. // check if already initialized
  416. var done = $("#colors > div").length;
  417. if (done > 0) return;
  418. // add template
  419. var template = $("#colorHSVTemplate").children();
  420. var line = $(template).clone();
  421. line.appendTo("#colors");
  422. // init color wheel
  423. $('input[name="color"]').wheelColorPicker({
  424. sliders: 'whsvp'
  425. }).on('sliderup', function() {
  426. var color = $(this).wheelColorPicker('getColor');
  427. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  428. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  429. });
  430. }
  431. function initChannels(num) {
  432. // check if already initialized
  433. var done = $("#channels > div").length > 0;
  434. if (done) return;
  435. // does it have color channels?
  436. var colors = $("#colors > div").length > 0;
  437. // calculate channels to create
  438. var max = num;
  439. if (colors) {
  440. max = num % 3;
  441. if ((max > 0) & useWhite) max--;
  442. }
  443. var start = num - max;
  444. // add templates
  445. var template = $("#channelTemplate").children();
  446. for (var i=0; i<max; i++) {
  447. var channel_id = start + i;
  448. var line = $(template).clone();
  449. $("span.slider", line).attr("data", channel_id);
  450. $("input.slider", line).attr("data", channel_id).on("change", function() {
  451. var id = $(this).attr("data");
  452. var value = $(this).val();
  453. var parent = $(this).parents(".pure-g");
  454. $("span", parent).html(value);
  455. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  456. });
  457. $("label", line).html("Channel " + (channel_id + 1));
  458. line.appendTo("#channels");
  459. }
  460. }
  461. // -----------------------------------------------------------------------------
  462. // RFBridge
  463. // -----------------------------------------------------------------------------
  464. function addRfbNode() {
  465. var numNodes = $("#rfbNodes > fieldset").length;
  466. var template = $("#rfbNodeTemplate").children();
  467. var line = $(template).clone();
  468. var status = true;
  469. $("span", line).html(numNodes+1);
  470. $(line).find("input").each(function() {
  471. $(this).attr("data-id", numNodes);
  472. $(this).attr("data-status", status ? 1 : 0);
  473. status = !status;
  474. });
  475. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  476. $(line).find(".button-rfb-forget").on('click', rfbForget);
  477. $(line).find(".button-rfb-send").on('click', rfbSend);
  478. line.appendTo("#rfbNodes");
  479. return line;
  480. }
  481. function rfbLearn() {
  482. var parent = $(this).parents(".pure-g");
  483. var input = $("input", parent);
  484. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  485. }
  486. function rfbForget() {
  487. var parent = $(this).parents(".pure-g");
  488. var input = $("input", parent);
  489. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  490. }
  491. function rfbSend() {
  492. var parent = $(this).parents(".pure-g");
  493. var input = $("input", parent);
  494. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  495. }
  496. // -----------------------------------------------------------------------------
  497. // Processing
  498. // -----------------------------------------------------------------------------
  499. function processData(data) {
  500. console.log(data);
  501. // title
  502. if ("app_name" in data) {
  503. var title = data.app_name;
  504. if ("app_version" in data) {
  505. title = title + " " + data.app_version;
  506. }
  507. $(".pure-menu-heading").html(title);
  508. if ("hostname" in data) {
  509. title = data.hostname + " - " + title;
  510. }
  511. document.title = title;
  512. }
  513. Object.keys(data).forEach(function(key) {
  514. // ---------------------------------------------------------------------
  515. // ---------------------------------------------------------------------
  516. // Web mode
  517. // ---------------------------------------------------------------------
  518. if (key == "webMode") {
  519. password = data.webMode == 1;
  520. $("#layout").toggle(data.webMode == 0);
  521. $("#password").toggle(data.webMode == 1);
  522. }
  523. // ---------------------------------------------------------------------
  524. // Actions
  525. // ---------------------------------------------------------------------
  526. if (key == "action") {
  527. if (data.action == "reload") doReload(1000);
  528. return;
  529. }
  530. // ---------------------------------------------------------------------
  531. // RFBridge
  532. // ---------------------------------------------------------------------
  533. if (key == "rfbCount") {
  534. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  535. return;
  536. }
  537. if (key == "rfb") {
  538. var nodes = data.rfb;
  539. for (var i in nodes) {
  540. var node = nodes[i];
  541. var element = $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]");
  542. if (element.length) element.val(node["data"]);
  543. }
  544. return;
  545. }
  546. // ---------------------------------------------------------------------
  547. // Lights
  548. // ---------------------------------------------------------------------
  549. if (key == "rgb") {
  550. initColorRGB();
  551. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  552. return;
  553. }
  554. if (key == "hsv") {
  555. initColorHSV();
  556. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  557. var chunks = data[key].split(",");
  558. var obj = {};
  559. obj.h = chunks[0] / 360;
  560. obj.s = chunks[1] / 100;
  561. obj.v = chunks[2] / 100;
  562. $("input[name='color']").wheelColorPicker('setColor', obj);
  563. return;
  564. }
  565. if (key == "brightness") {
  566. var slider = $("#brightness");
  567. if (slider.length) slider.val(data[key]);
  568. var span = $("span.brightness");
  569. if (span.length) span.html(data[key]);
  570. return;
  571. }
  572. if (key == "channels") {
  573. var len = data[key].length;
  574. initChannels(len);
  575. for (var i=0; i<len; i++) {
  576. var slider = $("input.slider[data=" + i + "]");
  577. if (slider.length) slider.val(data[key][i]);
  578. var span = $("span.slider[data=" + i + "]");
  579. if (span.length) span.html(data[key][i]);
  580. }
  581. return;
  582. }
  583. if (key == "useWhite") {
  584. useWhite = data[key];
  585. }
  586. // ---------------------------------------------------------------------
  587. // Sensors & Magnitudes
  588. // ---------------------------------------------------------------------
  589. if (key == "magnitudes") {
  590. initMagnitudes(data[key]);
  591. for (var i=0; i<data[key].length; i++) {
  592. var element = $("input[name=magnitude][data=" + i + "]");
  593. if (element.length) {
  594. var error = data[key][i].error || 0;
  595. if (error == 0) {
  596. element.val(data[key][i].value + data[key][i].units);
  597. } else {
  598. element.val(magnitudeError(error));
  599. }
  600. }
  601. }
  602. return;
  603. }
  604. if (key == "manifest") {
  605. manifest = data[key];
  606. }
  607. // ---------------------------------------------------------------------
  608. // WiFi
  609. // ---------------------------------------------------------------------
  610. if (key == "maxNetworks") {
  611. maxNetworks = parseInt(data.maxNetworks);
  612. return;
  613. }
  614. if (key == "wifi") {
  615. var networks = data.wifi;
  616. for (var i in networks) {
  617. // add a new row
  618. var line = addNetwork();
  619. // fill in the blanks
  620. var wifi = data.wifi[i];
  621. Object.keys(wifi).forEach(function(key) {
  622. var element = $("input[name=" + key + "]", line);
  623. if (element.length) element.val(wifi[key]);
  624. });
  625. }
  626. return;
  627. }
  628. // ---------------------------------------------------------------------
  629. // Relays
  630. // ---------------------------------------------------------------------
  631. if (key == "relayStatus") {
  632. initRelays(data[key]);
  633. return;
  634. }
  635. // Relay groups
  636. if (key == "relayGroups") {
  637. var groups = data.relayGroups;
  638. for (var i in groups) {
  639. // add a new row
  640. var line = addRelayGroup();
  641. // fill in the blanks
  642. var group = data.relayGroups[i];
  643. Object.keys(group).forEach(function(key) {
  644. var element = $("input[name=" + key + "]", line);
  645. if (element.length) element.val(group[key]);
  646. });
  647. }
  648. return;
  649. }
  650. // ---------------------------------------------------------------------
  651. // Domoticz
  652. // ---------------------------------------------------------------------
  653. // Domoticz - Relays
  654. if (key == "dczRelayIdx") {
  655. createRelayIdxs(data[key]);
  656. return;
  657. }
  658. // Domoticz - Magnitudes
  659. if (key == "dczMagnitudes") {
  660. createMagnitudeIdxs(data[key]);
  661. return;
  662. }
  663. // ---------------------------------------------------------------------
  664. // General
  665. // ---------------------------------------------------------------------
  666. // Messages
  667. if (key == "message") {
  668. window.alert(messages[data.message]);
  669. return;
  670. }
  671. // Enable options
  672. if (key.endsWith("Visible")) {
  673. var module = key.slice(0,-7);
  674. $(".module-" + module).show();
  675. return;
  676. }
  677. // Pre-process
  678. if (key == "network") {
  679. data.network = data.network.toUpperCase();
  680. }
  681. if (key == "mqttStatus") {
  682. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  683. }
  684. if (key == "ntpStatus") {
  685. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  686. }
  687. if (key == "uptime") {
  688. var uptime = parseInt(data[key]);
  689. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  690. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  691. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  692. var days = uptime;
  693. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  694. }
  695. // ---------------------------------------------------------------------
  696. // Matching
  697. // ---------------------------------------------------------------------
  698. // Look for INPUTs
  699. var element = $("input[name=" + key + "]");
  700. if (element.length > 0) {
  701. if (element.attr('type') == 'checkbox') {
  702. element
  703. .prop("checked", data[key])
  704. .iphoneStyle("refresh");
  705. } else if (element.attr('type') == 'radio') {
  706. element.val([data[key]]);
  707. } else {
  708. var pre = element.attr("pre") || "";
  709. var post = element.attr("post") || "";
  710. element.val(pre + data[key] + post);
  711. }
  712. return;
  713. }
  714. // Look for SPANs
  715. var element = $("span[name=" + key + "]");
  716. if (element.length > 0) {
  717. var pre = element.attr("pre") || "";
  718. var post = element.attr("post") || "";
  719. element.html(pre + data[key] + post);
  720. return;
  721. }
  722. // Look for SELECTs
  723. var element = $("select[name=" + key + "]");
  724. if (element.length > 0) {
  725. element.val(data[key]);
  726. return;
  727. }
  728. });
  729. // Auto generate an APIKey if none defined yet
  730. if ($("input[name='apiKey']").val() == "") {
  731. generateAPIKey();
  732. }
  733. resetOriginals();
  734. }
  735. function hasChanged() {
  736. var newValue, originalValue;
  737. if ($(this).attr('type') == 'checkbox') {
  738. newValue = $(this).prop("checked")
  739. originalValue = $(this).attr("original") == "true";
  740. } else {
  741. newValue = $(this).val();
  742. originalValue = $(this).attr("original");
  743. }
  744. var hasChanged = $(this).attr("hasChanged") || 0;
  745. var action = $(this).attr("action");
  746. if (typeof originalValue == 'undefined') return;
  747. if (action == 'none') return;
  748. if (newValue != originalValue) {
  749. if (hasChanged == 0) {
  750. ++numChanged;
  751. if (action == "reconnect") ++numReconnect;
  752. if (action == "reboot") ++numReboot;
  753. if (action == "reload") ++numReload;
  754. $(this).attr("hasChanged", 1);
  755. }
  756. } else {
  757. if (hasChanged == 1) {
  758. --numChanged;
  759. if (action == "reconnect") --numReconnect;
  760. if (action == "reboot") --numReboot;
  761. if (action == "reload") --numReload;
  762. $(this).attr("hasChanged", 0);
  763. }
  764. }
  765. }
  766. function resetOriginals() {
  767. $("input").each(function() {
  768. $(this).attr("original", $(this).val());
  769. })
  770. $("select").each(function() {
  771. $(this).attr("original", $(this).val());
  772. })
  773. numReboot = numReconnect = numReload = 0;
  774. }
  775. // -----------------------------------------------------------------------------
  776. // Init & connect
  777. // -----------------------------------------------------------------------------
  778. function connect(host) {
  779. if (typeof host === 'undefined') {
  780. host = window.location.href.replace('#', '');
  781. } else {
  782. if (!host.startsWith("http")) {
  783. host = 'http://' + host + '/';
  784. }
  785. }
  786. if (!host.startsWith("http")) return;
  787. webhost = host;
  788. wshost = host.replace('http', 'ws') + 'ws';
  789. if (websock) websock.close();
  790. websock = new WebSocket(wshost);
  791. websock.onopen = function(evt) {
  792. console.log("Connected");
  793. };
  794. websock.onclose = function(evt) {
  795. console.log("Disconnected");
  796. };
  797. websock.onerror = function(evt) {
  798. console.log("Error: ", evt);
  799. };
  800. websock.onmessage = function(evt) {
  801. var data = getJson(evt.data);
  802. if (data) processData(data);
  803. };
  804. }
  805. function init() {
  806. initMessages();
  807. $("#menuLink").on('click', toggleMenu);
  808. $(".pure-menu-link").on('click', showPanel);
  809. $('progress').attr({ value: 0, max: 100 });
  810. $(".button-update").on('click', doUpdate);
  811. $(".button-update-password").on('click', doUpdatePassword);
  812. $(".button-reboot").on('click', doReboot);
  813. $(".button-reconnect").on('click', doReconnect);
  814. $(".button-settings-backup").on('click', doBackup);
  815. $(".button-settings-restore").on('click', doRestore);
  816. $('#uploader').on('change', onFileUpload);
  817. $(".button-upgrade").on('click', doUpgrade);
  818. $(".button-apikey").on('click', generateAPIKey);
  819. $(".button-upgrade-browse").on('click', function() {
  820. $("input[name='upgrade']")[0].click();
  821. return false;
  822. });
  823. $("input[name='upgrade']").change(function (){
  824. var fileName = $(this).val();
  825. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  826. });
  827. $(".button-add-network").on('click', function() {
  828. $("div.more", addNetwork()).toggle();
  829. });
  830. $(document).on('change', 'input', hasChanged);
  831. $(document).on('change', 'select', hasChanged);
  832. connect();
  833. }
  834. $(init);