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.

1481 lines
43 KiB

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