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.

2232 lines
64 KiB

8 years ago
7 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
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 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
6 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. if (0xE9 !== evt.target.result.charCodeAt(0)) callback(false);
  474. if (0x03 !== evt.target.result.charCodeAt(2)) {
  475. var response = window.confirm("Binary image is not using DOUT flash mode. This might cause resets in some devices. Press OK to continue.");
  476. callback(response);
  477. } else {
  478. callback(true);
  479. }
  480. }
  481. };
  482. var blob = file.slice(0, 3);
  483. reader.readAsBinaryString(blob);
  484. }
  485. function doUpgrade() {
  486. var file = $("input[name='upgrade']")[0].files[0];
  487. if (typeof file === "undefined") {
  488. alert("First you have to select a file from your computer.");
  489. return false;
  490. }
  491. if (file.size > free_size) {
  492. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  493. return false;
  494. }
  495. checkFirmware(file, function(ok) {
  496. if (!ok) {
  497. alert("The file does not seem to be a valid firmware image.");
  498. return;
  499. }
  500. var data = new FormData();
  501. data.append("upgrade", file, file.name);
  502. var xhr = new XMLHttpRequest();
  503. var network_error = function() {
  504. alert("There was a network error trying to upload the new image, please try again.");
  505. };
  506. xhr.addEventListener("error", network_error, false);
  507. xhr.addEventListener("abort", network_error, false);
  508. xhr.addEventListener("load", function(e) {
  509. $("#upgrade-progress").hide();
  510. if ("OK" === xhr.responseText) {
  511. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  512. doReload(5000);
  513. } else {
  514. alert("There was an error trying to upload the new image, please try again ("
  515. + "response: " + xhr.responseText + ", "
  516. + "status: " + xhr.statusText + ")");
  517. }
  518. }, false);
  519. xhr.upload.addEventListener("progress", function(e) {
  520. $("#upgrade-progress").show();
  521. if (e.lengthComputable) {
  522. $("progress").attr({ value: e.loaded, max: e.total });
  523. }
  524. }, false);
  525. xhr.open("POST", urls.upgrade.href);
  526. xhr.send(data);
  527. });
  528. return false;
  529. }
  530. function doUpdatePassword() {
  531. var form = $("#formPassword");
  532. if (validateFormPasswords(form)) {
  533. sendConfig(getData(form, true, false));
  534. }
  535. return false;
  536. }
  537. function checkChanges() {
  538. if (numChanged > 0) {
  539. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  540. if (response) {
  541. doUpdate();
  542. }
  543. }
  544. }
  545. function doAction(question, action) {
  546. checkChanges();
  547. if (question) {
  548. var response = window.confirm(question);
  549. if (false === response) {
  550. return false;
  551. }
  552. }
  553. sendAction(action, {});
  554. doReload(5000);
  555. return false;
  556. }
  557. function doReboot(ask) {
  558. var question = (typeof ask === "undefined" || false === ask) ?
  559. null :
  560. "Are you sure you want to reboot the device?";
  561. return doAction(question, "reboot");
  562. }
  563. function doReconnect(ask) {
  564. var question = (typeof ask === "undefined" || false === ask) ?
  565. null :
  566. "Are you sure you want to disconnect from the current WIFI network?";
  567. return doAction(question, "reconnect");
  568. }
  569. function doCheckOriginals() {
  570. var response;
  571. if (numReboot > 0) {
  572. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  573. if (response) { doReboot(false); }
  574. } else if (numReconnect > 0) {
  575. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  576. if (response) { doReconnect(false); }
  577. } else if (numReload > 0) {
  578. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  579. if (response) { doReload(0); }
  580. }
  581. resetOriginals();
  582. }
  583. function waitForSave(){
  584. if (!configurationSaved) {
  585. setTimeout(waitForSave, 1000);
  586. } else {
  587. doCheckOriginals();
  588. }
  589. }
  590. function doUpdate() {
  591. var forms = $(".form-settings");
  592. if (validateForm(forms)) {
  593. // Get data
  594. sendConfig(getData(forms));
  595. // Empty special fields
  596. $(".pwrExpected").val(0);
  597. $("input[name='snsResetCalibration']").prop("checked", false);
  598. $("input[name='pwrResetCalibration']").prop("checked", false);
  599. $("input[name='pwrResetE']").prop("checked", false);
  600. // Change handling
  601. numChanged = 0;
  602. waitForSave();
  603. }
  604. return false;
  605. }
  606. function doBackup() {
  607. document.getElementById("downloader").src = urls.config.href;
  608. return false;
  609. }
  610. function onFileUpload(event) {
  611. var inputFiles = this.files;
  612. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  613. return false;
  614. }
  615. var inputFile = inputFiles[0];
  616. this.value = "";
  617. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  618. if (!response) {
  619. return false;
  620. }
  621. var reader = new FileReader();
  622. reader.onload = function(e) {
  623. var data = getJson(e.target.result);
  624. if (data) {
  625. sendAction("restore", data);
  626. } else {
  627. window.alert(messages[4]);
  628. }
  629. };
  630. reader.readAsText(inputFile);
  631. return false;
  632. }
  633. function doRestore() {
  634. if (typeof window.FileReader !== "function") {
  635. alert("The file API isn't supported on this browser yet.");
  636. } else {
  637. $("#uploader").click();
  638. }
  639. return false;
  640. }
  641. function doFactoryReset() {
  642. var response = window.confirm("Are you sure you want to restore to factory settings?");
  643. if (!response) {
  644. return false;
  645. }
  646. sendAction("factory_reset", {});
  647. doReload(5000);
  648. return false;
  649. }
  650. function doToggle(id, value) {
  651. sendAction("relay", {id: id, status: value ? 1 : 0 });
  652. return false;
  653. }
  654. function doScan() {
  655. $("#scanResult").html("");
  656. $("div.scan.loading").show();
  657. sendAction("scan", {});
  658. return false;
  659. }
  660. function doHAConfig() {
  661. $("#haConfig")
  662. .text("")
  663. .height(0)
  664. .show();
  665. sendAction("haconfig", {});
  666. return false;
  667. }
  668. function doDebugCommand() {
  669. var el = $("input[name='dbgcmd']");
  670. var command = el.val();
  671. el.val("");
  672. sendAction("dbgcmd", {command: command});
  673. return false;
  674. }
  675. function doDebugClear() {
  676. $("#weblog").text("");
  677. return false;
  678. }
  679. <!-- removeIf(!rfm69)-->
  680. function doClearCounts() {
  681. sendAction("clear-counts", {});
  682. return false;
  683. }
  684. function doClearMessages() {
  685. packets.clear().draw(false);
  686. return false;
  687. }
  688. function doFilter(e) {
  689. var index = packets.cell(this).index();
  690. if (index == 'undefined') return;
  691. var c = index.column;
  692. var column = packets.column(c);
  693. if (filters[c]) {
  694. filters[c] = false;
  695. column.search("");
  696. $(column.header()).removeClass("filtered");
  697. } else {
  698. filters[c] = true;
  699. var data = packets.row(this).data();
  700. if (e.which == 1) {
  701. column.search('^' + data[c] + '$', true, false );
  702. } else {
  703. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  704. }
  705. $(column.header()).addClass("filtered");
  706. }
  707. column.draw();
  708. return false;
  709. }
  710. function doClearFilters() {
  711. for (var i = 0; i < packets.columns()[0].length; i++) {
  712. if (filters[i]) {
  713. filters[i] = false;
  714. var column = packets.column(i);
  715. column.search("");
  716. $(column.header()).removeClass("filtered");
  717. column.draw();
  718. }
  719. }
  720. return false;
  721. }
  722. <!-- endRemoveIf(!rfm69)-->
  723. function delParent() {
  724. var parent = $(this).parent().parent();
  725. $(parent).remove();
  726. }
  727. // -----------------------------------------------------------------------------
  728. // Visualization
  729. // -----------------------------------------------------------------------------
  730. function toggleMenu() {
  731. $("#layout").toggleClass("active");
  732. $("#menu").toggleClass("active");
  733. $("#menuLink").toggleClass("active");
  734. }
  735. function showPanel() {
  736. $(".panel").hide();
  737. if ($("#layout").hasClass("active")) { toggleMenu(); }
  738. $("#" + $(this).attr("data")).show();
  739. }
  740. // -----------------------------------------------------------------------------
  741. // Relays & magnitudes mapping
  742. // -----------------------------------------------------------------------------
  743. function createRelayList(data, container, template_name) {
  744. var current = $("#" + container + " > div").length;
  745. if (current > 0) { return; }
  746. var template = $("#" + template_name + " .pure-g")[0];
  747. for (var i in data) {
  748. var line = $(template).clone();
  749. $("label", line).html("Switch #" + i);
  750. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  751. setOriginalsFromValues($("input", line));
  752. line.appendTo("#" + container);
  753. }
  754. }
  755. <!-- removeIf(!sensor)-->
  756. function createMagnitudeList(data, container, template_name) {
  757. var current = $("#" + container + " > div").length;
  758. if (current > 0) { return; }
  759. var template = $("#" + template_name + " .pure-g")[0];
  760. var size = data.size;
  761. for (var i=0; i<size; ++i) {
  762. var line = $(template).clone();
  763. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  764. $("div.hint", line).html(magnitudes[i].description);
  765. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  766. setOriginalsFromValues($("input", line));
  767. line.appendTo("#" + container);
  768. }
  769. }
  770. <!-- endRemoveIf(!sensor)-->
  771. // -----------------------------------------------------------------------------
  772. // RPN Rules
  773. // -----------------------------------------------------------------------------
  774. function addRPNRule() {
  775. var template = $("#rpnRuleTemplate .pure-g")[0];
  776. var line = $(template).clone();
  777. var tabindex = $("#rpnRules > div").length + 100;
  778. $(line).find("input").each(function() {
  779. $(this).attr("tabindex", tabindex++);
  780. });
  781. $(line).find("button").on('click', delParent);
  782. setOriginalsFromValues($("input", line));
  783. line.appendTo("#rpnRules");
  784. }
  785. function addRPNTopic() {
  786. var template = $("#rpnTopicTemplate .pure-g")[0];
  787. var line = $(template).clone();
  788. var tabindex = $("#rpnTopics > div").length + 120;
  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("#rpnTopics");
  795. }
  796. // -----------------------------------------------------------------------------
  797. // RFM69
  798. // -----------------------------------------------------------------------------
  799. <!-- removeIf(!rfm69)-->
  800. function addMapping() {
  801. var template = $("#nodeTemplate .pure-g")[0];
  802. var line = $(template).clone();
  803. var tabindex = $("#mapping > div").length * 3 + 50;
  804. $(line).find("input").each(function() {
  805. $(this).attr("tabindex", tabindex++);
  806. });
  807. $(line).find("button").on('click', delParent);
  808. setOriginalsFromValues($("input", line));
  809. line.appendTo("#mapping");
  810. }
  811. <!-- endRemoveIf(!rfm69)-->
  812. // -----------------------------------------------------------------------------
  813. // Wifi
  814. // -----------------------------------------------------------------------------
  815. function numNetworks() {
  816. return $("#networks > div").length;
  817. }
  818. function delNetwork() {
  819. var parent = $(this).parents(".pure-g");
  820. $(parent).remove();
  821. }
  822. function moreNetwork() {
  823. var parent = $(this).parents(".pure-g");
  824. $(".more", parent).toggle();
  825. }
  826. function addNetwork(values) {
  827. var number = numNetworks();
  828. if (number >= maxNetworks) {
  829. alert("Max number of networks reached");
  830. return null;
  831. }
  832. if (values === undefined) {
  833. values = {};
  834. }
  835. var tabindex = 200 + numNetworks * 10;
  836. var template = $("#networkTemplate").children();
  837. var line = $(template).clone();
  838. $(line).find("input").each(function() {
  839. $(this).attr("tabindex", tabindex);
  840. tabindex++;
  841. });
  842. $(".password-reveal", line).on("click", toggleVisiblePassword);
  843. $(line).find(".button-del-network").on("click", delNetwork);
  844. $(line).find(".button-more-network").on("click", moreNetwork);
  845. Object.entries(values).forEach(function(kv) {
  846. $("input[name='" + kv[0] + "']", line).val(kv[1]);
  847. });
  848. line.appendTo("#networks");
  849. return line;
  850. }
  851. // -----------------------------------------------------------------------------
  852. // Relays scheduler
  853. // -----------------------------------------------------------------------------
  854. function numSchedules() {
  855. return $("#schedules > div").length;
  856. }
  857. function maxSchedules() {
  858. var value = $("#schedules").attr("data-settings-max");
  859. return parseInt(value === undefined ? 0 : value, 10);
  860. }
  861. function delSchedule() {
  862. var parent = $(this).parents(".pure-g");
  863. $(parent).remove();
  864. }
  865. function moreSchedule() {
  866. var parent = $(this).parents(".pure-g");
  867. $("div.more", parent).toggle();
  868. }
  869. function addSchedule(values) {
  870. var schedules = numSchedules();
  871. if (schedules >= maxSchedules()) {
  872. alert("Max number of schedules reached");
  873. return null;
  874. }
  875. if (values === undefined) {
  876. values = {};
  877. }
  878. var tabindex = 200 + numSchedules * 10;
  879. var template = $("#scheduleTemplate").children();
  880. var line = $(template).clone();
  881. var type = (1 === values.schType) ? "switch" : "light";
  882. template = $("#" + type + "ActionTemplate").children();
  883. $(line).find("#schActionDiv").append(template.clone());
  884. $(line).find("input").each(function() {
  885. $(this).attr("tabindex", tabindex);
  886. tabindex++;
  887. });
  888. $(line).find(".button-del-schedule").on("click", delSchedule);
  889. $(line).find(".button-more-schedule").on("click", moreSchedule);
  890. var schUTC_id = "schUTC" + (schedules + 1);
  891. $(line).find("input[name='schUTC']").prop("id", schUTC_id).next().prop("for", schUTC_id);
  892. var schEnabled_id = "schEnabled" + (schedules + 1);
  893. $(line).find("input[name='schEnabled']").prop("id", schEnabled_id).next().prop("for", schEnabled_id);
  894. $(line).find("input[type='checkbox']").prop("checked", false);
  895. Object.entries(values).forEach(function(kv) {
  896. var key = kv[0], value = kv[1];
  897. $("input[name='" + key + "']", line).val(value);
  898. $("select[name='" + key + "']", line).prop("value", value);
  899. $("input[type='checkbox'][name='" + key + "']", line).prop("checked", value);
  900. });
  901. line.appendTo("#schedules");
  902. return line;
  903. }
  904. // -----------------------------------------------------------------------------
  905. // Relays
  906. // -----------------------------------------------------------------------------
  907. function initRelays(data) {
  908. var current = $("#relays > div").length;
  909. if (current > 0) { return; }
  910. var template = $("#relayTemplate .pure-g")[0];
  911. for (var i=0; i<data.length; i++) {
  912. // Add relay fields
  913. var line = $(template).clone();
  914. $(".id", line).html(i);
  915. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  916. .prop("id", "relay" + i)
  917. .on("change", function (event) {
  918. var id = parseInt($(event.target).attr("data"), 10);
  919. var status = $(event.target).prop("checked");
  920. doToggle(id, status);
  921. });
  922. $("label.toggle", line).prop("for", "relay" + i)
  923. line.appendTo("#relays");
  924. }
  925. }
  926. function updateRelays(data) {
  927. var size = data.size;
  928. for (var i=0; i<size; ++i) {
  929. var elem = $("input[name='relay'][data='" + i + "']");
  930. elem.prop("checked", data.status[i]);
  931. var lock = {
  932. 0: false,
  933. 1: !data.status[i],
  934. 2: data.status[i]
  935. };
  936. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  937. }
  938. }
  939. function createCheckboxes() {
  940. $("input[type='checkbox']").each(function() {
  941. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  942. $(this).parent().addClass("toggleWrapper");
  943. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  944. });
  945. }
  946. function initRelayConfig(data) {
  947. var current = $("#relayConfig > legend").length; // there is a legend per relay
  948. if (current > 0) { return; }
  949. var size = data.size;
  950. var start = data.start;
  951. var template = $("#relayConfigTemplate").children();
  952. for (var i=start; i<size; ++i) {
  953. var line = $(template).clone();
  954. $("span.id", line).html(i);
  955. $("span.gpio", line).html(data.gpio[i]);
  956. $("select[name='relayBoot']", line).val(data.boot[i]);
  957. $("select[name='relayPulse']", line).val(data.pulse[i]);
  958. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  959. if ("sch_last" in data) {
  960. $("input[name='relayLastSch']", line)
  961. .prop('checked', data.sch_last[i])
  962. .attr("id", "relayLastSch" + i)
  963. .attr("name", "relayLastSch" + i)
  964. .next().attr("for","relayLastSch" + (i));
  965. }
  966. if ("group" in data) {
  967. $("input[name='mqttGroup']", line).val(data.group[i]);
  968. }
  969. if ("group_sync" in data) {
  970. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  971. }
  972. if ("on_disc" in data) {
  973. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  974. }
  975. setOriginalsFromValues($("input,select", line));
  976. line.appendTo("#relayConfig");
  977. // Populate the relay SELECTs
  978. $("select.isrelay").append(
  979. $("<option></option>")
  980. .attr("value", i)
  981. .text("Switch #" + i)
  982. );
  983. }
  984. }
  985. function initLeds(data) {
  986. var current = $("#ledConfig > div").length;
  987. if (current > 0) { return; }
  988. var size = data.length;
  989. var template = $("#ledConfigTemplate").children();
  990. for (var i=0; i<size; ++i) {
  991. var line = $(template).clone();
  992. $("span.id", line).html(i);
  993. $("select", line).attr("data", i);
  994. $("input", line).attr("data", i);
  995. line.appendTo("#ledConfig");
  996. }
  997. }
  998. // -----------------------------------------------------------------------------
  999. // Sensors & Magnitudes
  1000. // -----------------------------------------------------------------------------
  1001. <!-- removeIf(!sensor)-->
  1002. function initMagnitudes(data) {
  1003. // check if already initialized (each magnitude is inside div.pure-g)
  1004. var done = $("#magnitudes > div").length;
  1005. if (done > 0) { return; }
  1006. var size = data.size;
  1007. // add templates
  1008. var template = $("#magnitudeTemplate").children();
  1009. for (var i=0; i<size; ++i) {
  1010. var magnitude = {
  1011. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  1012. "units": data.units[i],
  1013. "description": data.description[i]
  1014. };
  1015. magnitudes.push(magnitude);
  1016. var line = $(template).clone();
  1017. $("label", line).html(magnitude.name);
  1018. $("div.hint", line).html(magnitude.description);
  1019. $("input", line).attr("data", i);
  1020. line.appendTo("#magnitudes");
  1021. }
  1022. }
  1023. <!-- endRemoveIf(!sensor)-->
  1024. // -----------------------------------------------------------------------------
  1025. // Lights
  1026. // -----------------------------------------------------------------------------
  1027. <!-- removeIf(!light)-->
  1028. // wheelColorPicker accepts:
  1029. // hsv(0...360,0...1,0...1)
  1030. // hsv(0...100%,0...100%,0...100%)
  1031. // While we use:
  1032. // hsv(0...360,0...100%,0...100%)
  1033. function _hsv_round(value) {
  1034. return Math.round(value * 100) / 100;
  1035. }
  1036. function getPickerRGB(picker) {
  1037. return $(picker).wheelColorPicker("getValue", "css");
  1038. }
  1039. function setPickerRGB(picker, value) {
  1040. $(picker).wheelColorPicker("setValue", value, true);
  1041. }
  1042. // TODO: use pct values instead of doing conversion?
  1043. function getPickerHSV(picker) {
  1044. var color = $(picker).wheelColorPicker("getColor");
  1045. return String(Math.ceil(_hsv_round(color.h) * 360))
  1046. + "," + String(Math.ceil(_hsv_round(color.s) * 100))
  1047. + "," + String(Math.ceil(_hsv_round(color.v) * 100));
  1048. }
  1049. function setPickerHSV(picker, value) {
  1050. if (value === getPickerHSV(picker)) return;
  1051. var chunks = value.split(",");
  1052. $(picker).wheelColorPicker("setColor", {
  1053. h: _hsv_round(chunks[0] / 360),
  1054. s: _hsv_round(chunks[1] / 100),
  1055. v: _hsv_round(chunks[2] / 100)
  1056. });
  1057. }
  1058. function initColor(cfg) {
  1059. var rgb = false;
  1060. if (typeof cfg === "object") {
  1061. rgb = cfg.rgb;
  1062. }
  1063. // check if already initialized
  1064. var done = $("#colors > div").length;
  1065. if (done > 0) { return; }
  1066. // add template
  1067. var template = $("#colorTemplate").children();
  1068. var line = $(template).clone();
  1069. line.appendTo("#colors");
  1070. // init color wheel
  1071. $("input[name='color']").wheelColorPicker({
  1072. sliders: (rgb ? "wrgbp" : "whsp")
  1073. }).on("sliderup", function() {
  1074. if (rgb) {
  1075. sendAction("color", {rgb: getPickerRGB(this)});
  1076. } else {
  1077. sendAction("color", {hsv: getPickerHSV(this)});
  1078. }
  1079. });
  1080. }
  1081. function initCCT() {
  1082. // check if already initialized
  1083. var done = $("#cct > div").length;
  1084. if (done > 0) { return; }
  1085. $("#miredsTemplate").children().clone().appendTo("#cct");
  1086. $("#mireds").on("change", function() {
  1087. var value = $(this).val();
  1088. var parent = $(this).parents(".pure-g");
  1089. $("span", parent).html(value);
  1090. sendAction("mireds", {mireds: value});
  1091. });
  1092. }
  1093. function initChannels(num) {
  1094. // check if already initialized
  1095. var done = $("#channels > div").length > 0;
  1096. if (done) { return; }
  1097. // does it have color channels?
  1098. var colors = $("#colors > div").length > 0;
  1099. // calculate channels to create
  1100. var max = num;
  1101. if (colors) {
  1102. max = num % 3;
  1103. if ((max > 0) & useWhite) {
  1104. max--;
  1105. if (useCCT) {
  1106. max--;
  1107. }
  1108. }
  1109. }
  1110. var start = num - max;
  1111. var onChannelSliderChange = function() {
  1112. var id = $(this).attr("data");
  1113. var value = $(this).val();
  1114. var parent = $(this).parents(".pure-g");
  1115. $("span", parent).html(value);
  1116. sendAction("channel", {id: id, value: value});
  1117. };
  1118. // add channel templates
  1119. var i = 0;
  1120. var template = $("#channelTemplate").children();
  1121. for (i=0; i<max; i++) {
  1122. var channel_id = start + i;
  1123. var line = $(template).clone();
  1124. $("span.slider", line).attr("data", channel_id);
  1125. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1126. $("label", line).html("Channel #" + channel_id);
  1127. line.appendTo("#channels");
  1128. }
  1129. // Init channel dropdowns
  1130. for (i=0; i<num; i++) {
  1131. $("select.islight").append(
  1132. $("<option></option>").attr("value",i).text("Channel #" + i));
  1133. }
  1134. // add brightness template
  1135. var template = $("#brightnessTemplate").children();
  1136. var line = $(template).clone();
  1137. line.appendTo("#channels");
  1138. // init bright slider
  1139. $("#brightness").on("change", function() {
  1140. var value = $(this).val();
  1141. var parent = $(this).parents(".pure-g");
  1142. $("span", parent).html(value);
  1143. sendAction("brightness", {value: value});
  1144. });
  1145. }
  1146. <!-- endRemoveIf(!light)-->
  1147. // -----------------------------------------------------------------------------
  1148. // RFBridge
  1149. // -----------------------------------------------------------------------------
  1150. <!-- removeIf(!rfbridge)-->
  1151. function rfbLearn() {
  1152. var parent = $(this).parents(".pure-g");
  1153. var input = $("input", parent);
  1154. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1155. }
  1156. function rfbForget() {
  1157. var parent = $(this).parents(".pure-g");
  1158. var input = $("input", parent);
  1159. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1160. }
  1161. function rfbSend() {
  1162. var parent = $(this).parents(".pure-g");
  1163. var input = $("input", parent);
  1164. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1165. }
  1166. function addRfbNode() {
  1167. var numNodes = $("#rfbNodes > legend").length;
  1168. var template = $("#rfbNodeTemplate").children();
  1169. var line = $(template).clone();
  1170. $("span", line).html(numNodes);
  1171. $(line).find("input").each(function() {
  1172. this.dataset["id"] = numNodes;
  1173. });
  1174. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1175. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1176. $(line).find(".button-rfb-send").on("click", rfbSend);
  1177. line.appendTo("#rfbNodes");
  1178. return line;
  1179. }
  1180. <!-- endRemoveIf(!rfbridge)-->
  1181. // -----------------------------------------------------------------------------
  1182. // LightFox
  1183. // -----------------------------------------------------------------------------
  1184. <!-- removeIf(!lightfox)-->
  1185. function lightfoxLearn() {
  1186. sendAction("lightfoxLearn", {});
  1187. }
  1188. function lightfoxClear() {
  1189. sendAction("lightfoxClear", {});
  1190. }
  1191. function initLightfox(data, relayCount) {
  1192. var numNodes = data.length;
  1193. var template = $("#lightfoxNodeTemplate").children();
  1194. var i, j;
  1195. for (i=0; i<numNodes; i++) {
  1196. var $line = $(template).clone();
  1197. $line.find("label > span").text(data[i]["id"]);
  1198. $line.find("select").each(function() {
  1199. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1200. for (j=0; j < relayCount; j++) {
  1201. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1202. }
  1203. $(this).val(data[i]["relay"]);
  1204. status = !status;
  1205. });
  1206. setOriginalsFromValues($("input,select", $line));
  1207. $line.appendTo("#lightfoxNodes");
  1208. }
  1209. var $panel = $("#panel-lightfox")
  1210. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1211. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1212. }
  1213. <!-- endRemoveIf(!lightfox)-->
  1214. // -----------------------------------------------------------------------------
  1215. // Processing
  1216. // -----------------------------------------------------------------------------
  1217. function processData(data) {
  1218. if (debug) console.log(data);
  1219. // title
  1220. if ("app_name" in data) {
  1221. var title = data.app_name;
  1222. if ("app_version" in data) {
  1223. title = title + " " + data.app_version;
  1224. }
  1225. $("span[name=title]").html(title);
  1226. if ("hostname" in data) {
  1227. title = data.hostname + " - " + title;
  1228. }
  1229. document.title = title;
  1230. }
  1231. Object.keys(data).forEach(function(key) {
  1232. var i;
  1233. var value = data[key];
  1234. // ---------------------------------------------------------------------
  1235. // Web mode
  1236. // ---------------------------------------------------------------------
  1237. if ("webMode" === key) {
  1238. password = (1 === value);
  1239. $("#layout").toggle(!password);
  1240. $("#password").toggle(password);
  1241. }
  1242. // ---------------------------------------------------------------------
  1243. // Actions
  1244. // ---------------------------------------------------------------------
  1245. if ("action" === key) {
  1246. if ("reload" === data.action) { doReload(1000); }
  1247. return;
  1248. }
  1249. // ---------------------------------------------------------------------
  1250. // RFBridge
  1251. // ---------------------------------------------------------------------
  1252. <!-- removeIf(!rfbridge)-->
  1253. if ("rfbCount" === key) {
  1254. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1255. return;
  1256. }
  1257. if ("rfb" === key) {
  1258. var rfb = data.rfb;
  1259. var size = rfb.size;
  1260. var start = rfb.start;
  1261. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1262. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1263. for (var i=0; i<size; ++i) {
  1264. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1265. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1266. }
  1267. return;
  1268. }
  1269. <!-- endRemoveIf(!rfbridge)-->
  1270. // ---------------------------------------------------------------------
  1271. // LightFox
  1272. // ---------------------------------------------------------------------
  1273. <!-- removeIf(!lightfox)-->
  1274. if ("lightfoxButtons" === key) {
  1275. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1276. return;
  1277. }
  1278. <!-- endRemoveIf(!lightfox)-->
  1279. // ---------------------------------------------------------------------
  1280. // RFM69
  1281. // ---------------------------------------------------------------------
  1282. <!-- removeIf(!rfm69)-->
  1283. if (key == "packet") {
  1284. var packet = data.packet;
  1285. var d = new Date();
  1286. packets.row.add([
  1287. d.toLocaleTimeString('en-US', { hour12: false }),
  1288. packet.senderID,
  1289. packet.packetID,
  1290. packet.targetID,
  1291. packet.key,
  1292. packet.value,
  1293. packet.rssi,
  1294. packet.duplicates,
  1295. packet.missing,
  1296. ]).draw(false);
  1297. return;
  1298. }
  1299. if (key == "mapping") {
  1300. for (var i in data.mapping) {
  1301. // add a new row
  1302. addMapping();
  1303. // get group
  1304. var line = $("#mapping .pure-g")[i];
  1305. // fill in the blanks
  1306. var mapping = data.mapping[i];
  1307. Object.keys(mapping).forEach(function(key) {
  1308. var id = "input[name=" + key + "]";
  1309. if ($(id, line).length) $(id, line).val(mapping[key]);
  1310. });
  1311. setOriginalsFromValues($("input", line));
  1312. }
  1313. return;
  1314. }
  1315. <!-- endRemoveIf(!rfm69)-->
  1316. // ---------------------------------------------------------------------
  1317. // RPN Rules
  1318. // ---------------------------------------------------------------------
  1319. if (key == "rpnRules") {
  1320. for (var i in data.rpnRules) {
  1321. // add a new row
  1322. addRPNRule();
  1323. // get group
  1324. var line = $("#rpnRules .pure-g")[i];
  1325. // fill in the blanks
  1326. var rule = data.rpnRules[i];
  1327. $("input", line).val(rule);
  1328. setOriginalsFromValues($("input", line));
  1329. }
  1330. return;
  1331. }
  1332. if (key == "rpnTopics") {
  1333. for (var i in data.rpnTopics) {
  1334. // add a new row
  1335. addRPNTopic();
  1336. // get group
  1337. var line = $("#rpnTopics .pure-g")[i];
  1338. // fill in the blanks
  1339. var topic = data.rpnTopics[i];
  1340. var name = data.rpnNames[i];
  1341. $("input[name='rpnTopic']", line).val(topic);
  1342. $("input[name='rpnName']", line).val(name);
  1343. setOriginalsFromValues($("input", line));
  1344. }
  1345. return;
  1346. }
  1347. if (key == "rpnNames") return;
  1348. // ---------------------------------------------------------------------
  1349. // Lights
  1350. // ---------------------------------------------------------------------
  1351. <!-- removeIf(!light)-->
  1352. if ("rgb" === key) {
  1353. initColor({rgb: true});
  1354. setPickerRGB($("input[name='color']"), value);
  1355. return;
  1356. }
  1357. if ("hsv" === key) {
  1358. initColor({hsv: true});
  1359. setPickerHSV($("input[name='color']"), value);
  1360. return;
  1361. }
  1362. if ("brightness" === key) {
  1363. $("#brightness").val(value);
  1364. $("span.brightness").html(value);
  1365. return;
  1366. }
  1367. if ("channels" === key) {
  1368. var len = value.length;
  1369. initChannels(len);
  1370. for (i in value) {
  1371. var ch = value[i];
  1372. $("input.slider[data=" + i + "]").val(ch);
  1373. $("span.slider[data=" + i + "]").html(ch);
  1374. }
  1375. return;
  1376. }
  1377. if ("mireds" === key) {
  1378. $("#mireds").attr("min", value["cold"]);
  1379. $("#mireds").attr("max", value["warm"]);
  1380. $("#mireds").val(value["value"]);
  1381. $("span.mireds").html(value["value"]);
  1382. return;
  1383. }
  1384. if ("useWhite" === key) {
  1385. useWhite = value;
  1386. }
  1387. if ("useCCT" === key) {
  1388. initCCT();
  1389. useCCT = value;
  1390. }
  1391. <!-- endRemoveIf(!light)-->
  1392. // ---------------------------------------------------------------------
  1393. // Sensors & Magnitudes
  1394. // ---------------------------------------------------------------------
  1395. <!-- removeIf(!sensor)-->
  1396. if ("magnitudesConfig" === key) {
  1397. initMagnitudes(value);
  1398. }
  1399. if ("magnitudes" === key) {
  1400. for (var i=0; i<value.size; ++i) {
  1401. var error = value.error[i] || 0;
  1402. var text = (0 === error) ?
  1403. value.value[i] + magnitudes[i].units :
  1404. magnitudeError(error);
  1405. var element = $("input[name='magnitude'][data='" + i + "']");
  1406. element.val(text);
  1407. }
  1408. return;
  1409. }
  1410. <!-- endRemoveIf(!sensor)-->
  1411. // ---------------------------------------------------------------------
  1412. // WiFi
  1413. // ---------------------------------------------------------------------
  1414. if ("maxNetworks" === key) {
  1415. maxNetworks = parseInt(value, 10);
  1416. return;
  1417. }
  1418. if ("wifi" === key) {
  1419. value.forEach(addNetwork);
  1420. return;
  1421. }
  1422. if ("scanResult" === key) {
  1423. $("div.scan.loading").hide();
  1424. $("#scanResult").show();
  1425. }
  1426. // -----------------------------------------------------------------------------
  1427. // Home Assistant
  1428. // -----------------------------------------------------------------------------
  1429. if ("haConfig" === key) {
  1430. send("{}");
  1431. $("#haConfig")
  1432. .append(new Text(value))
  1433. .height($("#haConfig")[0].scrollHeight);
  1434. return;
  1435. }
  1436. // -----------------------------------------------------------------------------
  1437. // Relays scheduler
  1438. // -----------------------------------------------------------------------------
  1439. if ("schedules" === key) {
  1440. $("#schedules").attr("data-settings-max", value.max);
  1441. for (var i=0; i<value.size; ++i) {
  1442. // XXX: no
  1443. var sch_map = {};
  1444. Object.keys(value).forEach(function(key) {
  1445. if ("size" == key) return;
  1446. if ("max" == key) return;
  1447. sch_map[key] = value[key][i];
  1448. });
  1449. addSchedule(sch_map);
  1450. }
  1451. return;
  1452. }
  1453. // ---------------------------------------------------------------------
  1454. // Relays
  1455. // ---------------------------------------------------------------------
  1456. if ("relayState" === key) {
  1457. initRelays(value.status);
  1458. updateRelays(value);
  1459. return;
  1460. }
  1461. // Relay configuration
  1462. if ("relayConfig" === key) {
  1463. initRelayConfig(value);
  1464. return;
  1465. }
  1466. // ---------------------------------------------------------------------
  1467. // LEDs
  1468. // ---------------------------------------------------------------------
  1469. if ("ledConfig" === key) {
  1470. initLeds(value);
  1471. for (var i=0; i<value.length; ++i) {
  1472. var mode = $("select[name='ledMode'][data='" + i + "']");
  1473. var relay = $("select[name='ledRelay'][data='" + i + "']");
  1474. mode.val(value[i].mode);
  1475. relay.val(value[i].relay);
  1476. setOriginalsFromValues($([mode,relay]));
  1477. }
  1478. return;
  1479. }
  1480. // ---------------------------------------------------------------------
  1481. // Domoticz
  1482. // ---------------------------------------------------------------------
  1483. // Domoticz - Relays
  1484. if ("dczRelays" === key) {
  1485. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1486. return;
  1487. }
  1488. // Domoticz - Magnitudes
  1489. <!-- removeIf(!sensor)-->
  1490. if ("dczMagnitudes" === key) {
  1491. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1492. return;
  1493. }
  1494. <!-- endRemoveIf(!sensor)-->
  1495. // ---------------------------------------------------------------------
  1496. // Thingspeak
  1497. // ---------------------------------------------------------------------
  1498. // Thingspeak - Relays
  1499. if ("tspkRelays" === key) {
  1500. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1501. return;
  1502. }
  1503. // Thingspeak - Magnitudes
  1504. <!-- removeIf(!sensor)-->
  1505. if ("tspkMagnitudes" === key) {
  1506. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1507. return;
  1508. }
  1509. <!-- endRemoveIf(!sensor)-->
  1510. // ---------------------------------------------------------------------
  1511. // HTTP API
  1512. // ---------------------------------------------------------------------
  1513. // Auto generate an APIKey if none defined yet
  1514. if ("apiVisible" === key) {
  1515. if (data.apiKey === undefined || data.apiKey === "") {
  1516. generateAPIKey();
  1517. }
  1518. }
  1519. // ---------------------------------------------------------------------
  1520. // General
  1521. // ---------------------------------------------------------------------
  1522. // Messages
  1523. if ("message" === key) {
  1524. if (value == 8) {
  1525. configurationSaved = true;
  1526. }
  1527. window.alert(messages[value]);
  1528. return;
  1529. }
  1530. // Web log
  1531. if ("weblog" === key) {
  1532. send("{}");
  1533. var msg = value["msg"];
  1534. var pre = value["pre"];
  1535. for (var i=0; i < msg.length; ++i) {
  1536. if (pre[i]) {
  1537. $("#weblog").append(new Text(pre[i]));
  1538. }
  1539. $("#weblog").append(new Text(msg[i]));
  1540. }
  1541. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1542. return;
  1543. }
  1544. // Enable options
  1545. var position = key.indexOf("Visible");
  1546. if (position > 0 && position === key.length - 7) {
  1547. var module = key.slice(0,-7);
  1548. if (module == "sch") {
  1549. $("li.module-" + module).css("display", "inherit");
  1550. $("div.module-" + module).css("display", "flex");
  1551. return;
  1552. }
  1553. $(".module-" + module).css("display", "inherit");
  1554. return;
  1555. }
  1556. if ("deviceip" === key) {
  1557. var a_href = $("span[name='" + key + "']").parent();
  1558. a_href.attr("href", "//" + value);
  1559. a_href.next().attr("href", "telnet://" + value);
  1560. }
  1561. if ("now" === key) {
  1562. now = value;
  1563. return;
  1564. }
  1565. if ("free_size" === key) {
  1566. free_size = parseInt(value, 10);
  1567. }
  1568. // Pre-process
  1569. if ("mqttStatus" === key) {
  1570. value = value ? "CONNECTED" : "NOT CONNECTED";
  1571. }
  1572. if ("ntpStatus" === key) {
  1573. value = value ? "SYNC'D" : "NOT SYNC'D";
  1574. }
  1575. if ("uptime" === key) {
  1576. ago = 0;
  1577. var uptime = parseInt(value, 10);
  1578. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1579. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1580. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1581. var days = uptime;
  1582. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1583. }
  1584. <!-- removeIf(!thermostat)-->
  1585. if ("tmpUnits" == key) {
  1586. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1587. }
  1588. <!-- endRemoveIf(!thermostat)-->
  1589. // ---------------------------------------------------------------------
  1590. // Matching
  1591. // ---------------------------------------------------------------------
  1592. var elems = [];
  1593. var pre;
  1594. var post;
  1595. // Look for INPUTs
  1596. var input = $("input[name='" + key + "']");
  1597. if (input.length > 0) {
  1598. if (input.attr("type") === "checkbox") {
  1599. input.prop("checked", value);
  1600. } else if (input.attr("type") === "radio") {
  1601. input.val([value]);
  1602. } else {
  1603. pre = input.attr("pre") || "";
  1604. post = input.attr("post") || "";
  1605. input.val(pre + value + post);
  1606. }
  1607. elems.push(input);
  1608. }
  1609. // Look for SPANs
  1610. var span = $("span[name='" + key + "']");
  1611. if (span.length > 0) {
  1612. if (Array.isArray(value)) {
  1613. value.forEach(function(elem) {
  1614. span.append(elem);
  1615. span.append('</br>');
  1616. elems.push(span);
  1617. });
  1618. } else {
  1619. pre = span.attr("pre") || "";
  1620. post = span.attr("post") || "";
  1621. span.html(pre + value + post);
  1622. elems.push(span);
  1623. }
  1624. }
  1625. // Look for SELECTs
  1626. var select = $("select[name='" + key + "']");
  1627. if (select.length > 0) {
  1628. select.val(value);
  1629. elems.push(select);
  1630. }
  1631. setOriginalsFromValues($(elems));
  1632. });
  1633. }
  1634. function hasChanged() {
  1635. var newValue, originalValue;
  1636. if ($(this).attr("type") === "checkbox") {
  1637. newValue = $(this).prop("checked");
  1638. originalValue = ($(this).attr("original") === "true");
  1639. } else {
  1640. newValue = $(this).val();
  1641. originalValue = $(this).attr("original");
  1642. }
  1643. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1644. var action = $(this).attr("action");
  1645. if (typeof originalValue === "undefined") { return; }
  1646. if ("none" === action) { return; }
  1647. if (newValue !== originalValue) {
  1648. if (!hasChanged) {
  1649. ++numChanged;
  1650. if ("reconnect" === action) { ++numReconnect; }
  1651. if ("reboot" === action) { ++numReboot; }
  1652. if ("reload" === action) { ++numReload; }
  1653. }
  1654. $(this).attr("hasChanged", true);
  1655. } else {
  1656. if (hasChanged) {
  1657. --numChanged;
  1658. if ("reconnect" === action) { --numReconnect; }
  1659. if ("reboot" === action) { --numReboot; }
  1660. if ("reload" === action) { --numReload; }
  1661. }
  1662. $(this).attr("hasChanged", false);
  1663. }
  1664. }
  1665. // -----------------------------------------------------------------------------
  1666. // Init & connect
  1667. // -----------------------------------------------------------------------------
  1668. function initUrls(root) {
  1669. var paths = ["ws", "upgrade", "config", "auth"];
  1670. urls["root"] = root;
  1671. paths.forEach(function(path) {
  1672. urls[path] = new URL(path, root);
  1673. urls[path].protocol = root.protocol;
  1674. });
  1675. if (root.protocol == "https:") {
  1676. urls.ws.protocol = "wss:";
  1677. } else {
  1678. urls.ws.protocol = "ws:";
  1679. }
  1680. }
  1681. function connectToURL(url) {
  1682. initUrls(url);
  1683. fetch(urls.auth.href, {
  1684. 'method': 'GET',
  1685. 'cors': true,
  1686. 'credentials': 'same-origin'
  1687. }).then(function(response) {
  1688. // Nothing to do, reload page and retry
  1689. if (response.status != 200) {
  1690. doReload(5000);
  1691. return;
  1692. }
  1693. // update websock object
  1694. if (websock) { websock.close(); }
  1695. websock = new WebSocket(urls.ws.href);
  1696. websock.onmessage = function(evt) {
  1697. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1698. if (data) {
  1699. processData(data);
  1700. }
  1701. };
  1702. }).catch(function(error) {
  1703. console.log(error);
  1704. doReload(5000);
  1705. });
  1706. }
  1707. function connect(host) {
  1708. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1709. host = "http://" + host;
  1710. }
  1711. connectToURL(new URL(host));
  1712. }
  1713. function connectToCurrentURL() {
  1714. connectToURL(new URL(window.location));
  1715. }
  1716. $(function() {
  1717. initMessages();
  1718. loadTimeZones();
  1719. createCheckboxes();
  1720. setInterval(function() { keepTime(); }, 1000);
  1721. $(".password-reveal").on("click", toggleVisiblePassword);
  1722. $("#menuLink").on("click", toggleMenu);
  1723. $(".pure-menu-link").on("click", showPanel);
  1724. $("progress").attr({ value: 0, max: 100 });
  1725. $(".button-update").on("click", doUpdate);
  1726. $(".button-update-password").on("click", doUpdatePassword);
  1727. $(".button-generate-password").on("click", doGeneratePassword);
  1728. $(".button-reboot").on("click", doReboot);
  1729. $(".button-reconnect").on("click", doReconnect);
  1730. $(".button-wifi-scan").on("click", doScan);
  1731. $(".button-ha-config").on("click", doHAConfig);
  1732. $(".button-dbgcmd").on("click", doDebugCommand);
  1733. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1734. $(".button-dbg-clear").on("click", doDebugClear);
  1735. $(".button-settings-backup").on("click", doBackup);
  1736. $(".button-settings-restore").on("click", doRestore);
  1737. $(".button-settings-factory").on("click", doFactoryReset);
  1738. $("#uploader").on("change", onFileUpload);
  1739. $(".button-upgrade").on("click", doUpgrade);
  1740. <!-- removeIf(!thermostat)-->
  1741. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1742. <!-- endRemoveIf(!thermostat)-->
  1743. $(".button-apikey").on("click", generateAPIKey);
  1744. $(".button-upgrade-browse").on("click", function() {
  1745. $("input[name='upgrade']")[0].click();
  1746. return false;
  1747. });
  1748. $("input[name='upgrade']").change(function (){
  1749. var file = this.files[0];
  1750. $("input[name='filename']").val(file.name);
  1751. });
  1752. $(".button-add-network").on("click", function() {
  1753. $(".more", addNetwork()).toggle();
  1754. });
  1755. $(".button-add-switch-schedule").on("click", function() {
  1756. addSchedule({schType: 1, schSwitch: -1});
  1757. });
  1758. <!-- removeIf(!light)-->
  1759. $(".button-add-light-schedule").on("click", function() {
  1760. addSchedule({schType: 2, schSwitch: -1});
  1761. });
  1762. <!-- endRemoveIf(!light)-->
  1763. $(".button-add-rpnrule").on('click', addRPNRule);
  1764. $(".button-add-rpntopic").on('click', addRPNTopic);
  1765. $(".button-del-parent").on('click', delParent);
  1766. <!-- removeIf(!rfm69)-->
  1767. $(".button-add-mapping").on('click', addMapping);
  1768. $(".button-clear-counts").on('click', doClearCounts);
  1769. $(".button-clear-messages").on('click', doClearMessages);
  1770. $(".button-clear-filters").on('click', doClearFilters);
  1771. $('#packets tbody').on('mousedown', 'td', doFilter);
  1772. packets = $('#packets').DataTable({
  1773. "paging": false
  1774. });
  1775. for (var i = 0; i < packets.columns()[0].length; i++) {
  1776. filters[i] = false;
  1777. }
  1778. <!-- endRemoveIf(!rfm69)-->
  1779. $(".gpio-select").each(function(_, elem) {
  1780. initSelectGPIO(elem)
  1781. });
  1782. $(document).on("change", "input", hasChanged);
  1783. $(document).on("change", "select", hasChanged);
  1784. $("textarea").on("dblclick", function() { this.select(); });
  1785. resetOriginals();
  1786. $(".group-settings").each(function() {
  1787. groupSettingsObserver.observe(this, {childList: true});
  1788. });
  1789. // don't autoconnect when opening from filesystem
  1790. if (window.location.protocol === "file:") {
  1791. return;
  1792. }
  1793. // Check host param in query string
  1794. var search = new URLSearchParams(window.location.search),
  1795. host = search.get("host");
  1796. if (host !== null) {
  1797. connect(host);
  1798. } else {
  1799. connectToCurrentURL();
  1800. }
  1801. });