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.

1675 lines
48 KiB

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