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.

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