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.

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