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.

2107 lines
60 KiB

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