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.

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