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.

1295 lines
38 KiB

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