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.

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