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.

1702 lines
49 KiB

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