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.

1422 lines
41 KiB

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