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.

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