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.

1749 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 start = data.start;
  970. var on = rfb["on"];
  971. var off = rfb["off"];
  972. for (var i=start; i<start+size; ++i) {
  973. $("input[name='rfbcode'][data-id='" + i + "'][data-status='1']").val(on[i]);
  974. $("input[name='rfbcode'][data-id='" + i + "'][data-status='0']").val(off[i]);
  975. }
  976. return;
  977. }
  978. <!-- endRemoveIf(!rfbridge)-->
  979. // ---------------------------------------------------------------------
  980. // RFM69
  981. // ---------------------------------------------------------------------
  982. <!-- removeIf(!rfm69)-->
  983. if (key == "packet") {
  984. var packet = data.packet;
  985. var d = new Date();
  986. packets.row.add([
  987. d.toLocaleTimeString('en-US', { hour12: false }),
  988. packet.senderID,
  989. packet.packetID,
  990. packet.targetID,
  991. packet.key,
  992. packet.value,
  993. packet.rssi,
  994. packet.duplicates,
  995. packet.missing,
  996. ]).draw(false);
  997. return;
  998. }
  999. if (key == "mapping") {
  1000. for (var i in data.mapping) {
  1001. // add a new row
  1002. addMapping();
  1003. // get group
  1004. var line = $("#mapping .pure-g")[i];
  1005. // fill in the blanks
  1006. var mapping = data.mapping[i];
  1007. Object.keys(mapping).forEach(function(key) {
  1008. var id = "input[name=" + key + "]";
  1009. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1010. });
  1011. }
  1012. return;
  1013. }
  1014. <!-- endRemoveIf(!rfm69)-->
  1015. // ---------------------------------------------------------------------
  1016. // Lights
  1017. // ---------------------------------------------------------------------
  1018. <!-- removeIf(!light)-->
  1019. if ("rgb" === key) {
  1020. initColor(true);
  1021. $("input[name='color']").wheelColorPicker("setValue", value, true);
  1022. return;
  1023. }
  1024. if ("hsv" === key) {
  1025. initColor(false);
  1026. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  1027. var chunks = value.split(",");
  1028. var obj = {};
  1029. obj.h = chunks[0] / 360;
  1030. obj.s = chunks[1] / 100;
  1031. obj.v = chunks[2] / 100;
  1032. $("input[name='color']").wheelColorPicker("setColor", obj);
  1033. return;
  1034. }
  1035. if ("brightness" === key) {
  1036. $("#brightness").val(value);
  1037. $("span.brightness").html(value);
  1038. return;
  1039. }
  1040. if ("channels" === key) {
  1041. var len = value.length;
  1042. initChannels(len);
  1043. for (i in value) {
  1044. var ch = value[i];
  1045. $("input.slider[data=" + i + "]").val(ch);
  1046. $("span.slider[data=" + i + "]").html(ch);
  1047. }
  1048. return;
  1049. }
  1050. if ("mireds" === key) {
  1051. $("#mireds").val(value);
  1052. $("span.mireds").html(value);
  1053. return;
  1054. }
  1055. if ("useWhite" === key) {
  1056. useWhite = value;
  1057. }
  1058. if ("useCCT" === key) {
  1059. initCCT();
  1060. useCCT = value;
  1061. }
  1062. <!-- endRemoveIf(!light)-->
  1063. // ---------------------------------------------------------------------
  1064. // Sensors & Magnitudes
  1065. // ---------------------------------------------------------------------
  1066. <!-- removeIf(!sensor)-->
  1067. if ("magnitudes" === key) {
  1068. initMagnitudes(value);
  1069. for (var i=0; i<value.size; ++i) {
  1070. var error = value.error[i] || 0;
  1071. var text = (0 === error) ?
  1072. value.value[i] + value.units[i] :
  1073. magnitudeError(error);
  1074. var element = $("input[name='magnitude'][data='" + i + "']");
  1075. element.val(text);
  1076. }
  1077. return;
  1078. }
  1079. <!-- endRemoveIf(!sensor)-->
  1080. // ---------------------------------------------------------------------
  1081. // WiFi
  1082. // ---------------------------------------------------------------------
  1083. if ("maxNetworks" === key) {
  1084. maxNetworks = parseInt(value, 10);
  1085. return;
  1086. }
  1087. if ("wifi" === key) {
  1088. for (i in value) {
  1089. var wifi = value[i];
  1090. var nwk_line = addNetwork();
  1091. Object.keys(wifi).forEach(function(key) {
  1092. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1093. });
  1094. }
  1095. return;
  1096. }
  1097. if ("scanResult" === key) {
  1098. $("div.scan.loading").hide();
  1099. $("#scanResult").show();
  1100. }
  1101. // -----------------------------------------------------------------------------
  1102. // Home Assistant
  1103. // -----------------------------------------------------------------------------
  1104. if ("haConfig" === key) {
  1105. $("#haConfig").show();
  1106. }
  1107. // -----------------------------------------------------------------------------
  1108. // Relays scheduler
  1109. // -----------------------------------------------------------------------------
  1110. if ("maxSchedules" === key) {
  1111. maxSchedules = parseInt(value, 10);
  1112. return;
  1113. }
  1114. if ("schedules" === key) {
  1115. for (var i=0; i<value.size; ++i) {
  1116. var sch_line = addSchedule({ data: {schType: value.schType[i] }});
  1117. Object.keys(value).forEach(function(key) {
  1118. if ("size" == key) return;
  1119. var sch_value = value[key][i];
  1120. $("input[name='" + key + "']", sch_line).val(sch_value);
  1121. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1122. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1123. });
  1124. }
  1125. return;
  1126. }
  1127. // ---------------------------------------------------------------------
  1128. // Relays
  1129. // ---------------------------------------------------------------------
  1130. if ("relayStatus" === key) {
  1131. initRelays(value);
  1132. for (i in value) {
  1133. $("input[name='relay'][data='" + i + "']").prop("checked", value[i]);
  1134. }
  1135. return;
  1136. }
  1137. // Relay configuration
  1138. if ("relayConfig" === key) {
  1139. initRelayConfig(value);
  1140. return;
  1141. }
  1142. // ---------------------------------------------------------------------
  1143. // Domoticz
  1144. // ---------------------------------------------------------------------
  1145. // Domoticz - Relays
  1146. if ("dczRelays" === key) {
  1147. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1148. return;
  1149. }
  1150. // Domoticz - Magnitudes
  1151. <!-- removeIf(!sensor)-->
  1152. if ("dczMagnitudes" === key) {
  1153. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1154. return;
  1155. }
  1156. <!-- endRemoveIf(!sensor)-->
  1157. // ---------------------------------------------------------------------
  1158. // Thingspeak
  1159. // ---------------------------------------------------------------------
  1160. // Thingspeak - Relays
  1161. if ("tspkRelays" === key) {
  1162. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1163. return;
  1164. }
  1165. // Thingspeak - Magnitudes
  1166. <!-- removeIf(!sensor)-->
  1167. if ("tspkMagnitudes" === key) {
  1168. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1169. return;
  1170. }
  1171. <!-- endRemoveIf(!sensor)-->
  1172. // ---------------------------------------------------------------------
  1173. // General
  1174. // ---------------------------------------------------------------------
  1175. // Messages
  1176. if ("message" === key) {
  1177. window.alert(messages[value]);
  1178. return;
  1179. }
  1180. // Web log
  1181. if ("weblog" === key) {
  1182. websock.send("{}");
  1183. if (value.prefix) {
  1184. $("#weblog").append(new Text(value.prefix));
  1185. }
  1186. $("#weblog").append(new Text(value.message));
  1187. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1188. return;
  1189. }
  1190. // Enable options
  1191. var position = key.indexOf("Visible");
  1192. if (position > 0 && position === key.length - 7) {
  1193. var module = key.slice(0,-7);
  1194. $(".module-" + module).css("display", "inherit");
  1195. return;
  1196. }
  1197. if ("deviceip" === key) {
  1198. var a_href = $("span[name='" + key + "']").parent();
  1199. a_href.attr("href", "//" + value);
  1200. a_href.next().attr("href", "telnet://" + value);
  1201. }
  1202. if ("now" === key) {
  1203. now = value;
  1204. return;
  1205. }
  1206. if ("free_size" === key) {
  1207. free_size = parseInt(value, 10);
  1208. }
  1209. // Pre-process
  1210. if ("mqttStatus" === key) {
  1211. value = value ? "CONNECTED" : "NOT CONNECTED";
  1212. }
  1213. if ("ntpStatus" === key) {
  1214. value = value ? "SYNC'D" : "NOT SYNC'D";
  1215. }
  1216. if ("uptime" === key) {
  1217. ago = 0;
  1218. var uptime = parseInt(value, 10);
  1219. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1220. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1221. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1222. var days = uptime;
  1223. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1224. }
  1225. // ---------------------------------------------------------------------
  1226. // Matching
  1227. // ---------------------------------------------------------------------
  1228. var pre;
  1229. var post;
  1230. // Look for INPUTs
  1231. var input = $("input[name='" + key + "']");
  1232. if (input.length > 0) {
  1233. if (input.attr("type") === "checkbox") {
  1234. input.prop("checked", value);
  1235. } else if (input.attr("type") === "radio") {
  1236. input.val([value]);
  1237. } else {
  1238. pre = input.attr("pre") || "";
  1239. post = input.attr("post") || "";
  1240. input.val(pre + value + post);
  1241. }
  1242. }
  1243. // Look for SPANs
  1244. var span = $("span[name='" + key + "']");
  1245. if (span.length > 0) {
  1246. pre = span.attr("pre") || "";
  1247. post = span.attr("post") || "";
  1248. span.html(pre + value + post);
  1249. }
  1250. // Look for SELECTs
  1251. var select = $("select[name='" + key + "']");
  1252. if (select.length > 0) {
  1253. select.val(value);
  1254. }
  1255. });
  1256. // Auto generate an APIKey if none defined yet
  1257. if ($("input[name='apiKey']").val() === "") {
  1258. generateAPIKey();
  1259. }
  1260. setOriginalsFromValues();
  1261. }
  1262. function hasChanged() {
  1263. var newValue, originalValue;
  1264. if ($(this).attr("type") === "checkbox") {
  1265. newValue = $(this).prop("checked");
  1266. originalValue = ($(this).attr("original") === "true");
  1267. } else {
  1268. newValue = $(this).val();
  1269. originalValue = $(this).attr("original");
  1270. }
  1271. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1272. var action = $(this).attr("action");
  1273. if (typeof originalValue === "undefined") { return; }
  1274. if ("none" === action) { return; }
  1275. if (newValue !== originalValue) {
  1276. if (!hasChanged) {
  1277. ++numChanged;
  1278. if ("reconnect" === action) { ++numReconnect; }
  1279. if ("reboot" === action) { ++numReboot; }
  1280. if ("reload" === action) { ++numReload; }
  1281. $(this).attr("hasChanged", true);
  1282. }
  1283. } else {
  1284. if (hasChanged) {
  1285. --numChanged;
  1286. if ("reconnect" === action) { --numReconnect; }
  1287. if ("reboot" === action) { --numReboot; }
  1288. if ("reload" === action) { --numReload; }
  1289. $(this).attr("hasChanged", false);
  1290. }
  1291. }
  1292. }
  1293. // -----------------------------------------------------------------------------
  1294. // Init & connect
  1295. // -----------------------------------------------------------------------------
  1296. function initUrls(root) {
  1297. var paths = ["ws", "upgrade", "config", "auth"];
  1298. urls["root"] = root;
  1299. paths.forEach(function(path) {
  1300. urls[path] = new URL(path, root);
  1301. urls[path].protocol = root.protocol;
  1302. });
  1303. if (root.protocol == "https:") {
  1304. urls.ws.protocol = "wss:";
  1305. } else {
  1306. urls.ws.protocol = "ws:";
  1307. }
  1308. }
  1309. function connectToURL(url) {
  1310. initUrls(url);
  1311. $.ajax({
  1312. 'method': 'GET',
  1313. 'crossDomain': true,
  1314. 'url': urls.auth.href,
  1315. 'xhrFields': { 'withCredentials': true }
  1316. }).done(function(data) {
  1317. if (websock) { websock.close(); }
  1318. websock = new WebSocket(urls.ws.href);
  1319. websock.onmessage = function(evt) {
  1320. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1321. if (data) {
  1322. processData(data);
  1323. }
  1324. };
  1325. }).fail(function() {
  1326. // Nothing to do, reload page and retry
  1327. });
  1328. }
  1329. function connect(host) {
  1330. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1331. host = "http://" + host;
  1332. }
  1333. connectToURL(new URL(host));
  1334. }
  1335. function connectToCurrentURL() {
  1336. connectToURL(new URL(window.location));
  1337. }
  1338. function getParameterByName(name) {
  1339. var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  1340. return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  1341. }
  1342. $(function() {
  1343. initMessages();
  1344. loadTimeZones();
  1345. createCheckboxes();
  1346. setInterval(function() { keepTime(); }, 1000);
  1347. $(".password-reveal").on("click", toggleVisiblePassword);
  1348. $("#menuLink").on("click", toggleMenu);
  1349. $(".pure-menu-link").on("click", showPanel);
  1350. $("progress").attr({ value: 0, max: 100 });
  1351. $(".button-update").on("click", doUpdate);
  1352. $(".button-update-password").on("click", doUpdatePassword);
  1353. $(".button-generate-password").on("click", doGeneratePassword);
  1354. $(".button-reboot").on("click", doReboot);
  1355. $(".button-reconnect").on("click", doReconnect);
  1356. $(".button-wifi-scan").on("click", doScan);
  1357. $(".button-ha-config").on("click", doHAConfig);
  1358. $(".button-dbgcmd").on("click", doDebugCommand);
  1359. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1360. $(".button-dbg-clear").on("click", doDebugClear);
  1361. $(".button-settings-backup").on("click", doBackup);
  1362. $(".button-settings-restore").on("click", doRestore);
  1363. $(".button-settings-factory").on("click", doFactoryReset);
  1364. $("#uploader").on("change", onFileUpload);
  1365. $(".button-upgrade").on("click", doUpgrade);
  1366. $(".button-apikey").on("click", generateAPIKey);
  1367. $(".button-upgrade-browse").on("click", function() {
  1368. $("input[name='upgrade']")[0].click();
  1369. return false;
  1370. });
  1371. $("input[name='upgrade']").change(function (){
  1372. var file = this.files[0];
  1373. $("input[name='filename']").val(file.name);
  1374. });
  1375. $(".button-add-network").on("click", function() {
  1376. $(".more", addNetwork()).toggle();
  1377. });
  1378. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1379. <!-- removeIf(!light)-->
  1380. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1381. <!-- endRemoveIf(!light)-->
  1382. <!-- removeIf(!rfm69)-->
  1383. $(".button-add-mapping").on('click', addMapping);
  1384. $(".button-del-mapping").on('click', delMapping);
  1385. $(".button-clear-counts").on('click', doClearCounts);
  1386. $(".button-clear-messages").on('click', doClearMessages);
  1387. $(".button-clear-filters").on('click', doClearFilters);
  1388. $('#packets tbody').on('mousedown', 'td', doFilter);
  1389. packets = $('#packets').DataTable({
  1390. "paging": false
  1391. });
  1392. for (var i = 0; i < packets.columns()[0].length; i++) {
  1393. filters[i] = false;
  1394. }
  1395. <!-- endRemoveIf(!rfm69)-->
  1396. $(document).on("change", "input", hasChanged);
  1397. $(document).on("change", "select", hasChanged);
  1398. // don't autoconnect when opening from filesystem
  1399. if (window.location.protocol === "file:") { return; }
  1400. // Check host param in query string
  1401. if (host = getParameterByName('host')) {
  1402. connect(host);
  1403. } else {
  1404. connectToCurrentURL();
  1405. }
  1406. });