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.

1057 lines
32 KiB

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