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.

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