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.

1044 lines
31 KiB

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