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.

1409 lines
40 KiB

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