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.

1996 lines
57 KiB

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