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.

2261 lines
65 KiB

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