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.

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