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.

2235 lines
64 KiB

8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
5 years ago
5 years ago
8 years ago
8 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  5. var messages = [];
  6. var free_size = 0;
  7. var urls = {};
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var configurationSaved = false;
  13. var useWhite = false;
  14. var useCCT = false;
  15. var now = 0;
  16. var ago = 0;
  17. <!-- removeIf(!rfm69)-->
  18. var packets;
  19. var filters = [];
  20. <!-- endRemoveIf(!rfm69)-->
  21. <!-- removeIf(!sensor)-->
  22. var magnitudes = [];
  23. <!-- endRemoveIf(!sensor)-->
  24. // -----------------------------------------------------------------------------
  25. // Messages
  26. // -----------------------------------------------------------------------------
  27. function initMessages() {
  28. messages[1] = "Remote update started";
  29. messages[2] = "OTA update started";
  30. messages[3] = "Error parsing data!";
  31. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  32. messages[5] = "Changes saved. You should reboot your board now";
  33. messages[7] = "Passwords do not match!";
  34. messages[8] = "Changes saved";
  35. messages[9] = "No changes detected";
  36. messages[10] = "Session expired, please reload page...";
  37. }
  38. <!-- removeIf(!sensor)-->
  39. function sensorName(id) {
  40. var names = [
  41. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  42. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  43. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  44. "SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
  45. "T6613", "TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
  46. "NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
  47. "EZOPH"
  48. ];
  49. if (1 <= id && id <= names.length) {
  50. return names[id - 1];
  51. }
  52. return null;
  53. }
  54. function magnitudeType(type) {
  55. var types = [
  56. "Temperature", "Humidity", "Pressure",
  57. "Current", "Voltage", "Active Power", "Apparent Power",
  58. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  59. "Analog", "Digital", "Event",
  60. "PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
  61. "Local Dose Rate", "Local Dose Rate",
  62. "Count",
  63. "NO2", "CO", "Resistance", "pH"
  64. ];
  65. if (1 <= type && type <= types.length) {
  66. return types[type - 1];
  67. }
  68. return null;
  69. }
  70. function magnitudeError(error) {
  71. var errors = [
  72. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  73. "Data Error", "I2C Error", "GPIO Error", "Calibration error"
  74. ];
  75. if (0 <= error && error < errors.length) {
  76. return errors[error];
  77. }
  78. return "Error " + error;
  79. }
  80. <!-- endRemoveIf(!sensor)-->
  81. // -----------------------------------------------------------------------------
  82. // Utils
  83. // -----------------------------------------------------------------------------
  84. $.fn.enterKey = function (fnc) {
  85. return this.each(function () {
  86. $(this).keypress(function (ev) {
  87. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  88. if (13 === keycode) {
  89. return fnc.call(this, ev);
  90. }
  91. });
  92. });
  93. };
  94. function keepTime() {
  95. $("span[name='ago']").html(ago);
  96. ago++;
  97. if (0 === now) { return; }
  98. var date = new Date(now * 1000);
  99. var text = date.toISOString().substring(0, 19).replace("T", " ");
  100. $("input[name='now']").val(text);
  101. $("span[name='now']").html(text);
  102. now++;
  103. }
  104. function zeroPad(number, positions) {
  105. return number.toString().padStart(positions, "0");
  106. }
  107. function loadTimeZones() {
  108. var time_zones = [
  109. -720, -660, -600, -570, -540,
  110. -480, -420, -360, -300, -240,
  111. -210, -180, -120, -60, 0,
  112. 60, 120, 180, 210, 240,
  113. 270, 300, 330, 345, 360,
  114. 390, 420, 480, 510, 525,
  115. 540, 570, 600, 630, 660,
  116. 720, 765, 780, 840
  117. ];
  118. for (var i in time_zones) {
  119. var tz = time_zones[i];
  120. var offset = tz >= 0 ? tz : -tz;
  121. var text = "GMT" + (tz >= 0 ? "+" : "-") +
  122. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  123. zeroPad(offset % 60, 2);
  124. $("select[name='ntpOffset']").append(
  125. $("<option></option>")
  126. .attr("value", tz)
  127. .text(text)
  128. );
  129. }
  130. }
  131. function validatePassword(password) {
  132. // http://www.the-art-of-web.com/javascript/validate-password/
  133. // at least one lowercase and one uppercase letter or number
  134. // at least eight characters (letters, numbers or special characters)
  135. // MUST be 8..63 printable ASCII characters. See:
  136. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  137. // https://github.com/xoseperez/espurna/issues/1151
  138. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  139. return (
  140. (password !== undefined)
  141. && (typeof password === "string")
  142. && (password.length > 0)
  143. && re_password.test(password)
  144. );
  145. }
  146. function validateFormPasswords(form) {
  147. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  148. var adminPass1 = passwords.first().val(),
  149. adminPass2 = passwords.last().val();
  150. var formValidity = passwords.first()[0].checkValidity();
  151. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  152. return true;
  153. }
  154. var validPass1 = validatePassword(adminPass1),
  155. validPass2 = validatePassword(adminPass2);
  156. if (formValidity && validPass1 && validPass2) {
  157. return true;
  158. }
  159. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  160. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  161. }
  162. if (adminPass1 !== adminPass2) {
  163. alert("Passwords are different!");
  164. }
  165. return false;
  166. }
  167. function validateFormHostname(form) {
  168. // RFCs mandate that a hostname's labels may contain only
  169. // the ASCII letters 'a' through 'z' (case-insensitive),
  170. // the digits '0' through '9', and the hyphen.
  171. // Hostname labels cannot begin or end with a hyphen.
  172. // No other symbols, punctuation characters, or blank spaces are permitted.
  173. // Negative lookbehind does not work in Javascript
  174. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
  175. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
  176. var hostname = $("input[name='hostname']", form);
  177. if ("true" !== hostname.attr("hasChanged")) {
  178. return true;
  179. }
  180. if (re_hostname.test(hostname.val())) {
  181. return true;
  182. }
  183. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  184. return false;
  185. }
  186. function validateForm(form) {
  187. return validateFormPasswords(form) && validateFormHostname(form);
  188. }
  189. // Observe all group settings to selectively update originals based on the current data
  190. var groupSettingsObserver = new MutationObserver(function(mutations) {
  191. mutations.forEach(function(mutation) {
  192. // If any new elements are added, set "settings-target" element as changed to forcibly send the data
  193. var targets = $(mutation.target).attr("data-settings-target");
  194. if (targets !== undefined) {
  195. mutation.addedNodes.forEach(function(node) {
  196. var overrides = [];
  197. targets.split(" ").forEach(function(target) {
  198. var elem = $("[name='" + target + "']", node);
  199. if (!elem.length) return;
  200. var value = getValue(elem);
  201. if ((value === null) || (value === elem[0].defaultValue)) {
  202. overrides.push(elem);
  203. }
  204. });
  205. setOriginalsFromValues($("input,select", node));
  206. overrides.forEach(function(elem) {
  207. elem.attr("hasChanged", "true");
  208. if (elem.prop("tagName") === "SELECT") {
  209. elem.prop("value", 0);
  210. }
  211. });
  212. });
  213. }
  214. // If anything was removed, forcibly send **all** of the group to avoid having any outdated keys
  215. // TODO: hide instead of remove?
  216. var changed = $(mutation.target).attr("hasChanged") === "true";
  217. if (changed || mutation.removedNodes.length) {
  218. $(mutation.target).attr("hasChanged", "true");
  219. $("input,select", mutation.target.childNodes).attr("hasChanged", "true");
  220. }
  221. });
  222. });
  223. // These fields will always be a list of values
  224. function isGroupValue(value) {
  225. var names = [
  226. "ssid", "pass", "gw", "mask", "ip", "dns",
  227. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  228. "relayBoot", "relayPulse", "relayTime", "relayLastSch",
  229. "mqttGroup", "mqttGroupSync", "relayOnDisc",
  230. "dczRelayIdx", "dczMagnitude",
  231. "tspkRelay", "tspkMagnitude",
  232. "ledMode", "ledRelay",
  233. "adminPass",
  234. "node", "key", "topic",
  235. "rpnRule", "rpnTopic", "rpnName"
  236. ];
  237. return names.indexOf(value) >= 0;
  238. }
  239. function getValue(element) {
  240. if ($(element).attr("type") === "checkbox") {
  241. return $(element).prop("checked") ? 1 : 0;
  242. } else if ($(element).attr("type") === "radio") {
  243. if (!$(element).prop("checked")) {
  244. return null;
  245. }
  246. }
  247. return $(element).val();
  248. }
  249. function addValue(data, name, value) {
  250. if (name in data) {
  251. if (!Array.isArray(data[name])) {
  252. data[name] = [data[name]];
  253. }
  254. data[name].push(value);
  255. } else if (isGroupValue(name)) {
  256. data[name] = [value];
  257. } else {
  258. data[name] = value;
  259. }
  260. }
  261. function getData(form, changed, cleanup) {
  262. // Populate two sets of data, ones that had been changed and ones that stayed the same
  263. var data = {};
  264. var changed_data = [];
  265. if (cleanup === undefined) {
  266. cleanup = true;
  267. }
  268. if (changed === undefined) {
  269. changed = true;
  270. }
  271. $("input,select", form).each(function() {
  272. if ($(this).attr("data-settings-ignore") === "true") {
  273. return;
  274. }
  275. var name = $(this).attr("name");
  276. var real_name = $(this).attr("data-settings-real-name");
  277. if (real_name !== undefined) {
  278. name = real_name;
  279. }
  280. var value = getValue(this);
  281. if (null !== value) {
  282. var haschanged = ("true" === $(this).attr("hasChanged"));
  283. var indexed = changed_data.indexOf(name) >= 0;
  284. if ((haschanged || !changed) && !indexed) {
  285. changed_data.push(name);
  286. }
  287. addValue(data, name, value);
  288. }
  289. });
  290. // Finally, filter out only fields that had changed.
  291. // Note: We need to preserve dynamic lists like schedules, wifi etc.
  292. // so we don't accidentally break when user deletes entry in the middle
  293. var resulting_data = {};
  294. for (var value in data) {
  295. if (changed_data.indexOf(value) >= 0) {
  296. resulting_data[value] = data[value];
  297. }
  298. }
  299. // Hack: clean-up leftover arrays.
  300. // When empty, the receiving side will prune all keys greater than the current one.
  301. if (cleanup) {
  302. $(".group-settings").each(function() {
  303. var haschanged = ("true" === $(this).attr("hasChanged"));
  304. if (haschanged && !this.children.length) {
  305. var targets = this.dataset.settingsTarget;
  306. if (targets === undefined) return;
  307. targets.split(" ").forEach(function(target) {
  308. resulting_data[target] = [];
  309. });
  310. }
  311. });
  312. }
  313. return resulting_data;
  314. }
  315. function randomString(length, args) {
  316. if (typeof args === "undefined") {
  317. args = {
  318. lowercase: true,
  319. uppercase: true,
  320. numbers: true,
  321. special: true
  322. }
  323. }
  324. var mask = "";
  325. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  326. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  327. if (args.numbers || args.hex) { mask += "0123456789"; }
  328. if (args.hex) { mask += "ABCDEF"; }
  329. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  330. var source = new Uint32Array(length);
  331. var result = new Array(length);
  332. window.crypto.getRandomValues(source).forEach(function(value, i) {
  333. result[i] = mask[value % mask.length];
  334. });
  335. return result.join("");
  336. }
  337. function generateAPIKey() {
  338. var apikey = randomString(16, {hex: true});
  339. $("input[name='apiKey']")
  340. .val(apikey)
  341. .attr("original", "-".repeat(16))
  342. .attr("haschanged", "true");
  343. return false;
  344. }
  345. function generatePassword() {
  346. var password = "";
  347. do {
  348. password = randomString(10);
  349. } while (!validatePassword(password));
  350. return password;
  351. }
  352. function toggleVisiblePassword() {
  353. var elem = this.previousElementSibling;
  354. if (elem.type === "password") {
  355. elem.type = "text";
  356. } else {
  357. elem.type = "password";
  358. }
  359. return false;
  360. }
  361. function doGeneratePassword() {
  362. var elems = $("input", $("#formPassword"));
  363. elems
  364. .val(generatePassword())
  365. .attr("haschanged", "true")
  366. .each(function() {
  367. this.type = "text";
  368. });
  369. return false;
  370. }
  371. function getJson(str) {
  372. try {
  373. return JSON.parse(str);
  374. } catch (e) {
  375. return false;
  376. }
  377. }
  378. <!-- removeIf(!thermostat)-->
  379. function checkTempRangeMin() {
  380. var min = parseInt($("#tempRangeMinInput").val(), 10);
  381. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  382. if (min > max - 1) {
  383. $("#tempRangeMinInput").val(max - 1);
  384. }
  385. }
  386. function checkTempRangeMax() {
  387. var min = parseInt($("#tempRangeMinInput").val(), 10);
  388. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  389. if (max < min + 1) {
  390. $("#tempRangeMaxInput").val(min + 1);
  391. }
  392. }
  393. function doResetThermostatCounters(ask) {
  394. var question = (typeof ask === "undefined" || false === ask) ?
  395. null :
  396. "Are you sure you want to reset burning counters?";
  397. return doAction(question, "thermostat_reset_counters");
  398. }
  399. <!-- endRemoveIf(!thermostat)-->
  400. function initSelectGPIO(select) {
  401. // TODO: properly lock used GPIOs via locking and apply the mask here
  402. var mapping = [
  403. [153, "NONE"],
  404. [0, "0 (FLASH)"],
  405. [1, "1 (U0TXD)"],
  406. [2, "2 (U1TXD)"],
  407. [3, "3 (U0RXD)"],
  408. [4, "4 (SDA)"],
  409. [5, "5 (SCL)"],
  410. [9, "9 (SDD2)"],
  411. [10, "10 (SDD3)"],
  412. [12, "12 (MTDI)"],
  413. [13, "13 (MTCK)"],
  414. [14, "14 (MTMS)"],
  415. [15, "15 (MTDO)"],
  416. [16, "15 (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. var status = true;
  1171. $("span", line).html(numNodes);
  1172. $(line).find("input").each(function() {
  1173. $(this).data("id", numNodes);
  1174. $(this).attr("status", status ? 1 : 0);
  1175. status = !status;
  1176. });
  1177. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1178. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1179. $(line).find(".button-rfb-send").on("click", rfbSend);
  1180. line.appendTo("#rfbNodes");
  1181. return line;
  1182. }
  1183. <!-- endRemoveIf(!rfbridge)-->
  1184. // -----------------------------------------------------------------------------
  1185. // LightFox
  1186. // -----------------------------------------------------------------------------
  1187. <!-- removeIf(!lightfox)-->
  1188. function lightfoxLearn() {
  1189. sendAction("lightfoxLearn", {});
  1190. }
  1191. function lightfoxClear() {
  1192. sendAction("lightfoxClear", {});
  1193. }
  1194. function initLightfox(data, relayCount) {
  1195. var numNodes = data.length;
  1196. var template = $("#lightfoxNodeTemplate").children();
  1197. var i, j;
  1198. for (i=0; i<numNodes; i++) {
  1199. var $line = $(template).clone();
  1200. $line.find("label > span").text(data[i]["id"]);
  1201. $line.find("select").each(function() {
  1202. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1203. for (j=0; j < relayCount; j++) {
  1204. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1205. }
  1206. $(this).val(data[i]["relay"]);
  1207. status = !status;
  1208. });
  1209. setOriginalsFromValues($("input,select", $line));
  1210. $line.appendTo("#lightfoxNodes");
  1211. }
  1212. var $panel = $("#panel-lightfox")
  1213. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1214. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1215. }
  1216. <!-- endRemoveIf(!lightfox)-->
  1217. // -----------------------------------------------------------------------------
  1218. // Processing
  1219. // -----------------------------------------------------------------------------
  1220. function processData(data) {
  1221. if (debug) console.log(data);
  1222. // title
  1223. if ("app_name" in data) {
  1224. var title = data.app_name;
  1225. if ("app_version" in data) {
  1226. title = title + " " + data.app_version;
  1227. }
  1228. $("span[name=title]").html(title);
  1229. if ("hostname" in data) {
  1230. title = data.hostname + " - " + title;
  1231. }
  1232. document.title = title;
  1233. }
  1234. Object.keys(data).forEach(function(key) {
  1235. var i;
  1236. var value = data[key];
  1237. // ---------------------------------------------------------------------
  1238. // Web mode
  1239. // ---------------------------------------------------------------------
  1240. if ("webMode" === key) {
  1241. password = (1 === value);
  1242. $("#layout").toggle(!password);
  1243. $("#password").toggle(password);
  1244. }
  1245. // ---------------------------------------------------------------------
  1246. // Actions
  1247. // ---------------------------------------------------------------------
  1248. if ("action" === key) {
  1249. if ("reload" === data.action) { doReload(1000); }
  1250. return;
  1251. }
  1252. // ---------------------------------------------------------------------
  1253. // RFBridge
  1254. // ---------------------------------------------------------------------
  1255. <!-- removeIf(!rfbridge)-->
  1256. if ("rfbCount" === key) {
  1257. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1258. return;
  1259. }
  1260. if ("rfb" === key) {
  1261. var rfb = data.rfb;
  1262. var size = rfb.size;
  1263. var start = rfb.start;
  1264. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1265. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1266. for (var i=0; i<size; ++i) {
  1267. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1268. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1269. }
  1270. return;
  1271. }
  1272. <!-- endRemoveIf(!rfbridge)-->
  1273. // ---------------------------------------------------------------------
  1274. // LightFox
  1275. // ---------------------------------------------------------------------
  1276. <!-- removeIf(!lightfox)-->
  1277. if ("lightfoxButtons" === key) {
  1278. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1279. return;
  1280. }
  1281. <!-- endRemoveIf(!lightfox)-->
  1282. // ---------------------------------------------------------------------
  1283. // RFM69
  1284. // ---------------------------------------------------------------------
  1285. <!-- removeIf(!rfm69)-->
  1286. if (key == "packet") {
  1287. var packet = data.packet;
  1288. var d = new Date();
  1289. packets.row.add([
  1290. d.toLocaleTimeString('en-US', { hour12: false }),
  1291. packet.senderID,
  1292. packet.packetID,
  1293. packet.targetID,
  1294. packet.key,
  1295. packet.value,
  1296. packet.rssi,
  1297. packet.duplicates,
  1298. packet.missing,
  1299. ]).draw(false);
  1300. return;
  1301. }
  1302. if (key == "mapping") {
  1303. for (var i in data.mapping) {
  1304. // add a new row
  1305. addMapping();
  1306. // get group
  1307. var line = $("#mapping .pure-g")[i];
  1308. // fill in the blanks
  1309. var mapping = data.mapping[i];
  1310. Object.keys(mapping).forEach(function(key) {
  1311. var id = "input[name=" + key + "]";
  1312. if ($(id, line).length) $(id, line).val(mapping[key]);
  1313. });
  1314. setOriginalsFromValues($("input", line));
  1315. }
  1316. return;
  1317. }
  1318. <!-- endRemoveIf(!rfm69)-->
  1319. // ---------------------------------------------------------------------
  1320. // RPN Rules
  1321. // ---------------------------------------------------------------------
  1322. if (key == "rpnRules") {
  1323. for (var i in data.rpnRules) {
  1324. // add a new row
  1325. addRPNRule();
  1326. // get group
  1327. var line = $("#rpnRules .pure-g")[i];
  1328. // fill in the blanks
  1329. var rule = data.rpnRules[i];
  1330. $("input", line).val(rule);
  1331. setOriginalsFromValues($("input", line));
  1332. }
  1333. return;
  1334. }
  1335. if (key == "rpnTopics") {
  1336. for (var i in data.rpnTopics) {
  1337. // add a new row
  1338. addRPNTopic();
  1339. // get group
  1340. var line = $("#rpnTopics .pure-g")[i];
  1341. // fill in the blanks
  1342. var topic = data.rpnTopics[i];
  1343. var name = data.rpnNames[i];
  1344. $("input[name='rpnTopic']", line).val(topic);
  1345. $("input[name='rpnName']", line).val(name);
  1346. setOriginalsFromValues($("input", line));
  1347. }
  1348. return;
  1349. }
  1350. if (key == "rpnNames") return;
  1351. // ---------------------------------------------------------------------
  1352. // Lights
  1353. // ---------------------------------------------------------------------
  1354. <!-- removeIf(!light)-->
  1355. if ("rgb" === key) {
  1356. initColor({rgb: true});
  1357. setPickerRGB($("input[name='color']"), value);
  1358. return;
  1359. }
  1360. if ("hsv" === key) {
  1361. initColor({hsv: true});
  1362. setPickerHSV($("input[name='color']"), value);
  1363. return;
  1364. }
  1365. if ("brightness" === key) {
  1366. $("#brightness").val(value);
  1367. $("span.brightness").html(value);
  1368. return;
  1369. }
  1370. if ("channels" === key) {
  1371. var len = value.length;
  1372. initChannels(len);
  1373. for (i in value) {
  1374. var ch = value[i];
  1375. $("input.slider[data=" + i + "]").val(ch);
  1376. $("span.slider[data=" + i + "]").html(ch);
  1377. }
  1378. return;
  1379. }
  1380. if ("mireds" === key) {
  1381. $("#mireds").attr("min", value["cold"]);
  1382. $("#mireds").attr("max", value["warm"]);
  1383. $("#mireds").val(value["value"]);
  1384. $("span.mireds").html(value["value"]);
  1385. return;
  1386. }
  1387. if ("useWhite" === key) {
  1388. useWhite = value;
  1389. }
  1390. if ("useCCT" === key) {
  1391. initCCT();
  1392. useCCT = value;
  1393. }
  1394. <!-- endRemoveIf(!light)-->
  1395. // ---------------------------------------------------------------------
  1396. // Sensors & Magnitudes
  1397. // ---------------------------------------------------------------------
  1398. <!-- removeIf(!sensor)-->
  1399. if ("magnitudesConfig" === key) {
  1400. initMagnitudes(value);
  1401. }
  1402. if ("magnitudes" === key) {
  1403. for (var i=0; i<value.size; ++i) {
  1404. var error = value.error[i] || 0;
  1405. var text = (0 === error) ?
  1406. value.value[i] + magnitudes[i].units :
  1407. magnitudeError(error);
  1408. var element = $("input[name='magnitude'][data='" + i + "']");
  1409. element.val(text);
  1410. }
  1411. return;
  1412. }
  1413. <!-- endRemoveIf(!sensor)-->
  1414. // ---------------------------------------------------------------------
  1415. // WiFi
  1416. // ---------------------------------------------------------------------
  1417. if ("maxNetworks" === key) {
  1418. maxNetworks = parseInt(value, 10);
  1419. return;
  1420. }
  1421. if ("wifi" === key) {
  1422. value.forEach(addNetwork);
  1423. return;
  1424. }
  1425. if ("scanResult" === key) {
  1426. $("div.scan.loading").hide();
  1427. $("#scanResult").show();
  1428. }
  1429. // -----------------------------------------------------------------------------
  1430. // Home Assistant
  1431. // -----------------------------------------------------------------------------
  1432. if ("haConfig" === key) {
  1433. send("{}");
  1434. $("#haConfig")
  1435. .append(new Text(value))
  1436. .height($("#haConfig")[0].scrollHeight);
  1437. return;
  1438. }
  1439. // -----------------------------------------------------------------------------
  1440. // Relays scheduler
  1441. // -----------------------------------------------------------------------------
  1442. if ("schedules" === key) {
  1443. $("#schedules").attr("data-settings-max", value.max);
  1444. for (var i=0; i<value.size; ++i) {
  1445. // XXX: no
  1446. var sch_map = {};
  1447. Object.keys(value).forEach(function(key) {
  1448. if ("size" == key) return;
  1449. if ("max" == key) return;
  1450. sch_map[key] = value[key][i];
  1451. });
  1452. addSchedule(sch_map);
  1453. }
  1454. return;
  1455. }
  1456. // ---------------------------------------------------------------------
  1457. // Relays
  1458. // ---------------------------------------------------------------------
  1459. if ("relayState" === key) {
  1460. initRelays(value.status);
  1461. updateRelays(value);
  1462. return;
  1463. }
  1464. // Relay configuration
  1465. if ("relayConfig" === key) {
  1466. initRelayConfig(value);
  1467. return;
  1468. }
  1469. // ---------------------------------------------------------------------
  1470. // LEDs
  1471. // ---------------------------------------------------------------------
  1472. if ("ledConfig" === key) {
  1473. initLeds(value);
  1474. for (var i=0; i<value.length; ++i) {
  1475. var mode = $("select[name='ledMode'][data='" + i + "']");
  1476. var relay = $("select[name='ledRelay'][data='" + i + "']");
  1477. mode.val(value[i].mode);
  1478. relay.val(value[i].relay);
  1479. setOriginalsFromValues($([mode,relay]));
  1480. }
  1481. return;
  1482. }
  1483. // ---------------------------------------------------------------------
  1484. // Domoticz
  1485. // ---------------------------------------------------------------------
  1486. // Domoticz - Relays
  1487. if ("dczRelays" === key) {
  1488. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1489. return;
  1490. }
  1491. // Domoticz - Magnitudes
  1492. <!-- removeIf(!sensor)-->
  1493. if ("dczMagnitudes" === key) {
  1494. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1495. return;
  1496. }
  1497. <!-- endRemoveIf(!sensor)-->
  1498. // ---------------------------------------------------------------------
  1499. // Thingspeak
  1500. // ---------------------------------------------------------------------
  1501. // Thingspeak - Relays
  1502. if ("tspkRelays" === key) {
  1503. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1504. return;
  1505. }
  1506. // Thingspeak - Magnitudes
  1507. <!-- removeIf(!sensor)-->
  1508. if ("tspkMagnitudes" === key) {
  1509. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1510. return;
  1511. }
  1512. <!-- endRemoveIf(!sensor)-->
  1513. // ---------------------------------------------------------------------
  1514. // HTTP API
  1515. // ---------------------------------------------------------------------
  1516. // Auto generate an APIKey if none defined yet
  1517. if ("apiVisible" === key) {
  1518. if (data.apiKey === undefined || data.apiKey === "") {
  1519. generateAPIKey();
  1520. }
  1521. }
  1522. // ---------------------------------------------------------------------
  1523. // General
  1524. // ---------------------------------------------------------------------
  1525. // Messages
  1526. if ("message" === key) {
  1527. if (value == 8) {
  1528. configurationSaved = true;
  1529. }
  1530. window.alert(messages[value]);
  1531. return;
  1532. }
  1533. // Web log
  1534. if ("weblog" === key) {
  1535. send("{}");
  1536. var msg = value["msg"];
  1537. var pre = value["pre"];
  1538. for (var i=0; i < msg.length; ++i) {
  1539. if (pre[i]) {
  1540. $("#weblog").append(new Text(pre[i]));
  1541. }
  1542. $("#weblog").append(new Text(msg[i]));
  1543. }
  1544. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1545. return;
  1546. }
  1547. // Enable options
  1548. var position = key.indexOf("Visible");
  1549. if (position > 0 && position === key.length - 7) {
  1550. var module = key.slice(0,-7);
  1551. if (module == "sch") {
  1552. $("li.module-" + module).css("display", "inherit");
  1553. $("div.module-" + module).css("display", "flex");
  1554. return;
  1555. }
  1556. $(".module-" + module).css("display", "inherit");
  1557. return;
  1558. }
  1559. if ("deviceip" === key) {
  1560. var a_href = $("span[name='" + key + "']").parent();
  1561. a_href.attr("href", "//" + value);
  1562. a_href.next().attr("href", "telnet://" + value);
  1563. }
  1564. if ("now" === key) {
  1565. now = value;
  1566. return;
  1567. }
  1568. if ("free_size" === key) {
  1569. free_size = parseInt(value, 10);
  1570. }
  1571. // Pre-process
  1572. if ("mqttStatus" === key) {
  1573. value = value ? "CONNECTED" : "NOT CONNECTED";
  1574. }
  1575. if ("ntpStatus" === key) {
  1576. value = value ? "SYNC'D" : "NOT SYNC'D";
  1577. }
  1578. if ("uptime" === key) {
  1579. ago = 0;
  1580. var uptime = parseInt(value, 10);
  1581. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1582. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1583. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1584. var days = uptime;
  1585. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1586. }
  1587. <!-- removeIf(!thermostat)-->
  1588. if ("tmpUnits" == key) {
  1589. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1590. }
  1591. <!-- endRemoveIf(!thermostat)-->
  1592. // ---------------------------------------------------------------------
  1593. // Matching
  1594. // ---------------------------------------------------------------------
  1595. var elems = [];
  1596. var pre;
  1597. var post;
  1598. // Look for INPUTs
  1599. var input = $("input[name='" + key + "']");
  1600. if (input.length > 0) {
  1601. if (input.attr("type") === "checkbox") {
  1602. input.prop("checked", value);
  1603. } else if (input.attr("type") === "radio") {
  1604. input.val([value]);
  1605. } else {
  1606. pre = input.attr("pre") || "";
  1607. post = input.attr("post") || "";
  1608. input.val(pre + value + post);
  1609. }
  1610. elems.push(input);
  1611. }
  1612. // Look for SPANs
  1613. var span = $("span[name='" + key + "']");
  1614. if (span.length > 0) {
  1615. if (Array.isArray(value)) {
  1616. value.forEach(function(elem) {
  1617. span.append(elem);
  1618. span.append('</br>');
  1619. elems.push(span);
  1620. });
  1621. } else {
  1622. pre = span.attr("pre") || "";
  1623. post = span.attr("post") || "";
  1624. span.html(pre + value + post);
  1625. elems.push(span);
  1626. }
  1627. }
  1628. // Look for SELECTs
  1629. var select = $("select[name='" + key + "']");
  1630. if (select.length > 0) {
  1631. select.val(value);
  1632. elems.push(select);
  1633. }
  1634. setOriginalsFromValues($(elems));
  1635. });
  1636. }
  1637. function hasChanged() {
  1638. var newValue, originalValue;
  1639. if ($(this).attr("type") === "checkbox") {
  1640. newValue = $(this).prop("checked");
  1641. originalValue = ($(this).attr("original") === "true");
  1642. } else {
  1643. newValue = $(this).val();
  1644. originalValue = $(this).attr("original");
  1645. }
  1646. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1647. var action = $(this).attr("action");
  1648. if (typeof originalValue === "undefined") { return; }
  1649. if ("none" === action) { return; }
  1650. if (newValue !== originalValue) {
  1651. if (!hasChanged) {
  1652. ++numChanged;
  1653. if ("reconnect" === action) { ++numReconnect; }
  1654. if ("reboot" === action) { ++numReboot; }
  1655. if ("reload" === action) { ++numReload; }
  1656. }
  1657. $(this).attr("hasChanged", true);
  1658. } else {
  1659. if (hasChanged) {
  1660. --numChanged;
  1661. if ("reconnect" === action) { --numReconnect; }
  1662. if ("reboot" === action) { --numReboot; }
  1663. if ("reload" === action) { --numReload; }
  1664. }
  1665. $(this).attr("hasChanged", false);
  1666. }
  1667. }
  1668. // -----------------------------------------------------------------------------
  1669. // Init & connect
  1670. // -----------------------------------------------------------------------------
  1671. function initUrls(root) {
  1672. var paths = ["ws", "upgrade", "config", "auth"];
  1673. urls["root"] = root;
  1674. paths.forEach(function(path) {
  1675. urls[path] = new URL(path, root);
  1676. urls[path].protocol = root.protocol;
  1677. });
  1678. if (root.protocol == "https:") {
  1679. urls.ws.protocol = "wss:";
  1680. } else {
  1681. urls.ws.protocol = "ws:";
  1682. }
  1683. }
  1684. function connectToURL(url) {
  1685. initUrls(url);
  1686. fetch(urls.auth.href, {
  1687. 'method': 'GET',
  1688. 'cors': true,
  1689. 'credentials': 'same-origin'
  1690. }).then(function(response) {
  1691. // Nothing to do, reload page and retry
  1692. if (response.status != 200) {
  1693. doReload(5000);
  1694. return;
  1695. }
  1696. // update websock object
  1697. if (websock) { websock.close(); }
  1698. websock = new WebSocket(urls.ws.href);
  1699. websock.onmessage = function(evt) {
  1700. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1701. if (data) {
  1702. processData(data);
  1703. }
  1704. };
  1705. }).catch(function(error) {
  1706. console.log(error);
  1707. doReload(5000);
  1708. });
  1709. }
  1710. function connect(host) {
  1711. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1712. host = "http://" + host;
  1713. }
  1714. connectToURL(new URL(host));
  1715. }
  1716. function connectToCurrentURL() {
  1717. connectToURL(new URL(window.location));
  1718. }
  1719. $(function() {
  1720. initMessages();
  1721. loadTimeZones();
  1722. createCheckboxes();
  1723. setInterval(function() { keepTime(); }, 1000);
  1724. $(".password-reveal").on("click", toggleVisiblePassword);
  1725. $("#menuLink").on("click", toggleMenu);
  1726. $(".pure-menu-link").on("click", showPanel);
  1727. $("progress").attr({ value: 0, max: 100 });
  1728. $(".button-update").on("click", doUpdate);
  1729. $(".button-update-password").on("click", doUpdatePassword);
  1730. $(".button-generate-password").on("click", doGeneratePassword);
  1731. $(".button-reboot").on("click", doReboot);
  1732. $(".button-reconnect").on("click", doReconnect);
  1733. $(".button-wifi-scan").on("click", doScan);
  1734. $(".button-ha-config").on("click", doHAConfig);
  1735. $(".button-dbgcmd").on("click", doDebugCommand);
  1736. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1737. $(".button-dbg-clear").on("click", doDebugClear);
  1738. $(".button-settings-backup").on("click", doBackup);
  1739. $(".button-settings-restore").on("click", doRestore);
  1740. $(".button-settings-factory").on("click", doFactoryReset);
  1741. $("#uploader").on("change", onFileUpload);
  1742. $(".button-upgrade").on("click", doUpgrade);
  1743. <!-- removeIf(!thermostat)-->
  1744. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1745. <!-- endRemoveIf(!thermostat)-->
  1746. $(".button-apikey").on("click", generateAPIKey);
  1747. $(".button-upgrade-browse").on("click", function() {
  1748. $("input[name='upgrade']")[0].click();
  1749. return false;
  1750. });
  1751. $("input[name='upgrade']").change(function (){
  1752. var file = this.files[0];
  1753. $("input[name='filename']").val(file.name);
  1754. });
  1755. $(".button-add-network").on("click", function() {
  1756. $(".more", addNetwork()).toggle();
  1757. });
  1758. $(".button-add-switch-schedule").on("click", function() {
  1759. addSchedule({schType: 1, schSwitch: -1});
  1760. });
  1761. <!-- removeIf(!light)-->
  1762. $(".button-add-light-schedule").on("click", function() {
  1763. addSchedule({schType: 2, schSwitch: -1});
  1764. });
  1765. <!-- endRemoveIf(!light)-->
  1766. $(".button-add-rpnrule").on('click', addRPNRule);
  1767. $(".button-add-rpntopic").on('click', addRPNTopic);
  1768. $(".button-del-parent").on('click', delParent);
  1769. <!-- removeIf(!rfm69)-->
  1770. $(".button-add-mapping").on('click', addMapping);
  1771. $(".button-clear-counts").on('click', doClearCounts);
  1772. $(".button-clear-messages").on('click', doClearMessages);
  1773. $(".button-clear-filters").on('click', doClearFilters);
  1774. $('#packets tbody').on('mousedown', 'td', doFilter);
  1775. packets = $('#packets').DataTable({
  1776. "paging": false
  1777. });
  1778. for (var i = 0; i < packets.columns()[0].length; i++) {
  1779. filters[i] = false;
  1780. }
  1781. <!-- endRemoveIf(!rfm69)-->
  1782. $(".gpio-select").each(function(_, elem) {
  1783. initSelectGPIO(elem)
  1784. });
  1785. $(document).on("change", "input", hasChanged);
  1786. $(document).on("change", "select", hasChanged);
  1787. $("textarea").on("dblclick", function() { this.select(); });
  1788. resetOriginals();
  1789. $(".group-settings").each(function() {
  1790. groupSettingsObserver.observe(this, {childList: true});
  1791. });
  1792. // don't autoconnect when opening from filesystem
  1793. if (window.location.protocol === "file:") {
  1794. return;
  1795. }
  1796. // Check host param in query string
  1797. var search = new URLSearchParams(window.location.search),
  1798. host = search.get("host");
  1799. if (host !== null) {
  1800. connect(host);
  1801. } else {
  1802. connectToCurrentURL();
  1803. }
  1804. });