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.

1289 lines
37 KiB

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