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.

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