Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1296 lines
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
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
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
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
6 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 resetOriginals() {
  207. $("input,select").each(function() {
  208. $(this).attr("original", $(this).val());
  209. });
  210. numReboot = numReconnect = numReload = 0;
  211. }
  212. function doReload(milliseconds) {
  213. setTimeout(function() {
  214. window.location.reload();
  215. }, parseInt(milliseconds, 10));
  216. }
  217. /**
  218. * Check a file object to see if it is a valid firmware image
  219. * The file first byte should be 0xE9
  220. * @param {file} file File object
  221. * @param {Function} callback Function to call back with the result
  222. */
  223. function checkFirmware(file, callback) {
  224. var reader = new FileReader();
  225. reader.onloadend = function(evt) {
  226. if (evt.target.readyState === FileReader.DONE) {
  227. callback(evt.target.result.charCodeAt(0) === 0xE9);
  228. }
  229. };
  230. var blob = file.slice(0, 1);
  231. reader.readAsBinaryString(blob);
  232. }
  233. function doUpgrade() {
  234. var file = $("input[name='upgrade']")[0].files[0];
  235. if (typeof file === "undefined") {
  236. alert("First you have to select a file from your computer.");
  237. return false;
  238. }
  239. if (file.size > free_size) {
  240. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  241. return false;
  242. }
  243. checkFirmware(file, function(ok) {
  244. if (!ok) {
  245. alert("The file does not seem to be a valid firmware image.");
  246. return false;
  247. }
  248. var data = new FormData();
  249. data.append("upgrade", file, file.name);
  250. $.ajax({
  251. // Your server script to process the upload
  252. url: webhost + "upgrade",
  253. type: "POST",
  254. // Form data
  255. data: data,
  256. // Tell jQuery not to process data or worry about content-type
  257. // You *must* include these options!
  258. cache: false,
  259. contentType: false,
  260. processData: false,
  261. success: function(data, text) {
  262. $("#upgrade-progress").hide();
  263. if (data === "OK") {
  264. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  265. doReload(5000);
  266. } else {
  267. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  268. }
  269. },
  270. // Custom XMLHttpRequest
  271. xhr: function() {
  272. $("#upgrade-progress").show();
  273. var myXhr = $.ajaxSettings.xhr();
  274. if (myXhr.upload) {
  275. // For handling the progress of the upload
  276. myXhr.upload.addEventListener("progress", function(e) {
  277. if (e.lengthComputable) {
  278. $("progress").attr({ value: e.loaded, max: e.total });
  279. }
  280. } , false);
  281. }
  282. return myXhr;
  283. }
  284. });
  285. });
  286. return false;
  287. }
  288. function doUpdatePassword() {
  289. var form = $("#formPassword");
  290. if (validateForm(form)) {
  291. var data = getData(form);
  292. websock.send(JSON.stringify({"config": data}));
  293. }
  294. return false;
  295. }
  296. function checkChanges() {
  297. if (numChanged > 0) {
  298. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  299. if (response) {
  300. doUpdate();
  301. }
  302. }
  303. }
  304. function doAction(question, action) {
  305. checkChanges();
  306. if (question) {
  307. var response = window.confirm(question);
  308. if (false === response) {
  309. return false;
  310. }
  311. }
  312. websock.send(JSON.stringify({"action": action}));
  313. doReload(5000);
  314. return false;
  315. }
  316. function doReboot(ask) {
  317. var question = (typeof ask === "undefined" || false === ask) ?
  318. null :
  319. "Are you sure you want to reboot the device?";
  320. return doAction(question, "reboot");
  321. }
  322. function doReconnect(ask) {
  323. var question = (typeof ask === "undefined" || false === ask) ?
  324. null :
  325. "Are you sure you want to disconnect from the current WIFI network?";
  326. return doAction(question, "reconnect");
  327. }
  328. function doUpdate() {
  329. var form = $("#formSave");
  330. if (validateForm(form)) {
  331. // Get data
  332. var data = getData(form);
  333. websock.send(JSON.stringify({"config": data}));
  334. // Empty special fields
  335. $(".pwrExpected").val(0);
  336. $("input[name='pwrResetCalibration']").
  337. prop("checked", false).
  338. iphoneStyle("refresh");
  339. // Change handling
  340. numChanged = 0;
  341. setTimeout(function() {
  342. var response;
  343. if (numReboot > 0) {
  344. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  345. if (response === true) { doReboot(false); }
  346. } else if (numReconnect > 0) {
  347. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  348. if (response === true) { doReconnect(false); }
  349. } else if (numReload > 0) {
  350. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  351. if (response === true) { doReload(0); }
  352. }
  353. resetOriginals();
  354. }, 1000);
  355. }
  356. return false;
  357. }
  358. function doBackup() {
  359. document.getElementById("downloader").src = webhost + "config";
  360. return false;
  361. }
  362. function onFileUpload(event) {
  363. var inputFiles = this.files;
  364. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  365. return false;
  366. }
  367. var inputFile = inputFiles[0];
  368. this.value = "";
  369. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  370. if (response === false) {
  371. return false;
  372. }
  373. var reader = new FileReader();
  374. reader.onload = function(e) {
  375. var data = getJson(e.target.result);
  376. if (data) {
  377. websock.send(JSON.stringify({"action": "restore", "data": data}));
  378. } else {
  379. alert(messages[4]);
  380. }
  381. };
  382. reader.readAsText(inputFile);
  383. return false;
  384. }
  385. function doRestore() {
  386. if (typeof window.FileReader !== "function") {
  387. alert("The file API isn't supported on this browser yet.");
  388. } else {
  389. $("#uploader").click();
  390. }
  391. return false;
  392. }
  393. function doToggle(element, value) {
  394. var relayID = parseInt(element.attr("data"), 10);
  395. websock.send(JSON.stringify({"action": "relay", "data": { "id": relayID, "status": value ? 1 : 0 }}));
  396. return false;
  397. }
  398. function doScan() {
  399. $("#scanResult").html("");
  400. $("div.scan.loading").show();
  401. websock.send(JSON.stringify({"action": "scan", "data": {}}));
  402. return false;
  403. }
  404. // -----------------------------------------------------------------------------
  405. // Visualization
  406. // -----------------------------------------------------------------------------
  407. function toggleMenu() {
  408. $("#layout").toggleClass("active");
  409. $("#menu").toggleClass("active");
  410. $("#menuLink").toggleClass("active");
  411. }
  412. function showPanel() {
  413. $(".panel").hide();
  414. $("#" + $(this).attr("data")).show();
  415. if ($("#layout").hasClass("active")) { toggleMenu(); }
  416. $("input[type='checkbox']").
  417. iphoneStyle("calculateDimensions").
  418. iphoneStyle("refresh");
  419. }
  420. // -----------------------------------------------------------------------------
  421. // Relays & magnitudes mapping
  422. // -----------------------------------------------------------------------------
  423. function createRelayList(data, container, template_name) {
  424. var current = $("#" + container + " > div").length;
  425. if (current > 0) {
  426. return;
  427. }
  428. var template = $("#" + template_name + " .pure-g")[0];
  429. for (var i=0; i<data.length; i++) {
  430. var line = $(template).clone();
  431. $("label", line).html("Switch #" + i);
  432. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  433. line.appendTo("#" + container);
  434. }
  435. }
  436. function createMagnitudeList(data, container, template_name) {
  437. var current = $("#" + container + " > div").length;
  438. if (current > 0) {
  439. return;
  440. }
  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) {
  515. return;
  516. }
  517. var template = $("#relayTemplate .pure-g")[0];
  518. for (var i=0; i<data.length; i++) {
  519. // Add relay fields
  520. var line = $(template).clone();
  521. $(".id", line).html(i);
  522. $("input", line).attr("data", i);
  523. line.appendTo("#relays");
  524. $(":checkbox", line).iphoneStyle({
  525. onChange: doToggle,
  526. resizeContainer: true,
  527. resizeHandle: true,
  528. checkedLabel: "ON",
  529. uncheckedLabel: "OFF"
  530. });
  531. // Populate the relay SELECTs
  532. $("select.isrelay").append(
  533. $("<option></option>").attr("value",i).text("Switch #" + i));
  534. }
  535. }
  536. function initRelayConfig(data) {
  537. var current = $("#relayConfig > div").length;
  538. if (current > 0) {
  539. return;
  540. }
  541. var template = $("#relayConfigTemplate").children();
  542. for (var i=0; i < data.length; i++) {
  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) {
  562. return;
  563. }
  564. // add templates
  565. var template = $("#magnitudeTemplate").children();
  566. for (var i=0; i<data.length; i++) {
  567. var magnitude = data[i];
  568. var line = $(template).clone();
  569. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  570. $("div.hint", line).html(magnitude.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 = (1 === data.webMode);
  723. $("#layout").toggle(!password);
  724. $("#password").toggle(password);
  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. });