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.

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