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.

1883 lines
54 KiB

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