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.

1939 lines
55 KiB

8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var maxSchedules;
  5. var messages = [];
  6. var free_size = 0;
  7. var urls = {};
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var useWhite = false;
  13. var useCCT = false;
  14. var now = 0;
  15. var ago = 0;
  16. <!-- removeIf(!rfm69)-->
  17. var packets;
  18. var filters = [];
  19. <!-- endRemoveIf(!rfm69)-->
  20. <!-- removeIf(!sensor)-->
  21. var magnitudes = [];
  22. <!-- endRemoveIf(!sensor)-->
  23. // -----------------------------------------------------------------------------
  24. // Messages
  25. // -----------------------------------------------------------------------------
  26. function initMessages() {
  27. messages[1] = "Remote update started";
  28. messages[2] = "OTA update started";
  29. messages[3] = "Error parsing data!";
  30. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  31. messages[5] = "Changes saved. You should reboot your board now";
  32. messages[7] = "Passwords do not match!";
  33. messages[8] = "Changes saved";
  34. messages[9] = "No changes detected";
  35. messages[10] = "Session expired, please reload page...";
  36. }
  37. <!-- removeIf(!sensor)-->
  38. function sensorName(id) {
  39. var names = [
  40. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  41. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  42. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  43. "SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
  44. "TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
  45. "NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
  46. "EZOPH"
  47. ];
  48. if (1 <= id && id <= names.length) {
  49. return names[id - 1];
  50. }
  51. return null;
  52. }
  53. function magnitudeType(type) {
  54. var types = [
  55. "Temperature", "Humidity", "Pressure",
  56. "Current", "Voltage", "Active Power", "Apparent Power",
  57. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  58. "Analog", "Digital", "Event",
  59. "PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
  60. "Local Dose Rate", "Local Dose Rate",
  61. "Count",
  62. "NO2", "CO", "Resistance", "pH"
  63. ];
  64. if (1 <= type && type <= types.length) {
  65. return types[type - 1];
  66. }
  67. return null;
  68. }
  69. function magnitudeError(error) {
  70. var errors = [
  71. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  72. "Data Error", "I2C Error", "GPIO Error", "Calibration error"
  73. ];
  74. if (0 <= error && error < errors.length) {
  75. return errors[error];
  76. }
  77. return "Error " + error;
  78. }
  79. <!-- endRemoveIf(!sensor)-->
  80. // -----------------------------------------------------------------------------
  81. // Utils
  82. // -----------------------------------------------------------------------------
  83. $.fn.enterKey = function (fnc) {
  84. return this.each(function () {
  85. $(this).keypress(function (ev) {
  86. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  87. if (13 === keycode) {
  88. return fnc.call(this, ev);
  89. }
  90. });
  91. });
  92. };
  93. function keepTime() {
  94. $("span[name='ago']").html(ago);
  95. ago++;
  96. if (0 === now) { return; }
  97. var date = new Date(now * 1000);
  98. var text = date.toISOString().substring(0, 19).replace("T", " ");
  99. $("input[name='now']").val(text);
  100. $("span[name='now']").html(text);
  101. now++;
  102. }
  103. function zeroPad(number, positions) {
  104. var zeros = "";
  105. for (var i = 0; i < positions; i++) {
  106. zeros += "0";
  107. }
  108. return (zeros + number).slice(-positions);
  109. }
  110. function loadTimeZones() {
  111. var time_zones = [
  112. -720, -660, -600, -570, -540,
  113. -480, -420, -360, -300, -240,
  114. -210, -180, -120, -60, 0,
  115. 60, 120, 180, 210, 240,
  116. 270, 300, 330, 345, 360,
  117. 390, 420, 480, 510, 525,
  118. 540, 570, 600, 630, 660,
  119. 720, 765, 780, 840
  120. ];
  121. for (var i in time_zones) {
  122. var value = time_zones[i];
  123. var offset = value >= 0 ? value : -value;
  124. var text = "GMT" + (value >= 0 ? "+" : "-") +
  125. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  126. zeroPad(offset % 60, 2);
  127. $("select[name='ntpOffset']").append(
  128. $("<option></option>").
  129. attr("value",value).
  130. text(text));
  131. }
  132. }
  133. function validatePassword(password) {
  134. // http://www.the-art-of-web.com/javascript/validate-password/
  135. // at least one lowercase and one uppercase letter or number
  136. // at least eight characters (letters, numbers or special characters)
  137. // MUST be 8..63 printable ASCII characters. See:
  138. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  139. // https://github.com/xoseperez/espurna/issues/1151
  140. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  141. return (
  142. (password !== undefined)
  143. && (typeof password === "string")
  144. && (password.length > 0)
  145. && re_password.test(password)
  146. );
  147. }
  148. function validateFormPasswords(form) {
  149. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  150. var adminPass1 = passwords.first().val(),
  151. adminPass2 = passwords.last().val();
  152. var formValidity = passwords.first()[0].checkValidity();
  153. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  154. return true;
  155. }
  156. var validPass1 = validatePassword(adminPass1),
  157. validPass2 = validatePassword(adminPass2);
  158. if (formValidity && validPass1 && validPass2) {
  159. return true;
  160. }
  161. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  162. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  163. }
  164. if (adminPass1 !== adminPass2) {
  165. alert("Passwords are different!");
  166. }
  167. return false;
  168. }
  169. function validateFormHostname(form) {
  170. // RFCs mandate that a hostname's labels may contain only
  171. // the ASCII letters 'a' through 'z' (case-insensitive),
  172. // the digits '0' through '9', and the hyphen.
  173. // Hostname labels cannot begin or end with a hyphen.
  174. // No other symbols, punctuation characters, or blank spaces are permitted.
  175. // Negative lookbehind does not work in Javascript
  176. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
  177. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
  178. var hostname = $("input[name='hostname']", form);
  179. if ("true" !== hostname.attr("hasChanged")) {
  180. return true;
  181. }
  182. if (re_hostname.test(hostname.val())) {
  183. return true;
  184. }
  185. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  186. return false;
  187. }
  188. function validateForm(form) {
  189. return validateFormPasswords(form) && validateFormHostname(form);
  190. }
  191. function getValue(element) {
  192. if ($(element).attr("type") === "checkbox") {
  193. return $(element).prop("checked") ? 1 : 0;
  194. } else if ($(element).attr("type") === "radio") {
  195. if (!$(element).prop("checked")) {
  196. return null;
  197. }
  198. }
  199. return $(element).val();
  200. }
  201. function addValue(data, name, value) {
  202. // These fields will always be a list of values
  203. var is_group = [
  204. "ssid", "pass", "gw", "mask", "ip", "dns",
  205. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  206. "relayBoot", "relayPulse", "relayTime",
  207. "mqttGroup", "mqttGroupSync", "relayOnDisc",
  208. "dczRelayIdx", "dczMagnitude",
  209. "tspkRelay", "tspkMagnitude",
  210. "ledMode", "ledRelay",
  211. "adminPass",
  212. "node", "key", "topic"
  213. ];
  214. // join both adminPass 1 and 2
  215. if (name.startsWith("adminPass")) {
  216. name = "adminPass";
  217. }
  218. if (name in data) {
  219. if (!Array.isArray(data[name])) {
  220. data[name] = [data[name]];
  221. }
  222. data[name].push(value);
  223. } else if (is_group.indexOf(name) >= 0) {
  224. data[name] = [value];
  225. } else {
  226. data[name] = value;
  227. }
  228. }
  229. function getData(form) {
  230. var data = {};
  231. // Populate data
  232. $("input,select", form).each(function() {
  233. var name = $(this).attr("name");
  234. var value = getValue(this);
  235. if (null !== value) {
  236. addValue(data, name, value);
  237. }
  238. });
  239. // Post process
  240. addValue(data, "schSwitch", 0xFF);
  241. delete data["filename"];
  242. delete data["rfbcode"];
  243. return data;
  244. }
  245. function randomString(length, args) {
  246. if (typeof args === "undefined") {
  247. args = {
  248. lowercase: true,
  249. uppercase: true,
  250. numbers: true,
  251. special: true
  252. }
  253. }
  254. var mask = "";
  255. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  256. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  257. if (args.numbers || args.hex) { mask += "0123456789"; }
  258. if (args.hex) { mask += "ABCDEF"; }
  259. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  260. var source = new Uint32Array(length);
  261. var result = new Array(length);
  262. window.crypto.getRandomValues(source).forEach(function(value, i) {
  263. result[i] = mask[value % mask.length];
  264. });
  265. return result.join("");
  266. }
  267. function generateAPIKey() {
  268. var apikey = randomString(16, {hex: true});
  269. $("input[name='apiKey']").val(apikey);
  270. return false;
  271. }
  272. function generatePassword() {
  273. var password = "";
  274. do {
  275. password = randomString(10);
  276. } while (!validatePassword(password));
  277. return password;
  278. }
  279. function toggleVisiblePassword() {
  280. var elem = this.previousElementSibling;
  281. if (elem.type === "password") {
  282. elem.type = "text";
  283. } else {
  284. elem.type = "password";
  285. }
  286. return false;
  287. }
  288. function doGeneratePassword() {
  289. $("input", $("#formPassword"))
  290. .val(generatePassword())
  291. .each(function() {
  292. this.type = "text";
  293. });
  294. return false;
  295. }
  296. function getJson(str) {
  297. try {
  298. return JSON.parse(str);
  299. } catch (e) {
  300. return false;
  301. }
  302. }
  303. <!-- removeIf(!thermostat)-->
  304. function checkTempRangeMin() {
  305. var min = parseInt($("#tempRangeMinInput").val(), 10);
  306. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  307. if (min > max - 1) {
  308. $("#tempRangeMinInput").val(max - 1);
  309. }
  310. }
  311. function checkTempRangeMax() {
  312. var min = parseInt($("#tempRangeMinInput").val(), 10);
  313. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  314. if (max < min + 1) {
  315. $("#tempRangeMaxInput").val(min + 1);
  316. }
  317. }
  318. function doResetThermostatCounters(ask) {
  319. var question = (typeof ask === "undefined" || false === ask) ?
  320. null :
  321. "Are you sure you want to reset burning counters?";
  322. return doAction(question, "thermostat_reset_counters");
  323. }
  324. <!-- endRemoveIf(!thermostat)-->
  325. function initGPIO(node, name, key, value) {
  326. var template = $("#gpioConfigTemplate").children();
  327. var line = $(template).clone();
  328. $("span.id", line).html(value);
  329. $("select", line).attr("name", key);
  330. line.appendTo(node);
  331. }
  332. function initSelectGPIO(select) {
  333. // TODO: cross-check used GPIOs
  334. // TODO: support 9 & 10 with esp8285 variant
  335. var mapping = [
  336. [153, "NONE"],
  337. [0, "0"],
  338. [1, "1 (U0TXD)"],
  339. [2, "2 (U1TXD)"],
  340. [3, "3 (U0RXD)"],
  341. [4, "4"],
  342. [5, "5"],
  343. [12, "12 (MTDI)"],
  344. [13, "13 (MTCK)"],
  345. [14, "14 (MTMS)"],
  346. [15, "15 (MTDO)"],
  347. ];
  348. for (n in mapping) {
  349. var elem = $('<option value="' + mapping[n][0] + '">');
  350. elem.html(mapping[n][1]);
  351. elem.appendTo(select);
  352. }
  353. }
  354. // -----------------------------------------------------------------------------
  355. // Actions
  356. // -----------------------------------------------------------------------------
  357. function sendAction(action, data) {
  358. websock.send(JSON.stringify({action: action, data: data}));
  359. }
  360. function sendConfig(data) {
  361. websock.send(JSON.stringify({config: data}));
  362. }
  363. function setOriginalsFromValues(force) {
  364. var force = (true === force);
  365. $("input,select").each(function() {
  366. var initial = (undefined === $(this).attr("original"));
  367. if (force || initial) {
  368. $(this).attr("original", $(this).val());
  369. }
  370. });
  371. }
  372. function resetOriginals() {
  373. setOriginalsFromValues(true);
  374. numReboot = numReconnect = numReload = 0;
  375. }
  376. function doReload(milliseconds) {
  377. setTimeout(function() {
  378. window.location.reload();
  379. }, parseInt(milliseconds, 10));
  380. }
  381. /**
  382. * Check a file object to see if it is a valid firmware image
  383. * The file first byte should be 0xE9
  384. * @param {file} file File object
  385. * @param {Function} callback Function to call back with the result
  386. */
  387. function checkFirmware(file, callback) {
  388. var reader = new FileReader();
  389. reader.onloadend = function(evt) {
  390. if (FileReader.DONE === evt.target.readyState) {
  391. if (0xE9 !== evt.target.result.charCodeAt(0)) callback(false);
  392. if (0x03 !== evt.target.result.charCodeAt(2)) {
  393. var response = window.confirm("Binary image is not using DOUT flash mode. This might cause resets in some devices. Press OK to continue.");
  394. callback(response);
  395. } else {
  396. callback(true);
  397. }
  398. }
  399. };
  400. var blob = file.slice(0, 3);
  401. reader.readAsBinaryString(blob);
  402. }
  403. function doUpgrade() {
  404. var file = $("input[name='upgrade']")[0].files[0];
  405. if (typeof file === "undefined") {
  406. alert("First you have to select a file from your computer.");
  407. return false;
  408. }
  409. if (file.size > free_size) {
  410. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  411. return false;
  412. }
  413. checkFirmware(file, function(ok) {
  414. if (!ok) {
  415. alert("The file does not seem to be a valid firmware image.");
  416. return;
  417. }
  418. var data = new FormData();
  419. data.append("upgrade", file, file.name);
  420. $.ajax({
  421. // Your server script to process the upload
  422. url: urls.upgrade.href,
  423. type: "POST",
  424. // Form data
  425. data: data,
  426. // Tell jQuery not to process data or worry about content-type
  427. // You *must* include these options!
  428. cache: false,
  429. contentType: false,
  430. processData: false,
  431. success: function(data, text) {
  432. $("#upgrade-progress").hide();
  433. if ("OK" === data) {
  434. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  435. doReload(5000);
  436. } else {
  437. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  438. }
  439. },
  440. // Custom XMLHttpRequest
  441. xhr: function() {
  442. $("#upgrade-progress").show();
  443. var myXhr = $.ajaxSettings.xhr();
  444. if (myXhr.upload) {
  445. // For handling the progress of the upload
  446. myXhr.upload.addEventListener("progress", function(e) {
  447. if (e.lengthComputable) {
  448. $("progress").attr({ value: e.loaded, max: e.total });
  449. }
  450. } , false);
  451. }
  452. return myXhr;
  453. }
  454. });
  455. });
  456. return false;
  457. }
  458. function doUpdatePassword() {
  459. var form = $("#formPassword");
  460. if (validateFormPasswords(form)) {
  461. sendConfig(getData(form));
  462. }
  463. return false;
  464. }
  465. function checkChanges() {
  466. if (numChanged > 0) {
  467. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  468. if (response) {
  469. doUpdate();
  470. }
  471. }
  472. }
  473. function doAction(question, action) {
  474. checkChanges();
  475. if (question) {
  476. var response = window.confirm(question);
  477. if (false === response) {
  478. return false;
  479. }
  480. }
  481. sendAction(action, {});
  482. doReload(5000);
  483. return false;
  484. }
  485. function doReboot(ask) {
  486. var question = (typeof ask === "undefined" || false === ask) ?
  487. null :
  488. "Are you sure you want to reboot the device?";
  489. return doAction(question, "reboot");
  490. }
  491. function doReconnect(ask) {
  492. var question = (typeof ask === "undefined" || false === ask) ?
  493. null :
  494. "Are you sure you want to disconnect from the current WIFI network?";
  495. return doAction(question, "reconnect");
  496. }
  497. function doUpdate() {
  498. var forms = $(".form-settings");
  499. if (validateForm(forms)) {
  500. // Get data
  501. sendConfig(getData(forms));
  502. // Empty special fields
  503. $(".pwrExpected").val(0);
  504. $("input[name='snsResetCalibration']").prop("checked", false);
  505. $("input[name='pwrResetCalibration']").prop("checked", false);
  506. $("input[name='pwrResetE']").prop("checked", false);
  507. // Change handling
  508. numChanged = 0;
  509. setTimeout(function() {
  510. var response;
  511. if (numReboot > 0) {
  512. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  513. if (response) { doReboot(false); }
  514. } else if (numReconnect > 0) {
  515. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  516. if (response) { doReconnect(false); }
  517. } else if (numReload > 0) {
  518. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  519. if (response) { doReload(0); }
  520. }
  521. resetOriginals();
  522. }, 1000);
  523. }
  524. return false;
  525. }
  526. function doBackup() {
  527. document.getElementById("downloader").src = urls.config.href;
  528. return false;
  529. }
  530. function onFileUpload(event) {
  531. var inputFiles = this.files;
  532. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  533. return false;
  534. }
  535. var inputFile = inputFiles[0];
  536. this.value = "";
  537. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  538. if (!response) {
  539. return false;
  540. }
  541. var reader = new FileReader();
  542. reader.onload = function(e) {
  543. var data = getJson(e.target.result);
  544. if (data) {
  545. sendAction("restore", data);
  546. } else {
  547. window.alert(messages[4]);
  548. }
  549. };
  550. reader.readAsText(inputFile);
  551. return false;
  552. }
  553. function doRestore() {
  554. if (typeof window.FileReader !== "function") {
  555. alert("The file API isn't supported on this browser yet.");
  556. } else {
  557. $("#uploader").click();
  558. }
  559. return false;
  560. }
  561. function doFactoryReset() {
  562. var response = window.confirm("Are you sure you want to restore to factory settings?");
  563. if (response === false) {
  564. return false;
  565. }
  566. sendAction("factory_reset", {});
  567. doReload(5000);
  568. return false;
  569. }
  570. function doToggle(id, value) {
  571. sendAction("relay", {id: id, status: value ? 1 : 0 });
  572. return false;
  573. }
  574. function doScan() {
  575. $("#scanResult").html("");
  576. $("div.scan.loading").show();
  577. sendAction("scan", {});
  578. return false;
  579. }
  580. function doHAConfig() {
  581. $("#haConfig")
  582. .text("")
  583. .height(0)
  584. .show();
  585. sendAction("haconfig", {});
  586. return false;
  587. }
  588. function doDebugCommand() {
  589. var el = $("input[name='dbgcmd']");
  590. var command = el.val();
  591. el.val("");
  592. sendAction("dbgcmd", {command: command});
  593. return false;
  594. }
  595. function doDebugClear() {
  596. $("#weblog").text("");
  597. return false;
  598. }
  599. <!-- removeIf(!rfm69)-->
  600. function doClearCounts() {
  601. sendAction("clear-counts", {});
  602. return false;
  603. }
  604. function doClearMessages() {
  605. packets.clear().draw(false);
  606. return false;
  607. }
  608. function doFilter(e) {
  609. var index = packets.cell(this).index();
  610. if (index == 'undefined') return;
  611. var c = index.column;
  612. var column = packets.column(c);
  613. if (filters[c]) {
  614. filters[c] = false;
  615. column.search("");
  616. $(column.header()).removeClass("filtered");
  617. } else {
  618. filters[c] = true;
  619. var data = packets.row(this).data();
  620. if (e.which == 1) {
  621. column.search('^' + data[c] + '$', true, false );
  622. } else {
  623. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  624. }
  625. $(column.header()).addClass("filtered");
  626. }
  627. column.draw();
  628. return false;
  629. }
  630. function doClearFilters() {
  631. for (var i = 0; i < packets.columns()[0].length; i++) {
  632. if (filters[i]) {
  633. filters[i] = false;
  634. var column = packets.column(i);
  635. column.search("");
  636. $(column.header()).removeClass("filtered");
  637. column.draw();
  638. }
  639. }
  640. return false;
  641. }
  642. <!-- endRemoveIf(!rfm69)-->
  643. // -----------------------------------------------------------------------------
  644. // Visualization
  645. // -----------------------------------------------------------------------------
  646. function toggleMenu() {
  647. $("#layout").toggleClass("active");
  648. $("#menu").toggleClass("active");
  649. $("#menuLink").toggleClass("active");
  650. }
  651. function showPanel() {
  652. $(".panel").hide();
  653. if ($("#layout").hasClass("active")) { toggleMenu(); }
  654. $("#" + $(this).attr("data")).show();
  655. }
  656. // -----------------------------------------------------------------------------
  657. // Relays & magnitudes mapping
  658. // -----------------------------------------------------------------------------
  659. function createRelayList(data, container, template_name) {
  660. var current = $("#" + container + " > div").length;
  661. if (current > 0) { return; }
  662. var template = $("#" + template_name + " .pure-g")[0];
  663. for (var i in data) {
  664. var line = $(template).clone();
  665. $("label", line).html("Switch #" + i);
  666. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  667. line.appendTo("#" + container);
  668. }
  669. }
  670. <!-- removeIf(!sensor)-->
  671. function createMagnitudeList(data, container, template_name) {
  672. var current = $("#" + container + " > div").length;
  673. if (current > 0) { return; }
  674. var template = $("#" + template_name + " .pure-g")[0];
  675. var size = data.size;
  676. for (var i=0; i<size; ++i) {
  677. var line = $(template).clone();
  678. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  679. $("div.hint", line).html(magnitudes[i].description);
  680. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  681. line.appendTo("#" + container);
  682. }
  683. }
  684. <!-- endRemoveIf(!sensor)-->
  685. // -----------------------------------------------------------------------------
  686. // RFM69
  687. // -----------------------------------------------------------------------------
  688. <!-- removeIf(!rfm69)-->
  689. function addMapping() {
  690. var template = $("#nodeTemplate .pure-g")[0];
  691. var line = $(template).clone();
  692. var tabindex = $("#mapping > div").length * 3 + 50;
  693. $(line).find("input").each(function() {
  694. $(this).attr("tabindex", tabindex++);
  695. });
  696. $(line).find("button").on('click', delMapping);
  697. line.appendTo("#mapping");
  698. }
  699. function delMapping() {
  700. var parent = $(this).parent().parent();
  701. $(parent).remove();
  702. }
  703. <!-- endRemoveIf(!rfm69)-->
  704. // -----------------------------------------------------------------------------
  705. // Wifi
  706. // -----------------------------------------------------------------------------
  707. function delNetwork() {
  708. var parent = $(this).parents(".pure-g");
  709. $(parent).remove();
  710. }
  711. function moreNetwork() {
  712. var parent = $(this).parents(".pure-g");
  713. $(".more", parent).toggle();
  714. }
  715. function addNetwork() {
  716. var numNetworks = $("#networks > div").length;
  717. if (numNetworks >= maxNetworks) {
  718. alert("Max number of networks reached");
  719. return null;
  720. }
  721. var tabindex = 200 + numNetworks * 10;
  722. var template = $("#networkTemplate").children();
  723. var line = $(template).clone();
  724. $(line).find("input").each(function() {
  725. $(this).attr("tabindex", tabindex);
  726. tabindex++;
  727. });
  728. $(".password-reveal", line).on("click", toggleVisiblePassword);
  729. $(line).find(".button-del-network").on("click", delNetwork);
  730. $(line).find(".button-more-network").on("click", moreNetwork);
  731. line.appendTo("#networks");
  732. return line;
  733. }
  734. // -----------------------------------------------------------------------------
  735. // Relays scheduler
  736. // -----------------------------------------------------------------------------
  737. function delSchedule() {
  738. var parent = $(this).parents(".pure-g");
  739. $(parent).remove();
  740. }
  741. function moreSchedule() {
  742. var parent = $(this).parents(".pure-g");
  743. $("div.more", parent).toggle();
  744. }
  745. function addSchedule(event) {
  746. var numSchedules = $("#schedules > div").length;
  747. if (numSchedules >= maxSchedules) {
  748. alert("Max number of schedules reached");
  749. return null;
  750. }
  751. var tabindex = 200 + numSchedules * 10;
  752. var template = $("#scheduleTemplate").children();
  753. var line = $(template).clone();
  754. var type = (1 === event.data.schType) ? "switch" : "light";
  755. template = $("#" + type + "ActionTemplate").children();
  756. var actionLine = template.clone();
  757. $(line).find("#schActionDiv").append(actionLine);
  758. $(line).find("input").each(function() {
  759. $(this).attr("tabindex", tabindex);
  760. tabindex++;
  761. });
  762. $(line).find(".button-del-schedule").on("click", delSchedule);
  763. $(line).find(".button-more-schedule").on("click", moreSchedule);
  764. $(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
  765. .next().prop("for", "schUTC" + (numSchedules + 1));
  766. $(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
  767. .next().prop("for", "schEnabled" + (numSchedules + 1));
  768. line.appendTo("#schedules");
  769. $(line).find("input[type='checkbox']").prop("checked", false);
  770. return line;
  771. }
  772. // -----------------------------------------------------------------------------
  773. // Relays
  774. // -----------------------------------------------------------------------------
  775. function initRelays(data) {
  776. var current = $("#relays > div").length;
  777. if (current > 0) { return; }
  778. var template = $("#relayTemplate .pure-g")[0];
  779. for (var i=0; i<data.length; i++) {
  780. // Add relay fields
  781. var line = $(template).clone();
  782. $(".id", line).html(i);
  783. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  784. .prop("id", "relay" + i)
  785. .on("change", function (event) {
  786. var id = parseInt($(event.target).attr("data"), 10);
  787. var status = $(event.target).prop("checked");
  788. doToggle(id, status);
  789. });
  790. $("label.toggle", line).prop("for", "relay" + i)
  791. line.appendTo("#relays");
  792. // Populate the relay SELECTs
  793. $("select.isrelay").append(
  794. $("<option></option>").attr("value",i).text("Switch #" + i));
  795. }
  796. }
  797. function updateRelays(data) {
  798. var size = data.size;
  799. for (var i=0; i<size; ++i) {
  800. var elem = $("input[name='relay'][data='" + i + "']");
  801. elem.prop("checked", data.status[i]);
  802. elem.prop("disabled", data.lock[i] < 2); // RELAY_LOCK_DISABLED=2
  803. }
  804. }
  805. function createCheckboxes() {
  806. $("input[type='checkbox']").each(function() {
  807. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  808. $(this).parent().addClass("toggleWrapper");
  809. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  810. });
  811. }
  812. function initRelayConfig(data) {
  813. var current = $("#relayConfig > legend").length; // there is a legend per relay
  814. if (current > 0) { return; }
  815. var size = data.size;
  816. var start = data.start;
  817. var template = $("#relayConfigTemplate").children();
  818. for (var i=start; i<size; ++i) {
  819. var line = $(template).clone();
  820. $("span.id", line).html(i);
  821. $("span.gpio", line).html(data.gpio[i]);
  822. $("select[name='relayBoot']", line).val(data.boot[i]);
  823. $("select[name='relayPulse']", line).val(data.pulse[i]);
  824. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  825. if ("group" in data) {
  826. $("input[name='mqttGroup']", line).val(data.group[i]);
  827. }
  828. if ("group_sync" in data) {
  829. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  830. }
  831. if ("on_disc" in data) {
  832. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  833. }
  834. line.appendTo("#relayConfig");
  835. }
  836. }
  837. function initLeds(data) {
  838. var current = $("#ledConfig > div").length;
  839. if (current > 0) { return; }
  840. var size = data.length;
  841. var template = $("#ledConfigTemplate").children();
  842. for (var i=0; i<size; ++i) {
  843. var line = $(template).clone();
  844. $("span.id", line).html(i);
  845. $("select", line).attr("data", i);
  846. $("input", line).attr("data", i);
  847. line.appendTo("#ledConfig");
  848. }
  849. }
  850. // -----------------------------------------------------------------------------
  851. // Sensors & Magnitudes
  852. // -----------------------------------------------------------------------------
  853. <!-- removeIf(!sensor)-->
  854. function initMagnitudes(data) {
  855. // check if already initialized (each magnitude is inside div.pure-g)
  856. var done = $("#magnitudes > div").length;
  857. if (done > 0) { return; }
  858. var size = data.size;
  859. // add templates
  860. var template = $("#magnitudeTemplate").children();
  861. for (var i=0; i<size; ++i) {
  862. var magnitude = {
  863. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  864. "units": data.units[i],
  865. "description": data.description[i]
  866. };
  867. magnitudes.push(magnitude);
  868. var line = $(template).clone();
  869. $("label", line).html(magnitude.name);
  870. $("div.hint", line).html(magnitude.description);
  871. $("input", line).attr("data", i);
  872. line.appendTo("#magnitudes");
  873. }
  874. }
  875. <!-- endRemoveIf(!sensor)-->
  876. // -----------------------------------------------------------------------------
  877. // Lights
  878. // -----------------------------------------------------------------------------
  879. <!-- removeIf(!light)-->
  880. function initColor(rgb) {
  881. // check if already initialized
  882. var done = $("#colors > div").length;
  883. if (done > 0) { return; }
  884. // add template
  885. var template = $("#colorTemplate").children();
  886. var line = $(template).clone();
  887. line.appendTo("#colors");
  888. // init color wheel
  889. $("input[name='color']").wheelColorPicker({
  890. sliders: (rgb ? "wrgbp" : "whsvp")
  891. }).on("sliderup", function() {
  892. if (rgb) {
  893. var value = $(this).wheelColorPicker("getValue", "css");
  894. sendAction("color", {rgb: value});
  895. } else {
  896. var color = $(this).wheelColorPicker("getColor");
  897. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  898. sendAction("color", {hsv: value});
  899. }
  900. });
  901. }
  902. function initCCT() {
  903. // check if already initialized
  904. var done = $("#cct > div").length;
  905. if (done > 0) { return; }
  906. $("#miredsTemplate").children().clone().appendTo("#cct");
  907. $("#mireds").on("change", function() {
  908. var value = $(this).val();
  909. var parent = $(this).parents(".pure-g");
  910. $("span", parent).html(value);
  911. sendAction("mireds", {mireds: value});
  912. });
  913. }
  914. function initChannels(num) {
  915. // check if already initialized
  916. var done = $("#channels > div").length > 0;
  917. if (done) { return; }
  918. // does it have color channels?
  919. var colors = $("#colors > div").length > 0;
  920. // calculate channels to create
  921. var max = num;
  922. if (colors) {
  923. max = num % 3;
  924. if ((max > 0) & useWhite) {
  925. max--;
  926. if (useCCT) {
  927. max--;
  928. }
  929. }
  930. }
  931. var start = num - max;
  932. var onChannelSliderChange = function() {
  933. var id = $(this).attr("data");
  934. var value = $(this).val();
  935. var parent = $(this).parents(".pure-g");
  936. $("span", parent).html(value);
  937. sendAction("channel", {id: id, value: value});
  938. };
  939. // add channel templates
  940. var i = 0;
  941. var template = $("#channelTemplate").children();
  942. for (i=0; i<max; i++) {
  943. var channel_id = start + i;
  944. var line = $(template).clone();
  945. $("span.slider", line).attr("data", channel_id);
  946. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  947. $("label", line).html("Channel #" + channel_id);
  948. line.appendTo("#channels");
  949. }
  950. // Init channel dropdowns
  951. for (i=0; i<num; i++) {
  952. $("select.islight").append(
  953. $("<option></option>").attr("value",i).text("Channel #" + i));
  954. }
  955. // add brightness template
  956. var template = $("#brightnessTemplate").children();
  957. var line = $(template).clone();
  958. line.appendTo("#channels");
  959. // init bright slider
  960. $("#brightness").on("change", function() {
  961. var value = $(this).val();
  962. var parent = $(this).parents(".pure-g");
  963. $("span", parent).html(value);
  964. sendAction("brightness", {value: value});
  965. });
  966. }
  967. <!-- endRemoveIf(!light)-->
  968. // -----------------------------------------------------------------------------
  969. // RFBridge
  970. // -----------------------------------------------------------------------------
  971. <!-- removeIf(!rfbridge)-->
  972. function rfbLearn() {
  973. var parent = $(this).parents(".pure-g");
  974. var input = $("input", parent);
  975. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  976. }
  977. function rfbForget() {
  978. var parent = $(this).parents(".pure-g");
  979. var input = $("input", parent);
  980. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  981. }
  982. function rfbSend() {
  983. var parent = $(this).parents(".pure-g");
  984. var input = $("input", parent);
  985. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  986. }
  987. function addRfbNode() {
  988. var numNodes = $("#rfbNodes > legend").length;
  989. var template = $("#rfbNodeTemplate").children();
  990. var line = $(template).clone();
  991. var status = true;
  992. $("span", line).html(numNodes);
  993. $(line).find("input").each(function() {
  994. $(this).attr("data-id", numNodes);
  995. $(this).attr("data-status", status ? 1 : 0);
  996. status = !status;
  997. });
  998. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  999. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1000. $(line).find(".button-rfb-send").on("click", rfbSend);
  1001. line.appendTo("#rfbNodes");
  1002. return line;
  1003. }
  1004. <!-- endRemoveIf(!rfbridge)-->
  1005. // -----------------------------------------------------------------------------
  1006. // LightFox
  1007. // -----------------------------------------------------------------------------
  1008. <!-- removeIf(!lightfox)-->
  1009. function lightfoxLearn() {
  1010. sendAction("lightfoxLearn", {});
  1011. }
  1012. function lightfoxClear() {
  1013. sendAction("lightfoxClear", {});
  1014. }
  1015. function initLightfox(data, relayCount) {
  1016. var numNodes = data.length;
  1017. var template = $("#lightfoxNodeTemplate").children();
  1018. var i, j;
  1019. for (i=0; i<numNodes; i++) {
  1020. var $line = $(template).clone();
  1021. $line.find("label > span").text(data[i]["id"]);
  1022. $line.find("select").each(function() {
  1023. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1024. for (j=0; j < relayCount; j++) {
  1025. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1026. }
  1027. $(this).val(data[i]["relay"]);
  1028. status = !status;
  1029. });
  1030. $line.appendTo("#lightfoxNodes");
  1031. }
  1032. var $panel = $("#panel-lightfox")
  1033. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1034. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1035. }
  1036. <!-- endRemoveIf(!lightfox)-->
  1037. // -----------------------------------------------------------------------------
  1038. // Processing
  1039. // -----------------------------------------------------------------------------
  1040. function processData(data) {
  1041. // title
  1042. if ("app_name" in data) {
  1043. var title = data.app_name;
  1044. if ("app_version" in data) {
  1045. title = title + " " + data.app_version;
  1046. }
  1047. $("span[name=title]").html(title);
  1048. if ("hostname" in data) {
  1049. title = data.hostname + " - " + title;
  1050. }
  1051. document.title = title;
  1052. }
  1053. Object.keys(data).forEach(function(key) {
  1054. var i;
  1055. var value = data[key];
  1056. // ---------------------------------------------------------------------
  1057. // Web mode
  1058. // ---------------------------------------------------------------------
  1059. if ("webMode" === key) {
  1060. password = (1 === value);
  1061. $("#layout").toggle(!password);
  1062. $("#password").toggle(password);
  1063. }
  1064. // ---------------------------------------------------------------------
  1065. // Actions
  1066. // ---------------------------------------------------------------------
  1067. if ("action" === key) {
  1068. if ("reload" === data.action) { doReload(1000); }
  1069. return;
  1070. }
  1071. // ---------------------------------------------------------------------
  1072. // RFBridge
  1073. // ---------------------------------------------------------------------
  1074. <!-- removeIf(!rfbridge)-->
  1075. if ("rfbCount" === key) {
  1076. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1077. return;
  1078. }
  1079. if ("rfb" === key) {
  1080. var rfb = data.rfb;
  1081. var size = rfb.size;
  1082. var start = rfb.start;
  1083. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1084. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1085. for (var i=0; i<size; ++i) {
  1086. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1087. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1088. }
  1089. return;
  1090. }
  1091. <!-- endRemoveIf(!rfbridge)-->
  1092. // ---------------------------------------------------------------------
  1093. // LightFox
  1094. // ---------------------------------------------------------------------
  1095. <!-- removeIf(!lightfox)-->
  1096. if ("lightfoxButtons" === key) {
  1097. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1098. return;
  1099. }
  1100. <!-- endRemoveIf(!rfbridge)-->
  1101. // ---------------------------------------------------------------------
  1102. // RFM69
  1103. // ---------------------------------------------------------------------
  1104. <!-- removeIf(!rfm69)-->
  1105. if (key == "packet") {
  1106. var packet = data.packet;
  1107. var d = new Date();
  1108. packets.row.add([
  1109. d.toLocaleTimeString('en-US', { hour12: false }),
  1110. packet.senderID,
  1111. packet.packetID,
  1112. packet.targetID,
  1113. packet.key,
  1114. packet.value,
  1115. packet.rssi,
  1116. packet.duplicates,
  1117. packet.missing,
  1118. ]).draw(false);
  1119. return;
  1120. }
  1121. if (key == "mapping") {
  1122. for (var i in data.mapping) {
  1123. // add a new row
  1124. addMapping();
  1125. // get group
  1126. var line = $("#mapping .pure-g")[i];
  1127. // fill in the blanks
  1128. var mapping = data.mapping[i];
  1129. Object.keys(mapping).forEach(function(key) {
  1130. var id = "input[name=" + key + "]";
  1131. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1132. });
  1133. }
  1134. return;
  1135. }
  1136. <!-- endRemoveIf(!rfm69)-->
  1137. // ---------------------------------------------------------------------
  1138. // Lights
  1139. // ---------------------------------------------------------------------
  1140. <!-- removeIf(!light)-->
  1141. if ("rgb" === key) {
  1142. initColor(true);
  1143. $("input[name='color']").wheelColorPicker("setValue", value, true);
  1144. return;
  1145. }
  1146. if ("hsv" === key) {
  1147. initColor(false);
  1148. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  1149. var chunks = value.split(",");
  1150. var obj = {};
  1151. obj.h = chunks[0] / 360;
  1152. obj.s = chunks[1] / 100;
  1153. obj.v = chunks[2] / 100;
  1154. $("input[name='color']").wheelColorPicker("setColor", obj);
  1155. return;
  1156. }
  1157. if ("brightness" === key) {
  1158. $("#brightness").val(value);
  1159. $("span.brightness").html(value);
  1160. return;
  1161. }
  1162. if ("channels" === key) {
  1163. var len = value.length;
  1164. initChannels(len);
  1165. for (i in value) {
  1166. var ch = value[i];
  1167. $("input.slider[data=" + i + "]").val(ch);
  1168. $("span.slider[data=" + i + "]").html(ch);
  1169. }
  1170. return;
  1171. }
  1172. if ("mireds" === key) {
  1173. $("#mireds").val(value);
  1174. $("span.mireds").html(value);
  1175. return;
  1176. }
  1177. if ("useWhite" === key) {
  1178. useWhite = value;
  1179. }
  1180. if ("useCCT" === key) {
  1181. initCCT();
  1182. useCCT = value;
  1183. }
  1184. <!-- endRemoveIf(!light)-->
  1185. // ---------------------------------------------------------------------
  1186. // Sensors & Magnitudes
  1187. // ---------------------------------------------------------------------
  1188. <!-- removeIf(!sensor)-->
  1189. if ("magnitudesConfig" === key) {
  1190. initMagnitudes(value);
  1191. }
  1192. if ("magnitudes" === key) {
  1193. for (var i=0; i<value.size; ++i) {
  1194. var error = value.error[i] || 0;
  1195. var text = (0 === error) ?
  1196. value.value[i] + magnitudes[i].units :
  1197. magnitudeError(error);
  1198. var element = $("input[name='magnitude'][data='" + i + "']");
  1199. element.val(text);
  1200. }
  1201. return;
  1202. }
  1203. <!-- endRemoveIf(!sensor)-->
  1204. // ---------------------------------------------------------------------
  1205. // WiFi
  1206. // ---------------------------------------------------------------------
  1207. if ("maxNetworks" === key) {
  1208. maxNetworks = parseInt(value, 10);
  1209. return;
  1210. }
  1211. if ("wifi" === key) {
  1212. for (i in value) {
  1213. var wifi = value[i];
  1214. var nwk_line = addNetwork();
  1215. Object.keys(wifi).forEach(function(key) {
  1216. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1217. });
  1218. }
  1219. return;
  1220. }
  1221. if ("scanResult" === key) {
  1222. $("div.scan.loading").hide();
  1223. $("#scanResult").show();
  1224. }
  1225. // -----------------------------------------------------------------------------
  1226. // Home Assistant
  1227. // -----------------------------------------------------------------------------
  1228. if ("haConfig" === key) {
  1229. websock.send("{}");
  1230. $("#haConfig")
  1231. .append(new Text(value))
  1232. .height($("#haConfig")[0].scrollHeight);
  1233. return;
  1234. }
  1235. // -----------------------------------------------------------------------------
  1236. // Relays scheduler
  1237. // -----------------------------------------------------------------------------
  1238. if ("maxSchedules" === key) {
  1239. maxSchedules = parseInt(value, 10);
  1240. return;
  1241. }
  1242. if ("schedules" === key) {
  1243. for (var i=0; i<value.size; ++i) {
  1244. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1245. Object.keys(value).forEach(function(key) {
  1246. if ("size" == key) return;
  1247. var sch_value = value[key][i];
  1248. $("input[name='" + key + "']", sch_line).val(sch_value);
  1249. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1250. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1251. });
  1252. }
  1253. return;
  1254. }
  1255. // ---------------------------------------------------------------------
  1256. // Relays
  1257. // ---------------------------------------------------------------------
  1258. if ("relayState" === key) {
  1259. initRelays(value.status);
  1260. updateRelays(value);
  1261. return;
  1262. }
  1263. // Relay configuration
  1264. if ("relayConfig" === key) {
  1265. initRelayConfig(value);
  1266. return;
  1267. }
  1268. // ---------------------------------------------------------------------
  1269. // LEDs
  1270. // ---------------------------------------------------------------------
  1271. if ("ledConfig" === key) {
  1272. initLeds(value);
  1273. for (var i=0; i<value.length; ++i) {
  1274. $("select[name='ledMode'][data='" + i + "']").val(value[i].mode);
  1275. $("input[name='ledRelay'][data='" + i + "']").val(value[i].relay);
  1276. }
  1277. return;
  1278. }
  1279. // ---------------------------------------------------------------------
  1280. // Domoticz
  1281. // ---------------------------------------------------------------------
  1282. // Domoticz - Relays
  1283. if ("dczRelays" === key) {
  1284. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1285. return;
  1286. }
  1287. // Domoticz - Magnitudes
  1288. <!-- removeIf(!sensor)-->
  1289. if ("dczMagnitudes" === key) {
  1290. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1291. return;
  1292. }
  1293. <!-- endRemoveIf(!sensor)-->
  1294. // ---------------------------------------------------------------------
  1295. // Thingspeak
  1296. // ---------------------------------------------------------------------
  1297. // Thingspeak - Relays
  1298. if ("tspkRelays" === key) {
  1299. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1300. return;
  1301. }
  1302. // Thingspeak - Magnitudes
  1303. <!-- removeIf(!sensor)-->
  1304. if ("tspkMagnitudes" === key) {
  1305. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1306. return;
  1307. }
  1308. <!-- endRemoveIf(!sensor)-->
  1309. // ---------------------------------------------------------------------
  1310. // General
  1311. // ---------------------------------------------------------------------
  1312. // Messages
  1313. if ("message" === key) {
  1314. window.alert(messages[value]);
  1315. return;
  1316. }
  1317. // Web log
  1318. if ("weblog" === key) {
  1319. websock.send("{}");
  1320. msg = value["msg"];
  1321. pre = value["pre"];
  1322. for (var i=0; i < msg.length; ++i) {
  1323. if (pre[i]) {
  1324. $("#weblog").append(new Text(pre[i]));
  1325. }
  1326. $("#weblog").append(new Text(msg[i]));
  1327. }
  1328. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1329. return;
  1330. }
  1331. // Enable options
  1332. var position = key.indexOf("Visible");
  1333. if (position > 0 && position === key.length - 7) {
  1334. var module = key.slice(0,-7);
  1335. $(".module-" + module).css("display", "inherit");
  1336. return;
  1337. }
  1338. if ("deviceip" === key) {
  1339. var a_href = $("span[name='" + key + "']").parent();
  1340. a_href.attr("href", "//" + value);
  1341. a_href.next().attr("href", "telnet://" + value);
  1342. }
  1343. if ("now" === key) {
  1344. now = value;
  1345. return;
  1346. }
  1347. if ("free_size" === key) {
  1348. free_size = parseInt(value, 10);
  1349. }
  1350. // Pre-process
  1351. if ("mqttStatus" === key) {
  1352. value = value ? "CONNECTED" : "NOT CONNECTED";
  1353. }
  1354. if ("ntpStatus" === key) {
  1355. value = value ? "SYNC'D" : "NOT SYNC'D";
  1356. }
  1357. if ("uptime" === key) {
  1358. ago = 0;
  1359. var uptime = parseInt(value, 10);
  1360. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1361. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1362. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1363. var days = uptime;
  1364. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1365. }
  1366. <!-- removeIf(!thermostat)-->
  1367. if ("tmpUnits" == key) {
  1368. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1369. }
  1370. <!-- endRemoveIf(!thermostat)-->
  1371. // ---------------------------------------------------------------------
  1372. // Matching
  1373. // ---------------------------------------------------------------------
  1374. var pre;
  1375. var post;
  1376. // Look for INPUTs
  1377. var input = $("input[name='" + key + "']");
  1378. if (input.length > 0) {
  1379. if (input.attr("type") === "checkbox") {
  1380. input.prop("checked", value);
  1381. } else if (input.attr("type") === "radio") {
  1382. input.val([value]);
  1383. } else {
  1384. pre = input.attr("pre") || "";
  1385. post = input.attr("post") || "";
  1386. input.val(pre + value + post);
  1387. }
  1388. }
  1389. // Look for SPANs
  1390. var span = $("span[name='" + key + "']");
  1391. if (span.length > 0) {
  1392. pre = span.attr("pre") || "";
  1393. post = span.attr("post") || "";
  1394. span.html(pre + value + post);
  1395. }
  1396. // Look for SELECTs
  1397. var select = $("select[name='" + key + "']");
  1398. if (select.length > 0) {
  1399. select.val(value);
  1400. }
  1401. });
  1402. // Auto generate an APIKey if none defined yet
  1403. if ($("input[name='apiKey']").val() === "") {
  1404. generateAPIKey();
  1405. }
  1406. setOriginalsFromValues();
  1407. }
  1408. function hasChanged() {
  1409. var newValue, originalValue;
  1410. if ($(this).attr("type") === "checkbox") {
  1411. newValue = $(this).prop("checked");
  1412. originalValue = ($(this).attr("original") === "true");
  1413. } else {
  1414. newValue = $(this).val();
  1415. originalValue = $(this).attr("original");
  1416. }
  1417. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1418. var action = $(this).attr("action");
  1419. if (typeof originalValue === "undefined") { return; }
  1420. if ("none" === action) { return; }
  1421. if (newValue !== originalValue) {
  1422. if (!hasChanged) {
  1423. ++numChanged;
  1424. if ("reconnect" === action) { ++numReconnect; }
  1425. if ("reboot" === action) { ++numReboot; }
  1426. if ("reload" === action) { ++numReload; }
  1427. $(this).attr("hasChanged", true);
  1428. }
  1429. } else {
  1430. if (hasChanged) {
  1431. --numChanged;
  1432. if ("reconnect" === action) { --numReconnect; }
  1433. if ("reboot" === action) { --numReboot; }
  1434. if ("reload" === action) { --numReload; }
  1435. $(this).attr("hasChanged", false);
  1436. }
  1437. }
  1438. }
  1439. // -----------------------------------------------------------------------------
  1440. // Init & connect
  1441. // -----------------------------------------------------------------------------
  1442. function initUrls(root) {
  1443. var paths = ["ws", "upgrade", "config", "auth"];
  1444. urls["root"] = root;
  1445. paths.forEach(function(path) {
  1446. urls[path] = new URL(path, root);
  1447. urls[path].protocol = root.protocol;
  1448. });
  1449. if (root.protocol == "https:") {
  1450. urls.ws.protocol = "wss:";
  1451. } else {
  1452. urls.ws.protocol = "ws:";
  1453. }
  1454. }
  1455. function connectToURL(url) {
  1456. initUrls(url);
  1457. $.ajax({
  1458. 'method': 'GET',
  1459. 'crossDomain': true,
  1460. 'url': urls.auth.href,
  1461. 'xhrFields': { 'withCredentials': true }
  1462. }).done(function(data) {
  1463. if (websock) { websock.close(); }
  1464. websock = new WebSocket(urls.ws.href);
  1465. websock.onmessage = function(evt) {
  1466. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1467. if (data) {
  1468. processData(data);
  1469. }
  1470. };
  1471. }).fail(function() {
  1472. // Nothing to do, reload page and retry
  1473. });
  1474. }
  1475. function connect(host) {
  1476. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1477. host = "http://" + host;
  1478. }
  1479. connectToURL(new URL(host));
  1480. }
  1481. function connectToCurrentURL() {
  1482. connectToURL(new URL(window.location));
  1483. }
  1484. function getParameterByName(name) {
  1485. var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  1486. return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  1487. }
  1488. $(function() {
  1489. initMessages();
  1490. loadTimeZones();
  1491. createCheckboxes();
  1492. setInterval(function() { keepTime(); }, 1000);
  1493. $(".password-reveal").on("click", toggleVisiblePassword);
  1494. $("#menuLink").on("click", toggleMenu);
  1495. $(".pure-menu-link").on("click", showPanel);
  1496. $("progress").attr({ value: 0, max: 100 });
  1497. $(".button-update").on("click", doUpdate);
  1498. $(".button-update-password").on("click", doUpdatePassword);
  1499. $(".button-generate-password").on("click", doGeneratePassword);
  1500. $(".button-reboot").on("click", doReboot);
  1501. $(".button-reconnect").on("click", doReconnect);
  1502. $(".button-wifi-scan").on("click", doScan);
  1503. $(".button-ha-config").on("click", doHAConfig);
  1504. $(".button-dbgcmd").on("click", doDebugCommand);
  1505. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1506. $(".button-dbg-clear").on("click", doDebugClear);
  1507. $(".button-settings-backup").on("click", doBackup);
  1508. $(".button-settings-restore").on("click", doRestore);
  1509. $(".button-settings-factory").on("click", doFactoryReset);
  1510. $("#uploader").on("change", onFileUpload);
  1511. $(".button-upgrade").on("click", doUpgrade);
  1512. <!-- removeIf(!thermostat)-->
  1513. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1514. <!-- endRemoveIf(!thermostat)-->
  1515. $(".button-apikey").on("click", generateAPIKey);
  1516. $(".button-upgrade-browse").on("click", function() {
  1517. $("input[name='upgrade']")[0].click();
  1518. return false;
  1519. });
  1520. $("input[name='upgrade']").change(function (){
  1521. var file = this.files[0];
  1522. $("input[name='filename']").val(file.name);
  1523. });
  1524. $(".button-add-network").on("click", function() {
  1525. $(".more", addNetwork()).toggle();
  1526. });
  1527. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1528. <!-- removeIf(!light)-->
  1529. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1530. <!-- endRemoveIf(!light)-->
  1531. <!-- removeIf(!rfm69)-->
  1532. $(".button-add-mapping").on('click', addMapping);
  1533. $(".button-del-mapping").on('click', delMapping);
  1534. $(".button-clear-counts").on('click', doClearCounts);
  1535. $(".button-clear-messages").on('click', doClearMessages);
  1536. $(".button-clear-filters").on('click', doClearFilters);
  1537. $('#packets tbody').on('mousedown', 'td', doFilter);
  1538. packets = $('#packets').DataTable({
  1539. "paging": false
  1540. });
  1541. for (var i = 0; i < packets.columns()[0].length; i++) {
  1542. filters[i] = false;
  1543. }
  1544. <!-- endRemoveIf(!rfm69)-->
  1545. $(".gpio-select").each(function(_, elem) {
  1546. initSelectGPIO(elem)
  1547. });
  1548. $(document).on("change", "input", hasChanged);
  1549. $(document).on("change", "select", hasChanged);
  1550. $("textarea").on("dblclick", function() { this.select(); });
  1551. // don't autoconnect when opening from filesystem
  1552. if (window.location.protocol === "file:") { return; }
  1553. // Check host param in query string
  1554. if (host = getParameterByName('host')) {
  1555. connect(host);
  1556. } else {
  1557. connectToCurrentURL();
  1558. }
  1559. });