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.

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