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
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 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
7 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  5. var 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. var actionLine = template.clone();
  800. $(line).find("#schActionDiv").append(actionLine);
  801. $(line).find("input").each(function() {
  802. $(this).attr("tabindex", tabindex);
  803. tabindex++;
  804. });
  805. $(line).find(".button-del-schedule").on("click", delSchedule);
  806. $(line).find(".button-more-schedule").on("click", moreSchedule);
  807. $(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
  808. .next().prop("for", "schUTC" + (numSchedules + 1));
  809. $(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
  810. .next().prop("for", "schEnabled" + (numSchedules + 1));
  811. line.appendTo("#schedules");
  812. $(line).find("input[type='checkbox']").prop("checked", false);
  813. return line;
  814. }
  815. // -----------------------------------------------------------------------------
  816. // Relays
  817. // -----------------------------------------------------------------------------
  818. function initRelays(data) {
  819. var current = $("#relays > div").length;
  820. if (current > 0) { return; }
  821. var template = $("#relayTemplate .pure-g")[0];
  822. for (var i=0; i<data.length; i++) {
  823. // Add relay fields
  824. var line = $(template).clone();
  825. $(".id", line).html(i);
  826. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  827. .prop("id", "relay" + i)
  828. .on("change", function (event) {
  829. var id = parseInt($(event.target).attr("data"), 10);
  830. var status = $(event.target).prop("checked");
  831. doToggle(id, status);
  832. });
  833. $("label.toggle", line).prop("for", "relay" + i)
  834. line.appendTo("#relays");
  835. // Populate the relay SELECTs
  836. $("select.isrelay").append(
  837. $("<option></option>").attr("value",i).text("Switch #" + i));
  838. }
  839. }
  840. function updateRelays(data) {
  841. var size = data.size;
  842. for (var i=0; i<size; ++i) {
  843. var elem = $("input[name='relay'][data='" + i + "']");
  844. elem.prop("checked", data.status[i]);
  845. var lock = {
  846. 0: false,
  847. 1: !data.status[i],
  848. 2: data.status[i]
  849. };
  850. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  851. }
  852. }
  853. function createCheckboxes() {
  854. $("input[type='checkbox']").each(function() {
  855. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  856. $(this).parent().addClass("toggleWrapper");
  857. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  858. });
  859. }
  860. function initRelayConfig(data) {
  861. var current = $("#relayConfig > legend").length; // there is a legend per relay
  862. if (current > 0) { return; }
  863. var size = data.size;
  864. var start = data.start;
  865. var template = $("#relayConfigTemplate").children();
  866. for (var i=start; i<size; ++i) {
  867. var line = $(template).clone();
  868. $("span.id", line).html(i);
  869. $("span.gpio", line).html(data.gpio[i]);
  870. $("select[name='relayBoot']", line).val(data.boot[i]);
  871. $("select[name='relayPulse']", line).val(data.pulse[i]);
  872. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  873. $("input[name='relayLastSch']", line).prop('checked', data.sch_last[i]);
  874. $("input[name='relayLastSch']", line).attr("id", "relayLastSch" + i);
  875. $("input[name='relayLastSch']", line).attr("name", "relayLastSch" + i);
  876. $("input[name='relayLastSch" + i + "']", line).next().attr("for","relayLastSch" + (i));
  877. if ("group" in data) {
  878. $("input[name='mqttGroup']", line).val(data.group[i]);
  879. }
  880. if ("group_sync" in data) {
  881. $("select[name='mqttGroupSync']", line).val(data.group_sync[i]);
  882. }
  883. if ("on_disc" in data) {
  884. $("select[name='relayOnDisc']", line).val(data.on_disc[i]);
  885. }
  886. line.appendTo("#relayConfig");
  887. }
  888. }
  889. function initLeds(data) {
  890. var current = $("#ledConfig > div").length;
  891. if (current > 0) { return; }
  892. var size = data.length;
  893. var template = $("#ledConfigTemplate").children();
  894. for (var i=0; i<size; ++i) {
  895. var line = $(template).clone();
  896. $("span.id", line).html(i);
  897. $("select", line).attr("data", i);
  898. $("input", line).attr("data", i);
  899. line.appendTo("#ledConfig");
  900. }
  901. }
  902. // -----------------------------------------------------------------------------
  903. // Sensors & Magnitudes
  904. // -----------------------------------------------------------------------------
  905. <!-- removeIf(!sensor)-->
  906. function initMagnitudes(data) {
  907. // check if already initialized (each magnitude is inside div.pure-g)
  908. var done = $("#magnitudes > div").length;
  909. if (done > 0) { return; }
  910. var size = data.size;
  911. // add templates
  912. var template = $("#magnitudeTemplate").children();
  913. for (var i=0; i<size; ++i) {
  914. var magnitude = {
  915. "name": magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10),
  916. "units": data.units[i],
  917. "description": data.description[i]
  918. };
  919. magnitudes.push(magnitude);
  920. var line = $(template).clone();
  921. $("label", line).html(magnitude.name);
  922. $("div.hint", line).html(magnitude.description);
  923. $("input", line).attr("data", i);
  924. line.appendTo("#magnitudes");
  925. }
  926. }
  927. <!-- endRemoveIf(!sensor)-->
  928. // -----------------------------------------------------------------------------
  929. // Lights
  930. // -----------------------------------------------------------------------------
  931. <!-- removeIf(!light)-->
  932. // wheelColorPicker accepts:
  933. // hsv(0...360,0...1,0...1)
  934. // hsv(0...100%,0...100%,0...100%)
  935. // While we use:
  936. // hsv(0...360,0...100%,0...100%)
  937. function _hsv_round(value) {
  938. return Math.round(value * 100) / 100;
  939. }
  940. function getPickerRGB(picker) {
  941. return $(picker).wheelColorPicker("getValue", "css");
  942. }
  943. function setPickerRGB(picker, color) {
  944. $(picker).wheelColorPicker("setValue", value, true);
  945. }
  946. // TODO: use pct values instead of doing conversion?
  947. function getPickerHSV(picker) {
  948. var color = $(picker).wheelColorPicker("getColor");
  949. return String(Math.ceil(_hsv_round(color.h) * 360))
  950. + "," + String(Math.ceil(_hsv_round(color.s) * 100))
  951. + "," + String(Math.ceil(_hsv_round(color.v) * 100));
  952. }
  953. function setPickerHSV(picker, value) {
  954. if (value === getPickerHSV(picker)) return;
  955. var chunks = value.split(",");
  956. $(picker).wheelColorPicker("setColor", {
  957. h: _hsv_round(chunks[0] / 360),
  958. s: _hsv_round(chunks[1] / 100),
  959. v: _hsv_round(chunks[2] / 100)
  960. });
  961. }
  962. function initColor(cfg) {
  963. var rgb = false;
  964. if (typeof cfg === "object") {
  965. rgb = cfg.rgb;
  966. }
  967. // check if already initialized
  968. var done = $("#colors > div").length;
  969. if (done > 0) { return; }
  970. // add template
  971. var template = $("#colorTemplate").children();
  972. var line = $(template).clone();
  973. line.appendTo("#colors");
  974. // init color wheel
  975. $("input[name='color']").wheelColorPicker({
  976. sliders: (rgb ? "wrgbp" : "whsp")
  977. }).on("sliderup", function() {
  978. if (rgb) {
  979. sendAction("color", {rgb: getPickerRGB(this)});
  980. } else {
  981. sendAction("color", {hsv: getPickerHSV(this)});
  982. }
  983. });
  984. }
  985. function initCCT() {
  986. // check if already initialized
  987. var done = $("#cct > div").length;
  988. if (done > 0) { return; }
  989. $("#miredsTemplate").children().clone().appendTo("#cct");
  990. $("#mireds").on("change", function() {
  991. var value = $(this).val();
  992. var parent = $(this).parents(".pure-g");
  993. $("span", parent).html(value);
  994. sendAction("mireds", {mireds: value});
  995. });
  996. }
  997. function initChannels(num) {
  998. // check if already initialized
  999. var done = $("#channels > div").length > 0;
  1000. if (done) { return; }
  1001. // does it have color channels?
  1002. var colors = $("#colors > div").length > 0;
  1003. // calculate channels to create
  1004. var max = num;
  1005. if (colors) {
  1006. max = num % 3;
  1007. if ((max > 0) & useWhite) {
  1008. max--;
  1009. if (useCCT) {
  1010. max--;
  1011. }
  1012. }
  1013. }
  1014. var start = num - max;
  1015. var onChannelSliderChange = function() {
  1016. var id = $(this).attr("data");
  1017. var value = $(this).val();
  1018. var parent = $(this).parents(".pure-g");
  1019. $("span", parent).html(value);
  1020. sendAction("channel", {id: id, value: value});
  1021. };
  1022. // add channel templates
  1023. var i = 0;
  1024. var template = $("#channelTemplate").children();
  1025. for (i=0; i<max; i++) {
  1026. var channel_id = start + i;
  1027. var line = $(template).clone();
  1028. $("span.slider", line).attr("data", channel_id);
  1029. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1030. $("label", line).html("Channel #" + channel_id);
  1031. line.appendTo("#channels");
  1032. }
  1033. // Init channel dropdowns
  1034. for (i=0; i<num; i++) {
  1035. $("select.islight").append(
  1036. $("<option></option>").attr("value",i).text("Channel #" + i));
  1037. }
  1038. // add brightness template
  1039. var template = $("#brightnessTemplate").children();
  1040. var line = $(template).clone();
  1041. line.appendTo("#channels");
  1042. // init bright slider
  1043. $("#brightness").on("change", function() {
  1044. var value = $(this).val();
  1045. var parent = $(this).parents(".pure-g");
  1046. $("span", parent).html(value);
  1047. sendAction("brightness", {value: value});
  1048. });
  1049. }
  1050. <!-- endRemoveIf(!light)-->
  1051. // -----------------------------------------------------------------------------
  1052. // RFBridge
  1053. // -----------------------------------------------------------------------------
  1054. <!-- removeIf(!rfbridge)-->
  1055. function rfbLearn() {
  1056. var parent = $(this).parents(".pure-g");
  1057. var input = $("input", parent);
  1058. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1059. }
  1060. function rfbForget() {
  1061. var parent = $(this).parents(".pure-g");
  1062. var input = $("input", parent);
  1063. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1064. }
  1065. function rfbSend() {
  1066. var parent = $(this).parents(".pure-g");
  1067. var input = $("input", parent);
  1068. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1069. }
  1070. function addRfbNode() {
  1071. var numNodes = $("#rfbNodes > legend").length;
  1072. var template = $("#rfbNodeTemplate").children();
  1073. var line = $(template).clone();
  1074. var status = true;
  1075. $("span", line).html(numNodes);
  1076. $(line).find("input").each(function() {
  1077. $(this).attr("data-id", numNodes);
  1078. $(this).attr("data-status", status ? 1 : 0);
  1079. status = !status;
  1080. });
  1081. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1082. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1083. $(line).find(".button-rfb-send").on("click", rfbSend);
  1084. line.appendTo("#rfbNodes");
  1085. return line;
  1086. }
  1087. <!-- endRemoveIf(!rfbridge)-->
  1088. // -----------------------------------------------------------------------------
  1089. // LightFox
  1090. // -----------------------------------------------------------------------------
  1091. <!-- removeIf(!lightfox)-->
  1092. function lightfoxLearn() {
  1093. sendAction("lightfoxLearn", {});
  1094. }
  1095. function lightfoxClear() {
  1096. sendAction("lightfoxClear", {});
  1097. }
  1098. function initLightfox(data, relayCount) {
  1099. var numNodes = data.length;
  1100. var template = $("#lightfoxNodeTemplate").children();
  1101. var i, j;
  1102. for (i=0; i<numNodes; i++) {
  1103. var $line = $(template).clone();
  1104. $line.find("label > span").text(data[i]["id"]);
  1105. $line.find("select").each(function() {
  1106. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1107. for (j=0; j < relayCount; j++) {
  1108. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1109. }
  1110. $(this).val(data[i]["relay"]);
  1111. status = !status;
  1112. });
  1113. $line.appendTo("#lightfoxNodes");
  1114. }
  1115. var $panel = $("#panel-lightfox")
  1116. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1117. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1118. }
  1119. <!-- endRemoveIf(!lightfox)-->
  1120. // -----------------------------------------------------------------------------
  1121. // Processing
  1122. // -----------------------------------------------------------------------------
  1123. function processData(data) {
  1124. if (debug) console.log(data);
  1125. // title
  1126. if ("app_name" in data) {
  1127. var title = data.app_name;
  1128. if ("app_version" in data) {
  1129. title = title + " " + data.app_version;
  1130. }
  1131. $("span[name=title]").html(title);
  1132. if ("hostname" in data) {
  1133. title = data.hostname + " - " + title;
  1134. }
  1135. document.title = title;
  1136. }
  1137. Object.keys(data).forEach(function(key) {
  1138. var i;
  1139. var value = data[key];
  1140. // ---------------------------------------------------------------------
  1141. // Web mode
  1142. // ---------------------------------------------------------------------
  1143. if ("webMode" === key) {
  1144. password = (1 === value);
  1145. $("#layout").toggle(!password);
  1146. $("#password").toggle(password);
  1147. }
  1148. // ---------------------------------------------------------------------
  1149. // Actions
  1150. // ---------------------------------------------------------------------
  1151. if ("action" === key) {
  1152. if ("reload" === data.action) { doReload(1000); }
  1153. return;
  1154. }
  1155. // ---------------------------------------------------------------------
  1156. // RFBridge
  1157. // ---------------------------------------------------------------------
  1158. <!-- removeIf(!rfbridge)-->
  1159. if ("rfbCount" === key) {
  1160. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1161. return;
  1162. }
  1163. if ("rfb" === key) {
  1164. var rfb = data.rfb;
  1165. var size = rfb.size;
  1166. var start = rfb.start;
  1167. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1168. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1169. for (var i=0; i<size; ++i) {
  1170. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1171. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1172. }
  1173. return;
  1174. }
  1175. <!-- endRemoveIf(!rfbridge)-->
  1176. // ---------------------------------------------------------------------
  1177. // LightFox
  1178. // ---------------------------------------------------------------------
  1179. <!-- removeIf(!lightfox)-->
  1180. if ("lightfoxButtons" === key) {
  1181. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1182. return;
  1183. }
  1184. <!-- endRemoveIf(!rfbridge)-->
  1185. // ---------------------------------------------------------------------
  1186. // RFM69
  1187. // ---------------------------------------------------------------------
  1188. <!-- removeIf(!rfm69)-->
  1189. if (key == "packet") {
  1190. var packet = data.packet;
  1191. var d = new Date();
  1192. packets.row.add([
  1193. d.toLocaleTimeString('en-US', { hour12: false }),
  1194. packet.senderID,
  1195. packet.packetID,
  1196. packet.targetID,
  1197. packet.key,
  1198. packet.value,
  1199. packet.rssi,
  1200. packet.duplicates,
  1201. packet.missing,
  1202. ]).draw(false);
  1203. return;
  1204. }
  1205. if (key == "mapping") {
  1206. for (var i in data.mapping) {
  1207. // add a new row
  1208. addMapping();
  1209. // get group
  1210. var line = $("#mapping .pure-g")[i];
  1211. // fill in the blanks
  1212. var mapping = data.mapping[i];
  1213. Object.keys(mapping).forEach(function(key) {
  1214. var id = "input[name=" + key + "]";
  1215. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1216. });
  1217. }
  1218. return;
  1219. }
  1220. <!-- endRemoveIf(!rfm69)-->
  1221. // ---------------------------------------------------------------------
  1222. // RPN Rules
  1223. // ---------------------------------------------------------------------
  1224. if (key == "rpnRules") {
  1225. for (var i in data.rpnRules) {
  1226. // add a new row
  1227. addRPNRule();
  1228. // get group
  1229. var line = $("#rpnRules .pure-g")[i];
  1230. // fill in the blanks
  1231. var rule = data.rpnRules[i];
  1232. $("input", line).val(rule).attr("original", rule);
  1233. }
  1234. return;
  1235. }
  1236. if (key == "rpnTopics") {
  1237. for (var i in data.rpnTopics) {
  1238. // add a new row
  1239. addRPNTopic();
  1240. // get group
  1241. var line = $("#rpnTopics .pure-g")[i];
  1242. // fill in the blanks
  1243. var topic = data.rpnTopics[i];
  1244. var name = data.rpnNames[i];
  1245. $("input[name='rpnTopic']", line).val(topic).attr("original", topic);
  1246. $("input[name='rpnName']", line).val(name).attr("original", name);
  1247. }
  1248. return;
  1249. }
  1250. if (key == "rpnNames") return;
  1251. // ---------------------------------------------------------------------
  1252. // Lights
  1253. // ---------------------------------------------------------------------
  1254. <!-- removeIf(!light)-->
  1255. if ("rgb" === key) {
  1256. initColor({rgb: true});
  1257. setPickerRGB($("input[name='color']"), value);
  1258. return;
  1259. }
  1260. if ("hsv" === key) {
  1261. initColor({hsv: true});
  1262. setPickerHSV($("input[name='color']"), value);
  1263. return;
  1264. }
  1265. if ("brightness" === key) {
  1266. $("#brightness").val(value);
  1267. $("span.brightness").html(value);
  1268. return;
  1269. }
  1270. if ("channels" === key) {
  1271. var len = value.length;
  1272. initChannels(len);
  1273. for (i in value) {
  1274. var ch = value[i];
  1275. $("input.slider[data=" + i + "]").val(ch);
  1276. $("span.slider[data=" + i + "]").html(ch);
  1277. }
  1278. return;
  1279. }
  1280. if ("mireds" === key) {
  1281. $("#mireds").attr("min", value["cold"]);
  1282. $("#mireds").attr("max", value["warm"]);
  1283. $("#mireds").val(value["value"]);
  1284. $("span.mireds").html(value["value"]);
  1285. return;
  1286. }
  1287. if ("useWhite" === key) {
  1288. useWhite = value;
  1289. }
  1290. if ("useCCT" === key) {
  1291. initCCT();
  1292. useCCT = value;
  1293. }
  1294. <!-- endRemoveIf(!light)-->
  1295. // ---------------------------------------------------------------------
  1296. // Sensors & Magnitudes
  1297. // ---------------------------------------------------------------------
  1298. <!-- removeIf(!sensor)-->
  1299. if ("magnitudesConfig" === key) {
  1300. initMagnitudes(value);
  1301. }
  1302. if ("magnitudes" === key) {
  1303. for (var i=0; i<value.size; ++i) {
  1304. var error = value.error[i] || 0;
  1305. var text = (0 === error) ?
  1306. value.value[i] + magnitudes[i].units :
  1307. magnitudeError(error);
  1308. var element = $("input[name='magnitude'][data='" + i + "']");
  1309. element.val(text);
  1310. }
  1311. return;
  1312. }
  1313. <!-- endRemoveIf(!sensor)-->
  1314. // ---------------------------------------------------------------------
  1315. // WiFi
  1316. // ---------------------------------------------------------------------
  1317. if ("maxNetworks" === key) {
  1318. maxNetworks = parseInt(value, 10);
  1319. return;
  1320. }
  1321. if ("wifi" === key) {
  1322. for (i in value) {
  1323. var wifi = value[i];
  1324. var nwk_line = addNetwork();
  1325. Object.keys(wifi).forEach(function(key) {
  1326. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1327. });
  1328. }
  1329. return;
  1330. }
  1331. if ("scanResult" === key) {
  1332. $("div.scan.loading").hide();
  1333. $("#scanResult").show();
  1334. }
  1335. // -----------------------------------------------------------------------------
  1336. // Home Assistant
  1337. // -----------------------------------------------------------------------------
  1338. if ("haConfig" === key) {
  1339. send("{}");
  1340. $("#haConfig")
  1341. .append(new Text(value))
  1342. .height($("#haConfig")[0].scrollHeight);
  1343. return;
  1344. }
  1345. // -----------------------------------------------------------------------------
  1346. // Relays scheduler
  1347. // -----------------------------------------------------------------------------
  1348. if ("maxSchedules" === key) {
  1349. maxSchedules = parseInt(value, 10);
  1350. return;
  1351. }
  1352. if ("schedules" === key) {
  1353. for (var i=0; i<value.size; ++i) {
  1354. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1355. Object.keys(value).forEach(function(key) {
  1356. if ("size" == key) return;
  1357. var sch_value = value[key][i];
  1358. $("input[name='" + key + "']", sch_line).val(sch_value);
  1359. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1360. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1361. });
  1362. }
  1363. return;
  1364. }
  1365. // ---------------------------------------------------------------------
  1366. // Relays
  1367. // ---------------------------------------------------------------------
  1368. if ("relayState" === key) {
  1369. initRelays(value.status);
  1370. updateRelays(value);
  1371. return;
  1372. }
  1373. // Relay configuration
  1374. if ("relayConfig" === key) {
  1375. initRelayConfig(value);
  1376. return;
  1377. }
  1378. // ---------------------------------------------------------------------
  1379. // LEDs
  1380. // ---------------------------------------------------------------------
  1381. if ("ledConfig" === key) {
  1382. initLeds(value);
  1383. for (var i=0; i<value.length; ++i) {
  1384. $("select[name='ledMode'][data='" + i + "']").val(value[i].mode);
  1385. $("input[name='ledRelay'][data='" + i + "']").val(value[i].relay);
  1386. }
  1387. return;
  1388. }
  1389. // ---------------------------------------------------------------------
  1390. // Domoticz
  1391. // ---------------------------------------------------------------------
  1392. // Domoticz - Relays
  1393. if ("dczRelays" === key) {
  1394. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1395. return;
  1396. }
  1397. // Domoticz - Magnitudes
  1398. <!-- removeIf(!sensor)-->
  1399. if ("dczMagnitudes" === key) {
  1400. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1401. return;
  1402. }
  1403. <!-- endRemoveIf(!sensor)-->
  1404. // ---------------------------------------------------------------------
  1405. // Thingspeak
  1406. // ---------------------------------------------------------------------
  1407. // Thingspeak - Relays
  1408. if ("tspkRelays" === key) {
  1409. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1410. return;
  1411. }
  1412. // Thingspeak - Magnitudes
  1413. <!-- removeIf(!sensor)-->
  1414. if ("tspkMagnitudes" === key) {
  1415. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1416. return;
  1417. }
  1418. <!-- endRemoveIf(!sensor)-->
  1419. // ---------------------------------------------------------------------
  1420. // HTTP API
  1421. // ---------------------------------------------------------------------
  1422. // Auto generate an APIKey if none defined yet
  1423. if ("apiVisible" === key) {
  1424. if (data.apiKey === undefined || data.apiKey === "") {
  1425. generateAPIKey();
  1426. }
  1427. }
  1428. // ---------------------------------------------------------------------
  1429. // General
  1430. // ---------------------------------------------------------------------
  1431. // Messages
  1432. if ("message" === key) {
  1433. if (value == 8 && (numReboot > 0 || numReload > 0 || numReconnect > 0)){
  1434. conf_saved = true;
  1435. }
  1436. window.alert(messages[value]);
  1437. return;
  1438. }
  1439. // Web log
  1440. if ("weblog" === key) {
  1441. send("{}");
  1442. msg = value["msg"];
  1443. pre = value["pre"];
  1444. for (var i=0; i < msg.length; ++i) {
  1445. if (pre[i]) {
  1446. $("#weblog").append(new Text(pre[i]));
  1447. }
  1448. $("#weblog").append(new Text(msg[i]));
  1449. }
  1450. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1451. return;
  1452. }
  1453. // Enable options
  1454. var position = key.indexOf("Visible");
  1455. if (position > 0 && position === key.length - 7) {
  1456. var module = key.slice(0,-7);
  1457. if (module == "sch") {
  1458. $("li.module-" + module).css("display", "inherit");
  1459. $("div.module-" + module).css("display", "flex");
  1460. return;
  1461. }
  1462. $(".module-" + module).css("display", "inherit");
  1463. return;
  1464. }
  1465. if ("deviceip" === key) {
  1466. var a_href = $("span[name='" + key + "']").parent();
  1467. a_href.attr("href", "//" + value);
  1468. a_href.next().attr("href", "telnet://" + value);
  1469. }
  1470. if ("now" === key) {
  1471. now = value;
  1472. return;
  1473. }
  1474. if ("free_size" === key) {
  1475. free_size = parseInt(value, 10);
  1476. }
  1477. // Pre-process
  1478. if ("mqttStatus" === key) {
  1479. value = value ? "CONNECTED" : "NOT CONNECTED";
  1480. }
  1481. if ("ntpStatus" === key) {
  1482. value = value ? "SYNC'D" : "NOT SYNC'D";
  1483. }
  1484. if ("uptime" === key) {
  1485. ago = 0;
  1486. var uptime = parseInt(value, 10);
  1487. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1488. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1489. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1490. var days = uptime;
  1491. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1492. }
  1493. <!-- removeIf(!thermostat)-->
  1494. if ("tmpUnits" == key) {
  1495. $("span.tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  1496. }
  1497. <!-- endRemoveIf(!thermostat)-->
  1498. // ---------------------------------------------------------------------
  1499. // Matching
  1500. // ---------------------------------------------------------------------
  1501. var pre;
  1502. var post;
  1503. // Look for INPUTs
  1504. var input = $("input[name='" + key + "']");
  1505. if (input.length > 0) {
  1506. if (input.attr("type") === "checkbox") {
  1507. input.prop("checked", value);
  1508. } else if (input.attr("type") === "radio") {
  1509. input.val([value]);
  1510. } else {
  1511. pre = input.attr("pre") || "";
  1512. post = input.attr("post") || "";
  1513. input.val(pre + value + post);
  1514. }
  1515. }
  1516. // Look for SPANs
  1517. var span = $("span[name='" + key + "']");
  1518. if (span.length > 0) {
  1519. if (Array.isArray(value)) {
  1520. value.forEach(function(elem) {
  1521. span.append(elem);
  1522. span.append('</br>');
  1523. });
  1524. } else {
  1525. pre = span.attr("pre") || "";
  1526. post = span.attr("post") || "";
  1527. span.html(pre + value + post);
  1528. }
  1529. }
  1530. // Look for SELECTs
  1531. var select = $("select[name='" + key + "']");
  1532. if (select.length > 0) {
  1533. select.val(value);
  1534. }
  1535. });
  1536. setOriginalsFromValues();
  1537. }
  1538. function hasChanged() {
  1539. var newValue, originalValue;
  1540. if ($(this).attr("type") === "checkbox") {
  1541. newValue = $(this).prop("checked");
  1542. originalValue = ($(this).attr("original") === "true");
  1543. } else {
  1544. newValue = $(this).val();
  1545. originalValue = $(this).attr("original");
  1546. }
  1547. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1548. var action = $(this).attr("action");
  1549. if (typeof originalValue === "undefined") { return; }
  1550. if ("none" === action) { return; }
  1551. if (newValue !== originalValue) {
  1552. if (!hasChanged) {
  1553. ++numChanged;
  1554. if ("reconnect" === action) { ++numReconnect; }
  1555. if ("reboot" === action) { ++numReboot; }
  1556. if ("reload" === action) { ++numReload; }
  1557. $(this).attr("hasChanged", true);
  1558. }
  1559. } else {
  1560. if (hasChanged) {
  1561. --numChanged;
  1562. if ("reconnect" === action) { --numReconnect; }
  1563. if ("reboot" === action) { --numReboot; }
  1564. if ("reload" === action) { --numReload; }
  1565. $(this).attr("hasChanged", false);
  1566. }
  1567. }
  1568. }
  1569. // -----------------------------------------------------------------------------
  1570. // Init & connect
  1571. // -----------------------------------------------------------------------------
  1572. function initUrls(root) {
  1573. var paths = ["ws", "upgrade", "config", "auth"];
  1574. urls["root"] = root;
  1575. paths.forEach(function(path) {
  1576. urls[path] = new URL(path, root);
  1577. urls[path].protocol = root.protocol;
  1578. });
  1579. if (root.protocol == "https:") {
  1580. urls.ws.protocol = "wss:";
  1581. } else {
  1582. urls.ws.protocol = "ws:";
  1583. }
  1584. }
  1585. function connectToURL(url) {
  1586. initUrls(url);
  1587. fetch(urls.auth.href, {
  1588. 'method': 'GET',
  1589. 'cors': true,
  1590. 'credentials': 'same-origin'
  1591. }).then(function(response) {
  1592. // Nothing to do, reload page and retry
  1593. if (response.status != 200) {
  1594. doReload(5000);
  1595. return;
  1596. }
  1597. // update websock object
  1598. if (websock) { websock.close(); }
  1599. websock = new WebSocket(urls.ws.href);
  1600. websock.onmessage = function(evt) {
  1601. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1602. if (data) {
  1603. processData(data);
  1604. }
  1605. };
  1606. }).catch(function(error) {
  1607. console.log(error);
  1608. doReload(5000);
  1609. });
  1610. }
  1611. function connect(host) {
  1612. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1613. host = "http://" + host;
  1614. }
  1615. connectToURL(new URL(host));
  1616. }
  1617. function connectToCurrentURL() {
  1618. connectToURL(new URL(window.location));
  1619. }
  1620. $(function() {
  1621. initMessages();
  1622. loadTimeZones();
  1623. createCheckboxes();
  1624. setInterval(function() { keepTime(); }, 1000);
  1625. $(".password-reveal").on("click", toggleVisiblePassword);
  1626. $("#menuLink").on("click", toggleMenu);
  1627. $(".pure-menu-link").on("click", showPanel);
  1628. $("progress").attr({ value: 0, max: 100 });
  1629. $(".button-update").on("click", doUpdate);
  1630. $(".button-update-password").on("click", doUpdatePassword);
  1631. $(".button-generate-password").on("click", doGeneratePassword);
  1632. $(".button-reboot").on("click", doReboot);
  1633. $(".button-reconnect").on("click", doReconnect);
  1634. $(".button-wifi-scan").on("click", doScan);
  1635. $(".button-ha-config").on("click", doHAConfig);
  1636. $(".button-dbgcmd").on("click", doDebugCommand);
  1637. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1638. $(".button-dbg-clear").on("click", doDebugClear);
  1639. $(".button-settings-backup").on("click", doBackup);
  1640. $(".button-settings-restore").on("click", doRestore);
  1641. $(".button-settings-factory").on("click", doFactoryReset);
  1642. $("#uploader").on("change", onFileUpload);
  1643. $(".button-upgrade").on("click", doUpgrade);
  1644. <!-- removeIf(!thermostat)-->
  1645. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1646. <!-- endRemoveIf(!thermostat)-->
  1647. $(".button-apikey").on("click", generateAPIKey);
  1648. $(".button-upgrade-browse").on("click", function() {
  1649. $("input[name='upgrade']")[0].click();
  1650. return false;
  1651. });
  1652. $("input[name='upgrade']").change(function (){
  1653. var file = this.files[0];
  1654. $("input[name='filename']").val(file.name);
  1655. });
  1656. $(".button-add-network").on("click", function() {
  1657. $(".more", addNetwork()).toggle();
  1658. });
  1659. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1660. <!-- removeIf(!light)-->
  1661. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1662. <!-- endRemoveIf(!light)-->
  1663. $(".button-add-rpnrule").on('click', addRPNRule);
  1664. $(".button-add-rpntopic").on('click', addRPNTopic);
  1665. $(".button-del-parent").on('click', delParent);
  1666. <!-- removeIf(!rfm69)-->
  1667. $(".button-add-mapping").on('click', addMapping);
  1668. $(".button-clear-counts").on('click', doClearCounts);
  1669. $(".button-clear-messages").on('click', doClearMessages);
  1670. $(".button-clear-filters").on('click', doClearFilters);
  1671. $('#packets tbody').on('mousedown', 'td', doFilter);
  1672. packets = $('#packets').DataTable({
  1673. "paging": false
  1674. });
  1675. for (var i = 0; i < packets.columns()[0].length; i++) {
  1676. filters[i] = false;
  1677. }
  1678. <!-- endRemoveIf(!rfm69)-->
  1679. $(".gpio-select").each(function(_, elem) {
  1680. initSelectGPIO(elem)
  1681. });
  1682. $(document).on("change", "input", hasChanged);
  1683. $(document).on("change", "select", hasChanged);
  1684. $("textarea").on("dblclick", function() { this.select(); });
  1685. // don't autoconnect when opening from filesystem
  1686. if (window.location.protocol === "file:") { return; }
  1687. // Check host param in query string
  1688. var search = new URLSearchParams(window.location.search),
  1689. host = search.get("host");
  1690. if (host !== null) {
  1691. connect(host);
  1692. } else {
  1693. connectToCurrentURL();
  1694. }
  1695. });