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.

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