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.

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