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.

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