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.

2103 lines
60 KiB

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