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.

1758 lines
50 KiB

8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 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
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
7 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
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 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", "mqttGroupInv", "relayOnDisc",
  205. "dczRelayIdx", "dczMagnitude",
  206. "tspkRelay", "tspkMagnitude",
  207. "ledMode",
  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_inv" in data) {
  767. $("input[name='mqttGroupInv']", line).val(data.group_inv[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. <!-- removeIf(!sensor)-->
  779. function initMagnitudes(data) {
  780. // check if already initialized (each magnitude is inside div.pure-g)
  781. var done = $("#magnitudes > div").length;
  782. if (done > 0) { return; }
  783. var size = data.size;
  784. // add templates
  785. var template = $("#magnitudeTemplate").children();
  786. for (var i=0; i<size; ++i) {
  787. var line = $(template).clone();
  788. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  789. $("div.hint", line).html(data.description[i]);
  790. $("input", line).attr("data", i);
  791. line.appendTo("#magnitudes");
  792. }
  793. }
  794. <!-- endRemoveIf(!sensor)-->
  795. // -----------------------------------------------------------------------------
  796. // Lights
  797. // -----------------------------------------------------------------------------
  798. <!-- removeIf(!light)-->
  799. function initColor(rgb) {
  800. // check if already initialized
  801. var done = $("#colors > div").length;
  802. if (done > 0) { return; }
  803. // add template
  804. var template = $("#colorTemplate").children();
  805. var line = $(template).clone();
  806. line.appendTo("#colors");
  807. // init color wheel
  808. $("input[name='color']").wheelColorPicker({
  809. sliders: (rgb ? "wrgbp" : "whsvp")
  810. }).on("sliderup", function() {
  811. if (rgb) {
  812. var value = $(this).wheelColorPicker("getValue", "css");
  813. sendAction("color", {rgb: value});
  814. } else {
  815. var color = $(this).wheelColorPicker("getColor");
  816. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  817. sendAction("color", {hsv: value});
  818. }
  819. });
  820. }
  821. function initCCT() {
  822. // check if already initialized
  823. var done = $("#cct > div").length;
  824. if (done > 0) { return; }
  825. $("#miredsTemplate").children().clone().appendTo("#cct");
  826. $("#mireds").on("change", function() {
  827. var value = $(this).val();
  828. var parent = $(this).parents(".pure-g");
  829. $("span", parent).html(value);
  830. sendAction("mireds", {mireds: value});
  831. });
  832. }
  833. function initChannels(num) {
  834. // check if already initialized
  835. var done = $("#channels > div").length > 0;
  836. if (done) { return; }
  837. // does it have color channels?
  838. var colors = $("#colors > div").length > 0;
  839. // calculate channels to create
  840. var max = num;
  841. if (colors) {
  842. max = num % 3;
  843. if ((max > 0) & useWhite) {
  844. max--;
  845. if (useCCT) {
  846. max--;
  847. }
  848. }
  849. }
  850. var start = num - max;
  851. var onChannelSliderChange = function() {
  852. var id = $(this).attr("data");
  853. var value = $(this).val();
  854. var parent = $(this).parents(".pure-g");
  855. $("span", parent).html(value);
  856. sendAction("channel", {id: id, value: value});
  857. };
  858. // add channel templates
  859. var i = 0;
  860. var template = $("#channelTemplate").children();
  861. for (i=0; i<max; i++) {
  862. var channel_id = start + i;
  863. var line = $(template).clone();
  864. $("span.slider", line).attr("data", channel_id);
  865. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  866. $("label", line).html("Channel #" + channel_id);
  867. line.appendTo("#channels");
  868. }
  869. // Init channel dropdowns
  870. for (i=0; i<num; i++) {
  871. $("select.islight").append(
  872. $("<option></option>").attr("value",i).text("Channel #" + i));
  873. }
  874. // add brightness template
  875. var template = $("#brightnessTemplate").children();
  876. var line = $(template).clone();
  877. line.appendTo("#channels");
  878. // init bright slider
  879. $("#brightness").on("change", function() {
  880. var value = $(this).val();
  881. var parent = $(this).parents(".pure-g");
  882. $("span", parent).html(value);
  883. sendAction("brightness", {value: value});
  884. });
  885. }
  886. <!-- endRemoveIf(!light)-->
  887. // -----------------------------------------------------------------------------
  888. // RFBridge
  889. // -----------------------------------------------------------------------------
  890. <!-- removeIf(!rfbridge)-->
  891. function rfbLearn() {
  892. var parent = $(this).parents(".pure-g");
  893. var input = $("input", parent);
  894. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  895. }
  896. function rfbForget() {
  897. var parent = $(this).parents(".pure-g");
  898. var input = $("input", parent);
  899. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  900. }
  901. function rfbSend() {
  902. var parent = $(this).parents(".pure-g");
  903. var input = $("input", parent);
  904. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  905. }
  906. function addRfbNode() {
  907. var numNodes = $("#rfbNodes > legend").length;
  908. var template = $("#rfbNodeTemplate").children();
  909. var line = $(template).clone();
  910. var status = true;
  911. $("span", line).html(numNodes);
  912. $(line).find("input").each(function() {
  913. $(this).attr("data-id", numNodes);
  914. $(this).attr("data-status", status ? 1 : 0);
  915. status = !status;
  916. });
  917. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  918. $(line).find(".button-rfb-forget").on("click", rfbForget);
  919. $(line).find(".button-rfb-send").on("click", rfbSend);
  920. line.appendTo("#rfbNodes");
  921. return line;
  922. }
  923. <!-- endRemoveIf(!rfbridge)-->
  924. // -----------------------------------------------------------------------------
  925. // Processing
  926. // -----------------------------------------------------------------------------
  927. function processData(data) {
  928. // title
  929. if ("app_name" in data) {
  930. var title = data.app_name;
  931. if ("app_version" in data) {
  932. title = title + " " + data.app_version;
  933. }
  934. $("span[name=title]").html(title);
  935. if ("hostname" in data) {
  936. title = data.hostname + " - " + title;
  937. }
  938. document.title = title;
  939. }
  940. Object.keys(data).forEach(function(key) {
  941. var i;
  942. var value = data[key];
  943. // ---------------------------------------------------------------------
  944. // Web mode
  945. // ---------------------------------------------------------------------
  946. if ("webMode" === key) {
  947. password = (1 === value);
  948. $("#layout").toggle(!password);
  949. $("#password").toggle(password);
  950. }
  951. // ---------------------------------------------------------------------
  952. // Actions
  953. // ---------------------------------------------------------------------
  954. if ("action" === key) {
  955. if ("reload" === data.action) { doReload(1000); }
  956. return;
  957. }
  958. // ---------------------------------------------------------------------
  959. // RFBridge
  960. // ---------------------------------------------------------------------
  961. <!-- removeIf(!rfbridge)-->
  962. if ("rfbCount" === key) {
  963. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  964. return;
  965. }
  966. if ("rfbrawVisible" === key) {
  967. $("input[name='rfbcode']").attr("maxlength", 116);
  968. }
  969. if ("rfb" === key) {
  970. var rfb = data.rfb;
  971. var size = data.size;
  972. var start = data.start;
  973. var on = rfb["on"];
  974. var off = rfb["off"];
  975. for (var i=start; i<start+size; ++i) {
  976. $("input[name='rfbcode'][data-id='" + i + "'][data-status='1']").val(on[i]);
  977. $("input[name='rfbcode'][data-id='" + i + "'][data-status='0']").val(off[i]);
  978. }
  979. return;
  980. }
  981. <!-- endRemoveIf(!rfbridge)-->
  982. // ---------------------------------------------------------------------
  983. // RFM69
  984. // ---------------------------------------------------------------------
  985. <!-- removeIf(!rfm69)-->
  986. if (key == "packet") {
  987. var packet = data.packet;
  988. var d = new Date();
  989. packets.row.add([
  990. d.toLocaleTimeString('en-US', { hour12: false }),
  991. packet.senderID,
  992. packet.packetID,
  993. packet.targetID,
  994. packet.key,
  995. packet.value,
  996. packet.rssi,
  997. packet.duplicates,
  998. packet.missing,
  999. ]).draw(false);
  1000. return;
  1001. }
  1002. if (key == "mapping") {
  1003. for (var i in data.mapping) {
  1004. // add a new row
  1005. addMapping();
  1006. // get group
  1007. var line = $("#mapping .pure-g")[i];
  1008. // fill in the blanks
  1009. var mapping = data.mapping[i];
  1010. Object.keys(mapping).forEach(function(key) {
  1011. var id = "input[name=" + key + "]";
  1012. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1013. });
  1014. }
  1015. return;
  1016. }
  1017. <!-- endRemoveIf(!rfm69)-->
  1018. // ---------------------------------------------------------------------
  1019. // Lights
  1020. // ---------------------------------------------------------------------
  1021. <!-- removeIf(!light)-->
  1022. if ("rgb" === key) {
  1023. initColor(true);
  1024. $("input[name='color']").wheelColorPicker("setValue", value, true);
  1025. return;
  1026. }
  1027. if ("hsv" === key) {
  1028. initColor(false);
  1029. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  1030. var chunks = value.split(",");
  1031. var obj = {};
  1032. obj.h = chunks[0] / 360;
  1033. obj.s = chunks[1] / 100;
  1034. obj.v = chunks[2] / 100;
  1035. $("input[name='color']").wheelColorPicker("setColor", obj);
  1036. return;
  1037. }
  1038. if ("brightness" === key) {
  1039. $("#brightness").val(value);
  1040. $("span.brightness").html(value);
  1041. return;
  1042. }
  1043. if ("channels" === key) {
  1044. var len = value.length;
  1045. initChannels(len);
  1046. for (i in value) {
  1047. var ch = value[i];
  1048. $("input.slider[data=" + i + "]").val(ch);
  1049. $("span.slider[data=" + i + "]").html(ch);
  1050. }
  1051. return;
  1052. }
  1053. if ("mireds" === key) {
  1054. $("#mireds").val(value);
  1055. $("span.mireds").html(value);
  1056. return;
  1057. }
  1058. if ("useWhite" === key) {
  1059. useWhite = value;
  1060. }
  1061. if ("useCCT" === key) {
  1062. initCCT();
  1063. useCCT = value;
  1064. }
  1065. <!-- endRemoveIf(!light)-->
  1066. // ---------------------------------------------------------------------
  1067. // Sensors & Magnitudes
  1068. // ---------------------------------------------------------------------
  1069. <!-- removeIf(!sensor)-->
  1070. if ("magnitudes" === key) {
  1071. initMagnitudes(value);
  1072. for (var i=0; i<value.size; ++i) {
  1073. var error = value.error[i] || 0;
  1074. var text = (0 === error) ?
  1075. value.value[i] + value.units[i] :
  1076. magnitudeError(error);
  1077. var element = $("input[name='magnitude'][data='" + i + "']");
  1078. element.val(text);
  1079. }
  1080. return;
  1081. }
  1082. <!-- endRemoveIf(!sensor)-->
  1083. // ---------------------------------------------------------------------
  1084. // WiFi
  1085. // ---------------------------------------------------------------------
  1086. if ("maxNetworks" === key) {
  1087. maxNetworks = parseInt(value, 10);
  1088. return;
  1089. }
  1090. if ("wifi" === key) {
  1091. for (i in value) {
  1092. var wifi = value[i];
  1093. var nwk_line = addNetwork();
  1094. Object.keys(wifi).forEach(function(key) {
  1095. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1096. });
  1097. }
  1098. return;
  1099. }
  1100. if ("scanResult" === key) {
  1101. $("div.scan.loading").hide();
  1102. $("#scanResult").show();
  1103. }
  1104. // -----------------------------------------------------------------------------
  1105. // Home Assistant
  1106. // -----------------------------------------------------------------------------
  1107. if ("haConfig" === key) {
  1108. websock.send("{}");
  1109. $("#haConfig")
  1110. .append(new Text(value))
  1111. .height($("#haConfig")[0].scrollHeight);
  1112. return;
  1113. }
  1114. // -----------------------------------------------------------------------------
  1115. // Relays scheduler
  1116. // -----------------------------------------------------------------------------
  1117. if ("maxSchedules" === key) {
  1118. maxSchedules = parseInt(value, 10);
  1119. return;
  1120. }
  1121. if ("schedules" === key) {
  1122. for (var i=0; i<value.size; ++i) {
  1123. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1124. Object.keys(value).forEach(function(key) {
  1125. if ("size" == key) return;
  1126. var sch_value = value[key][i];
  1127. $("input[name='" + key + "']", sch_line).val(sch_value);
  1128. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1129. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1130. });
  1131. }
  1132. return;
  1133. }
  1134. // ---------------------------------------------------------------------
  1135. // Relays
  1136. // ---------------------------------------------------------------------
  1137. if ("relayStatus" === key) {
  1138. initRelays(value);
  1139. for (i in value) {
  1140. $("input[name='relay'][data='" + i + "']").prop("checked", value[i]);
  1141. }
  1142. return;
  1143. }
  1144. // Relay configuration
  1145. if ("relayConfig" === key) {
  1146. initRelayConfig(value);
  1147. return;
  1148. }
  1149. // ---------------------------------------------------------------------
  1150. // Domoticz
  1151. // ---------------------------------------------------------------------
  1152. // Domoticz - Relays
  1153. if ("dczRelays" === key) {
  1154. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1155. return;
  1156. }
  1157. // Domoticz - Magnitudes
  1158. <!-- removeIf(!sensor)-->
  1159. if ("dczMagnitudes" === key) {
  1160. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1161. return;
  1162. }
  1163. <!-- endRemoveIf(!sensor)-->
  1164. // ---------------------------------------------------------------------
  1165. // Thingspeak
  1166. // ---------------------------------------------------------------------
  1167. // Thingspeak - Relays
  1168. if ("tspkRelays" === key) {
  1169. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1170. return;
  1171. }
  1172. // Thingspeak - Magnitudes
  1173. <!-- removeIf(!sensor)-->
  1174. if ("tspkMagnitudes" === key) {
  1175. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1176. return;
  1177. }
  1178. <!-- endRemoveIf(!sensor)-->
  1179. // ---------------------------------------------------------------------
  1180. // General
  1181. // ---------------------------------------------------------------------
  1182. // Messages
  1183. if ("message" === key) {
  1184. window.alert(messages[value]);
  1185. return;
  1186. }
  1187. // Web log
  1188. if ("weblog" === key) {
  1189. websock.send("{}");
  1190. if (value.prefix) {
  1191. $("#weblog").append(new Text(value.prefix));
  1192. }
  1193. $("#weblog").append(new Text(value.message));
  1194. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1195. return;
  1196. }
  1197. // Enable options
  1198. var position = key.indexOf("Visible");
  1199. if (position > 0 && position === key.length - 7) {
  1200. var module = key.slice(0,-7);
  1201. $(".module-" + module).css("display", "inherit");
  1202. return;
  1203. }
  1204. if ("deviceip" === key) {
  1205. var a_href = $("span[name='" + key + "']").parent();
  1206. a_href.attr("href", "//" + value);
  1207. a_href.next().attr("href", "telnet://" + value);
  1208. }
  1209. if ("now" === key) {
  1210. now = value;
  1211. return;
  1212. }
  1213. if ("free_size" === key) {
  1214. free_size = parseInt(value, 10);
  1215. }
  1216. // Pre-process
  1217. if ("mqttStatus" === key) {
  1218. value = value ? "CONNECTED" : "NOT CONNECTED";
  1219. }
  1220. if ("ntpStatus" === key) {
  1221. value = value ? "SYNC'D" : "NOT SYNC'D";
  1222. }
  1223. if ("uptime" === key) {
  1224. ago = 0;
  1225. var uptime = parseInt(value, 10);
  1226. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1227. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1228. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1229. var days = uptime;
  1230. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1231. }
  1232. // ---------------------------------------------------------------------
  1233. // Matching
  1234. // ---------------------------------------------------------------------
  1235. var pre;
  1236. var post;
  1237. // Look for INPUTs
  1238. var input = $("input[name='" + key + "']");
  1239. if (input.length > 0) {
  1240. if (input.attr("type") === "checkbox") {
  1241. input.prop("checked", value);
  1242. } else if (input.attr("type") === "radio") {
  1243. input.val([value]);
  1244. } else {
  1245. pre = input.attr("pre") || "";
  1246. post = input.attr("post") || "";
  1247. input.val(pre + value + post);
  1248. }
  1249. }
  1250. // Look for SPANs
  1251. var span = $("span[name='" + key + "']");
  1252. if (span.length > 0) {
  1253. pre = span.attr("pre") || "";
  1254. post = span.attr("post") || "";
  1255. span.html(pre + value + post);
  1256. }
  1257. // Look for SELECTs
  1258. var select = $("select[name='" + key + "']");
  1259. if (select.length > 0) {
  1260. select.val(value);
  1261. }
  1262. });
  1263. // Auto generate an APIKey if none defined yet
  1264. if ($("input[name='apiKey']").val() === "") {
  1265. generateAPIKey();
  1266. }
  1267. setOriginalsFromValues();
  1268. }
  1269. function hasChanged() {
  1270. var newValue, originalValue;
  1271. if ($(this).attr("type") === "checkbox") {
  1272. newValue = $(this).prop("checked");
  1273. originalValue = ($(this).attr("original") === "true");
  1274. } else {
  1275. newValue = $(this).val();
  1276. originalValue = $(this).attr("original");
  1277. }
  1278. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1279. var action = $(this).attr("action");
  1280. if (typeof originalValue === "undefined") { return; }
  1281. if ("none" === action) { return; }
  1282. if (newValue !== originalValue) {
  1283. if (!hasChanged) {
  1284. ++numChanged;
  1285. if ("reconnect" === action) { ++numReconnect; }
  1286. if ("reboot" === action) { ++numReboot; }
  1287. if ("reload" === action) { ++numReload; }
  1288. $(this).attr("hasChanged", true);
  1289. }
  1290. } else {
  1291. if (hasChanged) {
  1292. --numChanged;
  1293. if ("reconnect" === action) { --numReconnect; }
  1294. if ("reboot" === action) { --numReboot; }
  1295. if ("reload" === action) { --numReload; }
  1296. $(this).attr("hasChanged", false);
  1297. }
  1298. }
  1299. }
  1300. // -----------------------------------------------------------------------------
  1301. // Init & connect
  1302. // -----------------------------------------------------------------------------
  1303. function initUrls(root) {
  1304. var paths = ["ws", "upgrade", "config", "auth"];
  1305. urls["root"] = root;
  1306. paths.forEach(function(path) {
  1307. urls[path] = new URL(path, root);
  1308. urls[path].protocol = root.protocol;
  1309. });
  1310. if (root.protocol == "https:") {
  1311. urls.ws.protocol = "wss:";
  1312. } else {
  1313. urls.ws.protocol = "ws:";
  1314. }
  1315. }
  1316. function connectToURL(url) {
  1317. initUrls(url);
  1318. $.ajax({
  1319. 'method': 'GET',
  1320. 'crossDomain': true,
  1321. 'url': urls.auth.href,
  1322. 'xhrFields': { 'withCredentials': true }
  1323. }).done(function(data) {
  1324. if (websock) { websock.close(); }
  1325. websock = new WebSocket(urls.ws.href);
  1326. websock.onmessage = function(evt) {
  1327. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1328. if (data) {
  1329. processData(data);
  1330. }
  1331. };
  1332. }).fail(function() {
  1333. // Nothing to do, reload page and retry
  1334. });
  1335. }
  1336. function connect(host) {
  1337. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1338. host = "http://" + host;
  1339. }
  1340. connectToURL(new URL(host));
  1341. }
  1342. function connectToCurrentURL() {
  1343. connectToURL(new URL(window.location));
  1344. }
  1345. function getParameterByName(name) {
  1346. var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  1347. return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  1348. }
  1349. $(function() {
  1350. initMessages();
  1351. loadTimeZones();
  1352. createCheckboxes();
  1353. setInterval(function() { keepTime(); }, 1000);
  1354. $(".password-reveal").on("click", toggleVisiblePassword);
  1355. $("#menuLink").on("click", toggleMenu);
  1356. $(".pure-menu-link").on("click", showPanel);
  1357. $("progress").attr({ value: 0, max: 100 });
  1358. $(".button-update").on("click", doUpdate);
  1359. $(".button-update-password").on("click", doUpdatePassword);
  1360. $(".button-generate-password").on("click", doGeneratePassword);
  1361. $(".button-reboot").on("click", doReboot);
  1362. $(".button-reconnect").on("click", doReconnect);
  1363. $(".button-wifi-scan").on("click", doScan);
  1364. $(".button-ha-config").on("click", doHAConfig);
  1365. $(".button-dbgcmd").on("click", doDebugCommand);
  1366. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1367. $(".button-dbg-clear").on("click", doDebugClear);
  1368. $(".button-settings-backup").on("click", doBackup);
  1369. $(".button-settings-restore").on("click", doRestore);
  1370. $(".button-settings-factory").on("click", doFactoryReset);
  1371. $("#uploader").on("change", onFileUpload);
  1372. $(".button-upgrade").on("click", doUpgrade);
  1373. $(".button-apikey").on("click", generateAPIKey);
  1374. $(".button-upgrade-browse").on("click", function() {
  1375. $("input[name='upgrade']")[0].click();
  1376. return false;
  1377. });
  1378. $("input[name='upgrade']").change(function (){
  1379. var file = this.files[0];
  1380. $("input[name='filename']").val(file.name);
  1381. });
  1382. $(".button-add-network").on("click", function() {
  1383. $(".more", addNetwork()).toggle();
  1384. });
  1385. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1386. <!-- removeIf(!light)-->
  1387. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1388. <!-- endRemoveIf(!light)-->
  1389. <!-- removeIf(!rfm69)-->
  1390. $(".button-add-mapping").on('click', addMapping);
  1391. $(".button-del-mapping").on('click', delMapping);
  1392. $(".button-clear-counts").on('click', doClearCounts);
  1393. $(".button-clear-messages").on('click', doClearMessages);
  1394. $(".button-clear-filters").on('click', doClearFilters);
  1395. $('#packets tbody').on('mousedown', 'td', doFilter);
  1396. packets = $('#packets').DataTable({
  1397. "paging": false
  1398. });
  1399. for (var i = 0; i < packets.columns()[0].length; i++) {
  1400. filters[i] = false;
  1401. }
  1402. <!-- endRemoveIf(!rfm69)-->
  1403. $(document).on("change", "input", hasChanged);
  1404. $(document).on("change", "select", hasChanged);
  1405. $("textarea").on("dblclick", function() { this.select(); });
  1406. // don't autoconnect when opening from filesystem
  1407. if (window.location.protocol === "file:") { return; }
  1408. // Check host param in query string
  1409. if (host = getParameterByName('host')) {
  1410. connect(host);
  1411. } else {
  1412. connectToCurrentURL();
  1413. }
  1414. });