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.

1299 lines
37 KiB

8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
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
7 years ago
6 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var maxSchedules;
  5. var messages = [];
  6. var free_size = 0;
  7. var webhost;
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var useWhite = false;
  13. var 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","schType","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(event) {
  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. template = $("#" + event.data.schType + "ActionTemplate").children();
  500. var actionLine = template.clone();
  501. $(line).find("#schActionDiv").append(actionLine);
  502. $(line).find("input").each(function() {
  503. $(this).attr("tabindex", tabindex);
  504. tabindex++;
  505. });
  506. $(line).find(".button-del-schedule").on("click", delSchedule);
  507. $(line).find(".button-more-schedule").on("click", moreSchedule);
  508. var ena = $(line).find(":checkbox");
  509. ena.prop("checked", false).iphoneStyle("refresh");
  510. line.appendTo("#schedules");
  511. return line;
  512. }
  513. // -----------------------------------------------------------------------------
  514. // Relays
  515. // -----------------------------------------------------------------------------
  516. function initRelays(data) {
  517. var current = $("#relays > div").length;
  518. if (current > 0) { return; }
  519. var template = $("#relayTemplate .pure-g")[0];
  520. for (var i=0; i<data.length; i++) {
  521. // Add relay fields
  522. var line = $(template).clone();
  523. $(".id", line).html(i);
  524. $("input", line).attr("data", i);
  525. line.appendTo("#relays");
  526. $(":checkbox", line).iphoneStyle({
  527. onChange: doToggle,
  528. resizeContainer: true,
  529. resizeHandle: true,
  530. checkedLabel: "ON",
  531. uncheckedLabel: "OFF"
  532. });
  533. // Populate the relay SELECTs
  534. $("select.isrelay").append(
  535. $("<option></option>").attr("value",i).text("Switch #" + i));
  536. }
  537. }
  538. function initRelayConfig(data) {
  539. var current = $("#relayConfig > div").length;
  540. if (current > 0) { return; }
  541. var template = $("#relayConfigTemplate").children();
  542. for (var i in data) {
  543. var relay = data[i];
  544. var line = $(template).clone();
  545. $("span.gpio", line).html(relay.gpio);
  546. $("span.id", line).html(i);
  547. $("select[name='relayBoot']", line).val(relay.boot);
  548. $("select[name='relayPulse']", line).val(relay.pulse);
  549. $("input[name='relayTime']", line).val(relay.pulse_ms);
  550. $("input[name='mqttGroup']", line).val(relay.group);
  551. $("select[name='mqttGroupInv']", line).val(relay.group_inv);
  552. line.appendTo("#relayConfig");
  553. }
  554. }
  555. // -----------------------------------------------------------------------------
  556. // Sensors & Magnitudes
  557. // -----------------------------------------------------------------------------
  558. function initMagnitudes(data) {
  559. // check if already initialized
  560. var done = $("#magnitudes > div").length;
  561. if (done > 0) { return; }
  562. // add templates
  563. var template = $("#magnitudeTemplate").children();
  564. for (var i in data) {
  565. var magnitude = data[i];
  566. var line = $(template).clone();
  567. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  568. $("div.hint", line).html(magnitude.description);
  569. $("input", line).attr("data", i);
  570. line.appendTo("#magnitudes");
  571. }
  572. }
  573. // -----------------------------------------------------------------------------
  574. // Lights
  575. // -----------------------------------------------------------------------------
  576. function initColorRGB() {
  577. // check if already initialized
  578. var done = $("#colors > div").length;
  579. if (done > 0) { return; }
  580. // add template
  581. var template = $("#colorRGBTemplate").children();
  582. var line = $(template).clone();
  583. line.appendTo("#colors");
  584. // init color wheel
  585. $("input[name='color']").wheelColorPicker({
  586. sliders: "wrgbp"
  587. }).on("sliderup", function() {
  588. var value = $(this).wheelColorPicker("getValue", "css");
  589. sendAction("color", {rgb: value});
  590. });
  591. // init bright slider
  592. $("#brightness").on("change", function() {
  593. var value = $(this).val();
  594. var parent = $(this).parents(".pure-g");
  595. $("span", parent).html(value);
  596. sendAction("color", {brightness: value});
  597. });
  598. }
  599. function initColorHSV() {
  600. // check if already initialized
  601. var done = $("#colors > div").length;
  602. if (done > 0) { return; }
  603. // add template
  604. var template = $("#colorHSVTemplate").children();
  605. var line = $(template).clone();
  606. line.appendTo("#colors");
  607. // init color wheel
  608. $("input[name='color']").wheelColorPicker({
  609. sliders: "whsvp"
  610. }).on("sliderup", function() {
  611. var color = $(this).wheelColorPicker("getColor");
  612. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  613. sendAction("color", {hsv: value});
  614. });
  615. }
  616. function initChannels(num) {
  617. // check if already initialized
  618. var done = $("#channels > div").length > 0;
  619. if (done) { return; }
  620. // does it have color channels?
  621. var colors = $("#colors > div").length > 0;
  622. // calculate channels to create
  623. var max = num;
  624. if (colors) {
  625. max = num % 3;
  626. if ((max > 0) & useWhite) {
  627. max--;
  628. }
  629. }
  630. var start = num - max;
  631. var onChannelSliderChange = function() {
  632. var id = $(this).attr("data");
  633. var value = $(this).val();
  634. var parent = $(this).parents(".pure-g");
  635. $("span", parent).html(value);
  636. sendAction("channel", {id: id, value: value});
  637. };
  638. // add templates
  639. var template = $("#channelTemplate").children();
  640. for (var i=0; i<max; i++) {
  641. var channel_id = start + i;
  642. var line = $(template).clone();
  643. $("span.slider", line).attr("data", channel_id);
  644. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  645. $("label", line).html("Channel " + (channel_id + 1));
  646. line.appendTo("#channels");
  647. $("select.islight").append(
  648. $("<option></option>").attr("value",i).text("Light #" + i));
  649. }
  650. }
  651. // -----------------------------------------------------------------------------
  652. // RFBridge
  653. // -----------------------------------------------------------------------------
  654. function rfbLearn() {
  655. var parent = $(this).parents(".pure-g");
  656. var input = $("input", parent);
  657. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  658. }
  659. function rfbForget() {
  660. var parent = $(this).parents(".pure-g");
  661. var input = $("input", parent);
  662. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  663. }
  664. function rfbSend() {
  665. var parent = $(this).parents(".pure-g");
  666. var input = $("input", parent);
  667. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  668. }
  669. function addRfbNode() {
  670. var numNodes = $("#rfbNodes > legend").length;
  671. var template = $("#rfbNodeTemplate").children();
  672. var line = $(template).clone();
  673. var status = true;
  674. $("span", line).html(numNodes);
  675. $(line).find("input").each(function() {
  676. $(this).attr("data-id", numNodes);
  677. $(this).attr("data-status", status ? 1 : 0);
  678. status = !status;
  679. });
  680. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  681. $(line).find(".button-rfb-forget").on("click", rfbForget);
  682. $(line).find(".button-rfb-send").on("click", rfbSend);
  683. line.appendTo("#rfbNodes");
  684. return line;
  685. }
  686. // -----------------------------------------------------------------------------
  687. // Processing
  688. // -----------------------------------------------------------------------------
  689. function processData(data) {
  690. // title
  691. if ("app_name" in data) {
  692. var title = data.app_name;
  693. if ("app_version" in data) {
  694. title = title + " " + data.app_version;
  695. }
  696. $("span[name=title]").html(title);
  697. if ("hostname" in data) {
  698. title = data.hostname + " - " + title;
  699. }
  700. document.title = title;
  701. }
  702. Object.keys(data).forEach(function(key) {
  703. var i;
  704. var value = data[key];
  705. // ---------------------------------------------------------------------
  706. // Web mode
  707. // ---------------------------------------------------------------------
  708. if ("webMode" === key) {
  709. password = (1 === value);
  710. $("#layout").toggle(!password);
  711. $("#password").toggle(password);
  712. }
  713. // ---------------------------------------------------------------------
  714. // Actions
  715. // ---------------------------------------------------------------------
  716. if ("action" === key) {
  717. if ("reload" === data.action) { doReload(1000); }
  718. return;
  719. }
  720. // ---------------------------------------------------------------------
  721. // RFBridge
  722. // ---------------------------------------------------------------------
  723. if ("rfbCount" === key) {
  724. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  725. return;
  726. }
  727. if ("rfbrawVisible" === key) {
  728. $("input[name='rfbcode']").attr("maxlength", 116);
  729. }
  730. if ("rfb" === key) {
  731. var nodes = data.rfb;
  732. for (i in nodes) {
  733. var node = nodes[i];
  734. $("input[name='rfbcode'][data-id='" + node.id + "'][data-status='" + node.status + "']").val(node.data);
  735. }
  736. return;
  737. }
  738. // ---------------------------------------------------------------------
  739. // Lights
  740. // ---------------------------------------------------------------------
  741. if ("rgb" === key) {
  742. initColorRGB();
  743. $("input[name='color']").wheelColorPicker("setValue", value, true);
  744. return;
  745. }
  746. if ("hsv" === key) {
  747. initColorHSV();
  748. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  749. var chunks = value.split(",");
  750. var obj = {};
  751. obj.h = chunks[0] / 360;
  752. obj.s = chunks[1] / 100;
  753. obj.v = chunks[2] / 100;
  754. $("input[name='color']").wheelColorPicker("setColor", obj);
  755. return;
  756. }
  757. if ("brightness" === key) {
  758. $("#brightness").val(value);
  759. $("span.brightness").html(value);
  760. return;
  761. }
  762. if ("channels" === key) {
  763. var len = value.length;
  764. initChannels(len);
  765. for (i in value) {
  766. var ch = value[i];
  767. $("input.slider[data=" + i + "]").val(ch);
  768. $("span.slider[data=" + i + "]").html(ch);
  769. }
  770. return;
  771. }
  772. if ("useWhite" === key) {
  773. useWhite = value;
  774. }
  775. // ---------------------------------------------------------------------
  776. // Sensors & Magnitudes
  777. // ---------------------------------------------------------------------
  778. if ("magnitudes" === key) {
  779. initMagnitudes(value);
  780. for (i in value) {
  781. var magnitude = value[i];
  782. var error = magnitude.error || 0;
  783. var text = (0 === error) ?
  784. magnitude.value + magnitude.units :
  785. magnitudeError(error);
  786. $("input[name='magnitude'][data='" + i + "']").val(text);
  787. }
  788. return;
  789. }
  790. // ---------------------------------------------------------------------
  791. // WiFi
  792. // ---------------------------------------------------------------------
  793. if ("maxNetworks" === key) {
  794. maxNetworks = parseInt(value, 10);
  795. return;
  796. }
  797. if ("wifi" === key) {
  798. for (i in value) {
  799. var wifi = value[i];
  800. var nwk_line = addNetwork();
  801. Object.keys(wifi).forEach(function(key) {
  802. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  803. });
  804. }
  805. return;
  806. }
  807. if ("scanResult" === key) {
  808. $("div.scan.loading").hide();
  809. }
  810. // -----------------------------------------------------------------------------
  811. // Relays scheduler
  812. // -----------------------------------------------------------------------------
  813. if ("maxSchedules" === key) {
  814. maxSchedules = parseInt(value, 10);
  815. return;
  816. }
  817. if ("schedule" === key) {
  818. for (i in value) {
  819. var schedule = value[i];
  820. var sch_line = addSchedule({ data: {schType: schedule['schType'] }});
  821. Object.keys(schedule).forEach(function(key) {
  822. var sch_value = schedule[key];
  823. $("input[name='" + key + "']", sch_line).val(sch_value);
  824. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  825. $(":checkbox[name='" + key + "']", sch_line).
  826. prop("checked", sch_value).
  827. iphoneStyle("refresh");
  828. });
  829. }
  830. return;
  831. }
  832. // ---------------------------------------------------------------------
  833. // Relays
  834. // ---------------------------------------------------------------------
  835. if ("relayStatus" === key) {
  836. initRelays(value);
  837. for (i in value) {
  838. // Set the status for each relay
  839. $("input.relayStatus[data='" + i + "']").
  840. prop("checked", value[i]).
  841. iphoneStyle("refresh");
  842. }
  843. return;
  844. }
  845. // Relay configuration
  846. if ("relayConfig" === key) {
  847. initRelayConfig(value);
  848. return;
  849. }
  850. // ---------------------------------------------------------------------
  851. // Domoticz
  852. // ---------------------------------------------------------------------
  853. // Domoticz - Relays
  854. if ("dczRelays" === key) {
  855. createRelayList(value, "dczRelays", "dczRelayTemplate");
  856. return;
  857. }
  858. // Domoticz - Magnitudes
  859. if ("dczMagnitudes" === key) {
  860. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  861. return;
  862. }
  863. // ---------------------------------------------------------------------
  864. // Thingspeak
  865. // ---------------------------------------------------------------------
  866. // Thingspeak - Relays
  867. if ("tspkRelays" === key) {
  868. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  869. return;
  870. }
  871. // Thingspeak - Magnitudes
  872. if ("tspkMagnitudes" === key) {
  873. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  874. return;
  875. }
  876. // ---------------------------------------------------------------------
  877. // General
  878. // ---------------------------------------------------------------------
  879. // Messages
  880. if ("message" === key) {
  881. window.alert(messages[value]);
  882. return;
  883. }
  884. if ("colorVisible" === key) {
  885. $(".button-add-light-schedule").show();
  886. }
  887. if ("relayVisible" === key) {
  888. $(".button-add-switch-schedule").show();
  889. }
  890. // Enable options
  891. var position = key.indexOf("Visible");
  892. if (position > 0 && position === key.length - 7) {
  893. var module = key.slice(0,-7);
  894. $(".module-" + module).show();
  895. return;
  896. }
  897. if ("now" === key) {
  898. now = value;
  899. ago = 0;
  900. return;
  901. }
  902. if ("free_size" === key) {
  903. free_size = parseInt(value, 10);
  904. }
  905. // Pre-process
  906. if ("network" === key) {
  907. value = value.toUpperCase();
  908. }
  909. if ("mqttStatus" === key) {
  910. value = value ? "CONNECTED" : "NOT CONNECTED";
  911. }
  912. if ("ntpStatus" === key) {
  913. value = value ? "SYNC'D" : "NOT SYNC'D";
  914. }
  915. if ("uptime" === key) {
  916. var uptime = parseInt(value, 10);
  917. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  918. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  919. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  920. var days = uptime;
  921. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  922. }
  923. // ---------------------------------------------------------------------
  924. // Matching
  925. // ---------------------------------------------------------------------
  926. var pre;
  927. var post;
  928. // Look for INPUTs
  929. var input = $("input[name='" + key + "']");
  930. if (input.length > 0) {
  931. if (input.attr("type") === "checkbox") {
  932. input.
  933. prop("checked", value).
  934. iphoneStyle("refresh");
  935. } else if (input.attr("type") === "radio") {
  936. input.val([value]);
  937. } else {
  938. pre = input.attr("pre") || "";
  939. post = input.attr("post") || "";
  940. input.val(pre + value + post);
  941. }
  942. }
  943. // Look for SPANs
  944. var span = $("span[name='" + key + "']");
  945. if (span.length > 0) {
  946. pre = span.attr("pre") || "";
  947. post = span.attr("post") || "";
  948. span.html(pre + value + post);
  949. }
  950. // Look for SELECTs
  951. var select = $("select[name='" + key + "']");
  952. if (select.length > 0) {
  953. select.val(value);
  954. }
  955. });
  956. // Auto generate an APIKey if none defined yet
  957. if ($("input[name='apiKey']").val() === "") {
  958. generateAPIKey();
  959. }
  960. resetOriginals();
  961. }
  962. function hasChanged() {
  963. var newValue, originalValue;
  964. if ($(this).attr("type") === "checkbox") {
  965. newValue = $(this).prop("checked");
  966. originalValue = ($(this).attr("original") === "true");
  967. } else {
  968. newValue = $(this).val();
  969. originalValue = $(this).attr("original");
  970. }
  971. var hasChanged = $(this).attr("hasChanged") || 0;
  972. var action = $(this).attr("action");
  973. if (typeof originalValue === "undefined") { return; }
  974. if ("none" === action) { return; }
  975. if (newValue !== originalValue) {
  976. if (0 === hasChanged) {
  977. ++numChanged;
  978. if ("reconnect" === action) { ++numReconnect; }
  979. if ("reboot" === action) { ++numReboot; }
  980. if ("reload" === action) { ++numReload; }
  981. $(this).attr("hasChanged", 1);
  982. }
  983. } else {
  984. if (1 === hasChanged) {
  985. --numChanged;
  986. if ("reconnect" === action) { --numReconnect; }
  987. if ("reboot" === action) { --numReboot; }
  988. if ("reload" === action) { --numReload; }
  989. $(this).attr("hasChanged", 0);
  990. }
  991. }
  992. }
  993. // -----------------------------------------------------------------------------
  994. // Init & connect
  995. // -----------------------------------------------------------------------------
  996. function connect(host) {
  997. if (typeof host === "undefined") {
  998. host = window.location.href.replace("#", "");
  999. } else {
  1000. if (host.indexOf("http") !== 0) {
  1001. host = "http://" + host + "/";
  1002. }
  1003. }
  1004. if (host.indexOf("http") !== 0) { return; }
  1005. webhost = host;
  1006. wshost = host.replace("http", "ws") + "ws";
  1007. if (websock) { websock.close(); }
  1008. websock = new WebSocket(wshost);
  1009. websock.onmessage = function(evt) {
  1010. var data = getJson(evt.data);
  1011. if (data) { processData(data); }
  1012. };
  1013. }
  1014. $(function() {
  1015. initMessages();
  1016. loadTimeZones();
  1017. setInterval(function() { keepTime(); }, 1000);
  1018. $("#menuLink").on("click", toggleMenu);
  1019. $(".pure-menu-link").on("click", showPanel);
  1020. $("progress").attr({ value: 0, max: 100 });
  1021. $(".button-update").on("click", doUpdate);
  1022. $(".button-update-password").on("click", doUpdatePassword);
  1023. $(".button-reboot").on("click", doReboot);
  1024. $(".button-reconnect").on("click", doReconnect);
  1025. $(".button-wifi-scan").on("click", doScan);
  1026. $(".button-settings-backup").on("click", doBackup);
  1027. $(".button-settings-restore").on("click", doRestore);
  1028. $("#uploader").on("change", onFileUpload);
  1029. $(".button-upgrade").on("click", doUpgrade);
  1030. $(".button-apikey").on("click", generateAPIKey);
  1031. $(".button-upgrade-browse").on("click", function() {
  1032. $("input[name='upgrade']")[0].click();
  1033. return false;
  1034. });
  1035. $("input[name='upgrade']").change(function (){
  1036. var file = this.files[0];
  1037. $("input[name='filename']").val(file.name);
  1038. });
  1039. $(".button-add-network").on("click", function() {
  1040. $(".more", addNetwork()).toggle();
  1041. });
  1042. $(".button-add-switch-schedule").on("click", { schType: "switch" }, addSchedule);
  1043. $(".button-add-light-schedule").on("click", { schType: "light" }, addSchedule);
  1044. $(document).on("change", "input", hasChanged);
  1045. $(document).on("change", "select", hasChanged);
  1046. connect();
  1047. });