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.

1525 lines
44 KiB

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