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.

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