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.

2424 lines
70 KiB

8 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
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
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
5 years ago
5 years ago
8 years ago
8 years ago
6 years ago
6 years ago
5 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
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
8 years ago
8 years ago
6 years ago
8 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
7 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  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 configurationSaved = false;
  13. var ws_pingpong;
  14. var useWhite = false;
  15. var useCCT = false;
  16. var now = 0;
  17. var ago = 0;
  18. <!-- removeIf(!rfm69)-->
  19. var packets;
  20. var filters = [];
  21. <!-- endRemoveIf(!rfm69)-->
  22. <!-- removeIf(!sensor)-->
  23. var magnitudes = [];
  24. <!-- endRemoveIf(!sensor)-->
  25. // -----------------------------------------------------------------------------
  26. // Messages
  27. // -----------------------------------------------------------------------------
  28. function initMessages() {
  29. messages[1] = "Remote update started";
  30. messages[2] = "OTA update started";
  31. messages[3] = "Error parsing data!";
  32. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  33. messages[5] = "Changes saved. You should reboot your board now";
  34. messages[7] = "Passwords do not match!";
  35. messages[8] = "Changes saved";
  36. messages[9] = "No changes detected";
  37. messages[10] = "Session expired, please reload page...";
  38. }
  39. <!-- removeIf(!sensor)-->
  40. function sensorName(id) {
  41. var names = [
  42. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  43. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  44. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  45. "SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
  46. "T6613", "TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
  47. "NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
  48. "EZOPH"
  49. ];
  50. if (1 <= id && id <= names.length) {
  51. return names[id - 1];
  52. }
  53. return null;
  54. }
  55. function magnitudeType(type) {
  56. var types = [
  57. "Temperature", "Humidity", "Pressure",
  58. "Current", "Voltage", "Active Power", "Apparent Power",
  59. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  60. "Analog", "Digital", "Event",
  61. "PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
  62. "Local Dose Rate", "Local Dose Rate",
  63. "Count",
  64. "NO2", "CO", "Resistance", "pH"
  65. ];
  66. if (1 <= type && type <= types.length) {
  67. return types[type - 1];
  68. }
  69. return null;
  70. }
  71. function magnitudeError(error) {
  72. var errors = [
  73. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  74. "Data Error", "I2C Error", "GPIO Error", "Calibration error"
  75. ];
  76. if (0 <= error && error < errors.length) {
  77. return errors[error];
  78. }
  79. return "Error " + error;
  80. }
  81. <!-- endRemoveIf(!sensor)-->
  82. // -----------------------------------------------------------------------------
  83. // Utils
  84. // -----------------------------------------------------------------------------
  85. $.fn.enterKey = function (fnc) {
  86. return this.each(function () {
  87. $(this).keypress(function (ev) {
  88. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  89. if (13 === keycode) {
  90. return fnc.call(this, ev);
  91. }
  92. });
  93. });
  94. };
  95. function keepTime() {
  96. $("span[name='ago']").html(ago);
  97. ago++;
  98. if (0 === now) { return; }
  99. var date = new Date(now * 1000);
  100. var text = date.toISOString().substring(0, 19).replace("T", " ");
  101. $("input[name='now']").val(text);
  102. $("span[name='now']").html(text);
  103. now++;
  104. }
  105. function zeroPad(number, positions) {
  106. return number.toString().padStart(positions, "0");
  107. }
  108. function loadTimeZones() {
  109. var time_zones = [
  110. -720, -660, -600, -570, -540,
  111. -480, -420, -360, -300, -240,
  112. -210, -180, -120, -60, 0,
  113. 60, 120, 180, 210, 240,
  114. 270, 300, 330, 345, 360,
  115. 390, 420, 480, 510, 525,
  116. 540, 570, 600, 630, 660,
  117. 720, 765, 780, 840
  118. ];
  119. for (var i in time_zones) {
  120. var tz = time_zones[i];
  121. var offset = tz >= 0 ? tz : -tz;
  122. var text = "GMT" + (tz >= 0 ? "+" : "-") +
  123. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  124. zeroPad(offset % 60, 2);
  125. $("select[name='ntpOffset']").append(
  126. $("<option></option>")
  127. .attr("value", tz)
  128. .text(text)
  129. );
  130. }
  131. }
  132. function validatePassword(password) {
  133. // http://www.the-art-of-web.com/javascript/validate-password/
  134. // at least one lowercase and one uppercase letter or number
  135. // at least eight characters (letters, numbers or special characters)
  136. // MUST be 8..63 printable ASCII characters. See:
  137. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  138. // https://github.com/xoseperez/espurna/issues/1151
  139. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  140. return (
  141. (password !== undefined)
  142. && (typeof password === "string")
  143. && (password.length > 0)
  144. && re_password.test(password)
  145. );
  146. }
  147. function validateFormPasswords(form) {
  148. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  149. var adminPass1 = passwords.first().val(),
  150. adminPass2 = passwords.last().val();
  151. var formValidity = passwords.first()[0].checkValidity();
  152. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  153. return true;
  154. }
  155. var validPass1 = validatePassword(adminPass1),
  156. validPass2 = validatePassword(adminPass2);
  157. if (formValidity && validPass1 && validPass2) {
  158. return true;
  159. }
  160. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  161. 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!");
  162. }
  163. if (adminPass1 !== adminPass2) {
  164. alert("Passwords are different!");
  165. }
  166. return false;
  167. }
  168. function validateFormHostname(form) {
  169. // RFCs mandate that a hostname's labels may contain only
  170. // the ASCII letters 'a' through 'z' (case-insensitive),
  171. // the digits '0' through '9', and the hyphen.
  172. // Hostname labels cannot begin or end with a hyphen.
  173. // No other symbols, punctuation characters, or blank spaces are permitted.
  174. // Negative lookbehind does not work in Javascript
  175. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
  176. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
  177. var hostname = $("input[name='hostname']", form);
  178. if ("true" !== hostname.attr("hasChanged")) {
  179. return true;
  180. }
  181. if (re_hostname.test(hostname.val())) {
  182. return true;
  183. }
  184. 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.");
  185. return false;
  186. }
  187. function validateForm(form) {
  188. return validateFormPasswords(form) && validateFormHostname(form);
  189. }
  190. // Observe all group settings to selectively update originals based on the current data
  191. var groupSettingsObserver = new MutationObserver(function(mutations) {
  192. mutations.forEach(function(mutation) {
  193. // If any new elements are added, set "settings-target" element as changed to forcibly send the data
  194. var targets = $(mutation.target).attr("data-settings-target");
  195. if (targets !== undefined) {
  196. mutation.addedNodes.forEach(function(node) {
  197. var overrides = [];
  198. targets.split(" ").forEach(function(target) {
  199. var elem = $("[name='" + target + "']", node);
  200. if (!elem.length) return;
  201. var value = getValue(elem);
  202. if ((value === null) || (value === elem[0].defaultValue)) {
  203. overrides.push(elem);
  204. }
  205. });
  206. setOriginalsFromValues($("input,select", node));
  207. overrides.forEach(function(elem) {
  208. elem.attr("hasChanged", "true");
  209. if (elem.prop("tagName") === "SELECT") {
  210. elem.prop("value", 0);
  211. }
  212. });
  213. });
  214. }
  215. // If anything was removed, forcibly send **all** of the group to avoid having any outdated keys
  216. // TODO: hide instead of remove?
  217. var changed = $(mutation.target).attr("hasChanged") === "true";
  218. if (changed || mutation.removedNodes.length) {
  219. $(mutation.target).attr("hasChanged", "true");
  220. $("input,select", mutation.target.childNodes).attr("hasChanged", "true");
  221. }
  222. });
  223. });
  224. // These fields will always be a list of values
  225. function isGroupValue(value) {
  226. var names = [
  227. "ssid", "pass", "gw", "mask", "ip", "dns",
  228. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  229. "relayBoot", "relayPulse", "relayTime", "relayLastSch",
  230. "mqttGroup", "mqttGroupSync", "relayOnDisc",
  231. "dczRelayIdx", "dczMagnitude",
  232. "tspkRelay", "tspkMagnitude",
  233. "ledGPIO", "ledMode", "ledRelay",
  234. "adminPass",
  235. "node", "key", "topic",
  236. "rpnRule", "rpnTopic", "rpnName"
  237. ];
  238. return names.indexOf(value) >= 0;
  239. }
  240. function getValue(element) {
  241. if ($(element).attr("type") === "checkbox") {
  242. return $(element).prop("checked") ? 1 : 0;
  243. } else if ($(element).attr("type") === "radio") {
  244. if (!$(element).prop("checked")) {
  245. return null;
  246. }
  247. }
  248. return $(element).val();
  249. }
  250. function addValue(data, name, value) {
  251. if (name in data) {
  252. if (!Array.isArray(data[name])) {
  253. data[name] = [data[name]];
  254. }
  255. data[name].push(value);
  256. } else if (isGroupValue(name)) {
  257. data[name] = [value];
  258. } else {
  259. data[name] = value;
  260. }
  261. }
  262. function getData(form, changed, cleanup) {
  263. // Populate two sets of data, ones that had been changed and ones that stayed the same
  264. var data = {};
  265. var changed_data = [];
  266. if (cleanup === undefined) {
  267. cleanup = true;
  268. }
  269. if (changed === undefined) {
  270. changed = true;
  271. }
  272. $("input,select", form).each(function() {
  273. if ($(this).attr("data-settings-ignore") === "true") {
  274. return;
  275. }
  276. var name = $(this).attr("name");
  277. var real_name = $(this).attr("data-settings-real-name");
  278. if (real_name !== undefined) {
  279. name = real_name;
  280. }
  281. var value = getValue(this);
  282. if (null !== value) {
  283. var haschanged = ("true" === $(this).attr("hasChanged"));
  284. var indexed = changed_data.indexOf(name) >= 0;
  285. if ((haschanged || !changed) && !indexed) {
  286. changed_data.push(name);
  287. }
  288. addValue(data, name, value);
  289. }
  290. });
  291. // Finally, filter out only fields that had changed.
  292. // Note: We need to preserve dynamic lists like schedules, wifi etc.
  293. // so we don't accidentally break when user deletes entry in the middle
  294. var resulting_data = {};
  295. for (var value in data) {
  296. if (changed_data.indexOf(value) >= 0) {
  297. resulting_data[value] = data[value];
  298. }
  299. }
  300. // Hack: clean-up leftover arrays.
  301. // When empty, the receiving side will prune all keys greater than the current one.
  302. if (cleanup) {
  303. $(".group-settings").each(function() {
  304. var haschanged = ("true" === $(this).attr("hasChanged"));
  305. if (haschanged && !this.children.length) {
  306. var targets = this.dataset.settingsTarget;
  307. if (targets === undefined) return;
  308. targets.split(" ").forEach(function(target) {
  309. resulting_data[target] = [];
  310. });
  311. }
  312. });
  313. }
  314. return resulting_data;
  315. }
  316. function randomString(length, args) {
  317. if (typeof args === "undefined") {
  318. args = {
  319. lowercase: true,
  320. uppercase: true,
  321. numbers: true,
  322. special: true
  323. }
  324. }
  325. var mask = "";
  326. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  327. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  328. if (args.numbers || args.hex) { mask += "0123456789"; }
  329. if (args.hex) { mask += "ABCDEF"; }
  330. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  331. var source = new Uint32Array(length);
  332. var result = new Array(length);
  333. window.crypto.getRandomValues(source).forEach(function(value, i) {
  334. result[i] = mask[value % mask.length];
  335. });
  336. return result.join("");
  337. }
  338. function generateAPIKey() {
  339. var apikey = randomString(16, {hex: true});
  340. $("input[name='apiKey']")
  341. .val(apikey)
  342. .attr("original", "-".repeat(16))
  343. .attr("haschanged", "true");
  344. return false;
  345. }
  346. function generatePassword() {
  347. var password = "";
  348. do {
  349. password = randomString(10);
  350. } while (!validatePassword(password));
  351. return password;
  352. }
  353. function toggleVisiblePassword() {
  354. var elem = this.previousElementSibling;
  355. if (elem.type === "password") {
  356. elem.type = "text";
  357. } else {
  358. elem.type = "password";
  359. }
  360. return false;
  361. }
  362. function doGeneratePassword() {
  363. var elems = $("input", $("#formPassword"));
  364. elems
  365. .val(generatePassword())
  366. .attr("haschanged", "true")
  367. .each(function() {
  368. this.type = "text";
  369. });
  370. return false;
  371. }
  372. function getJson(str) {
  373. try {
  374. return JSON.parse(str);
  375. } catch (e) {
  376. return false;
  377. }
  378. }
  379. <!-- removeIf(!thermostat)-->
  380. function checkTempRangeMin() {
  381. var min = parseInt($("#tempRangeMinInput").val(), 10);
  382. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  383. if (min > max - 1) {
  384. $("#tempRangeMinInput").val(max - 1);
  385. }
  386. }
  387. function checkTempRangeMax() {
  388. var min = parseInt($("#tempRangeMinInput").val(), 10);
  389. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  390. if (max < min + 1) {
  391. $("#tempRangeMaxInput").val(min + 1);
  392. }
  393. }
  394. function doResetThermostatCounters(ask) {
  395. var question = (typeof ask === "undefined" || false === ask) ?
  396. null :
  397. "Are you sure you want to reset burning counters?";
  398. return doAction(question, "thermostat_reset_counters");
  399. }
  400. <!-- endRemoveIf(!thermostat)-->
  401. function initSelectGPIO(select) {
  402. // TODO: properly lock used GPIOs via locking and apply the mask here
  403. var mapping = [
  404. [153, "NONE"],
  405. [0, "0 (FLASH)"],
  406. [1, "1 (U0TXD)"],
  407. [2, "2 (U1TXD)"],
  408. [3, "3 (U0RXD)"],
  409. [4, "4 (SDA)"],
  410. [5, "5 (SCL)"],
  411. [9, "9 (SDD2)"],
  412. [10, "10 (SDD3)"],
  413. [12, "12 (MTDI)"],
  414. [13, "13 (MTCK)"],
  415. [14, "14 (MTMS)"],
  416. [15, "15 (MTDO)"],
  417. [16, "16 (WAKE)"],
  418. ];
  419. for (n in mapping) {
  420. var elem = $('<option value="' + mapping[n][0] + '">');
  421. elem.html(mapping[n][1]);
  422. elem.appendTo(select);
  423. }
  424. }
  425. // -----------------------------------------------------------------------------
  426. // Actions
  427. // -----------------------------------------------------------------------------
  428. function send(json) {
  429. if (debug) console.log(json);
  430. websock.send(json);
  431. }
  432. function sendAction(action, data) {
  433. send(JSON.stringify({action: action, data: data}));
  434. }
  435. function sendConfig(data) {
  436. send(JSON.stringify({config: data}));
  437. }
  438. function setOriginalsFromValues(elems) {
  439. if (typeof elems == "undefined") {
  440. elems = $("input,select");
  441. }
  442. elems.each(function() {
  443. var value;
  444. if ($(this).attr("type") === "checkbox") {
  445. value = $(this).prop("checked");
  446. } else {
  447. value = $(this).val();
  448. }
  449. $(this).attr("original", value);
  450. hasChanged.call(this);
  451. });
  452. }
  453. function resetOriginals() {
  454. setOriginalsFromValues();
  455. $(".group-settings").attr("haschanged", "false")
  456. numReboot = numReconnect = numReload = 0;
  457. configurationSaved = false;
  458. }
  459. function doReload(milliseconds) {
  460. setTimeout(function() {
  461. window.location.reload();
  462. }, parseInt(milliseconds, 10));
  463. }
  464. /**
  465. * Check a file object to see if it is a valid firmware image
  466. * The file first byte should be 0xE9
  467. * @param {file} file File object
  468. * @param {Function} callback Function to call back with the result
  469. */
  470. function checkFirmware(file, callback) {
  471. var reader = new FileReader();
  472. reader.onloadend = function(evt) {
  473. if (FileReader.DONE === evt.target.readyState) {
  474. var magic = evt.target.result.charCodeAt(0);
  475. if ((0x1F === magic) && (0x8B === evt.target.result.charCodeAt(1))) {
  476. callback(true);
  477. return;
  478. }
  479. if (0xE9 !== magic) {
  480. alert("Binary image does not start with a magic byte");
  481. callback(false);
  482. return;
  483. }
  484. var modes = ['QIO', 'QOUT', 'DIO', 'DOUT'];
  485. var flash_mode = evt.target.result.charCodeAt(2);
  486. if (0x03 !== flash_mode) {
  487. var response = window.confirm("Binary image is using " + modes[flash_mode] + " flash mode! Make sure that the device supports it before proceeding.");
  488. callback(response);
  489. } else {
  490. callback(true);
  491. }
  492. }
  493. };
  494. var blob = file.slice(0, 3);
  495. reader.readAsBinaryString(blob);
  496. }
  497. function doUpgrade() {
  498. var file = $("input[name='upgrade']")[0].files[0];
  499. if (typeof file === "undefined") {
  500. alert("First you have to select a file from your computer.");
  501. return false;
  502. }
  503. if (file.size > free_size) {
  504. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  505. return false;
  506. }
  507. checkFirmware(file, function(ok) {
  508. if (!ok) {
  509. return;
  510. }
  511. var data = new FormData();
  512. data.append("upgrade", file, file.name);
  513. var xhr = new XMLHttpRequest();
  514. var msg_ok = "Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.";
  515. var msg_err = "There was an error trying to upload the new image, please try again: ";
  516. var network_error = function(e) {
  517. alert(msg_err + " xhr request " + e.type);
  518. };
  519. xhr.addEventListener("error", network_error, false);
  520. xhr.addEventListener("abort", network_error, false);
  521. xhr.addEventListener("load", function(e) {
  522. $("#upgrade-progress").hide();
  523. if ("OK" === xhr.responseText) {
  524. alert(msg_ok);
  525. doReload(5000);
  526. } else {
  527. alert(msg_err + xhr.status.toString() + " " + xhr.statusText + ", " + xhr.responseText);
  528. }
  529. }, false);
  530. xhr.upload.addEventListener("progress", function(e) {
  531. $("#upgrade-progress").show();
  532. if (e.lengthComputable) {
  533. $("progress").attr({ value: e.loaded, max: e.total });
  534. }
  535. }, false);
  536. xhr.open("POST", urls.upgrade.href);
  537. xhr.send(data);
  538. });
  539. return false;
  540. }
  541. function doUpdatePassword() {
  542. var form = $("#formPassword");
  543. if (validateFormPasswords(form)) {
  544. sendConfig(getData(form, true, false));
  545. }
  546. return false;
  547. }
  548. function checkChanges() {
  549. if (numChanged > 0) {
  550. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  551. if (response) {
  552. doUpdate();
  553. }
  554. }
  555. }
  556. function doAction(question, action) {
  557. checkChanges();
  558. if (question) {
  559. var response = window.confirm(question);
  560. if (false === response) {
  561. return false;
  562. }
  563. }
  564. sendAction(action, {});
  565. doReload(5000);
  566. return false;
  567. }
  568. function doReboot(ask) {
  569. var question = (typeof ask === "undefined" || false === ask) ?
  570. null :
  571. "Are you sure you want to reboot the device?";
  572. return doAction(question, "reboot");
  573. }
  574. function doReconnect(ask) {
  575. var question = (typeof ask === "undefined" || false === ask) ?
  576. null :
  577. "Are you sure you want to disconnect from the current WIFI network?";
  578. return doAction(question, "reconnect");
  579. }
  580. function doCheckOriginals() {
  581. var response;
  582. if (numReboot > 0) {
  583. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  584. if (response) { doReboot(false); }
  585. } else if (numReconnect > 0) {
  586. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  587. if (response) { doReconnect(false); }
  588. } else if (numReload > 0) {
  589. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  590. if (response) { doReload(0); }
  591. }
  592. resetOriginals();
  593. }
  594. function waitForSave(){
  595. if (!configurationSaved) {
  596. setTimeout(waitForSave, 1000);
  597. } else {
  598. doCheckOriginals();
  599. }
  600. }
  601. function doUpdate() {
  602. var forms = $(".form-settings");
  603. if (validateForm(forms)) {
  604. // Get data
  605. sendConfig(getData(forms));
  606. // Empty special fields
  607. $(".pwrExpected").val(0);
  608. $("input[name='snsResetCalibration']").prop("checked", false);
  609. $("input[name='pwrResetCalibration']").prop("checked", false);
  610. $("input[name='pwrResetE']").prop("checked", false);
  611. // Change handling
  612. numChanged = 0;
  613. waitForSave();
  614. }
  615. return false;
  616. }
  617. function doBackup() {
  618. document.getElementById("downloader").src = urls.config.href;
  619. return false;
  620. }
  621. function onFileUpload(event) {
  622. var inputFiles = this.files;
  623. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  624. return false;
  625. }
  626. var inputFile = inputFiles[0];
  627. this.value = "";
  628. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  629. if (!response) {
  630. return false;
  631. }
  632. var reader = new FileReader();
  633. reader.onload = function(e) {
  634. var data = getJson(e.target.result);
  635. if (data) {
  636. sendAction("restore", data);
  637. } else {
  638. window.alert(messages[4]);
  639. }
  640. };
  641. reader.readAsText(inputFile);
  642. return false;
  643. }
  644. function doRestore() {
  645. if (typeof window.FileReader !== "function") {
  646. alert("The file API isn't supported on this browser yet.");
  647. } else {
  648. $("#uploader").click();
  649. }
  650. return false;
  651. }
  652. function doFactoryReset() {
  653. var response = window.confirm("Are you sure you want to restore to factory settings?");
  654. if (!response) {
  655. return false;
  656. }
  657. sendAction("factory_reset", {});
  658. doReload(5000);
  659. return false;
  660. }
  661. function doToggle(id, value) {
  662. sendAction("relay", {id: id, status: value ? 1 : 0 });
  663. return false;
  664. }
  665. function doScan() {
  666. $("#scanResult").html("");
  667. $("div.scan.loading").show();
  668. sendAction("scan", {});
  669. return false;
  670. }
  671. function doHAConfig() {
  672. $("#haConfig")
  673. .text("")
  674. .height(0)
  675. .show();
  676. sendAction("haconfig", {});
  677. return false;
  678. }
  679. function doDebugCommand() {
  680. var el = $("input[name='dbgcmd']");
  681. var command = el.val();
  682. el.val("");
  683. sendAction("dbgcmd", {command: command});
  684. return false;
  685. }
  686. function doDebugClear() {
  687. $("#weblog").text("");
  688. return false;
  689. }
  690. <!-- removeIf(!rfm69)-->
  691. function doClearCounts() {
  692. sendAction("clear-counts", {});
  693. return false;
  694. }
  695. function doClearMessages() {
  696. packets.clear().draw(false);
  697. return false;
  698. }
  699. function doFilter(e) {
  700. var index = packets.cell(this).index();
  701. if (index == 'undefined') return;
  702. var c = index.column;
  703. var column = packets.column(c);
  704. if (filters[c]) {
  705. filters[c] = false;
  706. column.search("");
  707. $(column.header()).removeClass("filtered");
  708. } else {
  709. filters[c] = true;
  710. var data = packets.row(this).data();
  711. if (e.which == 1) {
  712. column.search('^' + data[c] + '$', true, false );
  713. } else {
  714. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  715. }
  716. $(column.header()).addClass("filtered");
  717. }
  718. column.draw();
  719. return false;
  720. }
  721. function doClearFilters() {
  722. for (var i = 0; i < packets.columns()[0].length; i++) {
  723. if (filters[i]) {
  724. filters[i] = false;
  725. var column = packets.column(i);
  726. column.search("");
  727. $(column.header()).removeClass("filtered");
  728. column.draw();
  729. }
  730. }
  731. return false;
  732. }
  733. <!-- endRemoveIf(!rfm69)-->
  734. function delParent() {
  735. var parent = $(this).parent().parent();
  736. $(parent).remove();
  737. }
  738. // -----------------------------------------------------------------------------
  739. // Visualization
  740. // -----------------------------------------------------------------------------
  741. function toggleMenu() {
  742. $("#layout").toggleClass("active");
  743. $("#menu").toggleClass("active");
  744. $("#menuLink").toggleClass("active");
  745. }
  746. function showPanel() {
  747. $(".panel").hide();
  748. if ($("#layout").hasClass("active")) { toggleMenu(); }
  749. $("#" + $(this).attr("data")).show();
  750. }
  751. // -----------------------------------------------------------------------------
  752. // Relays & magnitudes mapping
  753. // -----------------------------------------------------------------------------
  754. function createRelayList(data, container, template_name) {
  755. var current = $("#" + container + " > div").length;
  756. if (current > 0) { return; }
  757. var template = $("#" + template_name + " .pure-g")[0];
  758. for (var i in data) {
  759. var line = $(template).clone();
  760. $("label", line).html("Switch #" + i);
  761. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  762. setOriginalsFromValues($("input", line));
  763. line.appendTo("#" + container);
  764. }
  765. }
  766. <!-- removeIf(!sensor)-->
  767. function createMagnitudeList(data, container, template_name) {
  768. var current = $("#" + container + " > div").length;
  769. if (current > 0) { return; }
  770. var template = $("#" + template_name + " .pure-g")[0];
  771. var size = data.size;
  772. for (var i=0; i<size; ++i) {
  773. var line = $(template).clone();
  774. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  775. $("div.hint", line).html(magnitudes[i].description);
  776. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  777. setOriginalsFromValues($("input", line));
  778. line.appendTo("#" + container);
  779. }
  780. }
  781. <!-- endRemoveIf(!sensor)-->
  782. // -----------------------------------------------------------------------------
  783. // RPN Rules
  784. // -----------------------------------------------------------------------------
  785. function addRPNRule() {
  786. var template = $("#rpnRuleTemplate .pure-g")[0];
  787. var line = $(template).clone();
  788. var tabindex = $("#rpnRules > div").length + 100;
  789. $(line).find("input").each(function() {
  790. $(this).attr("tabindex", tabindex++);
  791. });
  792. $(line).find("button").on('click', delParent);
  793. setOriginalsFromValues($("input", line));
  794. line.appendTo("#rpnRules");
  795. }
  796. function addRPNTopic() {
  797. var template = $("#rpnTopicTemplate .pure-g")[0];
  798. var line = $(template).clone();
  799. var tabindex = $("#rpnTopics > div").length + 120;
  800. $(line).find("input").each(function() {
  801. $(this).attr("tabindex", tabindex++);
  802. });
  803. $(line).find("button").on('click', delParent);
  804. setOriginalsFromValues($("input", line));
  805. line.appendTo("#rpnTopics");
  806. }
  807. // -----------------------------------------------------------------------------
  808. // RFM69
  809. // -----------------------------------------------------------------------------
  810. <!-- removeIf(!rfm69)-->
  811. function addMapping() {
  812. var template = $("#nodeTemplate .pure-g")[0];
  813. var line = $(template).clone();
  814. var tabindex = $("#mapping > div").length * 3 + 50;
  815. $(line).find("input").each(function() {
  816. $(this).attr("tabindex", tabindex++);
  817. });
  818. $(line).find("button").on('click', delParent);
  819. setOriginalsFromValues($("input", line));
  820. line.appendTo("#mapping");
  821. }
  822. <!-- endRemoveIf(!rfm69)-->
  823. // -----------------------------------------------------------------------------
  824. // Wifi
  825. // -----------------------------------------------------------------------------
  826. function numNetworks() {
  827. return $("#networks > div").length;
  828. }
  829. function delNetwork() {
  830. var parent = $(this).parents(".pure-g");
  831. $(parent).remove();
  832. }
  833. function moreNetwork() {
  834. var parent = $(this).parents(".pure-g");
  835. $(".more", parent).toggle();
  836. }
  837. function addNetwork(network) {
  838. var number = numNetworks();
  839. if (number >= maxNetworks) {
  840. alert("Max number of networks reached");
  841. return null;
  842. }
  843. if (network === undefined) {
  844. network = {};
  845. }
  846. var tabindex = 200 + number * 10;
  847. var template = $("#networkTemplate").children();
  848. var line = $(template).clone();
  849. $(line).find("input").each(function() {
  850. $(this).attr("tabindex", tabindex);
  851. tabindex++;
  852. });
  853. $(".password-reveal", line).on("click", toggleVisiblePassword);
  854. $(line).find(".button-del-network").on("click", delNetwork);
  855. $(line).find(".button-more-network").on("click", moreNetwork);
  856. Object.entries(network).forEach(function(pair) {
  857. // XXX: UI deleting this network will only re-use stored values.
  858. var key = pair[0],
  859. val = pair[1];
  860. if (key === "stored") {
  861. $(line).find(".button-del-network").prop("disabled", val);
  862. return;
  863. }
  864. $("input[name='" + key + "']", line).val(val);
  865. });
  866. line.appendTo("#networks");
  867. return line;
  868. }
  869. // -----------------------------------------------------------------------------
  870. // Relays scheduler
  871. // -----------------------------------------------------------------------------
  872. function numSchedules() {
  873. return $("#schedules > div").length;
  874. }
  875. function maxSchedules() {
  876. var value = $("#schedules").attr("data-settings-max");
  877. return parseInt(value === undefined ? 0 : value, 10);
  878. }
  879. function delSchedule() {
  880. var parent = $(this).parents(".pure-g");
  881. $(parent).remove();
  882. }
  883. function moreSchedule() {
  884. var parent = $(this).parents(".pure-g");
  885. $("div.more", parent).toggle();
  886. }
  887. function addSchedule(values) {
  888. var schedules = numSchedules();
  889. if (schedules >= maxSchedules()) {
  890. alert("Max number of schedules reached");
  891. return null;
  892. }
  893. if (values === undefined) {
  894. values = {};
  895. }
  896. var tabindex = 200 + schedules * 10;
  897. var template = $("#scheduleTemplate").children();
  898. var line = $(template).clone();
  899. var type = "none";
  900. switch(values.schType) {
  901. case 1:
  902. type = "switch";
  903. break;
  904. case 2:
  905. type = "light";
  906. break;
  907. case 3:
  908. type = "curtain";
  909. break;
  910. }
  911. template = $("#" + type + "ActionTemplate").children();
  912. $(line).find("#schActionDiv").append(template.clone());
  913. $(line).find("input").each(function() {
  914. $(this).attr("tabindex", tabindex);
  915. tabindex++;
  916. });
  917. $(line).find(".button-del-schedule").on("click", delSchedule);
  918. $(line).find(".button-more-schedule").on("click", moreSchedule);
  919. var schUTC_id = "schUTC" + schedules;
  920. $(line).find("input[name='schUTC']").prop("id", schUTC_id).next().prop("for", schUTC_id);
  921. var schEnabled_id = "schEnabled" + schedules;
  922. $(line).find("input[name='schEnabled']").prop("id", schEnabled_id).next().prop("for", schEnabled_id);
  923. $(line).find("input[type='checkbox']").prop("checked", false);
  924. Object.entries(values).forEach(function(kv) {
  925. var key = kv[0], value = kv[1];
  926. $("input[name='" + key + "']", line).val(value);
  927. $("select[name='" + key + "']", line).prop("value", value);
  928. $("input[type='checkbox'][name='" + key + "']", line).prop("checked", value);
  929. });
  930. line.appendTo("#schedules");
  931. return line;
  932. }
  933. // -----------------------------------------------------------------------------
  934. // Relays
  935. // -----------------------------------------------------------------------------
  936. function initRelays(data) {
  937. var current = $("#relays > div").length;
  938. if (current > 0) { return; }
  939. var template = $("#relayTemplate .pure-g")[0];
  940. for (var i=0; i<data.length; i++) {
  941. // Add relay fields
  942. var line = $(template).clone();
  943. $(".id", line).html(i);
  944. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  945. .prop("id", "relay" + i)
  946. .on("change", function (event) {
  947. var id = parseInt($(event.target).attr("data"), 10);
  948. var status = $(event.target).prop("checked");
  949. doToggle(id, status);
  950. });
  951. $("label.toggle", line).prop("for", "relay" + i)
  952. line.appendTo("#relays");
  953. }
  954. }
  955. function updateRelays(data) {
  956. var size = data.size;
  957. for (var i=0; i<size; ++i) {
  958. var elem = $("input[name='relay'][data='" + i + "']");
  959. elem.prop("checked", data.status[i]);
  960. var lock = {
  961. 0: false,
  962. 1: !data.status[i],
  963. 2: data.status[i]
  964. };
  965. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  966. }
  967. }
  968. function createCheckboxes() {
  969. $("input[type='checkbox']").each(function() {
  970. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  971. $(this).parent().addClass("toggleWrapper");
  972. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  973. });
  974. }
  975. function initRelayConfig(data) {
  976. var current = $("#relayConfig > legend").length; // there is a legend per relay
  977. if (current > 0) { return; }
  978. var size = data.size;
  979. var start = data.start;
  980. var template = $("#relayConfigTemplate").children();
  981. for (var i=start; i<size; ++i) {
  982. var line = $(template).clone();
  983. $("span.id", line).html(i);
  984. $("span.gpio", line).html(data.gpio[i]);
  985. $("select[name='relayBoot']", line).val(data.boot[i]);
  986. $("select[name='relayPulse']", line).val(data.pulse[i]);
  987. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  988. if ("sch_last" in data) {
  989. $("input[name='relayLastSch']", line)
  990. .prop('checked', data.sch_last[i])
  991. .attr("id", "relayLastSch" + i)
  992. .attr("name", "relayLastSch" + i)
  993. .next().attr("for","relayLastSch" + (i));
  994. }
  995. if ("group" in data) {
  996. $("input[name='mqttGroup']", line).val(data.group[i]);
  997. }
  998. if ("group_sync" in data) {
  999. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  1000. }
  1001. if ("on_disc" in data) {
  1002. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  1003. }
  1004. setOriginalsFromValues($("input,select", line));
  1005. line.appendTo("#relayConfig");
  1006. // Populate the relay SELECTs
  1007. $("select.isrelay").append(
  1008. $("<option></option>")
  1009. .attr("value", i)
  1010. .text("Switch #" + i)
  1011. );
  1012. }
  1013. }
  1014. // -----------------------------------------------------------------------------
  1015. // Sensors & Magnitudes
  1016. // -----------------------------------------------------------------------------
  1017. <!-- removeIf(!sensor)-->
  1018. function initMagnitudes(data) {
  1019. // check if already initialized (each magnitude is inside div.pure-g)
  1020. var done = $("#magnitudes > div").length;
  1021. if (done > 0) { return; }
  1022. var size = data.size;
  1023. // add templates
  1024. var template = $("#magnitudeTemplate").children();
  1025. for (var i=0; i<size; ++i) {
  1026. var magnitude = {
  1027. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  1028. "units": data.units[i],
  1029. "description": data.description[i]
  1030. };
  1031. magnitudes.push(magnitude);
  1032. var line = $(template).clone();
  1033. $("label", line).html(magnitude.name);
  1034. $("input", line).attr("data", i);
  1035. $("div.sns-desc", line).html(magnitude.description);
  1036. $("div.sns-info", line).hide();
  1037. line.appendTo("#magnitudes");
  1038. }
  1039. }
  1040. <!-- endRemoveIf(!sensor)-->
  1041. // -----------------------------------------------------------------------------
  1042. // Curtains
  1043. // -----------------------------------------------------------------------------
  1044. <!-- removeIf(!curtain)-->
  1045. //Create the controls for one curtain. It is called when curtain is updated (so created the first time)
  1046. //Let this there as we plan to have more than one curtain per switch
  1047. function initCurtain(data) {
  1048. var current = $("#curtains > div").length;
  1049. if (current > 0) { return; }
  1050. // add curtain template (prepare multi switches)
  1051. var template = $("#curtainTemplate").children();
  1052. var line = $(template).clone();
  1053. // init curtain button
  1054. $(line).find(".button-curtain-open").on("click", function() {
  1055. sendAction("curtainAction", {button: 1});
  1056. $(this).css('background', 'red');
  1057. });
  1058. $(line).find(".button-curtain-pause").on("click", function() {
  1059. sendAction("curtainAction", {button: 0});
  1060. $(this).css('background', 'red');
  1061. });
  1062. $(line).find(".button-curtain-close").on("click", function() {
  1063. sendAction("curtainAction", {button: 2});
  1064. $(this).css('background', 'red');
  1065. });
  1066. line.appendTo("#curtains");
  1067. // init curtain slider
  1068. $("#curtainSet").on("change", function() {
  1069. var value = $(this).val();
  1070. var parent = $(this).parents(".pure-g");
  1071. $("span", parent).html(value);
  1072. sendAction("curtainAction", {position: value});
  1073. });
  1074. }
  1075. function initCurtainConfig(data) {
  1076. var current = $("#curtainConfig > legend").length; // there is a legend per relay
  1077. if (current > 0) { return; }
  1078. // Populate the curtain select
  1079. $("select.iscurtain").append(
  1080. $("<option></option>")
  1081. .attr("value", "0")
  1082. .text("Curtain #" + "0")
  1083. );
  1084. }
  1085. <!-- endRemoveIf(!curtain)-->
  1086. // -----------------------------------------------------------------------------
  1087. // Lights
  1088. // -----------------------------------------------------------------------------
  1089. <!-- removeIf(!light)-->
  1090. // wheelColorPicker accepts:
  1091. // hsv(0...360,0...1,0...1)
  1092. // hsv(0...100%,0...100%,0...100%)
  1093. // While we use:
  1094. // hsv(0...360,0...100%,0...100%)
  1095. function _hsv_round(value) {
  1096. return Math.round(value * 100) / 100;
  1097. }
  1098. function getPickerRGB(picker) {
  1099. return $(picker).wheelColorPicker("getValue", "css");
  1100. }
  1101. function setPickerRGB(picker, value) {
  1102. $(picker).wheelColorPicker("setValue", value, true);
  1103. }
  1104. // TODO: use pct values instead of doing conversion?
  1105. function getPickerHSV(picker) {
  1106. var color = $(picker).wheelColorPicker("getColor");
  1107. return String(Math.ceil(_hsv_round(color.h) * 360))
  1108. + "," + String(Math.ceil(_hsv_round(color.s) * 100))
  1109. + "," + String(Math.ceil(_hsv_round(color.v) * 100));
  1110. }
  1111. function setPickerHSV(picker, value) {
  1112. if (value === getPickerHSV(picker)) return;
  1113. var chunks = value.split(",");
  1114. $(picker).wheelColorPicker("setColor", {
  1115. h: _hsv_round(chunks[0] / 360),
  1116. s: _hsv_round(chunks[1] / 100),
  1117. v: _hsv_round(chunks[2] / 100)
  1118. });
  1119. }
  1120. function initColor(cfg) {
  1121. var rgb = false;
  1122. if (typeof cfg === "object") {
  1123. rgb = cfg.rgb;
  1124. }
  1125. // check if already initialized
  1126. var done = $("#colors > div").length;
  1127. if (done > 0) { return; }
  1128. // add template
  1129. var template = $("#colorTemplate").children();
  1130. var line = $(template).clone();
  1131. line.appendTo("#colors");
  1132. // init color wheel
  1133. $("input[name='color']").wheelColorPicker({
  1134. sliders: (rgb ? "wrgbp" : "whsp")
  1135. }).on("sliderup", function() {
  1136. if (rgb) {
  1137. sendAction("color", {rgb: getPickerRGB(this)});
  1138. } else {
  1139. sendAction("color", {hsv: getPickerHSV(this)});
  1140. }
  1141. });
  1142. }
  1143. function initCCT() {
  1144. // check if already initialized
  1145. var done = $("#cct > div").length;
  1146. if (done > 0) { return; }
  1147. $("#miredsTemplate").children().clone().appendTo("#cct");
  1148. $("#mireds").on("change", function() {
  1149. var value = $(this).val();
  1150. var parent = $(this).parents(".pure-g");
  1151. $("span", parent).html(value);
  1152. sendAction("mireds", {mireds: value});
  1153. });
  1154. }
  1155. function initChannels(num) {
  1156. // check if already initialized
  1157. var done = $("#channels > div").length > 0;
  1158. if (done) { return; }
  1159. // does it have color channels?
  1160. var colors = $("#colors > div").length > 0;
  1161. // calculate channels to create
  1162. var max = num;
  1163. if (colors) {
  1164. max = num % 3;
  1165. if ((max > 0) & useWhite) {
  1166. max--;
  1167. if (useCCT) {
  1168. max--;
  1169. }
  1170. }
  1171. }
  1172. var start = num - max;
  1173. var onChannelSliderChange = function() {
  1174. var id = $(this).attr("data");
  1175. var value = $(this).val();
  1176. var parent = $(this).parents(".pure-g");
  1177. $("span", parent).html(value);
  1178. sendAction("channel", {id: id, value: value});
  1179. };
  1180. // add channel templates
  1181. var i = 0;
  1182. var template = $("#channelTemplate").children();
  1183. for (i=0; i<max; i++) {
  1184. var channel_id = start + i;
  1185. var line = $(template).clone();
  1186. $("span.slider", line).attr("data", channel_id);
  1187. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1188. $("label", line).html("Channel #" + channel_id);
  1189. line.appendTo("#channels");
  1190. }
  1191. // Init channel dropdowns
  1192. for (i=0; i<num; i++) {
  1193. $("select.islight").append(
  1194. $("<option></option>").attr("value",i).text("Channel #" + i));
  1195. }
  1196. // add brightness template
  1197. var template = $("#brightnessTemplate").children();
  1198. var line = $(template).clone();
  1199. line.appendTo("#channels");
  1200. // init bright slider
  1201. $("#brightness").on("change", function() {
  1202. var value = $(this).val();
  1203. var parent = $(this).parents(".pure-g");
  1204. $("span", parent).html(value);
  1205. sendAction("brightness", {value: value});
  1206. });
  1207. }
  1208. <!-- endRemoveIf(!light)-->
  1209. // -----------------------------------------------------------------------------
  1210. // RFBridge
  1211. // -----------------------------------------------------------------------------
  1212. <!-- removeIf(!rfbridge)-->
  1213. function rfbLearn() {
  1214. var parent = $(this).parents(".pure-g");
  1215. var input = $("input", parent);
  1216. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1217. }
  1218. function rfbForget() {
  1219. var parent = $(this).parents(".pure-g");
  1220. var input = $("input", parent);
  1221. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1222. }
  1223. function rfbSend() {
  1224. var parent = $(this).parents(".pure-g");
  1225. var input = $("input", parent);
  1226. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1227. }
  1228. function addRfbNode() {
  1229. var numNodes = $("#rfbNodes > legend").length;
  1230. var template = $("#rfbNodeTemplate").children();
  1231. var line = $(template).clone();
  1232. $("span", line).html(numNodes);
  1233. $(line).find("input").each(function() {
  1234. this.dataset["id"] = numNodes;
  1235. });
  1236. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1237. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1238. $(line).find(".button-rfb-send").on("click", rfbSend);
  1239. line.appendTo("#rfbNodes");
  1240. return line;
  1241. }
  1242. <!-- endRemoveIf(!rfbridge)-->
  1243. // -----------------------------------------------------------------------------
  1244. // LightFox
  1245. // -----------------------------------------------------------------------------
  1246. <!-- removeIf(!lightfox)-->
  1247. function lightfoxLearn() {
  1248. sendAction("lightfoxLearn", {});
  1249. }
  1250. function lightfoxClear() {
  1251. sendAction("lightfoxClear", {});
  1252. }
  1253. function initLightfox(data, relayCount) {
  1254. var numNodes = data.length;
  1255. var template = $("#lightfoxNodeTemplate").children();
  1256. var i, j;
  1257. for (i=0; i<numNodes; i++) {
  1258. var $line = $(template).clone();
  1259. $line.find("label > span").text(data[i]["id"]);
  1260. $line.find("select").each(function() {
  1261. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1262. for (j=0; j < relayCount; j++) {
  1263. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1264. }
  1265. $(this).val(data[i]["relay"]);
  1266. status = !status;
  1267. });
  1268. setOriginalsFromValues($("input,select", $line));
  1269. $line.appendTo("#lightfoxNodes");
  1270. }
  1271. var $panel = $("#panel-lightfox")
  1272. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1273. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1274. }
  1275. <!-- endRemoveIf(!lightfox)-->
  1276. // -----------------------------------------------------------------------------
  1277. // Processing
  1278. // -----------------------------------------------------------------------------
  1279. function processData(data) {
  1280. if (debug) console.log(data);
  1281. // title
  1282. if ("app_name" in data) {
  1283. var title = data.app_name;
  1284. if ("app_version" in data) {
  1285. title = title + " " + data.app_version;
  1286. }
  1287. $("span[name=title]").html(title);
  1288. if ("hostname" in data) {
  1289. title = data.hostname + " - " + title;
  1290. }
  1291. document.title = title;
  1292. }
  1293. Object.keys(data).forEach(function(key) {
  1294. var i;
  1295. var value = data[key];
  1296. // ---------------------------------------------------------------------
  1297. // Web mode
  1298. // ---------------------------------------------------------------------
  1299. if ("webMode" === key) {
  1300. password = (1 === value);
  1301. $("#layout").toggle(!password);
  1302. $("#password").toggle(password);
  1303. }
  1304. // ---------------------------------------------------------------------
  1305. // Actions
  1306. // ---------------------------------------------------------------------
  1307. if ("action" === key) {
  1308. if ("reload" === data.action) { doReload(1000); }
  1309. return;
  1310. }
  1311. // ---------------------------------------------------------------------
  1312. // RFBridge
  1313. // ---------------------------------------------------------------------
  1314. <!-- removeIf(!rfbridge)-->
  1315. if ("rfbCount" === key) {
  1316. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1317. return;
  1318. }
  1319. if ("rfb" === key) {
  1320. var rfb = data.rfb;
  1321. var size = rfb.size;
  1322. var start = rfb.start;
  1323. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1324. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1325. for (var i=0; i<size; ++i) {
  1326. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1327. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1328. }
  1329. return;
  1330. }
  1331. <!-- endRemoveIf(!rfbridge)-->
  1332. // ---------------------------------------------------------------------
  1333. // LightFox
  1334. // ---------------------------------------------------------------------
  1335. <!-- removeIf(!lightfox)-->
  1336. if ("lightfoxButtons" === key) {
  1337. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1338. return;
  1339. }
  1340. <!-- endRemoveIf(!lightfox)-->
  1341. // ---------------------------------------------------------------------
  1342. // RFM69
  1343. // ---------------------------------------------------------------------
  1344. <!-- removeIf(!rfm69)-->
  1345. if (key == "packet") {
  1346. var packet = data.packet;
  1347. var d = new Date();
  1348. packets.row.add([
  1349. d.toLocaleTimeString('en-US', { hour12: false }),
  1350. packet.senderID,
  1351. packet.packetID,
  1352. packet.targetID,
  1353. packet.key,
  1354. packet.value,
  1355. packet.rssi,
  1356. packet.duplicates,
  1357. packet.missing,
  1358. ]).draw(false);
  1359. return;
  1360. }
  1361. if (key == "mapping") {
  1362. for (var i in data.mapping) {
  1363. // add a new row
  1364. addMapping();
  1365. // get group
  1366. var line = $("#mapping .pure-g")[i];
  1367. // fill in the blanks
  1368. var mapping = data.mapping[i];
  1369. Object.keys(mapping).forEach(function(key) {
  1370. var id = "input[name=" + key + "]";
  1371. if ($(id, line).length) $(id, line).val(mapping[key]);
  1372. });
  1373. setOriginalsFromValues($("input", line));
  1374. }
  1375. return;
  1376. }
  1377. <!-- endRemoveIf(!rfm69)-->
  1378. // ---------------------------------------------------------------------
  1379. // RPN Rules
  1380. // ---------------------------------------------------------------------
  1381. if (key == "rpnRules") {
  1382. for (var i in data.rpnRules) {
  1383. // add a new row
  1384. addRPNRule();
  1385. // get group
  1386. var line = $("#rpnRules .pure-g")[i];
  1387. // fill in the blanks
  1388. var rule = data.rpnRules[i];
  1389. $("input", line).val(rule);
  1390. setOriginalsFromValues($("input", line));
  1391. }
  1392. return;
  1393. }
  1394. if (key == "rpnTopics") {
  1395. for (var i in data.rpnTopics) {
  1396. // add a new row
  1397. addRPNTopic();
  1398. // get group
  1399. var line = $("#rpnTopics .pure-g")[i];
  1400. // fill in the blanks
  1401. var topic = data.rpnTopics[i];
  1402. var name = data.rpnNames[i];
  1403. $("input[name='rpnTopic']", line).val(topic);
  1404. $("input[name='rpnName']", line).val(name);
  1405. setOriginalsFromValues($("input", line));
  1406. }
  1407. return;
  1408. }
  1409. if (key == "rpnNames") return;
  1410. // ---------------------------------------------------------------------
  1411. // Curtains
  1412. // ---------------------------------------------------------------------
  1413. <!-- removeIf(!curtain)-->
  1414. function applyCurtain(a, b) {
  1415. $("#curtainGetPicture").css('background', 'linear-gradient(' + a + ', black ' + b + '%, #a0d6ff ' + b + '%)');
  1416. }
  1417. if ("curtainState" === key) {
  1418. initCurtain();
  1419. switch(value.type) {
  1420. case '0': //Roller
  1421. default:
  1422. applyCurtain('180deg', value.get);
  1423. break;
  1424. case '1': //One side left to right
  1425. applyCurtain('90deg', value.get);
  1426. break;
  1427. case '2': //One side right to left
  1428. applyCurtain('270deg', value.get);
  1429. break;
  1430. case '3': //Two sides
  1431. $("#curtainGetPicture").css('background', 'linear-gradient(90deg, black ' + value.get/2 + '%, #a0d6ff ' + value.get/2 + '% ' + (100 - value.get/2) + '%, black ' + (100 - value.get/2) + '%)');
  1432. break;
  1433. }
  1434. $("#curtainSet").val(value.set);
  1435. if(!value.moving) {
  1436. $("button.curtain-button").css('background', 'rgb(66, 184, 221)');
  1437. } else {
  1438. if(!value.button)
  1439. $("button.button-curtain-pause").css('background', 'rgb(192, 0, 0)');
  1440. else if(value.button == 1) {
  1441. $("button.button-curtain-close").css('background', 'rgb(66, 184, 221)');
  1442. $("button.button-curtain-open").css('background', 'rgb(192, 0, 0)');
  1443. }
  1444. else if(value.button == 2) {
  1445. $("button.button-curtain-open").css('background', 'rgb(66, 184, 221)');
  1446. $("button.button-curtain-close").css('background', 'rgb(192, 0, 0)');
  1447. }
  1448. }
  1449. return;
  1450. }
  1451. <!-- endRemoveIf(!curtain)-->
  1452. // ---------------------------------------------------------------------
  1453. // Lights
  1454. // ---------------------------------------------------------------------
  1455. <!-- removeIf(!light)-->
  1456. if ("rgb" === key) {
  1457. initColor({rgb: true});
  1458. setPickerRGB($("input[name='color']"), value);
  1459. return;
  1460. }
  1461. if ("hsv" === key) {
  1462. initColor({hsv: true});
  1463. setPickerHSV($("input[name='color']"), value);
  1464. return;
  1465. }
  1466. if ("brightness" === key) {
  1467. $("#brightness").val(value);
  1468. $("span.brightness").html(value);
  1469. return;
  1470. }
  1471. if ("channels" === key) {
  1472. var len = value.length;
  1473. initChannels(len);
  1474. for (i in value) {
  1475. var ch = value[i];
  1476. $("input.slider[data=" + i + "]").val(ch);
  1477. $("span.slider[data=" + i + "]").html(ch);
  1478. }
  1479. return;
  1480. }
  1481. if ("mireds" === key) {
  1482. $("#mireds").attr("min", value["cold"]);
  1483. $("#mireds").attr("max", value["warm"]);
  1484. $("#mireds").val(value["value"]);
  1485. $("span.mireds").html(value["value"]);
  1486. return;
  1487. }
  1488. if ("useWhite" === key) {
  1489. useWhite = value;
  1490. }
  1491. if ("useCCT" === key) {
  1492. initCCT();
  1493. useCCT = value;
  1494. }
  1495. <!-- endRemoveIf(!light)-->
  1496. // ---------------------------------------------------------------------
  1497. // Sensors & Magnitudes
  1498. // ---------------------------------------------------------------------
  1499. <!-- removeIf(!sensor)-->
  1500. if ("magnitudesConfig" === key) {
  1501. initMagnitudes(value);
  1502. }
  1503. if ("magnitudes" === key) {
  1504. for (var i=0; i<value.size; ++i) {
  1505. var inputElem = $("input[name='magnitude'][data='" + i + "']");
  1506. var infoElem = inputElem.parent().parent().find("div.sns-info");
  1507. var error = value.error[i] || 0;
  1508. var text = (0 === error)
  1509. ? value.value[i] + magnitudes[i].units
  1510. : magnitudeError(error);
  1511. inputElem.val(text);
  1512. if (value.info !== undefined) {
  1513. var info = value.info[i] || 0;
  1514. infoElem.toggle(info != 0);
  1515. infoElem.text(info);
  1516. }
  1517. }
  1518. return;
  1519. }
  1520. <!-- endRemoveIf(!sensor)-->
  1521. // ---------------------------------------------------------------------
  1522. // WiFi
  1523. // ---------------------------------------------------------------------
  1524. if ("wifi" === key) {
  1525. maxNetworks = parseInt(value["max"], 10);
  1526. value["networks"].forEach(function(network) {
  1527. var schema = value["schema"];
  1528. if (schema.length !== network.length) {
  1529. throw "WiFi schema mismatch!";
  1530. }
  1531. var _network = {};
  1532. schema.forEach(function(key, index) {
  1533. _network[key] = network[index];
  1534. });
  1535. addNetwork(_network);
  1536. });
  1537. return;
  1538. }
  1539. if ("scanResult" === key) {
  1540. $("div.scan.loading").hide();
  1541. $("#scanResult").show();
  1542. }
  1543. // -----------------------------------------------------------------------------
  1544. // Home Assistant
  1545. // -----------------------------------------------------------------------------
  1546. if ("haConfig" === key) {
  1547. send("{}");
  1548. $("#haConfig")
  1549. .append(new Text(value))
  1550. .height($("#haConfig")[0].scrollHeight);
  1551. return;
  1552. }
  1553. // -----------------------------------------------------------------------------
  1554. // Relays scheduler
  1555. // -----------------------------------------------------------------------------
  1556. if ("schedules" === key) {
  1557. $("#schedules").attr("data-settings-max", value.max);
  1558. for (var i=0; i<value.size; ++i) {
  1559. // XXX: no
  1560. var sch_map = {};
  1561. Object.keys(value).forEach(function(key) {
  1562. if ("size" == key) return;
  1563. if ("max" == key) return;
  1564. sch_map[key] = value[key][i];
  1565. });
  1566. addSchedule(sch_map);
  1567. }
  1568. return;
  1569. }
  1570. // ---------------------------------------------------------------------
  1571. // Relays
  1572. // ---------------------------------------------------------------------
  1573. if ("relayState" === key) {
  1574. initRelays(value.status);
  1575. updateRelays(value);
  1576. return;
  1577. }
  1578. // Relay configuration
  1579. if ("relayConfig" === key) {
  1580. initRelayConfig(value);
  1581. return;
  1582. }
  1583. // ---------------------------------------------------------------------
  1584. // Curtain(s)
  1585. // ---------------------------------------------------------------------
  1586. <!-- removeIf(!curtain)-->
  1587. // Relay configuration
  1588. if ("curtainConfig" === key) {
  1589. initCurtainConfig(value);
  1590. return;
  1591. }
  1592. <!-- endRemoveIf(!curtain)-->
  1593. // ---------------------------------------------------------------------
  1594. // LEDs
  1595. // ---------------------------------------------------------------------
  1596. if ("led" === key) {
  1597. if($("#ledConfig > div").length > 0) return;
  1598. var schema = value["schema"];
  1599. value["list"].forEach(function(led_data, index) {
  1600. if (schema.length !== led_data.length) {
  1601. throw "LED schema mismatch!";
  1602. }
  1603. var led = {};
  1604. schema.forEach(function(key, index) {
  1605. led[key] = led_data[index];
  1606. });
  1607. var line = $($("#ledConfigTemplate").children()).clone();
  1608. $("span.id", line).html(index);
  1609. $("select", line).attr("data", index);
  1610. $("input", line).attr("data", index);
  1611. $("select[name='ledGPIO']", line).val(led.GPIO);
  1612. // XXX: checkbox implementation depends on unique id
  1613. // $("input[name='ledInv']", line).val(led.Inv);
  1614. $("select[name='ledMode']", line).val(led.Mode);
  1615. $("input[name='ledRelay']", line).val(led.Relay);
  1616. setOriginalsFromValues($("input,select", line));
  1617. line.appendTo("#ledConfig");
  1618. });
  1619. return;
  1620. }
  1621. // ---------------------------------------------------------------------
  1622. // Domoticz
  1623. // ---------------------------------------------------------------------
  1624. // Domoticz - Relays
  1625. if ("dczRelays" === key) {
  1626. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1627. return;
  1628. }
  1629. // Domoticz - Magnitudes
  1630. <!-- removeIf(!sensor)-->
  1631. if ("dczMagnitudes" === key) {
  1632. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1633. return;
  1634. }
  1635. <!-- endRemoveIf(!sensor)-->
  1636. // ---------------------------------------------------------------------
  1637. // Thingspeak
  1638. // ---------------------------------------------------------------------
  1639. // Thingspeak - Relays
  1640. if ("tspkRelays" === key) {
  1641. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1642. return;
  1643. }
  1644. // Thingspeak - Magnitudes
  1645. <!-- removeIf(!sensor)-->
  1646. if ("tspkMagnitudes" === key) {
  1647. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1648. return;
  1649. }
  1650. <!-- endRemoveIf(!sensor)-->
  1651. // ---------------------------------------------------------------------
  1652. // HTTP API
  1653. // ---------------------------------------------------------------------
  1654. // Auto generate an APIKey if none defined yet
  1655. if ("apiVisible" === key) {
  1656. if (data.apiKey === undefined || data.apiKey === "") {
  1657. generateAPIKey();
  1658. }
  1659. }
  1660. // ---------------------------------------------------------------------
  1661. // General
  1662. // ---------------------------------------------------------------------
  1663. // Messages
  1664. if ("message" === key) {
  1665. if (value == 8) {
  1666. configurationSaved = true;
  1667. }
  1668. window.alert(messages[value]);
  1669. return;
  1670. }
  1671. // Web log
  1672. if ("weblog" === key) {
  1673. send("{}");
  1674. var msg = value["msg"];
  1675. var pre = value["pre"];
  1676. for (var i=0; i < msg.length; ++i) {
  1677. if (pre[i]) {
  1678. $("#weblog").append(new Text(pre[i]));
  1679. }
  1680. $("#weblog").append(new Text(msg[i]));
  1681. }
  1682. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1683. return;
  1684. }
  1685. // Enable options
  1686. var position = key.indexOf("Visible");
  1687. if (position > 0 && position === key.length - 7) {
  1688. var module = key.slice(0,-7);
  1689. if (module == "sch") {
  1690. $("li.module-" + module).css("display", "inherit");
  1691. $("div.module-" + module).css("display", "flex");
  1692. return;
  1693. }
  1694. $(".module-" + module).css("display", "inherit");
  1695. return;
  1696. }
  1697. if ("deviceip" === key) {
  1698. var a_href = $("span[name='" + key + "']").parent();
  1699. a_href.attr("href", "//" + value);
  1700. a_href.next().attr("href", "telnet://" + value);
  1701. }
  1702. if ("now" === key) {
  1703. now = value;
  1704. return;
  1705. }
  1706. if ("free_size" === key) {
  1707. free_size = parseInt(value, 10);
  1708. }
  1709. // Pre-process
  1710. if ("mqttStatus" === key) {
  1711. value = value ? "CONNECTED" : "NOT CONNECTED";
  1712. }
  1713. if ("ntpStatus" === key) {
  1714. value = value ? "SYNC'D" : "NOT SYNC'D";
  1715. }
  1716. if ("uptime" === key) {
  1717. ago = 0;
  1718. var uptime = parseInt(value, 10);
  1719. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1720. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1721. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1722. var days = uptime;
  1723. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1724. }
  1725. <!-- removeIf(!thermostat)-->
  1726. if ("tmpUnits" == key) {
  1727. $("span.tmpUnit").html(data[key] == 3 ? "ºF" : "ºC");
  1728. }
  1729. <!-- endRemoveIf(!thermostat)-->
  1730. // ---------------------------------------------------------------------
  1731. // Matching
  1732. // ---------------------------------------------------------------------
  1733. var elems = [];
  1734. var pre;
  1735. var post;
  1736. // Look for INPUTs
  1737. var input = $("input[name='" + key + "']");
  1738. if (input.length > 0) {
  1739. if (input.attr("type") === "checkbox") {
  1740. input.prop("checked", value);
  1741. } else if (input.attr("type") === "radio") {
  1742. input.val([value]);
  1743. } else {
  1744. pre = input.attr("pre") || "";
  1745. post = input.attr("post") || "";
  1746. input.val(pre + value + post);
  1747. }
  1748. elems.push(input);
  1749. }
  1750. // Look for SPANs
  1751. var span = $("span[name='" + key + "']");
  1752. if (span.length > 0) {
  1753. if (Array.isArray(value)) {
  1754. value.forEach(function(elem) {
  1755. span.append(elem);
  1756. span.append('</br>');
  1757. elems.push(span);
  1758. });
  1759. } else {
  1760. pre = span.attr("pre") || "";
  1761. post = span.attr("post") || "";
  1762. span.html(pre + value + post);
  1763. elems.push(span);
  1764. }
  1765. }
  1766. // Look for SELECTs
  1767. var select = $("select[name='" + key + "']");
  1768. if (select.length > 0) {
  1769. select.val(value);
  1770. elems.push(select);
  1771. }
  1772. setOriginalsFromValues($(elems));
  1773. });
  1774. }
  1775. function hasChanged() {
  1776. var newValue, originalValue;
  1777. if ($(this).attr("type") === "checkbox") {
  1778. newValue = $(this).prop("checked");
  1779. originalValue = ($(this).attr("original") === "true");
  1780. } else {
  1781. newValue = $(this).val();
  1782. originalValue = $(this).attr("original");
  1783. }
  1784. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1785. var action = $(this).attr("action");
  1786. if (typeof originalValue === "undefined") { return; }
  1787. if ("none" === action) { return; }
  1788. if (newValue !== originalValue) {
  1789. if (!hasChanged) {
  1790. ++numChanged;
  1791. if ("reconnect" === action) { ++numReconnect; }
  1792. if ("reboot" === action) { ++numReboot; }
  1793. if ("reload" === action) { ++numReload; }
  1794. }
  1795. $(this).attr("hasChanged", true);
  1796. } else {
  1797. if (hasChanged) {
  1798. --numChanged;
  1799. if ("reconnect" === action) { --numReconnect; }
  1800. if ("reboot" === action) { --numReboot; }
  1801. if ("reload" === action) { --numReload; }
  1802. }
  1803. $(this).attr("hasChanged", false);
  1804. }
  1805. }
  1806. // -----------------------------------------------------------------------------
  1807. // Init & connect
  1808. // -----------------------------------------------------------------------------
  1809. function initUrls(root) {
  1810. var paths = ["ws", "upgrade", "config", "auth"];
  1811. urls["root"] = root;
  1812. paths.forEach(function(path) {
  1813. urls[path] = new URL(path, root);
  1814. urls[path].protocol = root.protocol;
  1815. });
  1816. if (root.protocol == "https:") {
  1817. urls.ws.protocol = "wss:";
  1818. } else {
  1819. urls.ws.protocol = "ws:";
  1820. }
  1821. }
  1822. function connectToURL(url) {
  1823. initUrls(url);
  1824. fetch(urls.auth.href, {
  1825. 'method': 'GET',
  1826. 'cors': true,
  1827. 'credentials': 'same-origin'
  1828. }).then(function(response) {
  1829. // Nothing to do, reload page and retry
  1830. if (response.status != 200) {
  1831. doReload(5000);
  1832. return;
  1833. }
  1834. // update websock object
  1835. if (websock) { websock.close(); }
  1836. websock = new WebSocket(urls.ws.href);
  1837. websock.onmessage = function(evt) {
  1838. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1839. if (data) {
  1840. processData(data);
  1841. }
  1842. };
  1843. websock.onclose = function(evt) {
  1844. clearInterval(ws_pingpong);
  1845. if (window.confirm("Connection lost with the device, click OK to refresh the page")) {
  1846. $("#layout").toggle(false);
  1847. window.location.reload();
  1848. }
  1849. }
  1850. websock.onopen = function(evt) {
  1851. ws_pingpong = setInterval(function() { sendAction("ping", {}); }, 5000);
  1852. }
  1853. }).catch(function(error) {
  1854. console.log(error);
  1855. doReload(5000);
  1856. });
  1857. }
  1858. function connect(host) {
  1859. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1860. host = "http://" + host;
  1861. }
  1862. connectToURL(new URL(host));
  1863. }
  1864. function connectToCurrentURL() {
  1865. connectToURL(new URL(window.location));
  1866. }
  1867. $(function() {
  1868. initMessages();
  1869. loadTimeZones();
  1870. createCheckboxes();
  1871. setInterval(function() { keepTime(); }, 1000);
  1872. $(".password-reveal").on("click", toggleVisiblePassword);
  1873. $("#menuLink").on("click", toggleMenu);
  1874. $(".pure-menu-link").on("click", showPanel);
  1875. $("progress").attr({ value: 0, max: 100 });
  1876. $(".button-update").on("click", doUpdate);
  1877. $(".button-update-password").on("click", doUpdatePassword);
  1878. $(".button-generate-password").on("click", doGeneratePassword);
  1879. $(".button-reboot").on("click", doReboot);
  1880. $(".button-reconnect").on("click", doReconnect);
  1881. $(".button-wifi-scan").on("click", doScan);
  1882. $(".button-ha-config").on("click", doHAConfig);
  1883. $(".button-dbgcmd").on("click", doDebugCommand);
  1884. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1885. $(".button-dbg-clear").on("click", doDebugClear);
  1886. $(".button-settings-backup").on("click", doBackup);
  1887. $(".button-settings-restore").on("click", doRestore);
  1888. $(".button-settings-factory").on("click", doFactoryReset);
  1889. $("#uploader").on("change", onFileUpload);
  1890. $(".button-upgrade").on("click", doUpgrade);
  1891. <!-- removeIf(!thermostat)-->
  1892. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1893. <!-- endRemoveIf(!thermostat)-->
  1894. $(".button-apikey").on("click", generateAPIKey);
  1895. $(".button-upgrade-browse").on("click", function() {
  1896. $("input[name='upgrade']")[0].click();
  1897. return false;
  1898. });
  1899. $("input[name='upgrade']").change(function (){
  1900. var file = this.files[0];
  1901. $("input[name='filename']").val(file.name);
  1902. });
  1903. $(".button-add-network").on("click", function() {
  1904. $(".more", addNetwork()).toggle();
  1905. });
  1906. $(".button-add-switch-schedule").on("click", function() {
  1907. addSchedule({schType: 1, schSwitch: -1});
  1908. });
  1909. <!-- removeIf(!light)-->
  1910. $(".button-add-light-schedule").on("click", function() {
  1911. addSchedule({schType: 2, schSwitch: -1});
  1912. });
  1913. <!-- endRemoveIf(!light)-->
  1914. <!-- removeIf(!curtain)-->
  1915. $(".button-add-curtain-schedule").on("click", function() {
  1916. addSchedule({schType: 3, schSwitch: -1});
  1917. });
  1918. <!-- endRemoveIf(!curtain)-->
  1919. $(".button-add-rpnrule").on('click', addRPNRule);
  1920. $(".button-add-rpntopic").on('click', addRPNTopic);
  1921. $(".button-del-parent").on('click', delParent);
  1922. <!-- removeIf(!rfm69)-->
  1923. $(".button-add-mapping").on('click', addMapping);
  1924. $(".button-clear-counts").on('click', doClearCounts);
  1925. $(".button-clear-messages").on('click', doClearMessages);
  1926. $(".button-clear-filters").on('click', doClearFilters);
  1927. $('#packets tbody').on('mousedown', 'td', doFilter);
  1928. packets = $('#packets').DataTable({
  1929. "paging": false
  1930. });
  1931. for (var i = 0; i < packets.columns()[0].length; i++) {
  1932. filters[i] = false;
  1933. }
  1934. <!-- endRemoveIf(!rfm69)-->
  1935. $(".gpio-select").each(function(_, elem) {
  1936. initSelectGPIO(elem)
  1937. });
  1938. $(document).on("change", "input", hasChanged);
  1939. $(document).on("change", "select", hasChanged);
  1940. $("textarea").on("dblclick", function() { this.select(); });
  1941. resetOriginals();
  1942. $(".group-settings").each(function() {
  1943. groupSettingsObserver.observe(this, {childList: true});
  1944. });
  1945. // don't autoconnect when opening from filesystem
  1946. if (window.location.protocol === "file:") {
  1947. processData({"webMode": 0});
  1948. return;
  1949. }
  1950. // Check host param in query string
  1951. var search = new URLSearchParams(window.location.search),
  1952. host = search.get("host");
  1953. if (host !== null) {
  1954. connect(host);
  1955. } else {
  1956. connectToCurrentURL();
  1957. }
  1958. });