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.

1722 lines
50 KiB

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