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.

1988 lines
57 KiB

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