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.

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