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.

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