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.

1535 lines
44 KiB

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