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.

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