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.

1792 lines
51 KiB

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