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.

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