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.

1296 lines
38 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
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
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 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 two bytes should be E901
  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. var data = evt.target.result;
  232. callback(data.charCodeAt(0) == 0xe9 && data.charCodeAt(1) == 0x01);
  233. }
  234. };
  235. var blob = file.slice(0, 2);
  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(); }
  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 (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) max--;
  651. }
  652. var start = num - max;
  653. // add templates
  654. var template = $("#channelTemplate").children();
  655. for (var i=0; i<max; i++) {
  656. var channel_id = start + i;
  657. var line = $(template).clone();
  658. $("span.slider", line).attr("data", channel_id);
  659. $("input.slider", line).attr("data", channel_id).on("change", function() {
  660. var id = $(this).attr("data");
  661. var value = $(this).val();
  662. var parent = $(this).parents(".pure-g");
  663. $("span", parent).html(value);
  664. websock.send(JSON.stringify({"action": "channel", "data" : { "id": id, "value": value }}));
  665. });
  666. $("label", line).html("Channel " + (channel_id + 1));
  667. line.appendTo("#channels");
  668. }
  669. }
  670. // -----------------------------------------------------------------------------
  671. // RFBridge
  672. // -----------------------------------------------------------------------------
  673. function addRfbNode() {
  674. var numNodes = $("#rfbNodes > legend").length;
  675. var template = $("#rfbNodeTemplate").children();
  676. var line = $(template).clone();
  677. var status = true;
  678. $("span", line).html(numNodes);
  679. $(line).find("input").each(function() {
  680. $(this).attr("data-id", numNodes);
  681. $(this).attr("data-status", status ? 1 : 0);
  682. status = !status;
  683. });
  684. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  685. $(line).find(".button-rfb-forget").on("click", rfbForget);
  686. $(line).find(".button-rfb-send").on("click", rfbSend);
  687. line.appendTo("#rfbNodes");
  688. return line;
  689. }
  690. function rfbLearn() {
  691. var parent = $(this).parents(".pure-g");
  692. var input = $("input", parent);
  693. websock.send(JSON.stringify({"action": "rfblearn", "data" : {"id" : input.attr("data-id"), "status": input.attr("data-status")}}));
  694. }
  695. function rfbForget() {
  696. var parent = $(this).parents(".pure-g");
  697. var input = $("input", parent);
  698. websock.send(JSON.stringify({"action": "rfbforget", "data" : {"id" : input.attr("data-id"), "status": input.attr("data-status")}}));
  699. }
  700. function rfbSend() {
  701. var parent = $(this).parents(".pure-g");
  702. var input = $("input", parent);
  703. websock.send(JSON.stringify({"action": "rfbsend", "data" : {"id" : input.attr("data-id"), "status": input.attr("data-status"), "data": input.val()}}));
  704. }
  705. // -----------------------------------------------------------------------------
  706. // Processing
  707. // -----------------------------------------------------------------------------
  708. function processData(data) {
  709. // title
  710. if ("app_name" in data) {
  711. var title = data.app_name;
  712. if ("app_version" in data) {
  713. title = title + " " + data.app_version;
  714. }
  715. $("span[name=title]").html(title);
  716. if ("hostname" in data) {
  717. title = data.hostname + " - " + title;
  718. }
  719. document.title = title;
  720. }
  721. Object.keys(data).forEach(function(key) {
  722. var i;
  723. // ---------------------------------------------------------------------
  724. // Web mode
  725. // ---------------------------------------------------------------------
  726. if (key ==="webMode") {
  727. password = data.webMode == 1;
  728. $("#layout").toggle(data.webMode === 0);
  729. $("#password").toggle(data.webMode === 1);
  730. }
  731. // ---------------------------------------------------------------------
  732. // Actions
  733. // ---------------------------------------------------------------------
  734. if (key === "action") {
  735. if (data.action === "reload") doReload(1000);
  736. return;
  737. }
  738. // ---------------------------------------------------------------------
  739. // RFBridge
  740. // ---------------------------------------------------------------------
  741. if (key === "rfbCount") {
  742. for (i=0; i<data.rfbCount; i++) addRfbNode();
  743. return;
  744. }
  745. if (key === "rfbrawVisible") {
  746. $("input[name='rfbcode']").attr("maxlength", 116);
  747. }
  748. if (key === "rfb") {
  749. var nodes = data.rfb;
  750. for (i in nodes) {
  751. var node = nodes[i];
  752. $("input[name='rfbcode'][data-id='" + node["id"] + "'][data-status='" + node["status"] + "']").val(node["data"]);
  753. }
  754. return;
  755. }
  756. // ---------------------------------------------------------------------
  757. // Lights
  758. // ---------------------------------------------------------------------
  759. if (key === "rgb") {
  760. initColorRGB();
  761. $("input[name='color']").wheelColorPicker("setValue", data[key], true);
  762. return;
  763. }
  764. if (key === "hsv") {
  765. initColorHSV();
  766. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  767. var chunks = data[key].split(",");
  768. var obj = {};
  769. obj.h = chunks[0] / 360;
  770. obj.s = chunks[1] / 100;
  771. obj.v = chunks[2] / 100;
  772. $("input[name='color']").wheelColorPicker("setColor", obj);
  773. return;
  774. }
  775. if (key === "brightness") {
  776. $("#brightness").val(data[key]);
  777. $("span.brightness").html(data[key]);
  778. return;
  779. }
  780. if (key === "channels") {
  781. var len = data[key].length;
  782. initChannels(len);
  783. for (i=0; i<len; i++) {
  784. $("input.slider[data=" + i + "]").val(data[key][i]);
  785. $("span.slider[data=" + i + "]").html(data[key][i]);
  786. }
  787. return;
  788. }
  789. if (key === "useWhite") {
  790. useWhite = data[key];
  791. }
  792. // ---------------------------------------------------------------------
  793. // Sensors & Magnitudes
  794. // ---------------------------------------------------------------------
  795. if (key === "magnitudes") {
  796. initMagnitudes(data[key]);
  797. for (i=0; i<data[key].length; i++) {
  798. var error = data[key][i].error || 0;
  799. var text = (error === 0) ?
  800. data[key][i].value + data[key][i].units :
  801. magnitudeError(error);
  802. $("input[name='magnitude'][data='" + i + "']").val(text);
  803. }
  804. return;
  805. }
  806. if (key === "manifest") {
  807. manifest = data[key];
  808. }
  809. // ---------------------------------------------------------------------
  810. // WiFi
  811. // ---------------------------------------------------------------------
  812. if (key === "maxNetworks") {
  813. maxNetworks = parseInt(data.maxNetworks, 10);
  814. return;
  815. }
  816. if (key === "wifi") {
  817. for (i in data.wifi) {
  818. var nwk_line = addNetwork();
  819. var wifi = data.wifi[i];
  820. Object.keys(wifi).forEach(function(key) {
  821. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  822. });
  823. }
  824. return;
  825. }
  826. if (key == "scanResult") {
  827. $("div.scan.loading").hide();
  828. }
  829. // -----------------------------------------------------------------------------
  830. // Relays scheduler
  831. // -----------------------------------------------------------------------------
  832. if (key === "maxSchedules") {
  833. maxSchedules = parseInt(data.maxSchedules, 10);
  834. return;
  835. }
  836. if (key === "schedule") {
  837. for (i in data.schedule) {
  838. var sch_line = addSchedule();
  839. var schedule = data.schedule[i];
  840. Object.keys(schedule).forEach(function(key) {
  841. $("input[name='" + key + "']", sch_line).val(schedule[key]);
  842. $("select[name='" + key + "']", sch_line).prop("value", schedule[key]);
  843. $(":checkbox", sch_line).prop("checked", schedule[key]);
  844. });
  845. }
  846. return;
  847. }
  848. // ---------------------------------------------------------------------
  849. // Relays
  850. // ---------------------------------------------------------------------
  851. if (key === "relayStatus") {
  852. initRelays(data[key]);
  853. for (i in data[key]) {
  854. // Set the status for each relay
  855. $("input.relayStatus[data='" + i + "']").
  856. prop("checked", data[key][i]).
  857. iphoneStyle("refresh");
  858. }
  859. return;
  860. }
  861. // Relay configuration
  862. if (key === "relayConfig") {
  863. initRelayConfig(data[key]);
  864. return;
  865. }
  866. // ---------------------------------------------------------------------
  867. // Domoticz
  868. // ---------------------------------------------------------------------
  869. // Domoticz - Relays
  870. if (key === "dczRelays") {
  871. createRelayList(data[key], "dczRelays", "dczRelayTemplate");
  872. return;
  873. }
  874. // Domoticz - Magnitudes
  875. if (key === "dczMagnitudes") {
  876. createMagnitudeList(data[key], "dczMagnitudes", "dczMagnitudeTemplate");
  877. return;
  878. }
  879. // ---------------------------------------------------------------------
  880. // Thingspeak
  881. // ---------------------------------------------------------------------
  882. // Thingspeak - Relays
  883. if (key === "tspkRelays") {
  884. createRelayList(data[key], "tspkRelays", "tspkRelayTemplate");
  885. return;
  886. }
  887. // Thingspeak - Magnitudes
  888. if (key === "tspkMagnitudes") {
  889. createMagnitudeList(data[key], "tspkMagnitudes", "tspkMagnitudeTemplate");
  890. return;
  891. }
  892. // ---------------------------------------------------------------------
  893. // General
  894. // ---------------------------------------------------------------------
  895. // Messages
  896. if (key === "message") {
  897. window.alert(messages[data.message]);
  898. return;
  899. }
  900. // Enable options
  901. var position = key.indexOf("Visible");
  902. if (position > 0 && position === key.length - 7) {
  903. var module = key.slice(0,-7);
  904. $(".module-" + module).show();
  905. return;
  906. }
  907. if (key === "now") {
  908. now = data[key];
  909. ago = 0;
  910. return;
  911. }
  912. if (key == "free_size") {
  913. free_size = parseInt(data[key]);
  914. }
  915. // Pre-process
  916. if (key === "network") {
  917. data.network = data.network.toUpperCase();
  918. }
  919. if (key === "mqttStatus") {
  920. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  921. }
  922. if (key === "ntpStatus") {
  923. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  924. }
  925. if (key === "uptime") {
  926. var uptime = parseInt(data[key], 10);
  927. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  928. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  929. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  930. var days = uptime;
  931. data[key] = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  932. }
  933. // ---------------------------------------------------------------------
  934. // Matching
  935. // ---------------------------------------------------------------------
  936. var pre;
  937. var post;
  938. // Look for INPUTs
  939. var input = $("input[name='" + key + "']");
  940. if (input.length > 0) {
  941. if (input.attr("type") === "checkbox") {
  942. input.
  943. prop("checked", data[key]).
  944. iphoneStyle("refresh");
  945. } else if (input.attr("type") === "radio") {
  946. input.val([data[key]]);
  947. } else {
  948. pre = input.attr("pre") || "";
  949. post = input.attr("post") || "";
  950. input.val(pre + data[key] + post);
  951. }
  952. }
  953. // Look for SPANs
  954. var span = $("span[name='" + key + "']");
  955. if (span.length > 0) {
  956. pre = span.attr("pre") || "";
  957. post = span.attr("post") || "";
  958. span.html(pre + data[key] + post);
  959. }
  960. // Look for SELECTs
  961. var select = $("select[name='" + key + "']");
  962. if (select.length > 0) {
  963. select.val(data[key]);
  964. }
  965. });
  966. // Auto generate an APIKey if none defined yet
  967. if ($("input[name='apiKey']").val() === "") {
  968. generateAPIKey();
  969. }
  970. resetOriginals();
  971. }
  972. function hasChanged() {
  973. var newValue, originalValue;
  974. if ($(this).attr("type") === "checkbox") {
  975. newValue = $(this).prop("checked");
  976. originalValue = $(this).attr("original") == "true";
  977. } else {
  978. newValue = $(this).val();
  979. originalValue = $(this).attr("original");
  980. }
  981. var hasChanged = $(this).attr("hasChanged") || 0;
  982. var action = $(this).attr("action");
  983. if (typeof originalValue === "undefined") { return; }
  984. if (action === "none") { return; }
  985. if (newValue !== originalValue) {
  986. if (hasChanged === 0) {
  987. ++numChanged;
  988. if (action === "reconnect") ++numReconnect;
  989. if (action === "reboot") ++numReboot;
  990. if (action === "reload") ++numReload;
  991. $(this).attr("hasChanged", 1);
  992. }
  993. } else {
  994. if (hasChanged === 1) {
  995. --numChanged;
  996. if (action === "reconnect") --numReconnect;
  997. if (action === "reboot") --numReboot;
  998. if (action === "reload") --numReload;
  999. $(this).attr("hasChanged", 0);
  1000. }
  1001. }
  1002. }
  1003. // -----------------------------------------------------------------------------
  1004. // Init & connect
  1005. // -----------------------------------------------------------------------------
  1006. function connect(host) {
  1007. if (typeof host === "undefined") {
  1008. host = window.location.href.replace("#", "");
  1009. } else {
  1010. if (host.indexOf("http") !== 0) {
  1011. host = "http://" + host + "/";
  1012. }
  1013. }
  1014. if (host.indexOf("http") !== 0) {return;}
  1015. webhost = host;
  1016. wshost = host.replace("http", "ws") + "ws";
  1017. if (websock) websock.close();
  1018. websock = new WebSocket(wshost);
  1019. websock.onmessage = function(evt) {
  1020. var data = getJson(evt.data);
  1021. if (data) processData(data);
  1022. };
  1023. }
  1024. $(function() {
  1025. initMessages();
  1026. loadTimeZones();
  1027. setInterval(function() { keepTime(); }, 1000);
  1028. $("#menuLink").on("click", toggleMenu);
  1029. $(".pure-menu-link").on("click", showPanel);
  1030. $("progress").attr({ value: 0, max: 100 });
  1031. $(".button-update").on("click", doUpdate);
  1032. $(".button-update-password").on("click", doUpdatePassword);
  1033. $(".button-reboot").on("click", doReboot);
  1034. $(".button-reconnect").on("click", doReconnect);
  1035. $(".button-wifi-scan").on("click", doScan);
  1036. $(".button-settings-backup").on("click", doBackup);
  1037. $(".button-settings-restore").on("click", doRestore);
  1038. $("#uploader").on("change", onFileUpload);
  1039. $(".button-upgrade").on("click", doUpgrade);
  1040. $(".button-apikey").on("click", generateAPIKey);
  1041. $(".button-upgrade-browse").on("click", function() {
  1042. $("input[name='upgrade']")[0].click();
  1043. return false;
  1044. });
  1045. $("input[name='upgrade']").change(function (){
  1046. var file = this.files[0];
  1047. $("input[name='filename']").val(file.name);
  1048. });
  1049. $(".button-add-network").on("click", function() {
  1050. $(".more", addNetwork()).toggle();
  1051. });
  1052. $(".button-add-schedule").on("click", addSchedule);
  1053. $(document).on("change", "input", hasChanged);
  1054. $(document).on("change", "select", hasChanged);
  1055. connect();
  1056. });