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.

1387 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
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 useColdWhite = 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",
  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 (useColdWhite) {
  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 ("useColdWhite" === key) {
  823. useColdWhite = 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. $("input[name='magnitude'][data='" + i + "']").val(text);
  837. }
  838. return;
  839. }
  840. // ---------------------------------------------------------------------
  841. // WiFi
  842. // ---------------------------------------------------------------------
  843. if ("maxNetworks" === key) {
  844. maxNetworks = parseInt(value, 10);
  845. return;
  846. }
  847. if ("wifi" === key) {
  848. for (i in value) {
  849. var wifi = value[i];
  850. var nwk_line = addNetwork();
  851. Object.keys(wifi).forEach(function(key) {
  852. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  853. });
  854. }
  855. return;
  856. }
  857. if ("scanResult" === key) {
  858. $("div.scan.loading").hide();
  859. $("#scanResult").show();
  860. }
  861. // -----------------------------------------------------------------------------
  862. // Home Assistant
  863. // -----------------------------------------------------------------------------
  864. if ("haConfig" === key) {
  865. $("#haConfig").show();
  866. }
  867. // -----------------------------------------------------------------------------
  868. // Relays scheduler
  869. // -----------------------------------------------------------------------------
  870. if ("maxSchedules" === key) {
  871. maxSchedules = parseInt(value, 10);
  872. return;
  873. }
  874. if ("schedule" === key) {
  875. for (i in value) {
  876. var schedule = value[i];
  877. var sch_line = addSchedule({ data: {schType: schedule["schType"] }});
  878. Object.keys(schedule).forEach(function(key) {
  879. var sch_value = schedule[key];
  880. $("input[name='" + key + "']", sch_line).val(sch_value);
  881. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  882. $("input[type='checkbox'][name='" + key + "']", sch_line).
  883. prop("checked", sch_value).
  884. iphoneStyle("refresh");
  885. });
  886. }
  887. return;
  888. }
  889. // ---------------------------------------------------------------------
  890. // Relays
  891. // ---------------------------------------------------------------------
  892. if ("relayStatus" === key) {
  893. initRelays(value);
  894. for (i in value) {
  895. // Set the status for each relay
  896. $("input.relayStatus[data='" + i + "']").
  897. prop("checked", value[i]).
  898. iphoneStyle("refresh");
  899. }
  900. return;
  901. }
  902. // Relay configuration
  903. if ("relayConfig" === key) {
  904. initRelayConfig(value);
  905. return;
  906. }
  907. // ---------------------------------------------------------------------
  908. // Domoticz
  909. // ---------------------------------------------------------------------
  910. // Domoticz - Relays
  911. if ("dczRelays" === key) {
  912. createRelayList(value, "dczRelays", "dczRelayTemplate");
  913. return;
  914. }
  915. // Domoticz - Magnitudes
  916. if ("dczMagnitudes" === key) {
  917. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  918. return;
  919. }
  920. // ---------------------------------------------------------------------
  921. // Thingspeak
  922. // ---------------------------------------------------------------------
  923. // Thingspeak - Relays
  924. if ("tspkRelays" === key) {
  925. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  926. return;
  927. }
  928. // Thingspeak - Magnitudes
  929. if ("tspkMagnitudes" === key) {
  930. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  931. return;
  932. }
  933. // ---------------------------------------------------------------------
  934. // General
  935. // ---------------------------------------------------------------------
  936. // Messages
  937. if ("message" === key) {
  938. window.alert(messages[value]);
  939. return;
  940. }
  941. // Web log
  942. if ("weblog" === key) {
  943. $("#weblog").append(value);
  944. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  945. return;
  946. }
  947. // Enable options
  948. var position = key.indexOf("Visible");
  949. if (position > 0 && position === key.length - 7) {
  950. var module = key.slice(0,-7);
  951. $(".module-" + module).show();
  952. return;
  953. }
  954. if ("now" === key) {
  955. now = value;
  956. ago = 0;
  957. return;
  958. }
  959. if ("free_size" === key) {
  960. free_size = parseInt(value, 10);
  961. }
  962. // Pre-process
  963. if ("network" === key) {
  964. value = value.toUpperCase();
  965. }
  966. if ("mqttStatus" === key) {
  967. value = value ? "CONNECTED" : "NOT CONNECTED";
  968. }
  969. if ("ntpStatus" === key) {
  970. value = value ? "SYNC'D" : "NOT SYNC'D";
  971. }
  972. if ("uptime" === key) {
  973. var uptime = parseInt(value, 10);
  974. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  975. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  976. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  977. var days = uptime;
  978. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  979. }
  980. // ---------------------------------------------------------------------
  981. // Matching
  982. // ---------------------------------------------------------------------
  983. var pre;
  984. var post;
  985. // Look for INPUTs
  986. var input = $("input[name='" + key + "']");
  987. if (input.length > 0) {
  988. if (input.attr("type") === "checkbox") {
  989. input.
  990. prop("checked", value).
  991. iphoneStyle("refresh");
  992. } else if (input.attr("type") === "radio") {
  993. input.val([value]);
  994. } else {
  995. pre = input.attr("pre") || "";
  996. post = input.attr("post") || "";
  997. input.val(pre + value + post);
  998. }
  999. }
  1000. // Look for SPANs
  1001. var span = $("span[name='" + key + "']");
  1002. if (span.length > 0) {
  1003. pre = span.attr("pre") || "";
  1004. post = span.attr("post") || "";
  1005. span.html(pre + value + post);
  1006. }
  1007. // Look for SELECTs
  1008. var select = $("select[name='" + key + "']");
  1009. if (select.length > 0) {
  1010. select.val(value);
  1011. }
  1012. });
  1013. // Auto generate an APIKey if none defined yet
  1014. if ($("input[name='apiKey']").val() === "") {
  1015. generateAPIKey();
  1016. }
  1017. resetOriginals();
  1018. }
  1019. function hasChanged() {
  1020. var newValue, originalValue;
  1021. if ($(this).attr("type") === "checkbox") {
  1022. newValue = $(this).prop("checked");
  1023. originalValue = ($(this).attr("original") === "true");
  1024. } else {
  1025. newValue = $(this).val();
  1026. originalValue = $(this).attr("original");
  1027. }
  1028. var hasChanged = $(this).attr("hasChanged") || 0;
  1029. var action = $(this).attr("action");
  1030. if (typeof originalValue === "undefined") { return; }
  1031. if ("none" === action) { return; }
  1032. if (newValue !== originalValue) {
  1033. if (0 === hasChanged) {
  1034. ++numChanged;
  1035. if ("reconnect" === action) { ++numReconnect; }
  1036. if ("reboot" === action) { ++numReboot; }
  1037. if ("reload" === action) { ++numReload; }
  1038. $(this).attr("hasChanged", 1);
  1039. }
  1040. } else {
  1041. if (1 === hasChanged) {
  1042. --numChanged;
  1043. if ("reconnect" === action) { --numReconnect; }
  1044. if ("reboot" === action) { --numReboot; }
  1045. if ("reload" === action) { --numReload; }
  1046. $(this).attr("hasChanged", 0);
  1047. }
  1048. }
  1049. }
  1050. // -----------------------------------------------------------------------------
  1051. // Init & connect
  1052. // -----------------------------------------------------------------------------
  1053. function initUrls(root) {
  1054. var paths = ["ws", "upgrade", "config"];
  1055. urls["root"] = root;
  1056. paths.forEach(function(path) {
  1057. urls[path] = new URL(path, root);
  1058. });
  1059. urls.ws.protocol = "ws";
  1060. }
  1061. function connectToURL(url) {
  1062. initUrls(url);
  1063. if (websock) { websock.close(); }
  1064. websock = new WebSocket(urls.ws.href);
  1065. websock.onmessage = function(evt) {
  1066. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1067. if (data) {
  1068. processData(data);
  1069. }
  1070. };
  1071. }
  1072. function connect(host) {
  1073. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1074. host = "http://" + host;
  1075. }
  1076. connectToURL(new URL(host));
  1077. }
  1078. function connectToCurrentURL() {
  1079. connectToURL(new URL(window.location));
  1080. }
  1081. $(function() {
  1082. initMessages();
  1083. loadTimeZones();
  1084. setInterval(function() { keepTime(); }, 1000);
  1085. $("#menuLink").on("click", toggleMenu);
  1086. $(".pure-menu-link").on("click", showPanel);
  1087. $("progress").attr({ value: 0, max: 100 });
  1088. $(".button-update").on("click", doUpdate);
  1089. $(".button-update-password").on("click", doUpdatePassword);
  1090. $(".button-reboot").on("click", doReboot);
  1091. $(".button-reconnect").on("click", doReconnect);
  1092. $(".button-wifi-scan").on("click", doScan);
  1093. $(".button-ha-config").on("click", doHAConfig);
  1094. $(".button-dbgcmd").on("click", doDebugCommand);
  1095. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1096. $(".button-dbg-clear").on("click", doDebugClear);
  1097. $(".button-settings-backup").on("click", doBackup);
  1098. $(".button-settings-restore").on("click", doRestore);
  1099. $(".button-settings-factory").on("click", doFactoryReset);
  1100. $("#uploader").on("change", onFileUpload);
  1101. $(".button-upgrade").on("click", doUpgrade);
  1102. $(".button-apikey").on("click", generateAPIKey);
  1103. $(".button-upgrade-browse").on("click", function() {
  1104. $("input[name='upgrade']")[0].click();
  1105. return false;
  1106. });
  1107. $("input[name='upgrade']").change(function (){
  1108. var file = this.files[0];
  1109. $("input[name='filename']").val(file.name);
  1110. });
  1111. $(".button-add-network").on("click", function() {
  1112. $(".more", addNetwork()).toggle();
  1113. });
  1114. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1115. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1116. $(document).on("change", "input", hasChanged);
  1117. $(document).on("change", "select", hasChanged);
  1118. // don't autoconnect when opening from filesystem
  1119. if (window.location.protocol === "file:") { return; }
  1120. connectToCurrentURL();
  1121. });