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.

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