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.

1734 lines
50 KiB

8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var maxSchedules;
  5. var messages = [];
  6. var free_size = 0;
  7. var urls = {};
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var useWhite = false;
  13. var useCCT = false;
  14. var now = 0;
  15. var ago = 0;
  16. <!-- removeIf(!rfm69)-->
  17. var packets;
  18. var filters = [];
  19. <!-- endRemoveIf(!rfm69)-->
  20. // -----------------------------------------------------------------------------
  21. // Messages
  22. // -----------------------------------------------------------------------------
  23. function initMessages() {
  24. messages[1] = "Remote update started";
  25. messages[2] = "OTA update started";
  26. messages[3] = "Error parsing data!";
  27. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  28. messages[5] = "Changes saved. You should reboot your board now";
  29. messages[7] = "Passwords do not match!";
  30. messages[8] = "Changes saved";
  31. messages[9] = "No changes detected";
  32. messages[10] = "Session expired, please reload page...";
  33. }
  34. <!-- removeIf(!sensor)-->
  35. function sensorName(id) {
  36. var names = [
  37. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  38. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  39. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  40. "SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
  41. "TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
  42. "NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
  43. "EZOPH"
  44. ];
  45. if (1 <= id && id <= names.length) {
  46. return names[id - 1];
  47. }
  48. return null;
  49. }
  50. function magnitudeType(type) {
  51. var types = [
  52. "Temperature", "Humidity", "Pressure",
  53. "Current", "Voltage", "Active Power", "Apparent Power",
  54. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  55. "Analog", "Digital", "Event",
  56. "PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
  57. "Local Dose Rate", "Local Dose Rate",
  58. "Count",
  59. "NO2", "CO", "Resistance", "pH"
  60. ];
  61. if (1 <= type && type <= types.length) {
  62. return types[type - 1];
  63. }
  64. return null;
  65. }
  66. function magnitudeError(error) {
  67. var errors = [
  68. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  69. "Data Error", "I2C Error", "GPIO Error", "Calibration error"
  70. ];
  71. if (0 <= error && error < errors.length) {
  72. return errors[error];
  73. }
  74. return "Error " + error;
  75. }
  76. <!-- endRemoveIf(!sensor)-->
  77. // -----------------------------------------------------------------------------
  78. // Utils
  79. // -----------------------------------------------------------------------------
  80. $.fn.enterKey = function (fnc) {
  81. return this.each(function () {
  82. $(this).keypress(function (ev) {
  83. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  84. if (13 === keycode) {
  85. return fnc.call(this, ev);
  86. }
  87. });
  88. });
  89. };
  90. function keepTime() {
  91. $("span[name='ago']").html(ago);
  92. ago++;
  93. if (0 === now) { return; }
  94. var date = new Date(now * 1000);
  95. var text = date.toISOString().substring(0, 19).replace("T", " ");
  96. $("input[name='now']").val(text);
  97. $("span[name='now']").html(text);
  98. now++;
  99. }
  100. function zeroPad(number, positions) {
  101. var zeros = "";
  102. for (var i = 0; i < positions; i++) {
  103. zeros += "0";
  104. }
  105. return (zeros + number).slice(-positions);
  106. }
  107. function loadTimeZones() {
  108. var time_zones = [
  109. -720, -660, -600, -570, -540,
  110. -480, -420, -360, -300, -240,
  111. -210, -180, -120, -60, 0,
  112. 60, 120, 180, 210, 240,
  113. 270, 300, 330, 345, 360,
  114. 390, 420, 480, 510, 525,
  115. 540, 570, 600, 630, 660,
  116. 720, 765, 780, 840
  117. ];
  118. for (var i in time_zones) {
  119. var value = time_zones[i];
  120. var offset = value >= 0 ? value : -value;
  121. var text = "GMT" + (value >= 0 ? "+" : "-") +
  122. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  123. zeroPad(offset % 60, 2);
  124. $("select[name='ntpOffset']").append(
  125. $("<option></option>").
  126. attr("value",value).
  127. text(text));
  128. }
  129. }
  130. function validatePassword(password) {
  131. // http://www.the-art-of-web.com/javascript/validate-password/
  132. // at least one lowercase and one uppercase letter or number
  133. // at least eight characters (letters, numbers or special characters)
  134. // MUST be 8..63 printable ASCII characters. See:
  135. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  136. // https://github.com/xoseperez/espurna/issues/1151
  137. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  138. return (
  139. (password !== undefined)
  140. && (typeof password === "string")
  141. && (password.length > 0)
  142. && re_password.test(password)
  143. );
  144. }
  145. function validateFormPasswords(form) {
  146. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  147. var adminPass1 = passwords.first().val(),
  148. adminPass2 = passwords.last().val();
  149. var formValidity = passwords.first()[0].checkValidity();
  150. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  151. return true;
  152. }
  153. var validPass1 = validatePassword(adminPass1),
  154. validPass2 = validatePassword(adminPass2);
  155. if (formValidity && validPass1 && validPass2) {
  156. return true;
  157. }
  158. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  159. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  160. }
  161. if (adminPass1 !== adminPass2) {
  162. alert("Passwords are different!");
  163. }
  164. return false;
  165. }
  166. function validateFormHostname(form) {
  167. // RFCs mandate that a hostname's labels may contain only
  168. // the ASCII letters 'a' through 'z' (case-insensitive),
  169. // the digits '0' through '9', and the hyphen.
  170. // Hostname labels cannot begin or end with a hyphen.
  171. // No other symbols, punctuation characters, or blank spaces are permitted.
  172. // Negative lookbehind does not work in Javascript
  173. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
  174. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
  175. var hostname = $("input[name='hostname']", form);
  176. if ("true" !== hostname.attr("hasChanged")) {
  177. return true;
  178. }
  179. if (re_hostname.test(hostname.val())) {
  180. return true;
  181. }
  182. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  183. return false;
  184. }
  185. function validateForm(form) {
  186. return validateFormPasswords(form) && validateFormHostname(form);
  187. }
  188. function getValue(element) {
  189. if ($(element).attr("type") === "checkbox") {
  190. return $(element).prop("checked") ? 1 : 0;
  191. } else if ($(element).attr("type") === "radio") {
  192. if (!$(element).prop("checked")) {
  193. return null;
  194. }
  195. }
  196. return $(element).val();
  197. }
  198. function addValue(data, name, value) {
  199. // These fields will always be a list of values
  200. var is_group = [
  201. "ssid", "pass", "gw", "mask", "ip", "dns",
  202. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  203. "relayBoot", "relayPulse", "relayTime",
  204. "mqttGroup", "mqttGroupInv", "relayOnDisc",
  205. "dczRelayIdx", "dczMagnitude",
  206. "tspkRelay", "tspkMagnitude",
  207. "ledMode",
  208. "adminPass",
  209. "node", "key", "topic"
  210. ];
  211. // join both adminPass 1 and 2
  212. if (name.startsWith("adminPass")) {
  213. name = "adminPass";
  214. }
  215. if (name in data) {
  216. if (!Array.isArray(data[name])) {
  217. data[name] = [data[name]];
  218. }
  219. data[name].push(value);
  220. } else if (is_group.indexOf(name) >= 0) {
  221. data[name] = [value];
  222. } else {
  223. data[name] = value;
  224. }
  225. }
  226. function getData(form) {
  227. var data = {};
  228. // Populate data
  229. $("input,select", form).each(function() {
  230. var name = $(this).attr("name");
  231. var value = getValue(this);
  232. if (null !== value) {
  233. addValue(data, name, value);
  234. }
  235. });
  236. // Post process
  237. addValue(data, "schSwitch", 0xFF);
  238. delete data["filename"];
  239. delete data["rfbcode"];
  240. return data;
  241. }
  242. function randomString(length, args) {
  243. if (typeof args === "undefined") {
  244. args = {
  245. lowercase: true,
  246. uppercase: true,
  247. numbers: true,
  248. special: true
  249. }
  250. }
  251. var mask = "";
  252. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  253. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  254. if (args.numbers || args.hex) { mask += "0123456789"; }
  255. if (args.hex) { mask += "ABCDEF"; }
  256. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  257. var source = new Uint32Array(length);
  258. var result = new Array(length);
  259. window.crypto.getRandomValues(source).forEach(function(value, i) {
  260. result[i] = mask[value % mask.length];
  261. });
  262. return result.join("");
  263. }
  264. function generateAPIKey() {
  265. var apikey = randomString(16, {hex: true});
  266. $("input[name='apiKey']").val(apikey);
  267. return false;
  268. }
  269. function generatePassword() {
  270. var password = "";
  271. do {
  272. password = randomString(10);
  273. } while (!validatePassword(password));
  274. return password;
  275. }
  276. function toggleVisiblePassword() {
  277. var elem = this.previousElementSibling;
  278. if (elem.type === "password") {
  279. elem.type = "text";
  280. } else {
  281. elem.type = "password";
  282. }
  283. return false;
  284. }
  285. function doGeneratePassword() {
  286. $("input", $("#formPassword"))
  287. .val(generatePassword())
  288. .each(function() {
  289. this.type = "text";
  290. });
  291. return false;
  292. }
  293. function getJson(str) {
  294. try {
  295. return JSON.parse(str);
  296. } catch (e) {
  297. return false;
  298. }
  299. }
  300. // -----------------------------------------------------------------------------
  301. // Actions
  302. // -----------------------------------------------------------------------------
  303. function sendAction(action, data) {
  304. websock.send(JSON.stringify({action: action, data: data}));
  305. }
  306. function sendConfig(data) {
  307. websock.send(JSON.stringify({config: data}));
  308. }
  309. function setOriginalsFromValues(force) {
  310. var force = (true === force);
  311. $("input,select").each(function() {
  312. var initial = (undefined === $(this).attr("original"));
  313. if (force || initial) {
  314. $(this).attr("original", $(this).val());
  315. }
  316. });
  317. }
  318. function resetOriginals() {
  319. setOriginalsFromValues(true);
  320. numReboot = numReconnect = numReload = 0;
  321. }
  322. function doReload(milliseconds) {
  323. setTimeout(function() {
  324. window.location.reload();
  325. }, parseInt(milliseconds, 10));
  326. }
  327. /**
  328. * Check a file object to see if it is a valid firmware image
  329. * The file first byte should be 0xE9
  330. * @param {file} file File object
  331. * @param {Function} callback Function to call back with the result
  332. */
  333. function checkFirmware(file, callback) {
  334. var reader = new FileReader();
  335. reader.onloadend = function(evt) {
  336. if (FileReader.DONE === evt.target.readyState) {
  337. if (0xE9 !== evt.target.result.charCodeAt(0)) callback(false);
  338. if (0x03 !== evt.target.result.charCodeAt(2)) {
  339. var response = window.confirm("Binary image is not using DOUT flash mode. This might cause resets in some devices. Press OK to continue.");
  340. callback(response);
  341. } else {
  342. callback(true);
  343. }
  344. }
  345. };
  346. var blob = file.slice(0, 3);
  347. reader.readAsBinaryString(blob);
  348. }
  349. function doUpgrade() {
  350. var file = $("input[name='upgrade']")[0].files[0];
  351. if (typeof file === "undefined") {
  352. alert("First you have to select a file from your computer.");
  353. return false;
  354. }
  355. if (file.size > free_size) {
  356. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  357. return false;
  358. }
  359. checkFirmware(file, function(ok) {
  360. if (!ok) {
  361. alert("The file does not seem to be a valid firmware image.");
  362. return;
  363. }
  364. var data = new FormData();
  365. data.append("upgrade", file, file.name);
  366. $.ajax({
  367. // Your server script to process the upload
  368. url: urls.upgrade.href,
  369. type: "POST",
  370. // Form data
  371. data: data,
  372. // Tell jQuery not to process data or worry about content-type
  373. // You *must* include these options!
  374. cache: false,
  375. contentType: false,
  376. processData: false,
  377. success: function(data, text) {
  378. $("#upgrade-progress").hide();
  379. if ("OK" === data) {
  380. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  381. doReload(5000);
  382. } else {
  383. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  384. }
  385. },
  386. // Custom XMLHttpRequest
  387. xhr: function() {
  388. $("#upgrade-progress").show();
  389. var myXhr = $.ajaxSettings.xhr();
  390. if (myXhr.upload) {
  391. // For handling the progress of the upload
  392. myXhr.upload.addEventListener("progress", function(e) {
  393. if (e.lengthComputable) {
  394. $("progress").attr({ value: e.loaded, max: e.total });
  395. }
  396. } , false);
  397. }
  398. return myXhr;
  399. }
  400. });
  401. });
  402. return false;
  403. }
  404. function doUpdatePassword() {
  405. var form = $("#formPassword");
  406. if (validateFormPasswords(form)) {
  407. sendConfig(getData(form));
  408. }
  409. return false;
  410. }
  411. function checkChanges() {
  412. if (numChanged > 0) {
  413. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  414. if (response) {
  415. doUpdate();
  416. }
  417. }
  418. }
  419. function doAction(question, action) {
  420. checkChanges();
  421. if (question) {
  422. var response = window.confirm(question);
  423. if (false === response) {
  424. return false;
  425. }
  426. }
  427. sendAction(action, {});
  428. doReload(5000);
  429. return false;
  430. }
  431. function doReboot(ask) {
  432. var question = (typeof ask === "undefined" || false === ask) ?
  433. null :
  434. "Are you sure you want to reboot the device?";
  435. return doAction(question, "reboot");
  436. }
  437. function doReconnect(ask) {
  438. var question = (typeof ask === "undefined" || false === ask) ?
  439. null :
  440. "Are you sure you want to disconnect from the current WIFI network?";
  441. return doAction(question, "reconnect");
  442. }
  443. function doUpdate() {
  444. var forms = $(".form-settings");
  445. if (validateForm(forms)) {
  446. // Get data
  447. sendConfig(getData(forms));
  448. // Empty special fields
  449. $(".pwrExpected").val(0);
  450. $("input[name='snsResetCalibration']").prop("checked", false);
  451. $("input[name='pwrResetCalibration']").prop("checked", false);
  452. $("input[name='pwrResetE']").prop("checked", false);
  453. // Change handling
  454. numChanged = 0;
  455. setTimeout(function() {
  456. var response;
  457. if (numReboot > 0) {
  458. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  459. if (response) { doReboot(false); }
  460. } else if (numReconnect > 0) {
  461. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  462. if (response) { doReconnect(false); }
  463. } else if (numReload > 0) {
  464. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  465. if (response) { doReload(0); }
  466. }
  467. resetOriginals();
  468. }, 1000);
  469. }
  470. return false;
  471. }
  472. function doBackup() {
  473. document.getElementById("downloader").src = urls.config.href;
  474. return false;
  475. }
  476. function onFileUpload(event) {
  477. var inputFiles = this.files;
  478. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  479. return false;
  480. }
  481. var inputFile = inputFiles[0];
  482. this.value = "";
  483. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  484. if (!response) {
  485. return false;
  486. }
  487. var reader = new FileReader();
  488. reader.onload = function(e) {
  489. var data = getJson(e.target.result);
  490. if (data) {
  491. sendAction("restore", data);
  492. } else {
  493. window.alert(messages[4]);
  494. }
  495. };
  496. reader.readAsText(inputFile);
  497. return false;
  498. }
  499. function doRestore() {
  500. if (typeof window.FileReader !== "function") {
  501. alert("The file API isn't supported on this browser yet.");
  502. } else {
  503. $("#uploader").click();
  504. }
  505. return false;
  506. }
  507. function doFactoryReset() {
  508. var response = window.confirm("Are you sure you want to restore to factory settings?");
  509. if (response === false) {
  510. return false;
  511. }
  512. sendAction("factory_reset", {});
  513. doReload(5000);
  514. return false;
  515. }
  516. function doToggle(id, value) {
  517. sendAction("relay", {id: id, status: value ? 1 : 0 });
  518. return false;
  519. }
  520. function doScan() {
  521. $("#scanResult").html("");
  522. $("div.scan.loading").show();
  523. sendAction("scan", {});
  524. return false;
  525. }
  526. function doHAConfig() {
  527. $("#haConfig")
  528. .text("")
  529. .height(0)
  530. .show();
  531. sendAction("haconfig", {});
  532. return false;
  533. }
  534. function doDebugCommand() {
  535. var el = $("input[name='dbgcmd']");
  536. var command = el.val();
  537. el.val("");
  538. sendAction("dbgcmd", {command: command});
  539. return false;
  540. }
  541. function doDebugClear() {
  542. $("#weblog").text("");
  543. return false;
  544. }
  545. <!-- removeIf(!rfm69)-->
  546. function doClearCounts() {
  547. sendAction("clear-counts", {});
  548. return false;
  549. }
  550. function doClearMessages() {
  551. packets.clear().draw(false);
  552. return false;
  553. }
  554. function doFilter(e) {
  555. var index = packets.cell(this).index();
  556. if (index == 'undefined') return;
  557. var c = index.column;
  558. var column = packets.column(c);
  559. if (filters[c]) {
  560. filters[c] = false;
  561. column.search("");
  562. $(column.header()).removeClass("filtered");
  563. } else {
  564. filters[c] = true;
  565. var data = packets.row(this).data();
  566. if (e.which == 1) {
  567. column.search('^' + data[c] + '$', true, false );
  568. } else {
  569. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  570. }
  571. $(column.header()).addClass("filtered");
  572. }
  573. column.draw();
  574. return false;
  575. }
  576. function doClearFilters() {
  577. for (var i = 0; i < packets.columns()[0].length; i++) {
  578. if (filters[i]) {
  579. filters[i] = false;
  580. var column = packets.column(i);
  581. column.search("");
  582. $(column.header()).removeClass("filtered");
  583. column.draw();
  584. }
  585. }
  586. return false;
  587. }
  588. <!-- endRemoveIf(!rfm69)-->
  589. // -----------------------------------------------------------------------------
  590. // Visualization
  591. // -----------------------------------------------------------------------------
  592. function toggleMenu() {
  593. $("#layout").toggleClass("active");
  594. $("#menu").toggleClass("active");
  595. $("#menuLink").toggleClass("active");
  596. }
  597. function showPanel() {
  598. $(".panel").hide();
  599. if ($("#layout").hasClass("active")) { toggleMenu(); }
  600. $("#" + $(this).attr("data")).show();
  601. }
  602. // -----------------------------------------------------------------------------
  603. // Relays & magnitudes mapping
  604. // -----------------------------------------------------------------------------
  605. function createRelayList(data, container, template_name) {
  606. var current = $("#" + container + " > div").length;
  607. if (current > 0) { return; }
  608. var template = $("#" + template_name + " .pure-g")[0];
  609. for (var i in data) {
  610. var line = $(template).clone();
  611. $("label", line).html("Switch #" + i);
  612. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  613. line.appendTo("#" + container);
  614. }
  615. }
  616. <!-- removeIf(!sensor)-->
  617. function createMagnitudeList(data, container, template_name) {
  618. var current = $("#" + container + " > div").length;
  619. if (current > 0) { return; }
  620. var template = $("#" + template_name + " .pure-g")[0];
  621. for (var i in data) {
  622. var magnitude = data[i];
  623. var line = $(template).clone();
  624. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  625. $("div.hint", line).html(magnitude.name);
  626. $("input", line).attr("tabindex", 40 + i).val(magnitude.idx);
  627. line.appendTo("#" + container);
  628. }
  629. }
  630. <!-- endRemoveIf(!sensor)-->
  631. // -----------------------------------------------------------------------------
  632. // RFM69
  633. // -----------------------------------------------------------------------------
  634. <!-- removeIf(!rfm69)-->
  635. function addMapping() {
  636. var template = $("#nodeTemplate .pure-g")[0];
  637. var line = $(template).clone();
  638. var tabindex = $("#mapping > div").length * 3 + 50;
  639. $(line).find("input").each(function() {
  640. $(this).attr("tabindex", tabindex++);
  641. });
  642. $(line).find("button").on('click', delMapping);
  643. line.appendTo("#mapping");
  644. }
  645. function delMapping() {
  646. var parent = $(this).parent().parent();
  647. $(parent).remove();
  648. }
  649. <!-- endRemoveIf(!rfm69)-->
  650. // -----------------------------------------------------------------------------
  651. // Wifi
  652. // -----------------------------------------------------------------------------
  653. function delNetwork() {
  654. var parent = $(this).parents(".pure-g");
  655. $(parent).remove();
  656. }
  657. function moreNetwork() {
  658. var parent = $(this).parents(".pure-g");
  659. $(".more", parent).toggle();
  660. }
  661. function addNetwork() {
  662. var numNetworks = $("#networks > div").length;
  663. if (numNetworks >= maxNetworks) {
  664. alert("Max number of networks reached");
  665. return null;
  666. }
  667. var tabindex = 200 + numNetworks * 10;
  668. var template = $("#networkTemplate").children();
  669. var line = $(template).clone();
  670. $(line).find("input").each(function() {
  671. $(this).attr("tabindex", tabindex);
  672. tabindex++;
  673. });
  674. $(".password-reveal", line).on("click", toggleVisiblePassword);
  675. $(line).find(".button-del-network").on("click", delNetwork);
  676. $(line).find(".button-more-network").on("click", moreNetwork);
  677. line.appendTo("#networks");
  678. return line;
  679. }
  680. // -----------------------------------------------------------------------------
  681. // Relays scheduler
  682. // -----------------------------------------------------------------------------
  683. function delSchedule() {
  684. var parent = $(this).parents(".pure-g");
  685. $(parent).remove();
  686. }
  687. function moreSchedule() {
  688. var parent = $(this).parents(".pure-g");
  689. $("div.more", parent).toggle();
  690. }
  691. function addSchedule(event) {
  692. var numSchedules = $("#schedules > div").length;
  693. if (numSchedules >= maxSchedules) {
  694. alert("Max number of schedules reached");
  695. return null;
  696. }
  697. var tabindex = 200 + numSchedules * 10;
  698. var template = $("#scheduleTemplate").children();
  699. var line = $(template).clone();
  700. var type = (1 === event.data.schType) ? "switch" : "light";
  701. template = $("#" + type + "ActionTemplate").children();
  702. var actionLine = template.clone();
  703. $(line).find("#schActionDiv").append(actionLine);
  704. $(line).find("input").each(function() {
  705. $(this).attr("tabindex", tabindex);
  706. tabindex++;
  707. });
  708. $(line).find(".button-del-schedule").on("click", delSchedule);
  709. $(line).find(".button-more-schedule").on("click", moreSchedule);
  710. $(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
  711. .next().prop("for", "schUTC" + (numSchedules + 1));
  712. $(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
  713. .next().prop("for", "schEnabled" + (numSchedules + 1));
  714. line.appendTo("#schedules");
  715. $(line).find("input[type='checkbox']").prop("checked", false);
  716. return line;
  717. }
  718. // -----------------------------------------------------------------------------
  719. // Relays
  720. // -----------------------------------------------------------------------------
  721. function initRelays(data) {
  722. var current = $("#relays > div").length;
  723. if (current > 0) { return; }
  724. var template = $("#relayTemplate .pure-g")[0];
  725. for (var i=0; i<data.length; i++) {
  726. // Add relay fields
  727. var line = $(template).clone();
  728. $(".id", line).html(i);
  729. $(":checkbox", line).prop('checked', data[i]).attr("data", i)
  730. .prop("id", "relay" + i)
  731. .on("change", function (event) {
  732. var id = parseInt($(event.target).attr("data"), 10);
  733. var status = $(event.target).prop("checked");
  734. doToggle(id, status);
  735. });
  736. $("label.toggle", line).prop("for", "relay" + i)
  737. line.appendTo("#relays");
  738. // Populate the relay SELECTs
  739. $("select.isrelay").append(
  740. $("<option></option>").attr("value",i).text("Switch #" + i));
  741. }
  742. }
  743. function createCheckboxes() {
  744. $("input[type='checkbox']").each(function() {
  745. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  746. $(this).parent().addClass("toggleWrapper");
  747. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  748. });
  749. }
  750. function initRelayConfig(data) {
  751. var current = $("#relayConfig > div").length / 6; // there are 6 divs per each relay
  752. var template = $("#relayConfigTemplate").children();
  753. for (var i in data) {
  754. var relay = data[i];
  755. if (current > relay.id) continue;
  756. var line = $(template).clone();
  757. $("span.gpio", line).html(relay.gpio);
  758. $("span.id", line).html(relay.id);
  759. $("select[name='relayBoot']", line).val(relay.boot);
  760. $("select[name='relayPulse']", line).val(relay.pulse);
  761. $("input[name='relayTime']", line).val(relay.pulse_ms);
  762. $("input[name='mqttGroup']", line).val(relay.group);
  763. $("select[name='mqttGroupInv']", line).val(relay.group_inv);
  764. $("select[name='relayOnDisc']", line).val(relay.on_disc);
  765. line.appendTo("#relayConfig");
  766. }
  767. }
  768. // -----------------------------------------------------------------------------
  769. // Sensors & Magnitudes
  770. // -----------------------------------------------------------------------------
  771. <!-- removeIf(!sensor)-->
  772. function initMagnitudes(data) {
  773. // check if already initialized
  774. var done = $("#magnitudes > div").length;
  775. if (done > 0) { return; }
  776. // add templates
  777. var template = $("#magnitudeTemplate").children();
  778. for (var i in data) {
  779. var magnitude = data[i];
  780. var line = $(template).clone();
  781. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  782. $("div.hint", line).html(magnitude.description);
  783. $("input", line).attr("data", i);
  784. line.appendTo("#magnitudes");
  785. }
  786. }
  787. <!-- endRemoveIf(!sensor)-->
  788. // -----------------------------------------------------------------------------
  789. // Lights
  790. // -----------------------------------------------------------------------------
  791. <!-- removeIf(!light)-->
  792. function initColor(rgb) {
  793. // check if already initialized
  794. var done = $("#colors > div").length;
  795. if (done > 0) { return; }
  796. // add template
  797. var template = $("#colorTemplate").children();
  798. var line = $(template).clone();
  799. line.appendTo("#colors");
  800. // init color wheel
  801. $("input[name='color']").wheelColorPicker({
  802. sliders: (rgb ? "wrgbp" : "whsvp")
  803. }).on("sliderup", function() {
  804. if (rgb) {
  805. var value = $(this).wheelColorPicker("getValue", "css");
  806. sendAction("color", {rgb: value});
  807. } else {
  808. var color = $(this).wheelColorPicker("getColor");
  809. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  810. sendAction("color", {hsv: value});
  811. }
  812. });
  813. }
  814. function initCCT() {
  815. // check if already initialized
  816. var done = $("#cct > div").length;
  817. if (done > 0) { return; }
  818. $("#miredsTemplate").children().clone().appendTo("#cct");
  819. $("#mireds").on("change", function() {
  820. var value = $(this).val();
  821. var parent = $(this).parents(".pure-g");
  822. $("span", parent).html(value);
  823. sendAction("mireds", {mireds: value});
  824. });
  825. }
  826. function initChannels(num) {
  827. // check if already initialized
  828. var done = $("#channels > div").length > 0;
  829. if (done) { return; }
  830. // does it have color channels?
  831. var colors = $("#colors > div").length > 0;
  832. // calculate channels to create
  833. var max = num;
  834. if (colors) {
  835. max = num % 3;
  836. if ((max > 0) & useWhite) {
  837. max--;
  838. if (useCCT) {
  839. max--;
  840. }
  841. }
  842. }
  843. var start = num - max;
  844. var onChannelSliderChange = function() {
  845. var id = $(this).attr("data");
  846. var value = $(this).val();
  847. var parent = $(this).parents(".pure-g");
  848. $("span", parent).html(value);
  849. sendAction("channel", {id: id, value: value});
  850. };
  851. // add channel templates
  852. var i = 0;
  853. var template = $("#channelTemplate").children();
  854. for (i=0; i<max; i++) {
  855. var channel_id = start + i;
  856. var line = $(template).clone();
  857. $("span.slider", line).attr("data", channel_id);
  858. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  859. $("label", line).html("Channel #" + channel_id);
  860. line.appendTo("#channels");
  861. }
  862. // Init channel dropdowns
  863. for (i=0; i<num; i++) {
  864. $("select.islight").append(
  865. $("<option></option>").attr("value",i).text("Channel #" + i));
  866. }
  867. // add brightness template
  868. var template = $("#brightnessTemplate").children();
  869. var line = $(template).clone();
  870. line.appendTo("#channels");
  871. // init bright slider
  872. $("#brightness").on("change", function() {
  873. var value = $(this).val();
  874. var parent = $(this).parents(".pure-g");
  875. $("span", parent).html(value);
  876. sendAction("brightness", {value: value});
  877. });
  878. }
  879. <!-- endRemoveIf(!light)-->
  880. // -----------------------------------------------------------------------------
  881. // RFBridge
  882. // -----------------------------------------------------------------------------
  883. <!-- removeIf(!rfbridge)-->
  884. function rfbLearn() {
  885. var parent = $(this).parents(".pure-g");
  886. var input = $("input", parent);
  887. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  888. }
  889. function rfbForget() {
  890. var parent = $(this).parents(".pure-g");
  891. var input = $("input", parent);
  892. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  893. }
  894. function rfbSend() {
  895. var parent = $(this).parents(".pure-g");
  896. var input = $("input", parent);
  897. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  898. }
  899. function addRfbNode() {
  900. var numNodes = $("#rfbNodes > legend").length;
  901. var template = $("#rfbNodeTemplate").children();
  902. var line = $(template).clone();
  903. var status = true;
  904. $("span", line).html(numNodes);
  905. $(line).find("input").each(function() {
  906. $(this).attr("data-id", numNodes);
  907. $(this).attr("data-status", status ? 1 : 0);
  908. status = !status;
  909. });
  910. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  911. $(line).find(".button-rfb-forget").on("click", rfbForget);
  912. $(line).find(".button-rfb-send").on("click", rfbSend);
  913. line.appendTo("#rfbNodes");
  914. return line;
  915. }
  916. <!-- endRemoveIf(!rfbridge)-->
  917. // -----------------------------------------------------------------------------
  918. // Processing
  919. // -----------------------------------------------------------------------------
  920. function processData(data) {
  921. // title
  922. if ("app_name" in data) {
  923. var title = data.app_name;
  924. if ("app_version" in data) {
  925. title = title + " " + data.app_version;
  926. }
  927. $("span[name=title]").html(title);
  928. if ("hostname" in data) {
  929. title = data.hostname + " - " + title;
  930. }
  931. document.title = title;
  932. }
  933. Object.keys(data).forEach(function(key) {
  934. var i;
  935. var value = data[key];
  936. // ---------------------------------------------------------------------
  937. // Web mode
  938. // ---------------------------------------------------------------------
  939. if ("webMode" === key) {
  940. password = (1 === value);
  941. $("#layout").toggle(!password);
  942. $("#password").toggle(password);
  943. }
  944. // ---------------------------------------------------------------------
  945. // Actions
  946. // ---------------------------------------------------------------------
  947. if ("action" === key) {
  948. if ("reload" === data.action) { doReload(1000); }
  949. return;
  950. }
  951. // ---------------------------------------------------------------------
  952. // RFBridge
  953. // ---------------------------------------------------------------------
  954. <!-- removeIf(!rfbridge)-->
  955. if ("rfbCount" === key) {
  956. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  957. return;
  958. }
  959. if ("rfbrawVisible" === key) {
  960. $("input[name='rfbcode']").attr("maxlength", 116);
  961. }
  962. if ("rfb" === key) {
  963. var nodes = data.rfb;
  964. for (i in nodes) {
  965. var node = nodes[i];
  966. $("input[name='rfbcode'][data-id='" + node.id + "'][data-status='" + node.status + "']").val(node.data);
  967. }
  968. return;
  969. }
  970. <!-- endRemoveIf(!rfbridge)-->
  971. // ---------------------------------------------------------------------
  972. // RFM69
  973. // ---------------------------------------------------------------------
  974. <!-- removeIf(!rfm69)-->
  975. if (key == "packet") {
  976. var packet = data.packet;
  977. var d = new Date();
  978. packets.row.add([
  979. d.toLocaleTimeString('en-US', { hour12: false }),
  980. packet.senderID,
  981. packet.packetID,
  982. packet.targetID,
  983. packet.key,
  984. packet.value,
  985. packet.rssi,
  986. packet.duplicates,
  987. packet.missing,
  988. ]).draw(false);
  989. return;
  990. }
  991. if (key == "mapping") {
  992. for (var i in data.mapping) {
  993. // add a new row
  994. addMapping();
  995. // get group
  996. var line = $("#mapping .pure-g")[i];
  997. // fill in the blanks
  998. var mapping = data.mapping[i];
  999. Object.keys(mapping).forEach(function(key) {
  1000. var id = "input[name=" + key + "]";
  1001. if ($(id, line).length) $(id, line).val(mapping[key]).attr("original", mapping[key]);
  1002. });
  1003. }
  1004. return;
  1005. }
  1006. <!-- endRemoveIf(!rfm69)-->
  1007. // ---------------------------------------------------------------------
  1008. // Lights
  1009. // ---------------------------------------------------------------------
  1010. <!-- removeIf(!light)-->
  1011. if ("rgb" === key) {
  1012. initColor(true);
  1013. $("input[name='color']").wheelColorPicker("setValue", value, true);
  1014. return;
  1015. }
  1016. if ("hsv" === key) {
  1017. initColor(false);
  1018. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  1019. var chunks = value.split(",");
  1020. var obj = {};
  1021. obj.h = chunks[0] / 360;
  1022. obj.s = chunks[1] / 100;
  1023. obj.v = chunks[2] / 100;
  1024. $("input[name='color']").wheelColorPicker("setColor", obj);
  1025. return;
  1026. }
  1027. if ("brightness" === key) {
  1028. $("#brightness").val(value);
  1029. $("span.brightness").html(value);
  1030. return;
  1031. }
  1032. if ("channels" === key) {
  1033. var len = value.length;
  1034. initChannels(len);
  1035. for (i in value) {
  1036. var ch = value[i];
  1037. $("input.slider[data=" + i + "]").val(ch);
  1038. $("span.slider[data=" + i + "]").html(ch);
  1039. }
  1040. return;
  1041. }
  1042. if ("mireds" === key) {
  1043. $("#mireds").val(value);
  1044. $("span.mireds").html(value);
  1045. return;
  1046. }
  1047. if ("useWhite" === key) {
  1048. useWhite = value;
  1049. }
  1050. if ("useCCT" === key) {
  1051. initCCT();
  1052. useCCT = value;
  1053. }
  1054. <!-- endRemoveIf(!light)-->
  1055. // ---------------------------------------------------------------------
  1056. // Sensors & Magnitudes
  1057. // ---------------------------------------------------------------------
  1058. <!-- removeIf(!sensor)-->
  1059. if ("magnitudes" === key) {
  1060. initMagnitudes(value);
  1061. for (i in value) {
  1062. var magnitude = value[i];
  1063. var error = magnitude.error || 0;
  1064. var text = (0 === error) ?
  1065. magnitude.value + magnitude.units :
  1066. magnitudeError(error);
  1067. var element = $("input[name='magnitude'][data='" + i + "']");
  1068. element.val(text);
  1069. $("div.hint", element.parent().parent()).html(magnitude.description);
  1070. }
  1071. return;
  1072. }
  1073. <!-- endRemoveIf(!sensor)-->
  1074. // ---------------------------------------------------------------------
  1075. // WiFi
  1076. // ---------------------------------------------------------------------
  1077. if ("maxNetworks" === key) {
  1078. maxNetworks = parseInt(value, 10);
  1079. return;
  1080. }
  1081. if ("wifi" === key) {
  1082. for (i in value) {
  1083. var wifi = value[i];
  1084. var nwk_line = addNetwork();
  1085. Object.keys(wifi).forEach(function(key) {
  1086. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  1087. });
  1088. }
  1089. return;
  1090. }
  1091. if ("scanResult" === key) {
  1092. $("div.scan.loading").hide();
  1093. $("#scanResult").show();
  1094. }
  1095. // -----------------------------------------------------------------------------
  1096. // Home Assistant
  1097. // -----------------------------------------------------------------------------
  1098. if ("haConfig" === key) {
  1099. websock.send("{}");
  1100. $("#haConfig")
  1101. .append(new Text(value))
  1102. .height($("#haConfig")[0].scrollHeight);
  1103. return;
  1104. }
  1105. // -----------------------------------------------------------------------------
  1106. // Relays scheduler
  1107. // -----------------------------------------------------------------------------
  1108. if ("maxSchedules" === key) {
  1109. maxSchedules = parseInt(value, 10);
  1110. return;
  1111. }
  1112. if ("schedule" === key) {
  1113. for (i in value) {
  1114. var schedule = value[i];
  1115. var sch_line = addSchedule({ data: {schType: schedule["schType"] }});
  1116. Object.keys(schedule).forEach(function(key) {
  1117. var sch_value = schedule[key];
  1118. $("input[name='" + key + "']", sch_line).val(sch_value);
  1119. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  1120. $("input[type='checkbox'][name='" + key + "']", sch_line).prop("checked", sch_value);
  1121. });
  1122. }
  1123. return;
  1124. }
  1125. // ---------------------------------------------------------------------
  1126. // Relays
  1127. // ---------------------------------------------------------------------
  1128. if ("relayStatus" === key) {
  1129. initRelays(value);
  1130. for (i in value) {
  1131. $("input[name='relay'][data='" + i + "']").prop("checked", value[i]);
  1132. }
  1133. return;
  1134. }
  1135. // Relay configuration
  1136. if ("relayConfig" === key) {
  1137. initRelayConfig(value);
  1138. return;
  1139. }
  1140. // ---------------------------------------------------------------------
  1141. // Domoticz
  1142. // ---------------------------------------------------------------------
  1143. // Domoticz - Relays
  1144. if ("dczRelays" === key) {
  1145. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1146. return;
  1147. }
  1148. // Domoticz - Magnitudes
  1149. <!-- removeIf(!sensor)-->
  1150. if ("dczMagnitudes" === key) {
  1151. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1152. return;
  1153. }
  1154. <!-- endRemoveIf(!sensor)-->
  1155. // ---------------------------------------------------------------------
  1156. // Thingspeak
  1157. // ---------------------------------------------------------------------
  1158. // Thingspeak - Relays
  1159. if ("tspkRelays" === key) {
  1160. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1161. return;
  1162. }
  1163. // Thingspeak - Magnitudes
  1164. <!-- removeIf(!sensor)-->
  1165. if ("tspkMagnitudes" === key) {
  1166. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1167. return;
  1168. }
  1169. <!-- endRemoveIf(!sensor)-->
  1170. // ---------------------------------------------------------------------
  1171. // General
  1172. // ---------------------------------------------------------------------
  1173. // Messages
  1174. if ("message" === key) {
  1175. window.alert(messages[value]);
  1176. return;
  1177. }
  1178. // Web log
  1179. if ("weblog" === key) {
  1180. $("#weblog").append(new Text(value));
  1181. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  1182. return;
  1183. }
  1184. // Enable options
  1185. var position = key.indexOf("Visible");
  1186. if (position > 0 && position === key.length - 7) {
  1187. var module = key.slice(0,-7);
  1188. $(".module-" + module).css("display", "inherit");
  1189. return;
  1190. }
  1191. if ("deviceip" === key) {
  1192. var a_href = $("span[name='" + key + "']").parent();
  1193. a_href.attr("href", "//" + value);
  1194. a_href.next().attr("href", "telnet://" + value);
  1195. }
  1196. if ("now" === key) {
  1197. now = value;
  1198. return;
  1199. }
  1200. if ("free_size" === key) {
  1201. free_size = parseInt(value, 10);
  1202. }
  1203. // Pre-process
  1204. if ("mqttStatus" === key) {
  1205. value = value ? "CONNECTED" : "NOT CONNECTED";
  1206. }
  1207. if ("ntpStatus" === key) {
  1208. value = value ? "SYNC'D" : "NOT SYNC'D";
  1209. }
  1210. if ("uptime" === key) {
  1211. ago = 0;
  1212. var uptime = parseInt(value, 10);
  1213. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1214. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1215. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1216. var days = uptime;
  1217. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1218. }
  1219. // ---------------------------------------------------------------------
  1220. // Matching
  1221. // ---------------------------------------------------------------------
  1222. var pre;
  1223. var post;
  1224. // Look for INPUTs
  1225. var input = $("input[name='" + key + "']");
  1226. if (input.length > 0) {
  1227. if (input.attr("type") === "checkbox") {
  1228. input.prop("checked", value);
  1229. } else if (input.attr("type") === "radio") {
  1230. input.val([value]);
  1231. } else {
  1232. pre = input.attr("pre") || "";
  1233. post = input.attr("post") || "";
  1234. input.val(pre + value + post);
  1235. }
  1236. }
  1237. // Look for SPANs
  1238. var span = $("span[name='" + key + "']");
  1239. if (span.length > 0) {
  1240. pre = span.attr("pre") || "";
  1241. post = span.attr("post") || "";
  1242. span.html(pre + value + post);
  1243. }
  1244. // Look for SELECTs
  1245. var select = $("select[name='" + key + "']");
  1246. if (select.length > 0) {
  1247. select.val(value);
  1248. }
  1249. });
  1250. // Auto generate an APIKey if none defined yet
  1251. if ($("input[name='apiKey']").val() === "") {
  1252. generateAPIKey();
  1253. }
  1254. setOriginalsFromValues();
  1255. }
  1256. function hasChanged() {
  1257. var newValue, originalValue;
  1258. if ($(this).attr("type") === "checkbox") {
  1259. newValue = $(this).prop("checked");
  1260. originalValue = ($(this).attr("original") === "true");
  1261. } else {
  1262. newValue = $(this).val();
  1263. originalValue = $(this).attr("original");
  1264. }
  1265. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1266. var action = $(this).attr("action");
  1267. if (typeof originalValue === "undefined") { return; }
  1268. if ("none" === action) { return; }
  1269. if (newValue !== originalValue) {
  1270. if (!hasChanged) {
  1271. ++numChanged;
  1272. if ("reconnect" === action) { ++numReconnect; }
  1273. if ("reboot" === action) { ++numReboot; }
  1274. if ("reload" === action) { ++numReload; }
  1275. $(this).attr("hasChanged", true);
  1276. }
  1277. } else {
  1278. if (hasChanged) {
  1279. --numChanged;
  1280. if ("reconnect" === action) { --numReconnect; }
  1281. if ("reboot" === action) { --numReboot; }
  1282. if ("reload" === action) { --numReload; }
  1283. $(this).attr("hasChanged", false);
  1284. }
  1285. }
  1286. }
  1287. // -----------------------------------------------------------------------------
  1288. // Init & connect
  1289. // -----------------------------------------------------------------------------
  1290. function initUrls(root) {
  1291. var paths = ["ws", "upgrade", "config", "auth"];
  1292. urls["root"] = root;
  1293. paths.forEach(function(path) {
  1294. urls[path] = new URL(path, root);
  1295. urls[path].protocol = root.protocol;
  1296. });
  1297. if (root.protocol == "https:") {
  1298. urls.ws.protocol = "wss:";
  1299. } else {
  1300. urls.ws.protocol = "ws:";
  1301. }
  1302. }
  1303. function connectToURL(url) {
  1304. initUrls(url);
  1305. $.ajax({
  1306. 'method': 'GET',
  1307. 'crossDomain': true,
  1308. 'url': urls.auth.href,
  1309. 'xhrFields': { 'withCredentials': true }
  1310. }).done(function(data) {
  1311. if (websock) { websock.close(); }
  1312. websock = new WebSocket(urls.ws.href);
  1313. websock.onmessage = function(evt) {
  1314. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1315. if (data) {
  1316. processData(data);
  1317. }
  1318. };
  1319. }).fail(function() {
  1320. // Nothing to do, reload page and retry
  1321. });
  1322. }
  1323. function connect(host) {
  1324. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1325. host = "http://" + host;
  1326. }
  1327. connectToURL(new URL(host));
  1328. }
  1329. function connectToCurrentURL() {
  1330. connectToURL(new URL(window.location));
  1331. }
  1332. function getParameterByName(name) {
  1333. var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  1334. return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  1335. }
  1336. $(function() {
  1337. initMessages();
  1338. loadTimeZones();
  1339. createCheckboxes();
  1340. setInterval(function() { keepTime(); }, 1000);
  1341. $(".password-reveal").on("click", toggleVisiblePassword);
  1342. $("#menuLink").on("click", toggleMenu);
  1343. $(".pure-menu-link").on("click", showPanel);
  1344. $("progress").attr({ value: 0, max: 100 });
  1345. $(".button-update").on("click", doUpdate);
  1346. $(".button-update-password").on("click", doUpdatePassword);
  1347. $(".button-generate-password").on("click", doGeneratePassword);
  1348. $(".button-reboot").on("click", doReboot);
  1349. $(".button-reconnect").on("click", doReconnect);
  1350. $(".button-wifi-scan").on("click", doScan);
  1351. $(".button-ha-config").on("click", doHAConfig);
  1352. $(".button-dbgcmd").on("click", doDebugCommand);
  1353. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1354. $(".button-dbg-clear").on("click", doDebugClear);
  1355. $(".button-settings-backup").on("click", doBackup);
  1356. $(".button-settings-restore").on("click", doRestore);
  1357. $(".button-settings-factory").on("click", doFactoryReset);
  1358. $("#uploader").on("change", onFileUpload);
  1359. $(".button-upgrade").on("click", doUpgrade);
  1360. $(".button-apikey").on("click", generateAPIKey);
  1361. $(".button-upgrade-browse").on("click", function() {
  1362. $("input[name='upgrade']")[0].click();
  1363. return false;
  1364. });
  1365. $("input[name='upgrade']").change(function (){
  1366. var file = this.files[0];
  1367. $("input[name='filename']").val(file.name);
  1368. });
  1369. $(".button-add-network").on("click", function() {
  1370. $(".more", addNetwork()).toggle();
  1371. });
  1372. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1373. <!-- removeIf(!light)-->
  1374. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1375. <!-- endRemoveIf(!light)-->
  1376. <!-- removeIf(!rfm69)-->
  1377. $(".button-add-mapping").on('click', addMapping);
  1378. $(".button-del-mapping").on('click', delMapping);
  1379. $(".button-clear-counts").on('click', doClearCounts);
  1380. $(".button-clear-messages").on('click', doClearMessages);
  1381. $(".button-clear-filters").on('click', doClearFilters);
  1382. $('#packets tbody').on('mousedown', 'td', doFilter);
  1383. packets = $('#packets').DataTable({
  1384. "paging": false
  1385. });
  1386. for (var i = 0; i < packets.columns()[0].length; i++) {
  1387. filters[i] = false;
  1388. }
  1389. <!-- endRemoveIf(!rfm69)-->
  1390. $(document).on("change", "input", hasChanged);
  1391. $(document).on("change", "select", hasChanged);
  1392. $("textarea").on("dblclick", function() { this.select(); });
  1393. // don't autoconnect when opening from filesystem
  1394. if (window.location.protocol === "file:") { return; }
  1395. // Check host param in query string
  1396. if (host = getParameterByName('host')) {
  1397. connect(host);
  1398. } else {
  1399. connectToCurrentURL();
  1400. }
  1401. });