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.

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