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.

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