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.

1743 lines
50 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
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
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", "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").html("");
  528. sendAction("haconfig", {});
  529. return false;
  530. }
  531. function doDebugCommand() {
  532. var el = $("input[name='dbgcmd']");
  533. var command = el.val();
  534. el.val("");
  535. sendAction("dbgcmd", {command: command});
  536. return false;
  537. }
  538. function doDebugClear() {
  539. $("#weblog").text("");
  540. return false;
  541. }
  542. <!-- removeIf(!rfm69)-->
  543. function doClearCounts() {
  544. sendAction("clear-counts", {});
  545. return false;
  546. }
  547. function doClearMessages() {
  548. packets.clear().draw(false);
  549. return false;
  550. }
  551. function doFilter(e) {
  552. var index = packets.cell(this).index();
  553. if (index == 'undefined') return;
  554. var c = index.column;
  555. var column = packets.column(c);
  556. if (filters[c]) {
  557. filters[c] = false;
  558. column.search("");
  559. $(column.header()).removeClass("filtered");
  560. } else {
  561. filters[c] = true;
  562. var data = packets.row(this).data();
  563. if (e.which == 1) {
  564. column.search('^' + data[c] + '$', true, false );
  565. } else {
  566. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  567. }
  568. $(column.header()).addClass("filtered");
  569. }
  570. column.draw();
  571. return false;
  572. }
  573. function doClearFilters() {
  574. for (var i = 0; i < packets.columns()[0].length; i++) {
  575. if (filters[i]) {
  576. filters[i] = false;
  577. var column = packets.column(i);
  578. column.search("");
  579. $(column.header()).removeClass("filtered");
  580. column.draw();
  581. }
  582. }
  583. return false;
  584. }
  585. <!-- endRemoveIf(!rfm69)-->
  586. // -----------------------------------------------------------------------------
  587. // Visualization
  588. // -----------------------------------------------------------------------------
  589. function toggleMenu() {
  590. $("#layout").toggleClass("active");
  591. $("#menu").toggleClass("active");
  592. $("#menuLink").toggleClass("active");
  593. }
  594. function showPanel() {
  595. $(".panel").hide();
  596. if ($("#layout").hasClass("active")) { toggleMenu(); }
  597. $("#" + $(this).attr("data")).show();
  598. }
  599. // -----------------------------------------------------------------------------
  600. // Relays & magnitudes mapping
  601. // -----------------------------------------------------------------------------
  602. function createRelayList(data, container, template_name) {
  603. var current = $("#" + container + " > div").length;
  604. if (current > 0) { return; }
  605. var template = $("#" + template_name + " .pure-g")[0];
  606. for (var i in data) {
  607. var line = $(template).clone();
  608. $("label", line).html("Switch #" + i);
  609. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  610. line.appendTo("#" + container);
  611. }
  612. }
  613. <!-- removeIf(!sensor)-->
  614. function createMagnitudeList(data, container, template_name) {
  615. var current = $("#" + container + " > div").length;
  616. if (current > 0) { return; }
  617. var template = $("#" + template_name + " .pure-g")[0];
  618. var size = data.size;
  619. for (var i=0; i<size; ++i) {
  620. var line = $(template).clone();
  621. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  622. $("div.hint", line).html(data.name[i]);
  623. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  624. line.appendTo("#" + container);
  625. }
  626. }
  627. <!-- endRemoveIf(!sensor)-->
  628. // -----------------------------------------------------------------------------
  629. // RFM69
  630. // -----------------------------------------------------------------------------
  631. <!-- removeIf(!rfm69)-->
  632. function addMapping() {
  633. var template = $("#nodeTemplate .pure-g")[0];
  634. var line = $(template).clone();
  635. var tabindex = $("#mapping > div").length * 3 + 50;
  636. $(line).find("input").each(function() {
  637. $(this).attr("tabindex", tabindex++);
  638. });
  639. $(line).find("button").on('click', delMapping);
  640. line.appendTo("#mapping");
  641. }
  642. function delMapping() {
  643. var parent = $(this).parent().parent();
  644. $(parent).remove();
  645. }
  646. <!-- endRemoveIf(!rfm69)-->
  647. // -----------------------------------------------------------------------------
  648. // Wifi
  649. // -----------------------------------------------------------------------------
  650. function delNetwork() {
  651. var parent = $(this).parents(".pure-g");
  652. $(parent).remove();
  653. }
  654. function moreNetwork() {
  655. var parent = $(this).parents(".pure-g");
  656. $(".more", parent).toggle();
  657. }
  658. function addNetwork() {
  659. var numNetworks = $("#networks > div").length;
  660. if (numNetworks >= maxNetworks) {
  661. alert("Max number of networks reached");
  662. return null;
  663. }
  664. var tabindex = 200 + numNetworks * 10;
  665. var template = $("#networkTemplate").children();
  666. var line = $(template).clone();
  667. $(line).find("input").each(function() {
  668. $(this).attr("tabindex", tabindex);
  669. tabindex++;
  670. });
  671. $(".password-reveal", line).on("click", toggleVisiblePassword);
  672. $(line).find(".button-del-network").on("click", delNetwork);
  673. $(line).find(".button-more-network").on("click", moreNetwork);
  674. line.appendTo("#networks");
  675. return line;
  676. }
  677. // -----------------------------------------------------------------------------
  678. // Relays scheduler
  679. // -----------------------------------------------------------------------------
  680. function delSchedule() {
  681. var parent = $(this).parents(".pure-g");
  682. $(parent).remove();
  683. }
  684. function moreSchedule() {
  685. var parent = $(this).parents(".pure-g");
  686. $("div.more", parent).toggle();
  687. }
  688. function addSchedule(event) {
  689. var numSchedules = $("#schedules > div").length;
  690. if (numSchedules >= maxSchedules) {
  691. alert("Max number of schedules reached");
  692. return null;
  693. }
  694. var tabindex = 200 + numSchedules * 10;
  695. var template = $("#scheduleTemplate").children();
  696. var line = $(template).clone();
  697. var type = (1 === event.data.schType) ? "switch" : "light";
  698. template = $("#" + type + "ActionTemplate").children();
  699. var actionLine = template.clone();
  700. $(line).find("#schActionDiv").append(actionLine);
  701. $(line).find("input").each(function() {
  702. $(this).attr("tabindex", tabindex);
  703. tabindex++;
  704. });
  705. $(line).find(".button-del-schedule").on("click", delSchedule);
  706. $(line).find(".button-more-schedule").on("click", moreSchedule);
  707. $(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
  708. .next().prop("for", "schUTC" + (numSchedules + 1));
  709. $(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
  710. .next().prop("for", "schEnabled" + (numSchedules + 1));
  711. line.appendTo("#schedules");
  712. $(line).find("input[type='checkbox']").prop("checked", false);
  713. return line;
  714. }
  715. // -----------------------------------------------------------------------------
  716. // Relays
  717. // -----------------------------------------------------------------------------
  718. function initRelays(data) {
  719. var current = $("#relays > div").length;
  720. if (current > 0) { return; }
  721. var template = $("#relayTemplate .pure-g")[0];
  722. for (var i=0; i<data.length; i++) {
  723. // Add relay fields
  724. var line = $(template).clone();
  725. $(".id", line).html(i);
  726. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  727. .prop("id", "relay" + i)
  728. .on("change", function (event) {
  729. var id = parseInt($(event.target).attr("data"), 10);
  730. var status = $(event.target).prop("checked");
  731. doToggle(id, status);
  732. });
  733. $("label.toggle", line).prop("for", "relay" + i)
  734. line.appendTo("#relays");
  735. // Populate the relay SELECTs
  736. $("select.isrelay").append(
  737. $("<option></option>").attr("value",i).text("Switch #" + i));
  738. }
  739. }
  740. function createCheckboxes() {
  741. $("input[type='checkbox']").each(function() {
  742. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  743. $(this).parent().addClass("toggleWrapper");
  744. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  745. });
  746. }
  747. function initRelayConfig(data) {
  748. var current = $("#relayConfig > legend").length; // there is a legend per relay
  749. if (current > 0) { return; }
  750. var size = data.size;
  751. var start = data.start;
  752. var template = $("#relayConfigTemplate").children();
  753. for (var i=start; i<size; ++i) {
  754. var line = $(template).clone();
  755. $("span.id", line).html(i);
  756. $("span.gpio", line).html(data.gpio[i]);
  757. $("select[name='relayBoot']", line).val(data.boot[i]);
  758. $("select[name='relayPulse']", line).val(data.pulse[i]);
  759. $("input[name='relayTime']", line).val(data.pulse_time[i]);
  760. if ("group" in data) {
  761. $("input[name='mqttGroup']", line).val(data.group[i]);
  762. }
  763. if ("group_inv" in data) {
  764. $("input[name='mqttGroupInv']", line).val(data.group_inv[i]);
  765. }
  766. if ("on_disc" in data) {
  767. $("input[name='relayOnDisc']", line).val(data.on_disc[i]);
  768. }
  769. line.appendTo("#relayConfig");
  770. }
  771. }
  772. // -----------------------------------------------------------------------------
  773. // Sensors & Magnitudes
  774. // -----------------------------------------------------------------------------
  775. <!-- removeIf(!sensor)-->
  776. function initMagnitudes(data) {
  777. // check if already initialized (each magnitude is inside div.pure-g)
  778. var done = $("#magnitudes > div").length;
  779. if (done > 0) { return; }
  780. var size = data.size;
  781. // add templates
  782. var template = $("#magnitudeTemplate").children();
  783. for (var i=0; i<size; ++i) {
  784. var line = $(template).clone();
  785. $("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
  786. $("div.hint", line).html(data.description[i]);
  787. $("input", line).attr("data", i);
  788. line.appendTo("#magnitudes");
  789. }
  790. }
  791. <!-- endRemoveIf(!sensor)-->
  792. // -----------------------------------------------------------------------------
  793. // Lights
  794. // -----------------------------------------------------------------------------
  795. <!-- removeIf(!light)-->
  796. function initColor(rgb) {
  797. // check if already initialized
  798. var done = $("#colors > div").length;
  799. if (done > 0) { return; }
  800. // add template
  801. var template = $("#colorTemplate").children();
  802. var line = $(template).clone();
  803. line.appendTo("#colors");
  804. // init color wheel
  805. $("input[name='color']").wheelColorPicker({
  806. sliders: (rgb ? "wrgbp" : "whsvp")
  807. }).on("sliderup", function() {
  808. if (rgb) {
  809. var value = $(this).wheelColorPicker("getValue", "css");
  810. sendAction("color", {rgb: value});
  811. } else {
  812. var color = $(this).wheelColorPicker("getColor");
  813. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  814. sendAction("color", {hsv: value});
  815. }
  816. });
  817. }
  818. function initCCT() {
  819. // check if already initialized
  820. var done = $("#cct > div").length;
  821. if (done > 0) { return; }
  822. $("#miredsTemplate").children().clone().appendTo("#cct");
  823. $("#mireds").on("change", function() {
  824. var value = $(this).val();
  825. var parent = $(this).parents(".pure-g");
  826. $("span", parent).html(value);
  827. sendAction("mireds", {mireds: value});
  828. });
  829. }
  830. function initChannels(num) {
  831. // check if already initialized
  832. var done = $("#channels > div").length > 0;
  833. if (done) { return; }
  834. // does it have color channels?
  835. var colors = $("#colors > div").length > 0;
  836. // calculate channels to create
  837. var max = num;
  838. if (colors) {
  839. max = num % 3;
  840. if ((max > 0) & useWhite) {
  841. max--;
  842. if (useCCT) {
  843. max--;
  844. }
  845. }
  846. }
  847. var start = num - max;
  848. var onChannelSliderChange = function() {
  849. var id = $(this).attr("data");
  850. var value = $(this).val();
  851. var parent = $(this).parents(".pure-g");
  852. $("span", parent).html(value);
  853. sendAction("channel", {id: id, value: value});
  854. };
  855. // add channel templates
  856. var i = 0;
  857. var template = $("#channelTemplate").children();
  858. for (i=0; i<max; i++) {
  859. var channel_id = start + i;
  860. var line = $(template).clone();
  861. $("span.slider", line).attr("data", channel_id);
  862. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  863. $("label", line).html("Channel #" + channel_id);
  864. line.appendTo("#channels");
  865. }
  866. // Init channel dropdowns
  867. for (i=0; i<num; i++) {
  868. $("select.islight").append(
  869. $("<option></option>").attr("value",i).text("Channel #" + i));
  870. }
  871. // add brightness template
  872. var template = $("#brightnessTemplate").children();
  873. var line = $(template).clone();
  874. line.appendTo("#channels");
  875. // init bright slider
  876. $("#brightness").on("change", function() {
  877. var value = $(this).val();
  878. var parent = $(this).parents(".pure-g");
  879. $("span", parent).html(value);
  880. sendAction("brightness", {value: value});
  881. });
  882. }
  883. <!-- endRemoveIf(!light)-->
  884. // -----------------------------------------------------------------------------
  885. // RFBridge
  886. // -----------------------------------------------------------------------------
  887. <!-- removeIf(!rfbridge)-->
  888. function rfbLearn() {
  889. var parent = $(this).parents(".pure-g");
  890. var input = $("input", parent);
  891. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  892. }
  893. function rfbForget() {
  894. var parent = $(this).parents(".pure-g");
  895. var input = $("input", parent);
  896. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  897. }
  898. function rfbSend() {
  899. var parent = $(this).parents(".pure-g");
  900. var input = $("input", parent);
  901. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  902. }
  903. function addRfbNode() {
  904. var numNodes = $("#rfbNodes > legend").length;
  905. var template = $("#rfbNodeTemplate").children();
  906. var line = $(template).clone();
  907. var status = true;
  908. $("span", line).html(numNodes);
  909. $(line).find("input").each(function() {
  910. $(this).attr("data-id", numNodes);
  911. $(this).attr("data-status", status ? 1 : 0);
  912. status = !status;
  913. });
  914. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  915. $(line).find(".button-rfb-forget").on("click", rfbForget);
  916. $(line).find(".button-rfb-send").on("click", rfbSend);
  917. line.appendTo("#rfbNodes");
  918. return line;
  919. }
  920. <!-- endRemoveIf(!rfbridge)-->
  921. // -----------------------------------------------------------------------------
  922. // Processing
  923. // -----------------------------------------------------------------------------
  924. function processData(data) {
  925. // title
  926. if ("app_name" in data) {
  927. var title = data.app_name;
  928. if ("app_version" in data) {
  929. title = title + " " + data.app_version;
  930. }
  931. $("span[name=title]").html(title);
  932. if ("hostname" in data) {
  933. title = data.hostname + " - " + title;
  934. }
  935. document.title = title;
  936. }
  937. Object.keys(data).forEach(function(key) {
  938. var i;
  939. var value = data[key];
  940. // ---------------------------------------------------------------------
  941. // Web mode
  942. // ---------------------------------------------------------------------
  943. if ("webMode" === key) {
  944. password = (1 === value);
  945. $("#layout").toggle(!password);
  946. $("#password").toggle(password);
  947. }
  948. // ---------------------------------------------------------------------
  949. // Actions
  950. // ---------------------------------------------------------------------
  951. if ("action" === key) {
  952. if ("reload" === data.action) { doReload(1000); }
  953. return;
  954. }
  955. // ---------------------------------------------------------------------
  956. // RFBridge
  957. // ---------------------------------------------------------------------
  958. <!-- removeIf(!rfbridge)-->
  959. if ("rfbCount" === key) {
  960. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  961. return;
  962. }
  963. if ("rfbrawVisible" === key) {
  964. $("input[name='rfbcode']").attr("maxlength", 116);
  965. }
  966. if ("rfb" === key) {
  967. var rfb = data.rfb;
  968. var size = data.size;
  969. var on = rfb["on"];
  970. var off = rfb["off"];
  971. for (var i=0; i<size; ++i) {
  972. $("input[name='rfbcode'][data-id='" + i + "'][data-status='1']").val(on[i]);
  973. $("input[name='rfbcode'][data-id='" + i + "'][data-status='0']").val(off[i]);
  974. }
  975. return;
  976. }
  977. <!-- endRemoveIf(!rfbridge)-->
  978. // ---------------------------------------------------------------------
  979. // RFM69
  980. // ---------------------------------------------------------------------
  981. <!-- removeIf(!rfm69)-->
  982. if (key == "packet") {
  983. var packet = data.packet;
  984. var d = new Date();
  985. packets.row.add([
  986. d.toLocaleTimeString('en-US', { hour12: false }),
  987. packet.senderID,
  988. packet.packetID,
  989. packet.targetID,
  990. packet.key,
  991. packet.value,
  992. packet.rssi,
  993. packet.duplicates,
  994. packet.missing,
  995. ]).draw(false);
  996. return;
  997. }
  998. if (key == "mapping") {
  999. for (var i in data.mapping) {
  1000. // add a new row
  1001. addMapping();
  1002. // get group
  1003. var line = $("#mapping .pure-g")[i];
  1004. // fill in the blanks
  1005. var mapping = data.mapping[i];
  1006. Object.keys(mapping).forEach(function(key) {
  1007. var id = "input[name=" + key + "]";
  1008. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1009. });
  1010. }
  1011. return;
  1012. }
  1013. <!-- endRemoveIf(!rfm69)-->
  1014. // ---------------------------------------------------------------------
  1015. // Lights
  1016. // ---------------------------------------------------------------------
  1017. <!-- removeIf(!light)-->
  1018. if ("rgb" === key) {
  1019. initColor(true);
  1020. $("input[name='color']").wheelColorPicker("setValue", value, true);
  1021. return;
  1022. }
  1023. if ("hsv" === key) {
  1024. initColor(false);
  1025. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  1026. var chunks = value.split(",");
  1027. var obj = {};
  1028. obj.h = chunks[0] / 360;
  1029. obj.s = chunks[1] / 100;
  1030. obj.v = chunks[2] / 100;
  1031. $("input[name='color']").wheelColorPicker("setColor", obj);
  1032. return;
  1033. }
  1034. if ("brightness" === key) {
  1035. $("#brightness").val(value);
  1036. $("span.brightness").html(value);
  1037. return;
  1038. }
  1039. if ("channels" === key) {
  1040. var len = value.length;
  1041. initChannels(len);
  1042. for (i in value) {
  1043. var ch = value[i];
  1044. $("input.slider[data=" + i + "]").val(ch);
  1045. $("span.slider[data=" + i + "]").html(ch);
  1046. }
  1047. return;
  1048. }
  1049. if ("mireds" === key) {
  1050. $("#mireds").val(value);
  1051. $("span.mireds").html(value);
  1052. return;
  1053. }
  1054. if ("useWhite" === key) {
  1055. useWhite = value;
  1056. }
  1057. if ("useCCT" === key) {
  1058. initCCT();
  1059. useCCT = value;
  1060. }
  1061. <!-- endRemoveIf(!light)-->
  1062. // ---------------------------------------------------------------------
  1063. // Sensors & Magnitudes
  1064. // ---------------------------------------------------------------------
  1065. <!-- removeIf(!sensor)-->
  1066. if ("magnitudes" === key) {
  1067. initMagnitudes(value);
  1068. for (var i=0; i<value.size; ++i) {
  1069. var error = value.error[i] || 0;
  1070. var text = (0 === error) ?
  1071. value.value[i] + value.units[i] :
  1072. magnitudeError(error);
  1073. var element = $("input[name='magnitude'][data='" + i + "']");
  1074. element.val(text);
  1075. }
  1076. return;
  1077. }
  1078. <!-- endRemoveIf(!sensor)-->
  1079. // ---------------------------------------------------------------------
  1080. // WiFi
  1081. // ---------------------------------------------------------------------
  1082. if ("maxNetworks" === key) {
  1083. maxNetworks = parseInt(value, 10);
  1084. return;
  1085. }
  1086. if ("wifi" === key) {
  1087. for (i in value) {
  1088. var wifi = value[i];
  1089. var nwk_line = addNetwork();
  1090. Object.keys(wifi).forEach(function(key) {
  1091. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1092. });
  1093. }
  1094. return;
  1095. }
  1096. if ("scanResult" === key) {
  1097. $("div.scan.loading").hide();
  1098. $("#scanResult").show();
  1099. }
  1100. // -----------------------------------------------------------------------------
  1101. // Home Assistant
  1102. // -----------------------------------------------------------------------------
  1103. if ("haConfig" === key) {
  1104. $("#haConfig").show();
  1105. }
  1106. // -----------------------------------------------------------------------------
  1107. // Relays scheduler
  1108. // -----------------------------------------------------------------------------
  1109. if ("maxSchedules" === key) {
  1110. maxSchedules = parseInt(value, 10);
  1111. return;
  1112. }
  1113. if ("schedules" === key) {
  1114. for (var i=0; i<value.size; ++i) {
  1115. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1116. Object.keys(value).forEach(function(key) {
  1117. if ("size" == key) return;
  1118. var sch_value = value[key][i];
  1119. $("input[name='" + key + "']", sch_line).val(sch_value);
  1120. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1121. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1122. });
  1123. }
  1124. return;
  1125. }
  1126. // ---------------------------------------------------------------------
  1127. // Relays
  1128. // ---------------------------------------------------------------------
  1129. if ("relayStatus" === key) {
  1130. initRelays(value);
  1131. for (i in value) {
  1132. $("input[name='relay'][data='" + i + "']").prop("checked", value[i]);
  1133. }
  1134. return;
  1135. }
  1136. // Relay configuration
  1137. if ("relayConfig" === key) {
  1138. initRelayConfig(value);
  1139. return;
  1140. }
  1141. // ---------------------------------------------------------------------
  1142. // Domoticz
  1143. // ---------------------------------------------------------------------
  1144. // Domoticz - Relays
  1145. if ("dczRelays" === key) {
  1146. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1147. return;
  1148. }
  1149. // Domoticz - Magnitudes
  1150. <!-- removeIf(!sensor)-->
  1151. if ("dczMagnitudes" === key) {
  1152. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1153. return;
  1154. }
  1155. <!-- endRemoveIf(!sensor)-->
  1156. // ---------------------------------------------------------------------
  1157. // Thingspeak
  1158. // ---------------------------------------------------------------------
  1159. // Thingspeak - Relays
  1160. if ("tspkRelays" === key) {
  1161. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1162. return;
  1163. }
  1164. // Thingspeak - Magnitudes
  1165. <!-- removeIf(!sensor)-->
  1166. if ("tspkMagnitudes" === key) {
  1167. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1168. return;
  1169. }
  1170. <!-- endRemoveIf(!sensor)-->
  1171. // ---------------------------------------------------------------------
  1172. // General
  1173. // ---------------------------------------------------------------------
  1174. // Messages
  1175. if ("message" === key) {
  1176. window.alert(messages[value]);
  1177. return;
  1178. }
  1179. // Web log
  1180. if ("weblog" === key) {
  1181. websock.send("{}");
  1182. $("#weblog").append(new Text(value));
  1183. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1184. return;
  1185. }
  1186. // Enable options
  1187. var position = key.indexOf("Visible");
  1188. if (position > 0 && position === key.length - 7) {
  1189. var module = key.slice(0,-7);
  1190. $(".module-" + module).css("display", "inherit");
  1191. return;
  1192. }
  1193. if ("deviceip" === key) {
  1194. var a_href = $("span[name='" + key + "']").parent();
  1195. a_href.attr("href", "//" + value);
  1196. a_href.next().attr("href", "telnet://" + value);
  1197. }
  1198. if ("now" === key) {
  1199. now = value;
  1200. return;
  1201. }
  1202. if ("free_size" === key) {
  1203. free_size = parseInt(value, 10);
  1204. }
  1205. // Pre-process
  1206. if ("mqttStatus" === key) {
  1207. value = value ? "CONNECTED" : "NOT CONNECTED";
  1208. }
  1209. if ("ntpStatus" === key) {
  1210. value = value ? "SYNC'D" : "NOT SYNC'D";
  1211. }
  1212. if ("uptime" === key) {
  1213. ago = 0;
  1214. var uptime = parseInt(value, 10);
  1215. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1216. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1217. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1218. var days = uptime;
  1219. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1220. }
  1221. // ---------------------------------------------------------------------
  1222. // Matching
  1223. // ---------------------------------------------------------------------
  1224. var pre;
  1225. var post;
  1226. // Look for INPUTs
  1227. var input = $("input[name='" + key + "']");
  1228. if (input.length > 0) {
  1229. if (input.attr("type") === "checkbox") {
  1230. input.prop("checked", value);
  1231. } else if (input.attr("type") === "radio") {
  1232. input.val([value]);
  1233. } else {
  1234. pre = input.attr("pre") || "";
  1235. post = input.attr("post") || "";
  1236. input.val(pre + value + post);
  1237. }
  1238. }
  1239. // Look for SPANs
  1240. var span = $("span[name='" + key + "']");
  1241. if (span.length > 0) {
  1242. pre = span.attr("pre") || "";
  1243. post = span.attr("post") || "";
  1244. span.html(pre + value + post);
  1245. }
  1246. // Look for SELECTs
  1247. var select = $("select[name='" + key + "']");
  1248. if (select.length > 0) {
  1249. select.val(value);
  1250. }
  1251. });
  1252. // Auto generate an APIKey if none defined yet
  1253. if ($("input[name='apiKey']").val() === "") {
  1254. generateAPIKey();
  1255. }
  1256. setOriginalsFromValues();
  1257. }
  1258. function hasChanged() {
  1259. var newValue, originalValue;
  1260. if ($(this).attr("type") === "checkbox") {
  1261. newValue = $(this).prop("checked");
  1262. originalValue = ($(this).attr("original") === "true");
  1263. } else {
  1264. newValue = $(this).val();
  1265. originalValue = $(this).attr("original");
  1266. }
  1267. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1268. var action = $(this).attr("action");
  1269. if (typeof originalValue === "undefined") { return; }
  1270. if ("none" === action) { return; }
  1271. if (newValue !== originalValue) {
  1272. if (!hasChanged) {
  1273. ++numChanged;
  1274. if ("reconnect" === action) { ++numReconnect; }
  1275. if ("reboot" === action) { ++numReboot; }
  1276. if ("reload" === action) { ++numReload; }
  1277. $(this).attr("hasChanged", true);
  1278. }
  1279. } else {
  1280. if (hasChanged) {
  1281. --numChanged;
  1282. if ("reconnect" === action) { --numReconnect; }
  1283. if ("reboot" === action) { --numReboot; }
  1284. if ("reload" === action) { --numReload; }
  1285. $(this).attr("hasChanged", false);
  1286. }
  1287. }
  1288. }
  1289. // -----------------------------------------------------------------------------
  1290. // Init & connect
  1291. // -----------------------------------------------------------------------------
  1292. function initUrls(root) {
  1293. var paths = ["ws", "upgrade", "config", "auth"];
  1294. urls["root"] = root;
  1295. paths.forEach(function(path) {
  1296. urls[path] = new URL(path, root);
  1297. urls[path].protocol = root.protocol;
  1298. });
  1299. if (root.protocol == "https:") {
  1300. urls.ws.protocol = "wss:";
  1301. } else {
  1302. urls.ws.protocol = "ws:";
  1303. }
  1304. }
  1305. function connectToURL(url) {
  1306. initUrls(url);
  1307. $.ajax({
  1308. 'method': 'GET',
  1309. 'crossDomain': true,
  1310. 'url': urls.auth.href,
  1311. 'xhrFields': { 'withCredentials': true }
  1312. }).done(function(data) {
  1313. if (websock) { websock.close(); }
  1314. websock = new WebSocket(urls.ws.href);
  1315. websock.onmessage = function(evt) {
  1316. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1317. if (data) {
  1318. processData(data);
  1319. }
  1320. };
  1321. }).fail(function() {
  1322. // Nothing to do, reload page and retry
  1323. });
  1324. }
  1325. function connect(host) {
  1326. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1327. host = "http://" + host;
  1328. }
  1329. connectToURL(new URL(host));
  1330. }
  1331. function connectToCurrentURL() {
  1332. connectToURL(new URL(window.location));
  1333. }
  1334. function getParameterByName(name) {
  1335. var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  1336. return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  1337. }
  1338. $(function() {
  1339. initMessages();
  1340. loadTimeZones();
  1341. createCheckboxes();
  1342. setInterval(function() { keepTime(); }, 1000);
  1343. $(".password-reveal").on("click", toggleVisiblePassword);
  1344. $("#menuLink").on("click", toggleMenu);
  1345. $(".pure-menu-link").on("click", showPanel);
  1346. $("progress").attr({ value: 0, max: 100 });
  1347. $(".button-update").on("click", doUpdate);
  1348. $(".button-update-password").on("click", doUpdatePassword);
  1349. $(".button-generate-password").on("click", doGeneratePassword);
  1350. $(".button-reboot").on("click", doReboot);
  1351. $(".button-reconnect").on("click", doReconnect);
  1352. $(".button-wifi-scan").on("click", doScan);
  1353. $(".button-ha-config").on("click", doHAConfig);
  1354. $(".button-dbgcmd").on("click", doDebugCommand);
  1355. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1356. $(".button-dbg-clear").on("click", doDebugClear);
  1357. $(".button-settings-backup").on("click", doBackup);
  1358. $(".button-settings-restore").on("click", doRestore);
  1359. $(".button-settings-factory").on("click", doFactoryReset);
  1360. $("#uploader").on("change", onFileUpload);
  1361. $(".button-upgrade").on("click", doUpgrade);
  1362. $(".button-apikey").on("click", generateAPIKey);
  1363. $(".button-upgrade-browse").on("click", function() {
  1364. $("input[name='upgrade']")[0].click();
  1365. return false;
  1366. });
  1367. $("input[name='upgrade']").change(function (){
  1368. var file = this.files[0];
  1369. $("input[name='filename']").val(file.name);
  1370. });
  1371. $(".button-add-network").on("click", function() {
  1372. $(".more", addNetwork()).toggle();
  1373. });
  1374. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1375. <!-- removeIf(!light)-->
  1376. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1377. <!-- endRemoveIf(!light)-->
  1378. <!-- removeIf(!rfm69)-->
  1379. $(".button-add-mapping").on('click', addMapping);
  1380. $(".button-del-mapping").on('click', delMapping);
  1381. $(".button-clear-counts").on('click', doClearCounts);
  1382. $(".button-clear-messages").on('click', doClearMessages);
  1383. $(".button-clear-filters").on('click', doClearFilters);
  1384. $('#packets tbody').on('mousedown', 'td', doFilter);
  1385. packets = $('#packets').DataTable({
  1386. "paging": false
  1387. });
  1388. for (var i = 0; i < packets.columns()[0].length; i++) {
  1389. filters[i] = false;
  1390. }
  1391. <!-- endRemoveIf(!rfm69)-->
  1392. $(document).on("change", "input", hasChanged);
  1393. $(document).on("change", "select", hasChanged);
  1394. // don't autoconnect when opening from filesystem
  1395. if (window.location.protocol === "file:") { return; }
  1396. // Check host param in query string
  1397. if (host = getParameterByName('host')) {
  1398. connect(host);
  1399. } else {
  1400. connectToCurrentURL();
  1401. }
  1402. });