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.

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