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.

2272 lines
65 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
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. "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 = (1 === values.schType) ? "switch" : "light";
  900. template = $("#" + type + "ActionTemplate").children();
  901. $(line).find("#schActionDiv").append(template.clone());
  902. $(line).find("input").each(function() {
  903. $(this).attr("tabindex", tabindex);
  904. tabindex++;
  905. });
  906. $(line).find(".button-del-schedule").on("click", delSchedule);
  907. $(line).find(".button-more-schedule").on("click", moreSchedule);
  908. var schUTC_id = "schUTC" + schedules;
  909. $(line).find("input[name='schUTC']").prop("id", schUTC_id).next().prop("for", schUTC_id);
  910. var schEnabled_id = "schEnabled" + schedules;
  911. $(line).find("input[name='schEnabled']").prop("id", schEnabled_id).next().prop("for", schEnabled_id);
  912. $(line).find("input[type='checkbox']").prop("checked", false);
  913. Object.entries(values).forEach(function(kv) {
  914. var key = kv[0], value = kv[1];
  915. $("input[name='" + key + "']", line).val(value);
  916. $("select[name='" + key + "']", line).prop("value", value);
  917. $("input[type='checkbox'][name='" + key + "']", line).prop("checked", value);
  918. });
  919. line.appendTo("#schedules");
  920. return line;
  921. }
  922. // -----------------------------------------------------------------------------
  923. // Relays
  924. // -----------------------------------------------------------------------------
  925. function initRelays(data) {
  926. var current = $("#relays > div").length;
  927. if (current > 0) { return; }
  928. var template = $("#relayTemplate .pure-g")[0];
  929. for (var i=0; i<data.length; i++) {
  930. // Add relay fields
  931. var line = $(template).clone();
  932. $(".id", line).html(i);
  933. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  934. .prop("id", "relay" + i)
  935. .on("change", function (event) {
  936. var id = parseInt($(event.target).attr("data"), 10);
  937. var status = $(event.target).prop("checked");
  938. doToggle(id, status);
  939. });
  940. $("label.toggle", line).prop("for", "relay" + i)
  941. line.appendTo("#relays");
  942. }
  943. }
  944. function updateRelays(data) {
  945. var size = data.size;
  946. for (var i=0; i<size; ++i) {
  947. var elem = $("input[name='relay'][data='" + i + "']");
  948. elem.prop("checked", data.status[i]);
  949. var lock = {
  950. 0: false,
  951. 1: !data.status[i],
  952. 2: data.status[i]
  953. };
  954. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  955. }
  956. }
  957. function createCheckboxes() {
  958. $("input[type='checkbox']").each(function() {
  959. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  960. $(this).parent().addClass("toggleWrapper");
  961. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  962. });
  963. }
  964. function initRelayConfig(data) {
  965. var current = $("#relayConfig > legend").length; // there is a legend per relay
  966. if (current > 0) { return; }
  967. var size = data.size;
  968. var start = data.start;
  969. var template = $("#relayConfigTemplate").children();
  970. for (var i=start; i<size; ++i) {
  971. var line = $(template).clone();
  972. $("span.id", line).html(i);
  973. $("span.gpio", line).html(data.gpio[i]);
  974. $("select[name='relayBoot']", line).val(data.boot[i]);
  975. $("select[name='relayPulse']", line).val(data.pulse[i]);
  976. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  977. if ("sch_last" in data) {
  978. $("input[name='relayLastSch']", line)
  979. .prop('checked', data.sch_last[i])
  980. .attr("id", "relayLastSch" + i)
  981. .attr("name", "relayLastSch" + i)
  982. .next().attr("for","relayLastSch" + (i));
  983. }
  984. if ("group" in data) {
  985. $("input[name='mqttGroup']", line).val(data.group[i]);
  986. }
  987. if ("group_sync" in data) {
  988. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  989. }
  990. if ("on_disc" in data) {
  991. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  992. }
  993. setOriginalsFromValues($("input,select", line));
  994. line.appendTo("#relayConfig");
  995. // Populate the relay SELECTs
  996. $("select.isrelay").append(
  997. $("<option></option>")
  998. .attr("value", i)
  999. .text("Switch #" + i)
  1000. );
  1001. }
  1002. }
  1003. function initLeds(data) {
  1004. var current = $("#ledConfig > div").length;
  1005. if (current > 0) { return; }
  1006. var size = data.length;
  1007. var template = $("#ledConfigTemplate").children();
  1008. for (var i=0; i<size; ++i) {
  1009. var line = $(template).clone();
  1010. $("span.id", line).html(i);
  1011. $("select", line).attr("data", i);
  1012. $("input", line).attr("data", i);
  1013. line.appendTo("#ledConfig");
  1014. }
  1015. }
  1016. // -----------------------------------------------------------------------------
  1017. // Sensors & Magnitudes
  1018. // -----------------------------------------------------------------------------
  1019. <!-- removeIf(!sensor)-->
  1020. function initMagnitudes(data) {
  1021. // check if already initialized (each magnitude is inside div.pure-g)
  1022. var done = $("#magnitudes > div").length;
  1023. if (done > 0) { return; }
  1024. var size = data.size;
  1025. // add templates
  1026. var template = $("#magnitudeTemplate").children();
  1027. for (var i=0; i<size; ++i) {
  1028. var magnitude = {
  1029. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  1030. "units": data.units[i],
  1031. "description": data.description[i]
  1032. };
  1033. magnitudes.push(magnitude);
  1034. var line = $(template).clone();
  1035. $("label", line).html(magnitude.name);
  1036. $("div.hint", line).html(magnitude.description);
  1037. $("input", line).attr("data", i);
  1038. line.appendTo("#magnitudes");
  1039. }
  1040. }
  1041. <!-- endRemoveIf(!sensor)-->
  1042. // -----------------------------------------------------------------------------
  1043. // Lights
  1044. // -----------------------------------------------------------------------------
  1045. <!-- removeIf(!light)-->
  1046. // wheelColorPicker accepts:
  1047. // hsv(0...360,0...1,0...1)
  1048. // hsv(0...100%,0...100%,0...100%)
  1049. // While we use:
  1050. // hsv(0...360,0...100%,0...100%)
  1051. function _hsv_round(value) {
  1052. return Math.round(value * 100) / 100;
  1053. }
  1054. function getPickerRGB(picker) {
  1055. return $(picker).wheelColorPicker("getValue", "css");
  1056. }
  1057. function setPickerRGB(picker, value) {
  1058. $(picker).wheelColorPicker("setValue", value, true);
  1059. }
  1060. // TODO: use pct values instead of doing conversion?
  1061. function getPickerHSV(picker) {
  1062. var color = $(picker).wheelColorPicker("getColor");
  1063. return String(Math.ceil(_hsv_round(color.h) * 360))
  1064. + "," + String(Math.ceil(_hsv_round(color.s) * 100))
  1065. + "," + String(Math.ceil(_hsv_round(color.v) * 100));
  1066. }
  1067. function setPickerHSV(picker, value) {
  1068. if (value === getPickerHSV(picker)) return;
  1069. var chunks = value.split(",");
  1070. $(picker).wheelColorPicker("setColor", {
  1071. h: _hsv_round(chunks[0] / 360),
  1072. s: _hsv_round(chunks[1] / 100),
  1073. v: _hsv_round(chunks[2] / 100)
  1074. });
  1075. }
  1076. function initColor(cfg) {
  1077. var rgb = false;
  1078. if (typeof cfg === "object") {
  1079. rgb = cfg.rgb;
  1080. }
  1081. // check if already initialized
  1082. var done = $("#colors > div").length;
  1083. if (done > 0) { return; }
  1084. // add template
  1085. var template = $("#colorTemplate").children();
  1086. var line = $(template).clone();
  1087. line.appendTo("#colors");
  1088. // init color wheel
  1089. $("input[name='color']").wheelColorPicker({
  1090. sliders: (rgb ? "wrgbp" : "whsp")
  1091. }).on("sliderup", function() {
  1092. if (rgb) {
  1093. sendAction("color", {rgb: getPickerRGB(this)});
  1094. } else {
  1095. sendAction("color", {hsv: getPickerHSV(this)});
  1096. }
  1097. });
  1098. }
  1099. function initCCT() {
  1100. // check if already initialized
  1101. var done = $("#cct > div").length;
  1102. if (done > 0) { return; }
  1103. $("#miredsTemplate").children().clone().appendTo("#cct");
  1104. $("#mireds").on("change", function() {
  1105. var value = $(this).val();
  1106. var parent = $(this).parents(".pure-g");
  1107. $("span", parent).html(value);
  1108. sendAction("mireds", {mireds: value});
  1109. });
  1110. }
  1111. function initChannels(num) {
  1112. // check if already initialized
  1113. var done = $("#channels > div").length > 0;
  1114. if (done) { return; }
  1115. // does it have color channels?
  1116. var colors = $("#colors > div").length > 0;
  1117. // calculate channels to create
  1118. var max = num;
  1119. if (colors) {
  1120. max = num % 3;
  1121. if ((max > 0) & useWhite) {
  1122. max--;
  1123. if (useCCT) {
  1124. max--;
  1125. }
  1126. }
  1127. }
  1128. var start = num - max;
  1129. var onChannelSliderChange = function() {
  1130. var id = $(this).attr("data");
  1131. var value = $(this).val();
  1132. var parent = $(this).parents(".pure-g");
  1133. $("span", parent).html(value);
  1134. sendAction("channel", {id: id, value: value});
  1135. };
  1136. // add channel templates
  1137. var i = 0;
  1138. var template = $("#channelTemplate").children();
  1139. for (i=0; i<max; i++) {
  1140. var channel_id = start + i;
  1141. var line = $(template).clone();
  1142. $("span.slider", line).attr("data", channel_id);
  1143. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1144. $("label", line).html("Channel #" + channel_id);
  1145. line.appendTo("#channels");
  1146. }
  1147. // Init channel dropdowns
  1148. for (i=0; i<num; i++) {
  1149. $("select.islight").append(
  1150. $("<option></option>").attr("value",i).text("Channel #" + i));
  1151. }
  1152. // add brightness template
  1153. var template = $("#brightnessTemplate").children();
  1154. var line = $(template).clone();
  1155. line.appendTo("#channels");
  1156. // init bright slider
  1157. $("#brightness").on("change", function() {
  1158. var value = $(this).val();
  1159. var parent = $(this).parents(".pure-g");
  1160. $("span", parent).html(value);
  1161. sendAction("brightness", {value: value});
  1162. });
  1163. }
  1164. <!-- endRemoveIf(!light)-->
  1165. // -----------------------------------------------------------------------------
  1166. // RFBridge
  1167. // -----------------------------------------------------------------------------
  1168. <!-- removeIf(!rfbridge)-->
  1169. function rfbLearn() {
  1170. var parent = $(this).parents(".pure-g");
  1171. var input = $("input", parent);
  1172. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1173. }
  1174. function rfbForget() {
  1175. var parent = $(this).parents(".pure-g");
  1176. var input = $("input", parent);
  1177. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1178. }
  1179. function rfbSend() {
  1180. var parent = $(this).parents(".pure-g");
  1181. var input = $("input", parent);
  1182. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1183. }
  1184. function addRfbNode() {
  1185. var numNodes = $("#rfbNodes > legend").length;
  1186. var template = $("#rfbNodeTemplate").children();
  1187. var line = $(template).clone();
  1188. $("span", line).html(numNodes);
  1189. $(line).find("input").each(function() {
  1190. this.dataset["id"] = numNodes;
  1191. });
  1192. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1193. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1194. $(line).find(".button-rfb-send").on("click", rfbSend);
  1195. line.appendTo("#rfbNodes");
  1196. return line;
  1197. }
  1198. <!-- endRemoveIf(!rfbridge)-->
  1199. // -----------------------------------------------------------------------------
  1200. // LightFox
  1201. // -----------------------------------------------------------------------------
  1202. <!-- removeIf(!lightfox)-->
  1203. function lightfoxLearn() {
  1204. sendAction("lightfoxLearn", {});
  1205. }
  1206. function lightfoxClear() {
  1207. sendAction("lightfoxClear", {});
  1208. }
  1209. function initLightfox(data, relayCount) {
  1210. var numNodes = data.length;
  1211. var template = $("#lightfoxNodeTemplate").children();
  1212. var i, j;
  1213. for (i=0; i<numNodes; i++) {
  1214. var $line = $(template).clone();
  1215. $line.find("label > span").text(data[i]["id"]);
  1216. $line.find("select").each(function() {
  1217. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1218. for (j=0; j < relayCount; j++) {
  1219. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1220. }
  1221. $(this).val(data[i]["relay"]);
  1222. status = !status;
  1223. });
  1224. setOriginalsFromValues($("input,select", $line));
  1225. $line.appendTo("#lightfoxNodes");
  1226. }
  1227. var $panel = $("#panel-lightfox")
  1228. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1229. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1230. }
  1231. <!-- endRemoveIf(!lightfox)-->
  1232. // -----------------------------------------------------------------------------
  1233. // Processing
  1234. // -----------------------------------------------------------------------------
  1235. function processData(data) {
  1236. if (debug) console.log(data);
  1237. // title
  1238. if ("app_name" in data) {
  1239. var title = data.app_name;
  1240. if ("app_version" in data) {
  1241. title = title + " " + data.app_version;
  1242. }
  1243. $("span[name=title]").html(title);
  1244. if ("hostname" in data) {
  1245. title = data.hostname + " - " + title;
  1246. }
  1247. document.title = title;
  1248. }
  1249. Object.keys(data).forEach(function(key) {
  1250. var i;
  1251. var value = data[key];
  1252. // ---------------------------------------------------------------------
  1253. // Web mode
  1254. // ---------------------------------------------------------------------
  1255. if ("webMode" === key) {
  1256. password = (1 === value);
  1257. $("#layout").toggle(!password);
  1258. $("#password").toggle(password);
  1259. }
  1260. // ---------------------------------------------------------------------
  1261. // Actions
  1262. // ---------------------------------------------------------------------
  1263. if ("action" === key) {
  1264. if ("reload" === data.action) { doReload(1000); }
  1265. return;
  1266. }
  1267. // ---------------------------------------------------------------------
  1268. // RFBridge
  1269. // ---------------------------------------------------------------------
  1270. <!-- removeIf(!rfbridge)-->
  1271. if ("rfbCount" === key) {
  1272. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1273. return;
  1274. }
  1275. if ("rfb" === key) {
  1276. var rfb = data.rfb;
  1277. var size = rfb.size;
  1278. var start = rfb.start;
  1279. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1280. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1281. for (var i=0; i<size; ++i) {
  1282. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1283. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1284. }
  1285. return;
  1286. }
  1287. <!-- endRemoveIf(!rfbridge)-->
  1288. // ---------------------------------------------------------------------
  1289. // LightFox
  1290. // ---------------------------------------------------------------------
  1291. <!-- removeIf(!lightfox)-->
  1292. if ("lightfoxButtons" === key) {
  1293. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1294. return;
  1295. }
  1296. <!-- endRemoveIf(!lightfox)-->
  1297. // ---------------------------------------------------------------------
  1298. // RFM69
  1299. // ---------------------------------------------------------------------
  1300. <!-- removeIf(!rfm69)-->
  1301. if (key == "packet") {
  1302. var packet = data.packet;
  1303. var d = new Date();
  1304. packets.row.add([
  1305. d.toLocaleTimeString('en-US', { hour12: false }),
  1306. packet.senderID,
  1307. packet.packetID,
  1308. packet.targetID,
  1309. packet.key,
  1310. packet.value,
  1311. packet.rssi,
  1312. packet.duplicates,
  1313. packet.missing,
  1314. ]).draw(false);
  1315. return;
  1316. }
  1317. if (key == "mapping") {
  1318. for (var i in data.mapping) {
  1319. // add a new row
  1320. addMapping();
  1321. // get group
  1322. var line = $("#mapping .pure-g")[i];
  1323. // fill in the blanks
  1324. var mapping = data.mapping[i];
  1325. Object.keys(mapping).forEach(function(key) {
  1326. var id = "input[name=" + key + "]";
  1327. if ($(id, line).length) $(id, line).val(mapping[key]);
  1328. });
  1329. setOriginalsFromValues($("input", line));
  1330. }
  1331. return;
  1332. }
  1333. <!-- endRemoveIf(!rfm69)-->
  1334. // ---------------------------------------------------------------------
  1335. // RPN Rules
  1336. // ---------------------------------------------------------------------
  1337. if (key == "rpnRules") {
  1338. for (var i in data.rpnRules) {
  1339. // add a new row
  1340. addRPNRule();
  1341. // get group
  1342. var line = $("#rpnRules .pure-g")[i];
  1343. // fill in the blanks
  1344. var rule = data.rpnRules[i];
  1345. $("input", line).val(rule);
  1346. setOriginalsFromValues($("input", line));
  1347. }
  1348. return;
  1349. }
  1350. if (key == "rpnTopics") {
  1351. for (var i in data.rpnTopics) {
  1352. // add a new row
  1353. addRPNTopic();
  1354. // get group
  1355. var line = $("#rpnTopics .pure-g")[i];
  1356. // fill in the blanks
  1357. var topic = data.rpnTopics[i];
  1358. var name = data.rpnNames[i];
  1359. $("input[name='rpnTopic']", line).val(topic);
  1360. $("input[name='rpnName']", line).val(name);
  1361. setOriginalsFromValues($("input", line));
  1362. }
  1363. return;
  1364. }
  1365. if (key == "rpnNames") return;
  1366. // ---------------------------------------------------------------------
  1367. // Lights
  1368. // ---------------------------------------------------------------------
  1369. <!-- removeIf(!light)-->
  1370. if ("rgb" === key) {
  1371. initColor({rgb: true});
  1372. setPickerRGB($("input[name='color']"), value);
  1373. return;
  1374. }
  1375. if ("hsv" === key) {
  1376. initColor({hsv: true});
  1377. setPickerHSV($("input[name='color']"), value);
  1378. return;
  1379. }
  1380. if ("brightness" === key) {
  1381. $("#brightness").val(value);
  1382. $("span.brightness").html(value);
  1383. return;
  1384. }
  1385. if ("channels" === key) {
  1386. var len = value.length;
  1387. initChannels(len);
  1388. for (i in value) {
  1389. var ch = value[i];
  1390. $("input.slider[data=" + i + "]").val(ch);
  1391. $("span.slider[data=" + i + "]").html(ch);
  1392. }
  1393. return;
  1394. }
  1395. if ("mireds" === key) {
  1396. $("#mireds").attr("min", value["cold"]);
  1397. $("#mireds").attr("max", value["warm"]);
  1398. $("#mireds").val(value["value"]);
  1399. $("span.mireds").html(value["value"]);
  1400. return;
  1401. }
  1402. if ("useWhite" === key) {
  1403. useWhite = value;
  1404. }
  1405. if ("useCCT" === key) {
  1406. initCCT();
  1407. useCCT = value;
  1408. }
  1409. <!-- endRemoveIf(!light)-->
  1410. // ---------------------------------------------------------------------
  1411. // Sensors & Magnitudes
  1412. // ---------------------------------------------------------------------
  1413. <!-- removeIf(!sensor)-->
  1414. if ("magnitudesConfig" === key) {
  1415. initMagnitudes(value);
  1416. }
  1417. if ("magnitudes" === key) {
  1418. for (var i=0; i<value.size; ++i) {
  1419. var error = value.error[i] || 0;
  1420. var text = (0 === error) ?
  1421. value.value[i] + magnitudes[i].units :
  1422. magnitudeError(error);
  1423. var element = $("input[name='magnitude'][data='" + i + "']");
  1424. element.val(text);
  1425. }
  1426. return;
  1427. }
  1428. <!-- endRemoveIf(!sensor)-->
  1429. // ---------------------------------------------------------------------
  1430. // WiFi
  1431. // ---------------------------------------------------------------------
  1432. if ("wifi" === key) {
  1433. maxNetworks = parseInt(value["max"], 10);
  1434. value["networks"].forEach(function(network) {
  1435. var schema = value["schema"];
  1436. if (schema.length !== network.length) {
  1437. throw "WiFi schema mismatch!";
  1438. }
  1439. var _network = {};
  1440. schema.forEach(function(key, index) {
  1441. _network[key] = network[index];
  1442. });
  1443. addNetwork(_network);
  1444. });
  1445. return;
  1446. }
  1447. if ("scanResult" === key) {
  1448. $("div.scan.loading").hide();
  1449. $("#scanResult").show();
  1450. }
  1451. // -----------------------------------------------------------------------------
  1452. // Home Assistant
  1453. // -----------------------------------------------------------------------------
  1454. if ("haConfig" === key) {
  1455. send("{}");
  1456. $("#haConfig")
  1457. .append(new Text(value))
  1458. .height($("#haConfig")[0].scrollHeight);
  1459. return;
  1460. }
  1461. // -----------------------------------------------------------------------------
  1462. // Relays scheduler
  1463. // -----------------------------------------------------------------------------
  1464. if ("schedules" === key) {
  1465. $("#schedules").attr("data-settings-max", value.max);
  1466. for (var i=0; i<value.size; ++i) {
  1467. // XXX: no
  1468. var sch_map = {};
  1469. Object.keys(value).forEach(function(key) {
  1470. if ("size" == key) return;
  1471. if ("max" == key) return;
  1472. sch_map[key] = value[key][i];
  1473. });
  1474. addSchedule(sch_map);
  1475. }
  1476. return;
  1477. }
  1478. // ---------------------------------------------------------------------
  1479. // Relays
  1480. // ---------------------------------------------------------------------
  1481. if ("relayState" === key) {
  1482. initRelays(value.status);
  1483. updateRelays(value);
  1484. return;
  1485. }
  1486. // Relay configuration
  1487. if ("relayConfig" === key) {
  1488. initRelayConfig(value);
  1489. return;
  1490. }
  1491. // ---------------------------------------------------------------------
  1492. // LEDs
  1493. // ---------------------------------------------------------------------
  1494. if ("ledConfig" === key) {
  1495. initLeds(value);
  1496. for (var i=0; i<value.length; ++i) {
  1497. var mode = $("select[name='ledMode'][data='" + i + "']");
  1498. var relay = $("select[name='ledRelay'][data='" + i + "']");
  1499. mode.val(value[i].mode);
  1500. relay.val(value[i].relay);
  1501. setOriginalsFromValues($([mode,relay]));
  1502. }
  1503. return;
  1504. }
  1505. // ---------------------------------------------------------------------
  1506. // Domoticz
  1507. // ---------------------------------------------------------------------
  1508. // Domoticz - Relays
  1509. if ("dczRelays" === key) {
  1510. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1511. return;
  1512. }
  1513. // Domoticz - Magnitudes
  1514. <!-- removeIf(!sensor)-->
  1515. if ("dczMagnitudes" === key) {
  1516. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1517. return;
  1518. }
  1519. <!-- endRemoveIf(!sensor)-->
  1520. // ---------------------------------------------------------------------
  1521. // Thingspeak
  1522. // ---------------------------------------------------------------------
  1523. // Thingspeak - Relays
  1524. if ("tspkRelays" === key) {
  1525. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1526. return;
  1527. }
  1528. // Thingspeak - Magnitudes
  1529. <!-- removeIf(!sensor)-->
  1530. if ("tspkMagnitudes" === key) {
  1531. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1532. return;
  1533. }
  1534. <!-- endRemoveIf(!sensor)-->
  1535. // ---------------------------------------------------------------------
  1536. // HTTP API
  1537. // ---------------------------------------------------------------------
  1538. // Auto generate an APIKey if none defined yet
  1539. if ("apiVisible" === key) {
  1540. if (data.apiKey === undefined || data.apiKey === "") {
  1541. generateAPIKey();
  1542. }
  1543. }
  1544. // ---------------------------------------------------------------------
  1545. // General
  1546. // ---------------------------------------------------------------------
  1547. // Messages
  1548. if ("message" === key) {
  1549. if (value == 8) {
  1550. configurationSaved = true;
  1551. }
  1552. window.alert(messages[value]);
  1553. return;
  1554. }
  1555. // Web log
  1556. if ("weblog" === key) {
  1557. send("{}");
  1558. var msg = value["msg"];
  1559. var pre = value["pre"];
  1560. for (var i=0; i < msg.length; ++i) {
  1561. if (pre[i]) {
  1562. $("#weblog").append(new Text(pre[i]));
  1563. }
  1564. $("#weblog").append(new Text(msg[i]));
  1565. }
  1566. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1567. return;
  1568. }
  1569. // Enable options
  1570. var position = key.indexOf("Visible");
  1571. if (position > 0 && position === key.length - 7) {
  1572. var module = key.slice(0,-7);
  1573. if (module == "sch") {
  1574. $("li.module-" + module).css("display", "inherit");
  1575. $("div.module-" + module).css("display", "flex");
  1576. return;
  1577. }
  1578. $(".module-" + module).css("display", "inherit");
  1579. return;
  1580. }
  1581. if ("deviceip" === key) {
  1582. var a_href = $("span[name='" + key + "']").parent();
  1583. a_href.attr("href", "//" + value);
  1584. a_href.next().attr("href", "telnet://" + value);
  1585. }
  1586. if ("now" === key) {
  1587. now = value;
  1588. return;
  1589. }
  1590. if ("free_size" === key) {
  1591. free_size = parseInt(value, 10);
  1592. }
  1593. // Pre-process
  1594. if ("mqttStatus" === key) {
  1595. value = value ? "CONNECTED" : "NOT CONNECTED";
  1596. }
  1597. if ("ntpStatus" === key) {
  1598. value = value ? "SYNC'D" : "NOT SYNC'D";
  1599. }
  1600. if ("uptime" === key) {
  1601. ago = 0;
  1602. var uptime = parseInt(value, 10);
  1603. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1604. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1605. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1606. var days = uptime;
  1607. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1608. }
  1609. <!-- removeIf(!thermostat)-->
  1610. if ("tmpUnits" == key) {
  1611. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1612. }
  1613. <!-- endRemoveIf(!thermostat)-->
  1614. // ---------------------------------------------------------------------
  1615. // Matching
  1616. // ---------------------------------------------------------------------
  1617. var elems = [];
  1618. var pre;
  1619. var post;
  1620. // Look for INPUTs
  1621. var input = $("input[name='" + key + "']");
  1622. if (input.length > 0) {
  1623. if (input.attr("type") === "checkbox") {
  1624. input.prop("checked", value);
  1625. } else if (input.attr("type") === "radio") {
  1626. input.val([value]);
  1627. } else {
  1628. pre = input.attr("pre") || "";
  1629. post = input.attr("post") || "";
  1630. input.val(pre + value + post);
  1631. }
  1632. elems.push(input);
  1633. }
  1634. // Look for SPANs
  1635. var span = $("span[name='" + key + "']");
  1636. if (span.length > 0) {
  1637. if (Array.isArray(value)) {
  1638. value.forEach(function(elem) {
  1639. span.append(elem);
  1640. span.append('</br>');
  1641. elems.push(span);
  1642. });
  1643. } else {
  1644. pre = span.attr("pre") || "";
  1645. post = span.attr("post") || "";
  1646. span.html(pre + value + post);
  1647. elems.push(span);
  1648. }
  1649. }
  1650. // Look for SELECTs
  1651. var select = $("select[name='" + key + "']");
  1652. if (select.length > 0) {
  1653. select.val(value);
  1654. elems.push(select);
  1655. }
  1656. setOriginalsFromValues($(elems));
  1657. });
  1658. }
  1659. function hasChanged() {
  1660. var newValue, originalValue;
  1661. if ($(this).attr("type") === "checkbox") {
  1662. newValue = $(this).prop("checked");
  1663. originalValue = ($(this).attr("original") === "true");
  1664. } else {
  1665. newValue = $(this).val();
  1666. originalValue = $(this).attr("original");
  1667. }
  1668. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1669. var action = $(this).attr("action");
  1670. if (typeof originalValue === "undefined") { return; }
  1671. if ("none" === action) { return; }
  1672. if (newValue !== originalValue) {
  1673. if (!hasChanged) {
  1674. ++numChanged;
  1675. if ("reconnect" === action) { ++numReconnect; }
  1676. if ("reboot" === action) { ++numReboot; }
  1677. if ("reload" === action) { ++numReload; }
  1678. }
  1679. $(this).attr("hasChanged", true);
  1680. } else {
  1681. if (hasChanged) {
  1682. --numChanged;
  1683. if ("reconnect" === action) { --numReconnect; }
  1684. if ("reboot" === action) { --numReboot; }
  1685. if ("reload" === action) { --numReload; }
  1686. }
  1687. $(this).attr("hasChanged", false);
  1688. }
  1689. }
  1690. // -----------------------------------------------------------------------------
  1691. // Init & connect
  1692. // -----------------------------------------------------------------------------
  1693. function initUrls(root) {
  1694. var paths = ["ws", "upgrade", "config", "auth"];
  1695. urls["root"] = root;
  1696. paths.forEach(function(path) {
  1697. urls[path] = new URL(path, root);
  1698. urls[path].protocol = root.protocol;
  1699. });
  1700. if (root.protocol == "https:") {
  1701. urls.ws.protocol = "wss:";
  1702. } else {
  1703. urls.ws.protocol = "ws:";
  1704. }
  1705. }
  1706. function connectToURL(url) {
  1707. initUrls(url);
  1708. fetch(urls.auth.href, {
  1709. 'method': 'GET',
  1710. 'cors': true,
  1711. 'credentials': 'same-origin'
  1712. }).then(function(response) {
  1713. // Nothing to do, reload page and retry
  1714. if (response.status != 200) {
  1715. doReload(5000);
  1716. return;
  1717. }
  1718. // update websock object
  1719. if (websock) { websock.close(); }
  1720. websock = new WebSocket(urls.ws.href);
  1721. websock.onmessage = function(evt) {
  1722. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1723. if (data) {
  1724. processData(data);
  1725. }
  1726. };
  1727. websock.onclose = function(evt) {
  1728. clearInterval(ws_pingpong);
  1729. if (window.confirm("Connection lost with the device, click OK to refresh the page")) {
  1730. $("#layout").toggle(false);
  1731. window.location.reload();
  1732. }
  1733. }
  1734. websock.onopen = function(evt) {
  1735. ws_pingpong = setInterval(function() { sendAction("ping", {}); }, 5000);
  1736. }
  1737. }).catch(function(error) {
  1738. console.log(error);
  1739. doReload(5000);
  1740. });
  1741. }
  1742. function connect(host) {
  1743. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1744. host = "http://" + host;
  1745. }
  1746. connectToURL(new URL(host));
  1747. }
  1748. function connectToCurrentURL() {
  1749. connectToURL(new URL(window.location));
  1750. }
  1751. $(function() {
  1752. initMessages();
  1753. loadTimeZones();
  1754. createCheckboxes();
  1755. setInterval(function() { keepTime(); }, 1000);
  1756. $(".password-reveal").on("click", toggleVisiblePassword);
  1757. $("#menuLink").on("click", toggleMenu);
  1758. $(".pure-menu-link").on("click", showPanel);
  1759. $("progress").attr({ value: 0, max: 100 });
  1760. $(".button-update").on("click", doUpdate);
  1761. $(".button-update-password").on("click", doUpdatePassword);
  1762. $(".button-generate-password").on("click", doGeneratePassword);
  1763. $(".button-reboot").on("click", doReboot);
  1764. $(".button-reconnect").on("click", doReconnect);
  1765. $(".button-wifi-scan").on("click", doScan);
  1766. $(".button-ha-config").on("click", doHAConfig);
  1767. $(".button-dbgcmd").on("click", doDebugCommand);
  1768. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1769. $(".button-dbg-clear").on("click", doDebugClear);
  1770. $(".button-settings-backup").on("click", doBackup);
  1771. $(".button-settings-restore").on("click", doRestore);
  1772. $(".button-settings-factory").on("click", doFactoryReset);
  1773. $("#uploader").on("change", onFileUpload);
  1774. $(".button-upgrade").on("click", doUpgrade);
  1775. <!-- removeIf(!thermostat)-->
  1776. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1777. <!-- endRemoveIf(!thermostat)-->
  1778. $(".button-apikey").on("click", generateAPIKey);
  1779. $(".button-upgrade-browse").on("click", function() {
  1780. $("input[name='upgrade']")[0].click();
  1781. return false;
  1782. });
  1783. $("input[name='upgrade']").change(function (){
  1784. var file = this.files[0];
  1785. $("input[name='filename']").val(file.name);
  1786. });
  1787. $(".button-add-network").on("click", function() {
  1788. $(".more", addNetwork()).toggle();
  1789. });
  1790. $(".button-add-switch-schedule").on("click", function() {
  1791. addSchedule({schType: 1, schSwitch: -1});
  1792. });
  1793. <!-- removeIf(!light)-->
  1794. $(".button-add-light-schedule").on("click", function() {
  1795. addSchedule({schType: 2, schSwitch: -1});
  1796. });
  1797. <!-- endRemoveIf(!light)-->
  1798. $(".button-add-rpnrule").on('click', addRPNRule);
  1799. $(".button-add-rpntopic").on('click', addRPNTopic);
  1800. $(".button-del-parent").on('click', delParent);
  1801. <!-- removeIf(!rfm69)-->
  1802. $(".button-add-mapping").on('click', addMapping);
  1803. $(".button-clear-counts").on('click', doClearCounts);
  1804. $(".button-clear-messages").on('click', doClearMessages);
  1805. $(".button-clear-filters").on('click', doClearFilters);
  1806. $('#packets tbody').on('mousedown', 'td', doFilter);
  1807. packets = $('#packets').DataTable({
  1808. "paging": false
  1809. });
  1810. for (var i = 0; i < packets.columns()[0].length; i++) {
  1811. filters[i] = false;
  1812. }
  1813. <!-- endRemoveIf(!rfm69)-->
  1814. $(".gpio-select").each(function(_, elem) {
  1815. initSelectGPIO(elem)
  1816. });
  1817. $(document).on("change", "input", hasChanged);
  1818. $(document).on("change", "select", hasChanged);
  1819. $("textarea").on("dblclick", function() { this.select(); });
  1820. resetOriginals();
  1821. $(".group-settings").each(function() {
  1822. groupSettingsObserver.observe(this, {childList: true});
  1823. });
  1824. // don't autoconnect when opening from filesystem
  1825. if (window.location.protocol === "file:") {
  1826. return;
  1827. }
  1828. // Check host param in query string
  1829. var search = new URLSearchParams(window.location.search),
  1830. host = search.get("host");
  1831. if (host !== null) {
  1832. connect(host);
  1833. } else {
  1834. connectToCurrentURL();
  1835. }
  1836. });