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.

1258 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
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. "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. });
  819. }
  820. return;
  821. }
  822. // ---------------------------------------------------------------------
  823. // Relays
  824. // ---------------------------------------------------------------------
  825. if (key === "relayStatus") {
  826. initRelays(data[key]);
  827. for (i in data[key]) {
  828. // Set the status for each relay
  829. $("input.relayStatus[data='" + i + "']").
  830. prop("checked", data[key][i]).
  831. iphoneStyle("refresh");
  832. }
  833. return;
  834. }
  835. // Relay configuration
  836. if (key === "relayConfig") {
  837. initRelayConfig(data[key]);
  838. return;
  839. }
  840. // ---------------------------------------------------------------------
  841. // Domoticz
  842. // ---------------------------------------------------------------------
  843. // Domoticz - Relays
  844. if (key === "dczRelays") {
  845. createRelayList(data[key], "dczRelays", "dczRelayTemplate");
  846. return;
  847. }
  848. // Domoticz - Magnitudes
  849. if (key === "dczMagnitudes") {
  850. createMagnitudeList(data[key], "dczMagnitudes", "dczMagnitudeTemplate");
  851. return;
  852. }
  853. // ---------------------------------------------------------------------
  854. // Thingspeak
  855. // ---------------------------------------------------------------------
  856. // Thingspeak - Relays
  857. if (key === "tspkRelays") {
  858. createRelayList(data[key], "tspkRelays", "tspkRelayTemplate");
  859. return;
  860. }
  861. // Thingspeak - Magnitudes
  862. if (key === "tspkMagnitudes") {
  863. createMagnitudeList(data[key], "tspkMagnitudes", "tspkMagnitudeTemplate");
  864. return;
  865. }
  866. // ---------------------------------------------------------------------
  867. // General
  868. // ---------------------------------------------------------------------
  869. // Messages
  870. if (key === "message") {
  871. window.alert(messages[data.message]);
  872. return;
  873. }
  874. // Enable options
  875. var position = key.indexOf("Visible");
  876. if (position > 0 && position === key.length - 7) {
  877. var module = key.slice(0,-7);
  878. $(".module-" + module).show();
  879. return;
  880. }
  881. if (key === "now") {
  882. now = data[key];
  883. ago = 0;
  884. return;
  885. }
  886. // Pre-process
  887. if (key === "network") {
  888. data.network = data.network.toUpperCase();
  889. }
  890. if (key === "mqttStatus") {
  891. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  892. }
  893. if (key === "ntpStatus") {
  894. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  895. }
  896. if (key === "uptime") {
  897. var uptime = parseInt(data[key], 10);
  898. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  899. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  900. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  901. var days = uptime;
  902. data[key] = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  903. }
  904. // ---------------------------------------------------------------------
  905. // Matching
  906. // ---------------------------------------------------------------------
  907. var pre;
  908. var post;
  909. // Look for INPUTs
  910. var element = $("input[name='" + key + "']");
  911. if (element.length > 0) {
  912. if (element.attr("type") === "checkbox") {
  913. element.
  914. prop("checked", data[key]).
  915. iphoneStyle("refresh");
  916. } else if (element.attr("type") === "radio") {
  917. element.val([data[key]]);
  918. } else {
  919. pre = element.attr("pre") || "";
  920. post = element.attr("post") || "";
  921. element.val(pre + data[key] + post);
  922. }
  923. }
  924. // Look for SPANs
  925. var element = $("span[name='" + key + "']");
  926. if (element.length > 0) {
  927. pre = element.attr("pre") || "";
  928. post = element.attr("post") || "";
  929. element.html(pre + data[key] + post);
  930. }
  931. // Look for SELECTs
  932. var element = $("select[name='" + key + "']");
  933. if (element.length > 0) {
  934. element.val(data[key]);
  935. }
  936. });
  937. // Auto generate an APIKey if none defined yet
  938. if ($("input[name='apiKey']").val() === "") {
  939. generateAPIKey();
  940. }
  941. resetOriginals();
  942. }
  943. function hasChanged() {
  944. var newValue, originalValue;
  945. if ($(this).attr("type") === "checkbox") {
  946. newValue = $(this).prop("checked");
  947. originalValue = $(this).attr("original") == "true";
  948. } else {
  949. newValue = $(this).val();
  950. originalValue = $(this).attr("original");
  951. }
  952. var hasChanged = $(this).attr("hasChanged") || 0;
  953. var action = $(this).attr("action");
  954. if (typeof originalValue === "undefined") { return; }
  955. if (action === "none") { return; }
  956. if (newValue !== originalValue) {
  957. if (hasChanged === 0) {
  958. ++numChanged;
  959. if (action === "reconnect") ++numReconnect;
  960. if (action === "reboot") ++numReboot;
  961. if (action === "reload") ++numReload;
  962. $(this).attr("hasChanged", 1);
  963. }
  964. } else {
  965. if (hasChanged === 1) {
  966. --numChanged;
  967. if (action === "reconnect") --numReconnect;
  968. if (action === "reboot") --numReboot;
  969. if (action === "reload") --numReload;
  970. $(this).attr("hasChanged", 0);
  971. }
  972. }
  973. }
  974. // -----------------------------------------------------------------------------
  975. // Init & connect
  976. // -----------------------------------------------------------------------------
  977. function connect(host) {
  978. if (typeof host === "undefined") {
  979. host = window.location.href.replace("#", "");
  980. } else {
  981. if (host.indexOf("http") !== 0) {
  982. host = "http://" + host + "/";
  983. }
  984. }
  985. if (host.indexOf("http") !== 0) {return;}
  986. webhost = host;
  987. wshost = host.replace("http", "ws") + "ws";
  988. if (websock) websock.close();
  989. websock = new WebSocket(wshost);
  990. websock.onmessage = function(evt) {
  991. var data = getJson(evt.data);
  992. if (data) processData(data);
  993. };
  994. }
  995. $(function() {
  996. initMessages();
  997. loadTimeZones();
  998. setInterval(function() { keepTime(); }, 1000);
  999. $("#menuLink").on("click", toggleMenu);
  1000. $(".pure-menu-link").on("click", showPanel);
  1001. $("progress").attr({ value: 0, max: 100 });
  1002. $(".button-update").on("click", doUpdate);
  1003. $(".button-update-password").on("click", doUpdatePassword);
  1004. $(".button-reboot").on("click", doReboot);
  1005. $(".button-reconnect").on("click", doReconnect);
  1006. $(".button-wifi-scan").on("click", doScan);
  1007. $(".button-settings-backup").on("click", doBackup);
  1008. $(".button-settings-restore").on("click", doRestore);
  1009. $("#uploader").on("change", onFileUpload);
  1010. $(".button-upgrade").on("click", doUpgrade);
  1011. $(".button-apikey").on("click", generateAPIKey);
  1012. $(".button-upgrade-browse").on("click", function() {
  1013. $("input[name='upgrade']")[0].click();
  1014. return false;
  1015. });
  1016. $("input[name='upgrade']").change(function (){
  1017. var fileName = $(this).val();
  1018. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ""));
  1019. });
  1020. $(".button-add-network").on("click", function() {
  1021. $(".more", addNetwork()).toggle();
  1022. });
  1023. $(".button-add-schedule").on("click", function() {
  1024. $("div.more", addSchedule()).toggle();
  1025. });
  1026. $(document).on("change", "input", hasChanged);
  1027. $(document).on("change", "select", hasChanged);
  1028. connect();
  1029. });