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.

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