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.

1411 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 initCCT() {
  644. // check if already initialized
  645. var done = $("#cct > div").length;
  646. if (done > 0) { return; }
  647. $("#miredsTemplate").children().clone().appendTo("#cct");
  648. $("#mireds").on("change", function() {
  649. var value = $(this).val();
  650. var parent = $(this).parents(".pure-g");
  651. $("span", parent).html(value);
  652. sendAction("mireds", {mireds: value});
  653. });
  654. }
  655. function initColorHSV() {
  656. // check if already initialized
  657. var done = $("#colors > div").length;
  658. if (done > 0) { return; }
  659. // add template
  660. var template = $("#colorHSVTemplate").children();
  661. var line = $(template).clone();
  662. line.appendTo("#colors");
  663. // init color wheel
  664. $("input[name='color']").wheelColorPicker({
  665. sliders: "whsvp"
  666. }).on("sliderup", function() {
  667. var color = $(this).wheelColorPicker("getColor");
  668. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  669. sendAction("color", {hsv: value});
  670. });
  671. }
  672. function initChannels(num) {
  673. // check if already initialized
  674. var done = $("#channels > div").length > 0;
  675. if (done) { return; }
  676. // does it have color channels?
  677. var colors = $("#colors > div").length > 0;
  678. // calculate channels to create
  679. var max = num;
  680. if (colors) {
  681. max = num % 3;
  682. if ((max > 0) & useWhite) {
  683. max--;
  684. if (useCCT) {
  685. max--;
  686. }
  687. }
  688. }
  689. var start = num - max;
  690. var onChannelSliderChange = function() {
  691. var id = $(this).attr("data");
  692. var value = $(this).val();
  693. var parent = $(this).parents(".pure-g");
  694. $("span", parent).html(value);
  695. sendAction("channel", {id: id, value: value});
  696. };
  697. // add templates
  698. var template = $("#channelTemplate").children();
  699. for (var i=0; i<max; i++) {
  700. var channel_id = start + i;
  701. var line = $(template).clone();
  702. $("span.slider", line).attr("data", channel_id);
  703. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  704. $("label", line).html("Channel #" + channel_id);
  705. line.appendTo("#channels");
  706. }
  707. for (var i=0; i<num; i++) {
  708. $("select.islight").append(
  709. $("<option></option>").attr("value",i).text("Channel #" + i));
  710. }
  711. }
  712. // -----------------------------------------------------------------------------
  713. // RFBridge
  714. // -----------------------------------------------------------------------------
  715. function rfbLearn() {
  716. var parent = $(this).parents(".pure-g");
  717. var input = $("input", parent);
  718. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  719. }
  720. function rfbForget() {
  721. var parent = $(this).parents(".pure-g");
  722. var input = $("input", parent);
  723. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  724. }
  725. function rfbSend() {
  726. var parent = $(this).parents(".pure-g");
  727. var input = $("input", parent);
  728. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  729. }
  730. function addRfbNode() {
  731. var numNodes = $("#rfbNodes > legend").length;
  732. var template = $("#rfbNodeTemplate").children();
  733. var line = $(template).clone();
  734. var status = true;
  735. $("span", line).html(numNodes);
  736. $(line).find("input").each(function() {
  737. $(this).attr("data-id", numNodes);
  738. $(this).attr("data-status", status ? 1 : 0);
  739. status = !status;
  740. });
  741. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  742. $(line).find(".button-rfb-forget").on("click", rfbForget);
  743. $(line).find(".button-rfb-send").on("click", rfbSend);
  744. line.appendTo("#rfbNodes");
  745. return line;
  746. }
  747. // -----------------------------------------------------------------------------
  748. // Processing
  749. // -----------------------------------------------------------------------------
  750. function processData(data) {
  751. // title
  752. if ("app_name" in data) {
  753. var title = data.app_name;
  754. if ("app_version" in data) {
  755. title = title + " " + data.app_version;
  756. }
  757. $("span[name=title]").html(title);
  758. if ("hostname" in data) {
  759. title = data.hostname + " - " + title;
  760. }
  761. document.title = title;
  762. }
  763. Object.keys(data).forEach(function(key) {
  764. var i;
  765. var value = data[key];
  766. // ---------------------------------------------------------------------
  767. // Web mode
  768. // ---------------------------------------------------------------------
  769. if ("webMode" === key) {
  770. password = (1 === value);
  771. $("#layout").toggle(!password);
  772. $("#password").toggle(password);
  773. }
  774. // ---------------------------------------------------------------------
  775. // Actions
  776. // ---------------------------------------------------------------------
  777. if ("action" === key) {
  778. if ("reload" === data.action) { doReload(1000); }
  779. return;
  780. }
  781. // ---------------------------------------------------------------------
  782. // RFBridge
  783. // ---------------------------------------------------------------------
  784. if ("rfbCount" === key) {
  785. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  786. return;
  787. }
  788. if ("rfbrawVisible" === key) {
  789. $("input[name='rfbcode']").attr("maxlength", 116);
  790. }
  791. if ("rfb" === key) {
  792. var nodes = data.rfb;
  793. for (i in nodes) {
  794. var node = nodes[i];
  795. $("input[name='rfbcode'][data-id='" + node.id + "'][data-status='" + node.status + "']").val(node.data);
  796. }
  797. return;
  798. }
  799. // ---------------------------------------------------------------------
  800. // Lights
  801. // ---------------------------------------------------------------------
  802. if ("rgb" === key) {
  803. initColorRGB();
  804. $("input[name='color']").wheelColorPicker("setValue", value, true);
  805. return;
  806. }
  807. if ("hsv" === key) {
  808. initColorHSV();
  809. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  810. var chunks = value.split(",");
  811. var obj = {};
  812. obj.h = chunks[0] / 360;
  813. obj.s = chunks[1] / 100;
  814. obj.v = chunks[2] / 100;
  815. $("input[name='color']").wheelColorPicker("setColor", obj);
  816. return;
  817. }
  818. if ("brightness" === key) {
  819. $("#brightness").val(value);
  820. $("span.brightness").html(value);
  821. return;
  822. }
  823. if ("channels" === key) {
  824. var len = value.length;
  825. initChannels(len);
  826. for (i in value) {
  827. var ch = value[i];
  828. $("input.slider[data=" + i + "]").val(ch);
  829. $("span.slider[data=" + i + "]").html(ch);
  830. }
  831. return;
  832. }
  833. if ("mireds" === key) {
  834. $("#mireds").val(value);
  835. $("span.mireds").html(value);
  836. return;
  837. }
  838. if ("useWhite" === key) {
  839. useWhite = value;
  840. }
  841. if ("useCCT" === key) {
  842. initCCT();
  843. useCCT = value;
  844. }
  845. // ---------------------------------------------------------------------
  846. // Sensors & Magnitudes
  847. // ---------------------------------------------------------------------
  848. if ("magnitudes" === key) {
  849. initMagnitudes(value);
  850. for (i in value) {
  851. var magnitude = value[i];
  852. var error = magnitude.error || 0;
  853. var text = (0 === error) ?
  854. magnitude.value + magnitude.units :
  855. magnitudeError(error);
  856. var element = $("input[name='magnitude'][data='" + i + "']");
  857. element.val(text);
  858. $("div.hint", element.parent().parent()).html(magnitude.description);
  859. }
  860. return;
  861. }
  862. // ---------------------------------------------------------------------
  863. // WiFi
  864. // ---------------------------------------------------------------------
  865. if ("maxNetworks" === key) {
  866. maxNetworks = parseInt(value, 10);
  867. return;
  868. }
  869. if ("wifi" === key) {
  870. for (i in value) {
  871. var wifi = value[i];
  872. var nwk_line = addNetwork();
  873. Object.keys(wifi).forEach(function(key) {
  874. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  875. });
  876. }
  877. return;
  878. }
  879. if ("scanResult" === key) {
  880. $("div.scan.loading").hide();
  881. $("#scanResult").show();
  882. }
  883. // -----------------------------------------------------------------------------
  884. // Home Assistant
  885. // -----------------------------------------------------------------------------
  886. if ("haConfig" === key) {
  887. $("#haConfig").show();
  888. }
  889. // -----------------------------------------------------------------------------
  890. // Relays scheduler
  891. // -----------------------------------------------------------------------------
  892. if ("maxSchedules" === key) {
  893. maxSchedules = parseInt(value, 10);
  894. return;
  895. }
  896. if ("schedule" === key) {
  897. for (i in value) {
  898. var schedule = value[i];
  899. var sch_line = addSchedule({ data: {schType: schedule["schType"] }});
  900. Object.keys(schedule).forEach(function(key) {
  901. var sch_value = schedule[key];
  902. $("input[name='" + key + "']", sch_line).val(sch_value);
  903. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  904. $("input[type='checkbox'][name='" + key + "']", sch_line).
  905. prop("checked", sch_value).
  906. iphoneStyle("refresh");
  907. });
  908. }
  909. return;
  910. }
  911. // ---------------------------------------------------------------------
  912. // Relays
  913. // ---------------------------------------------------------------------
  914. if ("relayStatus" === key) {
  915. initRelays(value);
  916. for (i in value) {
  917. // Set the status for each relay
  918. $("input.relayStatus[data='" + i + "']").
  919. prop("checked", value[i]).
  920. iphoneStyle("refresh");
  921. }
  922. return;
  923. }
  924. // Relay configuration
  925. if ("relayConfig" === key) {
  926. initRelayConfig(value);
  927. return;
  928. }
  929. // ---------------------------------------------------------------------
  930. // Domoticz
  931. // ---------------------------------------------------------------------
  932. // Domoticz - Relays
  933. if ("dczRelays" === key) {
  934. createRelayList(value, "dczRelays", "dczRelayTemplate");
  935. return;
  936. }
  937. // Domoticz - Magnitudes
  938. if ("dczMagnitudes" === key) {
  939. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  940. return;
  941. }
  942. // ---------------------------------------------------------------------
  943. // Thingspeak
  944. // ---------------------------------------------------------------------
  945. // Thingspeak - Relays
  946. if ("tspkRelays" === key) {
  947. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  948. return;
  949. }
  950. // Thingspeak - Magnitudes
  951. if ("tspkMagnitudes" === key) {
  952. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  953. return;
  954. }
  955. // ---------------------------------------------------------------------
  956. // General
  957. // ---------------------------------------------------------------------
  958. // Messages
  959. if ("message" === key) {
  960. window.alert(messages[value]);
  961. return;
  962. }
  963. // Web log
  964. if ("weblog" === key) {
  965. $("#weblog").append(value);
  966. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  967. return;
  968. }
  969. // Enable options
  970. var position = key.indexOf("Visible");
  971. if (position > 0 && position === key.length - 7) {
  972. var module = key.slice(0,-7);
  973. $(".module-" + module).show();
  974. return;
  975. }
  976. if ("now" === key) {
  977. now = value;
  978. ago = 0;
  979. return;
  980. }
  981. if ("free_size" === key) {
  982. free_size = parseInt(value, 10);
  983. }
  984. // Pre-process
  985. if ("mqttStatus" === key) {
  986. value = value ? "CONNECTED" : "NOT CONNECTED";
  987. }
  988. if ("ntpStatus" === key) {
  989. value = value ? "SYNC'D" : "NOT SYNC'D";
  990. }
  991. if ("uptime" === key) {
  992. var uptime = parseInt(value, 10);
  993. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  994. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  995. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  996. var days = uptime;
  997. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  998. }
  999. // ---------------------------------------------------------------------
  1000. // Matching
  1001. // ---------------------------------------------------------------------
  1002. var pre;
  1003. var post;
  1004. // Look for INPUTs
  1005. var input = $("input[name='" + key + "']");
  1006. if (input.length > 0) {
  1007. if (input.attr("type") === "checkbox") {
  1008. input.
  1009. prop("checked", value).
  1010. iphoneStyle("refresh");
  1011. } else if (input.attr("type") === "radio") {
  1012. input.val([value]);
  1013. } else {
  1014. pre = input.attr("pre") || "";
  1015. post = input.attr("post") || "";
  1016. input.val(pre + value + post);
  1017. }
  1018. }
  1019. // Look for SPANs
  1020. var span = $("span[name='" + key + "']");
  1021. if (span.length > 0) {
  1022. pre = span.attr("pre") || "";
  1023. post = span.attr("post") || "";
  1024. span.html(pre + value + post);
  1025. }
  1026. // Look for SELECTs
  1027. var select = $("select[name='" + key + "']");
  1028. if (select.length > 0) {
  1029. select.val(value);
  1030. }
  1031. });
  1032. // Auto generate an APIKey if none defined yet
  1033. if ($("input[name='apiKey']").val() === "") {
  1034. generateAPIKey();
  1035. }
  1036. resetOriginals();
  1037. }
  1038. function hasChanged() {
  1039. var newValue, originalValue;
  1040. if ($(this).attr("type") === "checkbox") {
  1041. newValue = $(this).prop("checked");
  1042. originalValue = ($(this).attr("original") === "true");
  1043. } else {
  1044. newValue = $(this).val();
  1045. originalValue = $(this).attr("original");
  1046. }
  1047. var hasChanged = $(this).attr("hasChanged") || 0;
  1048. var action = $(this).attr("action");
  1049. if (typeof originalValue === "undefined") { return; }
  1050. if ("none" === action) { return; }
  1051. if (newValue !== originalValue) {
  1052. if (0 === hasChanged) {
  1053. ++numChanged;
  1054. if ("reconnect" === action) { ++numReconnect; }
  1055. if ("reboot" === action) { ++numReboot; }
  1056. if ("reload" === action) { ++numReload; }
  1057. $(this).attr("hasChanged", 1);
  1058. }
  1059. } else {
  1060. if (1 === hasChanged) {
  1061. --numChanged;
  1062. if ("reconnect" === action) { --numReconnect; }
  1063. if ("reboot" === action) { --numReboot; }
  1064. if ("reload" === action) { --numReload; }
  1065. $(this).attr("hasChanged", 0);
  1066. }
  1067. }
  1068. }
  1069. // -----------------------------------------------------------------------------
  1070. // Init & connect
  1071. // -----------------------------------------------------------------------------
  1072. function initUrls(root) {
  1073. var paths = ["ws", "upgrade", "config"];
  1074. urls["root"] = root;
  1075. paths.forEach(function(path) {
  1076. urls[path] = new URL(path, root);
  1077. });
  1078. urls.ws.protocol = "ws";
  1079. }
  1080. function connectToURL(url) {
  1081. initUrls(url);
  1082. if (websock) { websock.close(); }
  1083. websock = new WebSocket(urls.ws.href);
  1084. websock.onmessage = function(evt) {
  1085. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1086. if (data) {
  1087. processData(data);
  1088. }
  1089. };
  1090. }
  1091. function connect(host) {
  1092. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1093. host = "http://" + host;
  1094. }
  1095. connectToURL(new URL(host));
  1096. }
  1097. function connectToCurrentURL() {
  1098. connectToURL(new URL(window.location));
  1099. }
  1100. $(function() {
  1101. initMessages();
  1102. loadTimeZones();
  1103. setInterval(function() { keepTime(); }, 1000);
  1104. $("#menuLink").on("click", toggleMenu);
  1105. $(".pure-menu-link").on("click", showPanel);
  1106. $("progress").attr({ value: 0, max: 100 });
  1107. $(".button-update").on("click", doUpdate);
  1108. $(".button-update-password").on("click", doUpdatePassword);
  1109. $(".button-reboot").on("click", doReboot);
  1110. $(".button-reconnect").on("click", doReconnect);
  1111. $(".button-wifi-scan").on("click", doScan);
  1112. $(".button-ha-config").on("click", doHAConfig);
  1113. $(".button-dbgcmd").on("click", doDebugCommand);
  1114. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1115. $(".button-dbg-clear").on("click", doDebugClear);
  1116. $(".button-settings-backup").on("click", doBackup);
  1117. $(".button-settings-restore").on("click", doRestore);
  1118. $(".button-settings-factory").on("click", doFactoryReset);
  1119. $("#uploader").on("change", onFileUpload);
  1120. $(".button-upgrade").on("click", doUpgrade);
  1121. $(".button-apikey").on("click", generateAPIKey);
  1122. $(".button-upgrade-browse").on("click", function() {
  1123. $("input[name='upgrade']")[0].click();
  1124. return false;
  1125. });
  1126. $("input[name='upgrade']").change(function (){
  1127. var file = this.files[0];
  1128. $("input[name='filename']").val(file.name);
  1129. });
  1130. $(".button-add-network").on("click", function() {
  1131. $(".more", addNetwork()).toggle();
  1132. });
  1133. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1134. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1135. $(document).on("change", "input", hasChanged);
  1136. $(document).on("change", "select", hasChanged);
  1137. // don't autoconnect when opening from filesystem
  1138. if (window.location.protocol === "file:") { return; }
  1139. connectToCurrentURL();
  1140. });