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.

2082 lines
59 KiB

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