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.

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