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.

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