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.

2099 lines
60 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
6 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
6 years ago
6 years ago
7 years ago
6 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
8 years ago
6 years ago
6 years ago
6 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
8 years ago
6 years ago
8 years ago
6 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 maxSchedules;
  6. var messages = [];
  7. var free_size = 0;
  8. var urls = {};
  9. var numChanged = 0;
  10. var numReboot = 0;
  11. var numReconnect = 0;
  12. var numReload = 0;
  13. var conf_saved = false;
  14. var useWhite = false;
  15. var useCCT = false;
  16. var now = 0;
  17. var ago = 0;
  18. <!-- removeIf(!rfm69)-->
  19. var packets;
  20. var filters = [];
  21. <!-- endRemoveIf(!rfm69)-->
  22. <!-- removeIf(!sensor)-->
  23. var magnitudes = [];
  24. <!-- endRemoveIf(!sensor)-->
  25. // -----------------------------------------------------------------------------
  26. // Messages
  27. // -----------------------------------------------------------------------------
  28. function initMessages() {
  29. messages[1] = "Remote update started";
  30. messages[2] = "OTA update started";
  31. messages[3] = "Error parsing data!";
  32. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  33. messages[5] = "Changes saved. You should reboot your board now";
  34. messages[7] = "Passwords do not match!";
  35. messages[8] = "Changes saved";
  36. messages[9] = "No changes detected";
  37. messages[10] = "Session expired, please reload page...";
  38. }
  39. <!-- removeIf(!sensor)-->
  40. function sensorName(id) {
  41. var names = [
  42. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  43. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  44. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  45. "SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
  46. "T6613", "TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
  47. "NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
  48. "EZOPH"
  49. ];
  50. if (1 <= id && id <= names.length) {
  51. return names[id - 1];
  52. }
  53. return null;
  54. }
  55. function magnitudeType(type) {
  56. var types = [
  57. "Temperature", "Humidity", "Pressure",
  58. "Current", "Voltage", "Active Power", "Apparent Power",
  59. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  60. "Analog", "Digital", "Event",
  61. "PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
  62. "Local Dose Rate", "Local Dose Rate",
  63. "Count",
  64. "NO2", "CO", "Resistance", "pH"
  65. ];
  66. if (1 <= type && type <= types.length) {
  67. return types[type - 1];
  68. }
  69. return null;
  70. }
  71. function magnitudeError(error) {
  72. var errors = [
  73. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  74. "Data Error", "I2C Error", "GPIO Error", "Calibration error"
  75. ];
  76. if (0 <= error && error < errors.length) {
  77. return errors[error];
  78. }
  79. return "Error " + error;
  80. }
  81. <!-- endRemoveIf(!sensor)-->
  82. // -----------------------------------------------------------------------------
  83. // Utils
  84. // -----------------------------------------------------------------------------
  85. $.fn.enterKey = function (fnc) {
  86. return this.each(function () {
  87. $(this).keypress(function (ev) {
  88. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  89. if (13 === keycode) {
  90. return fnc.call(this, ev);
  91. }
  92. });
  93. });
  94. };
  95. function keepTime() {
  96. $("span[name='ago']").html(ago);
  97. ago++;
  98. if (0 === now) { return; }
  99. var date = new Date(now * 1000);
  100. var text = date.toISOString().substring(0, 19).replace("T", " ");
  101. $("input[name='now']").val(text);
  102. $("span[name='now']").html(text);
  103. now++;
  104. }
  105. function zeroPad(number, positions) {
  106. return number.toString().padStart(positions, "0");
  107. }
  108. function loadTimeZones() {
  109. var time_zones = [
  110. -720, -660, -600, -570, -540,
  111. -480, -420, -360, -300, -240,
  112. -210, -180, -120, -60, 0,
  113. 60, 120, 180, 210, 240,
  114. 270, 300, 330, 345, 360,
  115. 390, 420, 480, 510, 525,
  116. 540, 570, 600, 630, 660,
  117. 720, 765, 780, 840
  118. ];
  119. for (var i in time_zones) {
  120. var tz = time_zones[i];
  121. var offset = tz >= 0 ? tz : -tz;
  122. var text = "GMT" + (tz >= 0 ? "+" : "-") +
  123. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  124. zeroPad(offset % 60, 2);
  125. $("select[name='ntpOffset']").append(
  126. $("<option></option>")
  127. .attr("value", tz)
  128. .text(text)
  129. );
  130. }
  131. }
  132. function validatePassword(password) {
  133. // http://www.the-art-of-web.com/javascript/validate-password/
  134. // at least one lowercase and one uppercase letter or number
  135. // at least eight characters (letters, numbers or special characters)
  136. // MUST be 8..63 printable ASCII characters. See:
  137. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  138. // https://github.com/xoseperez/espurna/issues/1151
  139. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  140. return (
  141. (password !== undefined)
  142. && (typeof password === "string")
  143. && (password.length > 0)
  144. && re_password.test(password)
  145. );
  146. }
  147. function validateFormPasswords(form) {
  148. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  149. var adminPass1 = passwords.first().val(),
  150. adminPass2 = passwords.last().val();
  151. var formValidity = passwords.first()[0].checkValidity();
  152. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  153. return true;
  154. }
  155. var validPass1 = validatePassword(adminPass1),
  156. validPass2 = validatePassword(adminPass2);
  157. if (formValidity && validPass1 && validPass2) {
  158. return true;
  159. }
  160. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  161. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  162. }
  163. if (adminPass1 !== adminPass2) {
  164. alert("Passwords are different!");
  165. }
  166. return false;
  167. }
  168. function validateFormHostname(form) {
  169. // RFCs mandate that a hostname's labels may contain only
  170. // the ASCII letters 'a' through 'z' (case-insensitive),
  171. // the digits '0' through '9', and the hyphen.
  172. // Hostname labels cannot begin or end with a hyphen.
  173. // No other symbols, punctuation characters, or blank spaces are permitted.
  174. // Negative lookbehind does not work in Javascript
  175. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
  176. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
  177. var hostname = $("input[name='hostname']", form);
  178. if ("true" !== hostname.attr("hasChanged")) {
  179. return true;
  180. }
  181. if (re_hostname.test(hostname.val())) {
  182. return true;
  183. }
  184. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  185. return false;
  186. }
  187. function validateForm(form) {
  188. return validateFormPasswords(form) && validateFormHostname(form);
  189. }
  190. function getValue(element) {
  191. if ($(element).attr("type") === "checkbox") {
  192. return $(element).prop("checked") ? 1 : 0;
  193. } else if ($(element).attr("type") === "radio") {
  194. if (!$(element).prop("checked")) {
  195. return null;
  196. }
  197. }
  198. return $(element).val();
  199. }
  200. function addValue(data, name, value) {
  201. // These fields will always be a list of values
  202. var is_group = [
  203. "ssid", "pass", "gw", "mask", "ip", "dns",
  204. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  205. "relayBoot", "relayPulse", "relayTime", "relayLastSch",
  206. "mqttGroup", "mqttGroupSync", "relayOnDisc",
  207. "dczRelayIdx", "dczMagnitude",
  208. "tspkRelay", "tspkMagnitude",
  209. "ledMode", "ledRelay",
  210. "adminPass",
  211. "node", "key", "topic",
  212. "rpnRule", "rpnTopic", "rpnName"
  213. ];
  214. // join both adminPass 1 and 2
  215. if (name.startsWith("adminPass")) {
  216. name = "adminPass";
  217. }
  218. // join all relayLastSch values
  219. if (name.startsWith("relayLastSch")) {
  220. name = "relayLastSch";
  221. }
  222. if (name in data) {
  223. if (!Array.isArray(data[name])) {
  224. data[name] = [data[name]];
  225. }
  226. data[name].push(value);
  227. } else if (is_group.indexOf(name) >= 0) {
  228. data[name] = [value];
  229. } else {
  230. data[name] = value;
  231. }
  232. }
  233. function getData(form) {
  234. var data = {};
  235. // Populate data
  236. $("input,select", form).each(function() {
  237. var name = $(this).attr("name");
  238. var value = getValue(this);
  239. if (null !== value) {
  240. addValue(data, name, value);
  241. }
  242. });
  243. // Post process
  244. addValue(data, "schSwitch", 0xFF);
  245. delete data["filename"];
  246. delete data["rfbcode"];
  247. return data;
  248. }
  249. function randomString(length, args) {
  250. if (typeof args === "undefined") {
  251. args = {
  252. lowercase: true,
  253. uppercase: true,
  254. numbers: true,
  255. special: true
  256. }
  257. }
  258. var mask = "";
  259. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  260. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  261. if (args.numbers || args.hex) { mask += "0123456789"; }
  262. if (args.hex) { mask += "ABCDEF"; }
  263. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  264. var source = new Uint32Array(length);
  265. var result = new Array(length);
  266. window.crypto.getRandomValues(source).forEach(function(value, i) {
  267. result[i] = mask[value % mask.length];
  268. });
  269. return result.join("");
  270. }
  271. function generateAPIKey() {
  272. var apikey = randomString(16, {hex: true});
  273. $("input[name='apiKey']")
  274. .val(apikey)
  275. .attr("haschanged", "true");
  276. return false;
  277. }
  278. function generatePassword() {
  279. var password = "";
  280. do {
  281. password = randomString(10);
  282. } while (!validatePassword(password));
  283. return password;
  284. }
  285. function toggleVisiblePassword() {
  286. var elem = this.previousElementSibling;
  287. if (elem.type === "password") {
  288. elem.type = "text";
  289. } else {
  290. elem.type = "password";
  291. }
  292. return false;
  293. }
  294. function doGeneratePassword() {
  295. $("input", $("#formPassword"))
  296. .val(generatePassword())
  297. .attr("haschanged", "true")
  298. .each(function() {
  299. this.type = "text";
  300. });
  301. return false;
  302. }
  303. function getJson(str) {
  304. try {
  305. return JSON.parse(str);
  306. } catch (e) {
  307. return false;
  308. }
  309. }
  310. <!-- removeIf(!thermostat)-->
  311. function checkTempRangeMin() {
  312. var min = parseInt($("#tempRangeMinInput").val(), 10);
  313. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  314. if (min > max - 1) {
  315. $("#tempRangeMinInput").val(max - 1);
  316. }
  317. }
  318. function checkTempRangeMax() {
  319. var min = parseInt($("#tempRangeMinInput").val(), 10);
  320. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  321. if (max < min + 1) {
  322. $("#tempRangeMaxInput").val(min + 1);
  323. }
  324. }
  325. function doResetThermostatCounters(ask) {
  326. var question = (typeof ask === "undefined" || false === ask) ?
  327. null :
  328. "Are you sure you want to reset burning counters?";
  329. return doAction(question, "thermostat_reset_counters");
  330. }
  331. <!-- endRemoveIf(!thermostat)-->
  332. function initSelectGPIO(select) {
  333. // TODO: properly lock used GPIOs via locking and apply the mask here
  334. var mapping = [
  335. [153, "NONE"],
  336. [0, "0 (FLASH)"],
  337. [1, "1 (U0TXD)"],
  338. [2, "2 (U1TXD)"],
  339. [3, "3 (U0RXD)"],
  340. [4, "4 (SDA)"],
  341. [5, "5 (SCL)"],
  342. [9, "9 (SDD2)"],
  343. [10, "10 (SDD3)"],
  344. [12, "12 (MTDI)"],
  345. [13, "13 (MTCK)"],
  346. [14, "14 (MTMS)"],
  347. [15, "15 (MTDO)"],
  348. [16, "15 (WAKE)"],
  349. ];
  350. for (n in mapping) {
  351. var elem = $('<option value="' + mapping[n][0] + '">');
  352. elem.html(mapping[n][1]);
  353. elem.appendTo(select);
  354. }
  355. }
  356. // -----------------------------------------------------------------------------
  357. // Actions
  358. // -----------------------------------------------------------------------------
  359. function send(json) {
  360. if (debug) console.log(json);
  361. websock.send(json);
  362. }
  363. function sendAction(action, data) {
  364. send(JSON.stringify({action: action, data: data}));
  365. }
  366. function sendConfig(data) {
  367. send(JSON.stringify({config: data}));
  368. }
  369. function setOriginalsFromValues(force) {
  370. force = (true === force);
  371. $("input,select").each(function() {
  372. var initial = (undefined === $(this).attr("original"));
  373. if (force || initial) {
  374. var value;
  375. if ($(this).attr("type") === "checkbox") {
  376. value = $(this).prop("checked");
  377. } else {
  378. value = $(this).val();
  379. }
  380. $(this).attr("original", value);
  381. hasChanged.call(this);
  382. }
  383. });
  384. }
  385. function resetOriginals() {
  386. setOriginalsFromValues(true);
  387. numReboot = numReconnect = numReload = 0;
  388. conf_saved = false;
  389. }
  390. function doReload(milliseconds) {
  391. setTimeout(function() {
  392. window.location.reload();
  393. }, parseInt(milliseconds, 10));
  394. }
  395. /**
  396. * Check a file object to see if it is a valid firmware image
  397. * The file first byte should be 0xE9
  398. * @param {file} file File object
  399. * @param {Function} callback Function to call back with the result
  400. */
  401. function checkFirmware(file, callback) {
  402. var reader = new FileReader();
  403. reader.onloadend = function(evt) {
  404. if (FileReader.DONE === evt.target.readyState) {
  405. if (0xE9 !== evt.target.result.charCodeAt(0)) callback(false);
  406. if (0x03 !== evt.target.result.charCodeAt(2)) {
  407. var response = window.confirm("Binary image is not using DOUT flash mode. This might cause resets in some devices. Press OK to continue.");
  408. callback(response);
  409. } else {
  410. callback(true);
  411. }
  412. }
  413. };
  414. var blob = file.slice(0, 3);
  415. reader.readAsBinaryString(blob);
  416. }
  417. function doUpgrade() {
  418. var file = $("input[name='upgrade']")[0].files[0];
  419. if (typeof file === "undefined") {
  420. alert("First you have to select a file from your computer.");
  421. return false;
  422. }
  423. if (file.size > free_size) {
  424. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  425. return false;
  426. }
  427. checkFirmware(file, function(ok) {
  428. if (!ok) {
  429. alert("The file does not seem to be a valid firmware image.");
  430. return;
  431. }
  432. var data = new FormData();
  433. data.append("upgrade", file, file.name);
  434. var xhr = new XMLHttpRequest();
  435. var network_error = function() {
  436. alert("There was a network error trying to upload the new image, please try again.");
  437. };
  438. xhr.addEventListener("error", network_error, false);
  439. xhr.addEventListener("abort", network_error, false);
  440. xhr.addEventListener("load", function(e) {
  441. $("#upgrade-progress").hide();
  442. if ("OK" === xhr.responseText) {
  443. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  444. doReload(5000);
  445. } else {
  446. alert("There was an error trying to upload the new image, please try again ("
  447. + "response: " + xhr.responseText + ", "
  448. + "status: " + xhr.statusText + ")");
  449. }
  450. }, false);
  451. xhr.upload.addEventListener("progress", function(e) {
  452. $("#upgrade-progress").show();
  453. if (e.lengthComputable) {
  454. $("progress").attr({ value: e.loaded, max: e.total });
  455. }
  456. }, false);
  457. xhr.open("POST", urls.upgrade.href);
  458. xhr.send(data);
  459. });
  460. return false;
  461. }
  462. function doUpdatePassword() {
  463. var form = $("#formPassword");
  464. if (validateFormPasswords(form)) {
  465. sendConfig(getData(form));
  466. }
  467. return false;
  468. }
  469. function checkChanges() {
  470. if (numChanged > 0) {
  471. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  472. if (response) {
  473. doUpdate();
  474. }
  475. }
  476. }
  477. function doAction(question, action) {
  478. checkChanges();
  479. if (question) {
  480. var response = window.confirm(question);
  481. if (false === response) {
  482. return false;
  483. }
  484. }
  485. sendAction(action, {});
  486. doReload(5000);
  487. return false;
  488. }
  489. function doReboot(ask) {
  490. var question = (typeof ask === "undefined" || false === ask) ?
  491. null :
  492. "Are you sure you want to reboot the device?";
  493. return doAction(question, "reboot");
  494. }
  495. function doReconnect(ask) {
  496. var question = (typeof ask === "undefined" || false === ask) ?
  497. null :
  498. "Are you sure you want to disconnect from the current WIFI network?";
  499. return doAction(question, "reconnect");
  500. }
  501. function doCheckOriginals() {
  502. var response;
  503. if (numReboot > 0) {
  504. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  505. if (response) { doReboot(false); }
  506. } else if (numReconnect > 0) {
  507. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  508. if (response) { doReconnect(false); }
  509. } else if (numReload > 0) {
  510. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  511. if (response) { doReload(0); }
  512. }
  513. resetOriginals();
  514. }
  515. function waitForSave(){
  516. if (conf_saved == false) {
  517. setTimeout(waitForSave, 1000);
  518. } else {
  519. doCheckOriginals();
  520. }
  521. }
  522. function doUpdate() {
  523. var forms = $(".form-settings");
  524. if (validateForm(forms)) {
  525. // Get data
  526. sendConfig(getData(forms));
  527. // Empty special fields
  528. $(".pwrExpected").val(0);
  529. $("input[name='snsResetCalibration']").prop("checked", false);
  530. $("input[name='pwrResetCalibration']").prop("checked", false);
  531. $("input[name='pwrResetE']").prop("checked", false);
  532. // Change handling
  533. numChanged = 0;
  534. waitForSave();
  535. }
  536. return false;
  537. }
  538. function doBackup() {
  539. document.getElementById("downloader").src = urls.config.href;
  540. return false;
  541. }
  542. function onFileUpload(event) {
  543. var inputFiles = this.files;
  544. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  545. return false;
  546. }
  547. var inputFile = inputFiles[0];
  548. this.value = "";
  549. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  550. if (!response) {
  551. return false;
  552. }
  553. var reader = new FileReader();
  554. reader.onload = function(e) {
  555. var data = getJson(e.target.result);
  556. if (data) {
  557. sendAction("restore", data);
  558. } else {
  559. window.alert(messages[4]);
  560. }
  561. };
  562. reader.readAsText(inputFile);
  563. return false;
  564. }
  565. function doRestore() {
  566. if (typeof window.FileReader !== "function") {
  567. alert("The file API isn't supported on this browser yet.");
  568. } else {
  569. $("#uploader").click();
  570. }
  571. return false;
  572. }
  573. function doFactoryReset() {
  574. var response = window.confirm("Are you sure you want to restore to factory settings?");
  575. if (response === false) {
  576. return false;
  577. }
  578. sendAction("factory_reset", {});
  579. doReload(5000);
  580. return false;
  581. }
  582. function doToggle(id, value) {
  583. sendAction("relay", {id: id, status: value ? 1 : 0 });
  584. return false;
  585. }
  586. function doScan() {
  587. $("#scanResult").html("");
  588. $("div.scan.loading").show();
  589. sendAction("scan", {});
  590. return false;
  591. }
  592. function doHAConfig() {
  593. $("#haConfig")
  594. .text("")
  595. .height(0)
  596. .show();
  597. sendAction("haconfig", {});
  598. return false;
  599. }
  600. function doDebugCommand() {
  601. var el = $("input[name='dbgcmd']");
  602. var command = el.val();
  603. el.val("");
  604. sendAction("dbgcmd", {command: command});
  605. return false;
  606. }
  607. function doDebugClear() {
  608. $("#weblog").text("");
  609. return false;
  610. }
  611. <!-- removeIf(!rfm69)-->
  612. function doClearCounts() {
  613. sendAction("clear-counts", {});
  614. return false;
  615. }
  616. function doClearMessages() {
  617. packets.clear().draw(false);
  618. return false;
  619. }
  620. function doFilter(e) {
  621. var index = packets.cell(this).index();
  622. if (index == 'undefined') return;
  623. var c = index.column;
  624. var column = packets.column(c);
  625. if (filters[c]) {
  626. filters[c] = false;
  627. column.search("");
  628. $(column.header()).removeClass("filtered");
  629. } else {
  630. filters[c] = true;
  631. var data = packets.row(this).data();
  632. if (e.which == 1) {
  633. column.search('^' + data[c] + '$', true, false );
  634. } else {
  635. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  636. }
  637. $(column.header()).addClass("filtered");
  638. }
  639. column.draw();
  640. return false;
  641. }
  642. function doClearFilters() {
  643. for (var i = 0; i < packets.columns()[0].length; i++) {
  644. if (filters[i]) {
  645. filters[i] = false;
  646. var column = packets.column(i);
  647. column.search("");
  648. $(column.header()).removeClass("filtered");
  649. column.draw();
  650. }
  651. }
  652. return false;
  653. }
  654. <!-- endRemoveIf(!rfm69)-->
  655. function delParent() {
  656. var parent = $(this).parent().parent();
  657. $(parent).remove();
  658. }
  659. // -----------------------------------------------------------------------------
  660. // Visualization
  661. // -----------------------------------------------------------------------------
  662. function toggleMenu() {
  663. $("#layout").toggleClass("active");
  664. $("#menu").toggleClass("active");
  665. $("#menuLink").toggleClass("active");
  666. }
  667. function showPanel() {
  668. $(".panel").hide();
  669. if ($("#layout").hasClass("active")) { toggleMenu(); }
  670. $("#" + $(this).attr("data")).show();
  671. }
  672. // -----------------------------------------------------------------------------
  673. // Relays & magnitudes mapping
  674. // -----------------------------------------------------------------------------
  675. function createRelayList(data, container, template_name) {
  676. var current = $("#" + container + " > div").length;
  677. if (current > 0) { return; }
  678. var template = $("#" + template_name + " .pure-g")[0];
  679. for (var i in data) {
  680. var line = $(template).clone();
  681. $("label", line).html("Switch #" + i);
  682. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  683. line.appendTo("#" + container);
  684. }
  685. }
  686. <!-- removeIf(!sensor)-->
  687. function createMagnitudeList(data, container, template_name) {
  688. var current = $("#" + container + " > div").length;
  689. if (current > 0) { return; }
  690. var template = $("#" + template_name + " .pure-g")[0];
  691. var size = data.size;
  692. for (var i=0; i<size; ++i) {
  693. var line = $(template).clone();
  694. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  695. $("div.hint", line).html(magnitudes[i].description);
  696. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  697. line.appendTo("#" + container);
  698. }
  699. }
  700. <!-- endRemoveIf(!sensor)-->
  701. // -----------------------------------------------------------------------------
  702. // RPN Rules
  703. // -----------------------------------------------------------------------------
  704. function addRPNRule() {
  705. var template = $("#rpnRuleTemplate .pure-g")[0];
  706. var line = $(template).clone();
  707. var tabindex = $("#rpnRules > div").length + 100;
  708. $(line).find("input").each(function() {
  709. $(this).attr("tabindex", tabindex++);
  710. });
  711. $(line).find("button").on('click', delParent);
  712. line.appendTo("#rpnRules");
  713. }
  714. function addRPNTopic() {
  715. var template = $("#rpnTopicTemplate .pure-g")[0];
  716. var line = $(template).clone();
  717. var tabindex = $("#rpnTopics > div").length + 120;
  718. $(line).find("input").each(function() {
  719. $(this).attr("tabindex", tabindex++);
  720. });
  721. $(line).find("button").on('click', delParent);
  722. line.appendTo("#rpnTopics");
  723. }
  724. // -----------------------------------------------------------------------------
  725. // RFM69
  726. // -----------------------------------------------------------------------------
  727. <!-- removeIf(!rfm69)-->
  728. function addMapping() {
  729. var template = $("#nodeTemplate .pure-g")[0];
  730. var line = $(template).clone();
  731. var tabindex = $("#mapping > div").length * 3 + 50;
  732. $(line).find("input").each(function() {
  733. $(this).attr("tabindex", tabindex++);
  734. });
  735. $(line).find("button").on('click', delParent);
  736. line.appendTo("#mapping");
  737. }
  738. <!-- endRemoveIf(!rfm69)-->
  739. // -----------------------------------------------------------------------------
  740. // Wifi
  741. // -----------------------------------------------------------------------------
  742. function delNetwork() {
  743. var parent = $(this).parents(".pure-g");
  744. $(parent).remove();
  745. }
  746. function moreNetwork() {
  747. var parent = $(this).parents(".pure-g");
  748. $(".more", parent).toggle();
  749. }
  750. function addNetwork() {
  751. var numNetworks = $("#networks > div").length;
  752. if (numNetworks >= maxNetworks) {
  753. alert("Max number of networks reached");
  754. return null;
  755. }
  756. var tabindex = 200 + numNetworks * 10;
  757. var template = $("#networkTemplate").children();
  758. var line = $(template).clone();
  759. $(line).find("input").each(function() {
  760. $(this).attr("tabindex", tabindex);
  761. tabindex++;
  762. });
  763. $(".password-reveal", line).on("click", toggleVisiblePassword);
  764. $(line).find(".button-del-network").on("click", delNetwork);
  765. $(line).find(".button-more-network").on("click", moreNetwork);
  766. line.appendTo("#networks");
  767. return line;
  768. }
  769. // -----------------------------------------------------------------------------
  770. // Relays scheduler
  771. // -----------------------------------------------------------------------------
  772. function delSchedule() {
  773. var parent = $(this).parents(".pure-g");
  774. $(parent).remove();
  775. }
  776. function moreSchedule() {
  777. var parent = $(this).parents(".pure-g");
  778. $("div.more", parent).toggle();
  779. }
  780. function addSchedule(event) {
  781. var numSchedules = $("#schedules > div").length;
  782. if (numSchedules >= maxSchedules) {
  783. alert("Max number of schedules reached");
  784. return null;
  785. }
  786. var tabindex = 200 + numSchedules * 10;
  787. var template = $("#scheduleTemplate").children();
  788. var line = $(template).clone();
  789. var type = (1 === event.data.schType) ? "switch" : "light";
  790. template = $("#" + type + "ActionTemplate").children();
  791. $(line).find("#schActionDiv").append(template.clone());
  792. $(line).find("input").each(function() {
  793. $(this).attr("tabindex", tabindex);
  794. tabindex++;
  795. });
  796. $(line).find(".button-del-schedule").on("click", delSchedule);
  797. $(line).find(".button-more-schedule").on("click", moreSchedule);
  798. $(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
  799. .next().prop("for", "schUTC" + (numSchedules + 1));
  800. $(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
  801. .next().prop("for", "schEnabled" + (numSchedules + 1));
  802. line.appendTo("#schedules");
  803. $(line).find("input[type='checkbox']").prop("checked", false);
  804. return line;
  805. }
  806. // -----------------------------------------------------------------------------
  807. // Relays
  808. // -----------------------------------------------------------------------------
  809. function initRelays(data) {
  810. var current = $("#relays > div").length;
  811. if (current > 0) { return; }
  812. var template = $("#relayTemplate .pure-g")[0];
  813. for (var i=0; i<data.length; i++) {
  814. // Add relay fields
  815. var line = $(template).clone();
  816. $(".id", line).html(i);
  817. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  818. .prop("id", "relay" + i)
  819. .on("change", function (event) {
  820. var id = parseInt($(event.target).attr("data"), 10);
  821. var status = $(event.target).prop("checked");
  822. doToggle(id, status);
  823. });
  824. $("label.toggle", line).prop("for", "relay" + i)
  825. line.appendTo("#relays");
  826. }
  827. }
  828. function updateRelays(data) {
  829. var size = data.size;
  830. for (var i=0; i<size; ++i) {
  831. var elem = $("input[name='relay'][data='" + i + "']");
  832. elem.prop("checked", data.status[i]);
  833. var lock = {
  834. 0: false,
  835. 1: !data.status[i],
  836. 2: data.status[i]
  837. };
  838. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  839. }
  840. }
  841. function createCheckboxes() {
  842. $("input[type='checkbox']").each(function() {
  843. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  844. $(this).parent().addClass("toggleWrapper");
  845. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  846. });
  847. }
  848. function initRelayConfig(data) {
  849. var current = $("#relayConfig > legend").length; // there is a legend per relay
  850. if (current > 0) { return; }
  851. var size = data.size;
  852. var start = data.start;
  853. var template = $("#relayConfigTemplate").children();
  854. for (var i=start; i<size; ++i) {
  855. var line = $(template).clone();
  856. $("span.id", line).html(i);
  857. $("span.gpio", line).html(data.gpio[i]);
  858. $("select[name='relayBoot']", line).val(data.boot[i]);
  859. $("select[name='relayPulse']", line).val(data.pulse[i]);
  860. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  861. if ("sch_last" in data) {
  862. $("input[name='relayLastSch']", line)
  863. .prop('checked', data.sch_last[i])
  864. .attr("id", "relayLastSch" + i)
  865. .attr("name", "relayLastSch" + i)
  866. .next().attr("for","relayLastSch" + (i));
  867. }
  868. if ("group" in data) {
  869. $("input[name='mqttGroup']", line).val(data.group[i]);
  870. }
  871. if ("group_sync" in data) {
  872. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  873. }
  874. if ("on_disc" in data) {
  875. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  876. }
  877. line.appendTo("#relayConfig");
  878. // Populate the relay SELECTs
  879. $("select.isrelay").append(
  880. $("<option></option>")
  881. .attr("value", i)
  882. .text("Switch #" + i)
  883. );
  884. }
  885. }
  886. function initLeds(data) {
  887. var current = $("#ledConfig > div").length;
  888. if (current > 0) { return; }
  889. var size = data.length;
  890. var template = $("#ledConfigTemplate").children();
  891. for (var i=0; i<size; ++i) {
  892. var line = $(template).clone();
  893. $("span.id", line).html(i);
  894. $("select", line).attr("data", i);
  895. $("input", line).attr("data", i);
  896. line.appendTo("#ledConfig");
  897. }
  898. }
  899. // -----------------------------------------------------------------------------
  900. // Sensors & Magnitudes
  901. // -----------------------------------------------------------------------------
  902. <!-- removeIf(!sensor)-->
  903. function initMagnitudes(data) {
  904. // check if already initialized (each magnitude is inside div.pure-g)
  905. var done = $("#magnitudes > div").length;
  906. if (done > 0) { return; }
  907. var size = data.size;
  908. // add templates
  909. var template = $("#magnitudeTemplate").children();
  910. for (var i=0; i<size; ++i) {
  911. var magnitude = {
  912. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  913. "units": data.units[i],
  914. "description": data.description[i]
  915. };
  916. magnitudes.push(magnitude);
  917. var line = $(template).clone();
  918. $("label", line).html(magnitude.name);
  919. $("div.hint", line).html(magnitude.description);
  920. $("input", line).attr("data", i);
  921. line.appendTo("#magnitudes");
  922. }
  923. }
  924. <!-- endRemoveIf(!sensor)-->
  925. // -----------------------------------------------------------------------------
  926. // Lights
  927. // -----------------------------------------------------------------------------
  928. <!-- removeIf(!light)-->
  929. // wheelColorPicker accepts:
  930. // hsv(0...360,0...1,0...1)
  931. // hsv(0...100%,0...100%,0...100%)
  932. // While we use:
  933. // hsv(0...360,0...100%,0...100%)
  934. function _hsv_round(value) {
  935. return Math.round(value * 100) / 100;
  936. }
  937. function getPickerRGB(picker) {
  938. return $(picker).wheelColorPicker("getValue", "css");
  939. }
  940. function setPickerRGB(picker, value) {
  941. $(picker).wheelColorPicker("setValue", value, true);
  942. }
  943. // TODO: use pct values instead of doing conversion?
  944. function getPickerHSV(picker) {
  945. var color = $(picker).wheelColorPicker("getColor");
  946. return String(Math.ceil(_hsv_round(color.h) * 360))
  947. + "," + String(Math.ceil(_hsv_round(color.s) * 100))
  948. + "," + String(Math.ceil(_hsv_round(color.v) * 100));
  949. }
  950. function setPickerHSV(picker, value) {
  951. if (value === getPickerHSV(picker)) return;
  952. var chunks = value.split(",");
  953. $(picker).wheelColorPicker("setColor", {
  954. h: _hsv_round(chunks[0] / 360),
  955. s: _hsv_round(chunks[1] / 100),
  956. v: _hsv_round(chunks[2] / 100)
  957. });
  958. }
  959. function initColor(cfg) {
  960. var rgb = false;
  961. if (typeof cfg === "object") {
  962. rgb = cfg.rgb;
  963. }
  964. // check if already initialized
  965. var done = $("#colors > div").length;
  966. if (done > 0) { return; }
  967. // add template
  968. var template = $("#colorTemplate").children();
  969. var line = $(template).clone();
  970. line.appendTo("#colors");
  971. // init color wheel
  972. $("input[name='color']").wheelColorPicker({
  973. sliders: (rgb ? "wrgbp" : "whsp")
  974. }).on("sliderup", function() {
  975. if (rgb) {
  976. sendAction("color", {rgb: getPickerRGB(this)});
  977. } else {
  978. sendAction("color", {hsv: getPickerHSV(this)});
  979. }
  980. });
  981. }
  982. function initCCT() {
  983. // check if already initialized
  984. var done = $("#cct > div").length;
  985. if (done > 0) { return; }
  986. $("#miredsTemplate").children().clone().appendTo("#cct");
  987. $("#mireds").on("change", function() {
  988. var value = $(this).val();
  989. var parent = $(this).parents(".pure-g");
  990. $("span", parent).html(value);
  991. sendAction("mireds", {mireds: value});
  992. });
  993. }
  994. function initChannels(num) {
  995. // check if already initialized
  996. var done = $("#channels > div").length > 0;
  997. if (done) { return; }
  998. // does it have color channels?
  999. var colors = $("#colors > div").length > 0;
  1000. // calculate channels to create
  1001. var max = num;
  1002. if (colors) {
  1003. max = num % 3;
  1004. if ((max > 0) & useWhite) {
  1005. max--;
  1006. if (useCCT) {
  1007. max--;
  1008. }
  1009. }
  1010. }
  1011. var start = num - max;
  1012. var onChannelSliderChange = function() {
  1013. var id = $(this).attr("data");
  1014. var value = $(this).val();
  1015. var parent = $(this).parents(".pure-g");
  1016. $("span", parent).html(value);
  1017. sendAction("channel", {id: id, value: value});
  1018. };
  1019. // add channel templates
  1020. var i = 0;
  1021. var template = $("#channelTemplate").children();
  1022. for (i=0; i<max; i++) {
  1023. var channel_id = start + i;
  1024. var line = $(template).clone();
  1025. $("span.slider", line).attr("data", channel_id);
  1026. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1027. $("label", line).html("Channel #" + channel_id);
  1028. line.appendTo("#channels");
  1029. }
  1030. // Init channel dropdowns
  1031. for (i=0; i<num; i++) {
  1032. $("select.islight").append(
  1033. $("<option></option>").attr("value",i).text("Channel #" + i));
  1034. }
  1035. // add brightness template
  1036. var template = $("#brightnessTemplate").children();
  1037. var line = $(template).clone();
  1038. line.appendTo("#channels");
  1039. // init bright slider
  1040. $("#brightness").on("change", function() {
  1041. var value = $(this).val();
  1042. var parent = $(this).parents(".pure-g");
  1043. $("span", parent).html(value);
  1044. sendAction("brightness", {value: value});
  1045. });
  1046. }
  1047. <!-- endRemoveIf(!light)-->
  1048. // -----------------------------------------------------------------------------
  1049. // RFBridge
  1050. // -----------------------------------------------------------------------------
  1051. <!-- removeIf(!rfbridge)-->
  1052. function rfbLearn() {
  1053. var parent = $(this).parents(".pure-g");
  1054. var input = $("input", parent);
  1055. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1056. }
  1057. function rfbForget() {
  1058. var parent = $(this).parents(".pure-g");
  1059. var input = $("input", parent);
  1060. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1061. }
  1062. function rfbSend() {
  1063. var parent = $(this).parents(".pure-g");
  1064. var input = $("input", parent);
  1065. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1066. }
  1067. function addRfbNode() {
  1068. var numNodes = $("#rfbNodes > legend").length;
  1069. var template = $("#rfbNodeTemplate").children();
  1070. var line = $(template).clone();
  1071. var status = true;
  1072. $("span", line).html(numNodes);
  1073. $(line).find("input").each(function() {
  1074. $(this).attr("data-id", numNodes);
  1075. $(this).attr("data-status", status ? 1 : 0);
  1076. status = !status;
  1077. });
  1078. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1079. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1080. $(line).find(".button-rfb-send").on("click", rfbSend);
  1081. line.appendTo("#rfbNodes");
  1082. return line;
  1083. }
  1084. <!-- endRemoveIf(!rfbridge)-->
  1085. // -----------------------------------------------------------------------------
  1086. // LightFox
  1087. // -----------------------------------------------------------------------------
  1088. <!-- removeIf(!lightfox)-->
  1089. function lightfoxLearn() {
  1090. sendAction("lightfoxLearn", {});
  1091. }
  1092. function lightfoxClear() {
  1093. sendAction("lightfoxClear", {});
  1094. }
  1095. function initLightfox(data, relayCount) {
  1096. var numNodes = data.length;
  1097. var template = $("#lightfoxNodeTemplate").children();
  1098. var i, j;
  1099. for (i=0; i<numNodes; i++) {
  1100. var $line = $(template).clone();
  1101. $line.find("label > span").text(data[i]["id"]);
  1102. $line.find("select").each(function() {
  1103. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1104. for (j=0; j < relayCount; j++) {
  1105. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1106. }
  1107. $(this).val(data[i]["relay"]);
  1108. status = !status;
  1109. });
  1110. $line.appendTo("#lightfoxNodes");
  1111. }
  1112. var $panel = $("#panel-lightfox")
  1113. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1114. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1115. }
  1116. <!-- endRemoveIf(!lightfox)-->
  1117. // -----------------------------------------------------------------------------
  1118. // Processing
  1119. // -----------------------------------------------------------------------------
  1120. function processData(data) {
  1121. if (debug) console.log(data);
  1122. // title
  1123. if ("app_name" in data) {
  1124. var title = data.app_name;
  1125. if ("app_version" in data) {
  1126. title = title + " " + data.app_version;
  1127. }
  1128. $("span[name=title]").html(title);
  1129. if ("hostname" in data) {
  1130. title = data.hostname + " - " + title;
  1131. }
  1132. document.title = title;
  1133. }
  1134. Object.keys(data).forEach(function(key) {
  1135. var i;
  1136. var value = data[key];
  1137. // ---------------------------------------------------------------------
  1138. // Web mode
  1139. // ---------------------------------------------------------------------
  1140. if ("webMode" === key) {
  1141. password = (1 === value);
  1142. $("#layout").toggle(!password);
  1143. $("#password").toggle(password);
  1144. }
  1145. // ---------------------------------------------------------------------
  1146. // Actions
  1147. // ---------------------------------------------------------------------
  1148. if ("action" === key) {
  1149. if ("reload" === data.action) { doReload(1000); }
  1150. return;
  1151. }
  1152. // ---------------------------------------------------------------------
  1153. // RFBridge
  1154. // ---------------------------------------------------------------------
  1155. <!-- removeIf(!rfbridge)-->
  1156. if ("rfbCount" === key) {
  1157. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1158. return;
  1159. }
  1160. if ("rfb" === key) {
  1161. var rfb = data.rfb;
  1162. var size = rfb.size;
  1163. var start = rfb.start;
  1164. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1165. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1166. for (var i=0; i<size; ++i) {
  1167. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1168. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1169. }
  1170. return;
  1171. }
  1172. <!-- endRemoveIf(!rfbridge)-->
  1173. // ---------------------------------------------------------------------
  1174. // LightFox
  1175. // ---------------------------------------------------------------------
  1176. <!-- removeIf(!lightfox)-->
  1177. if ("lightfoxButtons" === key) {
  1178. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1179. return;
  1180. }
  1181. <!-- endRemoveIf(!lightfox)-->
  1182. // ---------------------------------------------------------------------
  1183. // RFM69
  1184. // ---------------------------------------------------------------------
  1185. <!-- removeIf(!rfm69)-->
  1186. if (key == "packet") {
  1187. var packet = data.packet;
  1188. var d = new Date();
  1189. packets.row.add([
  1190. d.toLocaleTimeString('en-US', { hour12: false }),
  1191. packet.senderID,
  1192. packet.packetID,
  1193. packet.targetID,
  1194. packet.key,
  1195. packet.value,
  1196. packet.rssi,
  1197. packet.duplicates,
  1198. packet.missing,
  1199. ]).draw(false);
  1200. return;
  1201. }
  1202. if (key == "mapping") {
  1203. for (var i in data.mapping) {
  1204. // add a new row
  1205. addMapping();
  1206. // get group
  1207. var line = $("#mapping .pure-g")[i];
  1208. // fill in the blanks
  1209. var mapping = data.mapping[i];
  1210. Object.keys(mapping).forEach(function(key) {
  1211. var id = "input[name=" + key + "]";
  1212. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1213. });
  1214. }
  1215. return;
  1216. }
  1217. <!-- endRemoveIf(!rfm69)-->
  1218. // ---------------------------------------------------------------------
  1219. // RPN Rules
  1220. // ---------------------------------------------------------------------
  1221. if (key == "rpnRules") {
  1222. for (var i in data.rpnRules) {
  1223. // add a new row
  1224. addRPNRule();
  1225. // get group
  1226. var line = $("#rpnRules .pure-g")[i];
  1227. // fill in the blanks
  1228. var rule = data.rpnRules[i];
  1229. $("input", line).val(rule).attr("original", rule);
  1230. }
  1231. return;
  1232. }
  1233. if (key == "rpnTopics") {
  1234. for (var i in data.rpnTopics) {
  1235. // add a new row
  1236. addRPNTopic();
  1237. // get group
  1238. var line = $("#rpnTopics .pure-g")[i];
  1239. // fill in the blanks
  1240. var topic = data.rpnTopics[i];
  1241. var name = data.rpnNames[i];
  1242. $("input[name='rpnTopic']", line).val(topic).attr("original", topic);
  1243. $("input[name='rpnName']", line).val(name).attr("original", name);
  1244. }
  1245. return;
  1246. }
  1247. if (key == "rpnNames") return;
  1248. // ---------------------------------------------------------------------
  1249. // Lights
  1250. // ---------------------------------------------------------------------
  1251. <!-- removeIf(!light)-->
  1252. if ("rgb" === key) {
  1253. initColor({rgb: true});
  1254. setPickerRGB($("input[name='color']"), value);
  1255. return;
  1256. }
  1257. if ("hsv" === key) {
  1258. initColor({hsv: true});
  1259. setPickerHSV($("input[name='color']"), value);
  1260. return;
  1261. }
  1262. if ("brightness" === key) {
  1263. $("#brightness").val(value);
  1264. $("span.brightness").html(value);
  1265. return;
  1266. }
  1267. if ("channels" === key) {
  1268. var len = value.length;
  1269. initChannels(len);
  1270. for (i in value) {
  1271. var ch = value[i];
  1272. $("input.slider[data=" + i + "]").val(ch);
  1273. $("span.slider[data=" + i + "]").html(ch);
  1274. }
  1275. return;
  1276. }
  1277. if ("mireds" === key) {
  1278. $("#mireds").attr("min", value["cold"]);
  1279. $("#mireds").attr("max", value["warm"]);
  1280. $("#mireds").val(value["value"]);
  1281. $("span.mireds").html(value["value"]);
  1282. return;
  1283. }
  1284. if ("useWhite" === key) {
  1285. useWhite = value;
  1286. }
  1287. if ("useCCT" === key) {
  1288. initCCT();
  1289. useCCT = value;
  1290. }
  1291. <!-- endRemoveIf(!light)-->
  1292. // ---------------------------------------------------------------------
  1293. // Sensors & Magnitudes
  1294. // ---------------------------------------------------------------------
  1295. <!-- removeIf(!sensor)-->
  1296. if ("magnitudesConfig" === key) {
  1297. initMagnitudes(value);
  1298. }
  1299. if ("magnitudes" === key) {
  1300. for (var i=0; i<value.size; ++i) {
  1301. var error = value.error[i] || 0;
  1302. var text = (0 === error) ?
  1303. value.value[i] + magnitudes[i].units :
  1304. magnitudeError(error);
  1305. var element = $("input[name='magnitude'][data='" + i + "']");
  1306. element.val(text);
  1307. }
  1308. return;
  1309. }
  1310. <!-- endRemoveIf(!sensor)-->
  1311. // ---------------------------------------------------------------------
  1312. // WiFi
  1313. // ---------------------------------------------------------------------
  1314. if ("maxNetworks" === key) {
  1315. maxNetworks = parseInt(value, 10);
  1316. return;
  1317. }
  1318. if ("wifi" === key) {
  1319. for (i in value) {
  1320. var wifi = value[i];
  1321. var nwk_line = addNetwork();
  1322. Object.keys(wifi).forEach(function(key) {
  1323. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1324. });
  1325. }
  1326. return;
  1327. }
  1328. if ("scanResult" === key) {
  1329. $("div.scan.loading").hide();
  1330. $("#scanResult").show();
  1331. }
  1332. // -----------------------------------------------------------------------------
  1333. // Home Assistant
  1334. // -----------------------------------------------------------------------------
  1335. if ("haConfig" === key) {
  1336. send("{}");
  1337. $("#haConfig")
  1338. .append(new Text(value))
  1339. .height($("#haConfig")[0].scrollHeight);
  1340. return;
  1341. }
  1342. // -----------------------------------------------------------------------------
  1343. // Relays scheduler
  1344. // -----------------------------------------------------------------------------
  1345. if ("maxSchedules" === key) {
  1346. maxSchedules = parseInt(value, 10);
  1347. return;
  1348. }
  1349. if ("schedules" === key) {
  1350. for (var i=0; i<value.size; ++i) {
  1351. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1352. Object.keys(value).forEach(function(key) {
  1353. if ("size" == key) return;
  1354. var sch_value = value[key][i];
  1355. $("input[name='" + key + "']", sch_line).val(sch_value);
  1356. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1357. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1358. });
  1359. }
  1360. return;
  1361. }
  1362. // ---------------------------------------------------------------------
  1363. // Relays
  1364. // ---------------------------------------------------------------------
  1365. if ("relayState" === key) {
  1366. initRelays(value.status);
  1367. updateRelays(value);
  1368. return;
  1369. }
  1370. // Relay configuration
  1371. if ("relayConfig" === key) {
  1372. initRelayConfig(value);
  1373. return;
  1374. }
  1375. // ---------------------------------------------------------------------
  1376. // LEDs
  1377. // ---------------------------------------------------------------------
  1378. if ("ledConfig" === key) {
  1379. initLeds(value);
  1380. for (var i=0; i<value.length; ++i) {
  1381. $("select[name='ledMode'][data='" + i + "']").val(value[i].mode);
  1382. $("input[name='ledRelay'][data='" + i + "']").val(value[i].relay);
  1383. }
  1384. return;
  1385. }
  1386. // ---------------------------------------------------------------------
  1387. // Domoticz
  1388. // ---------------------------------------------------------------------
  1389. // Domoticz - Relays
  1390. if ("dczRelays" === key) {
  1391. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1392. return;
  1393. }
  1394. // Domoticz - Magnitudes
  1395. <!-- removeIf(!sensor)-->
  1396. if ("dczMagnitudes" === key) {
  1397. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1398. return;
  1399. }
  1400. <!-- endRemoveIf(!sensor)-->
  1401. // ---------------------------------------------------------------------
  1402. // Thingspeak
  1403. // ---------------------------------------------------------------------
  1404. // Thingspeak - Relays
  1405. if ("tspkRelays" === key) {
  1406. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1407. return;
  1408. }
  1409. // Thingspeak - Magnitudes
  1410. <!-- removeIf(!sensor)-->
  1411. if ("tspkMagnitudes" === key) {
  1412. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1413. return;
  1414. }
  1415. <!-- endRemoveIf(!sensor)-->
  1416. // ---------------------------------------------------------------------
  1417. // HTTP API
  1418. // ---------------------------------------------------------------------
  1419. // Auto generate an APIKey if none defined yet
  1420. if ("apiVisible" === key) {
  1421. if (data.apiKey === undefined || data.apiKey === "") {
  1422. generateAPIKey();
  1423. }
  1424. }
  1425. // ---------------------------------------------------------------------
  1426. // General
  1427. // ---------------------------------------------------------------------
  1428. // Messages
  1429. if ("message" === key) {
  1430. if (value == 8 && (numReboot > 0 || numReload > 0 || numReconnect > 0)){
  1431. conf_saved = true;
  1432. }
  1433. window.alert(messages[value]);
  1434. return;
  1435. }
  1436. // Web log
  1437. if ("weblog" === key) {
  1438. send("{}");
  1439. var msg = value["msg"];
  1440. var pre = value["pre"];
  1441. for (var i=0; i < msg.length; ++i) {
  1442. if (pre[i]) {
  1443. $("#weblog").append(new Text(pre[i]));
  1444. }
  1445. $("#weblog").append(new Text(msg[i]));
  1446. }
  1447. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1448. return;
  1449. }
  1450. // Enable options
  1451. var position = key.indexOf("Visible");
  1452. if (position > 0 && position === key.length - 7) {
  1453. var module = key.slice(0,-7);
  1454. if (module == "sch") {
  1455. $("li.module-" + module).css("display", "inherit");
  1456. $("div.module-" + module).css("display", "flex");
  1457. return;
  1458. }
  1459. $(".module-" + module).css("display", "inherit");
  1460. return;
  1461. }
  1462. if ("deviceip" === key) {
  1463. var a_href = $("span[name='" + key + "']").parent();
  1464. a_href.attr("href", "//" + value);
  1465. a_href.next().attr("href", "telnet://" + value);
  1466. }
  1467. if ("now" === key) {
  1468. now = value;
  1469. return;
  1470. }
  1471. if ("free_size" === key) {
  1472. free_size = parseInt(value, 10);
  1473. }
  1474. // Pre-process
  1475. if ("mqttStatus" === key) {
  1476. value = value ? "CONNECTED" : "NOT CONNECTED";
  1477. }
  1478. if ("ntpStatus" === key) {
  1479. value = value ? "SYNC'D" : "NOT SYNC'D";
  1480. }
  1481. if ("uptime" === key) {
  1482. ago = 0;
  1483. var uptime = parseInt(value, 10);
  1484. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1485. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1486. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1487. var days = uptime;
  1488. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1489. }
  1490. <!-- removeIf(!thermostat)-->
  1491. if ("tmpUnits" == key) {
  1492. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1493. }
  1494. <!-- endRemoveIf(!thermostat)-->
  1495. // ---------------------------------------------------------------------
  1496. // Matching
  1497. // ---------------------------------------------------------------------
  1498. var pre;
  1499. var post;
  1500. // Look for INPUTs
  1501. var input = $("input[name='" + key + "']");
  1502. if (input.length > 0) {
  1503. if (input.attr("type") === "checkbox") {
  1504. input.prop("checked", value);
  1505. } else if (input.attr("type") === "radio") {
  1506. input.val([value]);
  1507. } else {
  1508. pre = input.attr("pre") || "";
  1509. post = input.attr("post") || "";
  1510. input.val(pre + value + post);
  1511. }
  1512. }
  1513. // Look for SPANs
  1514. var span = $("span[name='" + key + "']");
  1515. if (span.length > 0) {
  1516. if (Array.isArray(value)) {
  1517. value.forEach(function(elem) {
  1518. span.append(elem);
  1519. span.append('</br>');
  1520. });
  1521. } else {
  1522. pre = span.attr("pre") || "";
  1523. post = span.attr("post") || "";
  1524. span.html(pre + value + post);
  1525. }
  1526. }
  1527. // Look for SELECTs
  1528. var select = $("select[name='" + key + "']");
  1529. if (select.length > 0) {
  1530. select.val(value);
  1531. }
  1532. });
  1533. setOriginalsFromValues();
  1534. }
  1535. function hasChanged() {
  1536. var newValue, originalValue;
  1537. if ($(this).attr("type") === "checkbox") {
  1538. newValue = $(this).prop("checked");
  1539. originalValue = ($(this).attr("original") === "true");
  1540. } else {
  1541. newValue = $(this).val();
  1542. originalValue = $(this).attr("original");
  1543. }
  1544. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1545. var action = $(this).attr("action");
  1546. if (typeof originalValue === "undefined") { return; }
  1547. if ("none" === action) { return; }
  1548. if (newValue !== originalValue) {
  1549. if (!hasChanged) {
  1550. ++numChanged;
  1551. if ("reconnect" === action) { ++numReconnect; }
  1552. if ("reboot" === action) { ++numReboot; }
  1553. if ("reload" === action) { ++numReload; }
  1554. $(this).attr("hasChanged", true);
  1555. }
  1556. } else {
  1557. if (hasChanged) {
  1558. --numChanged;
  1559. if ("reconnect" === action) { --numReconnect; }
  1560. if ("reboot" === action) { --numReboot; }
  1561. if ("reload" === action) { --numReload; }
  1562. $(this).attr("hasChanged", false);
  1563. }
  1564. }
  1565. }
  1566. // -----------------------------------------------------------------------------
  1567. // Init & connect
  1568. // -----------------------------------------------------------------------------
  1569. function initUrls(root) {
  1570. var paths = ["ws", "upgrade", "config", "auth"];
  1571. urls["root"] = root;
  1572. paths.forEach(function(path) {
  1573. urls[path] = new URL(path, root);
  1574. urls[path].protocol = root.protocol;
  1575. });
  1576. if (root.protocol == "https:") {
  1577. urls.ws.protocol = "wss:";
  1578. } else {
  1579. urls.ws.protocol = "ws:";
  1580. }
  1581. }
  1582. function connectToURL(url) {
  1583. initUrls(url);
  1584. fetch(urls.auth.href, {
  1585. 'method': 'GET',
  1586. 'cors': true,
  1587. 'credentials': 'same-origin'
  1588. }).then(function(response) {
  1589. // Nothing to do, reload page and retry
  1590. if (response.status != 200) {
  1591. doReload(5000);
  1592. return;
  1593. }
  1594. // update websock object
  1595. if (websock) { websock.close(); }
  1596. websock = new WebSocket(urls.ws.href);
  1597. websock.onmessage = function(evt) {
  1598. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1599. if (data) {
  1600. processData(data);
  1601. }
  1602. };
  1603. }).catch(function(error) {
  1604. console.log(error);
  1605. doReload(5000);
  1606. });
  1607. }
  1608. function connect(host) {
  1609. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1610. host = "http://" + host;
  1611. }
  1612. connectToURL(new URL(host));
  1613. }
  1614. function connectToCurrentURL() {
  1615. connectToURL(new URL(window.location));
  1616. }
  1617. $(function() {
  1618. initMessages();
  1619. loadTimeZones();
  1620. createCheckboxes();
  1621. setInterval(function() { keepTime(); }, 1000);
  1622. $(".password-reveal").on("click", toggleVisiblePassword);
  1623. $("#menuLink").on("click", toggleMenu);
  1624. $(".pure-menu-link").on("click", showPanel);
  1625. $("progress").attr({ value: 0, max: 100 });
  1626. $(".button-update").on("click", doUpdate);
  1627. $(".button-update-password").on("click", doUpdatePassword);
  1628. $(".button-generate-password").on("click", doGeneratePassword);
  1629. $(".button-reboot").on("click", doReboot);
  1630. $(".button-reconnect").on("click", doReconnect);
  1631. $(".button-wifi-scan").on("click", doScan);
  1632. $(".button-ha-config").on("click", doHAConfig);
  1633. $(".button-dbgcmd").on("click", doDebugCommand);
  1634. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1635. $(".button-dbg-clear").on("click", doDebugClear);
  1636. $(".button-settings-backup").on("click", doBackup);
  1637. $(".button-settings-restore").on("click", doRestore);
  1638. $(".button-settings-factory").on("click", doFactoryReset);
  1639. $("#uploader").on("change", onFileUpload);
  1640. $(".button-upgrade").on("click", doUpgrade);
  1641. <!-- removeIf(!thermostat)-->
  1642. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1643. <!-- endRemoveIf(!thermostat)-->
  1644. $(".button-apikey").on("click", generateAPIKey);
  1645. $(".button-upgrade-browse").on("click", function() {
  1646. $("input[name='upgrade']")[0].click();
  1647. return false;
  1648. });
  1649. $("input[name='upgrade']").change(function (){
  1650. var file = this.files[0];
  1651. $("input[name='filename']").val(file.name);
  1652. });
  1653. $(".button-add-network").on("click", function() {
  1654. $(".more", addNetwork()).toggle();
  1655. });
  1656. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1657. <!-- removeIf(!light)-->
  1658. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1659. <!-- endRemoveIf(!light)-->
  1660. $(".button-add-rpnrule").on('click', addRPNRule);
  1661. $(".button-add-rpntopic").on('click', addRPNTopic);
  1662. $(".button-del-parent").on('click', delParent);
  1663. <!-- removeIf(!rfm69)-->
  1664. $(".button-add-mapping").on('click', addMapping);
  1665. $(".button-clear-counts").on('click', doClearCounts);
  1666. $(".button-clear-messages").on('click', doClearMessages);
  1667. $(".button-clear-filters").on('click', doClearFilters);
  1668. $('#packets tbody').on('mousedown', 'td', doFilter);
  1669. packets = $('#packets').DataTable({
  1670. "paging": false
  1671. });
  1672. for (var i = 0; i < packets.columns()[0].length; i++) {
  1673. filters[i] = false;
  1674. }
  1675. <!-- endRemoveIf(!rfm69)-->
  1676. $(".gpio-select").each(function(_, elem) {
  1677. initSelectGPIO(elem)
  1678. });
  1679. $(document).on("change", "input", hasChanged);
  1680. $(document).on("change", "select", hasChanged);
  1681. $("textarea").on("dblclick", function() { this.select(); });
  1682. // don't autoconnect when opening from filesystem
  1683. if (window.location.protocol === "file:") { return; }
  1684. // Check host param in query string
  1685. var search = new URLSearchParams(window.location.search),
  1686. host = search.get("host");
  1687. if (host !== null) {
  1688. connect(host);
  1689. } else {
  1690. connectToCurrentURL();
  1691. }
  1692. });