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.

1389 lines
40 KiB

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