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
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var maxSchedules;
  5. var messages = [];
  6. var free_size = 0;
  7. var webhost;
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var useWhite = false;
  13. var now = 0;
  14. var ago = 0;
  15. // -----------------------------------------------------------------------------
  16. // Messages
  17. // -----------------------------------------------------------------------------
  18. function initMessages() {
  19. messages[1] = "Remote update started";
  20. messages[2] = "OTA update started";
  21. messages[3] = "Error parsing data!";
  22. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  23. messages[5] = "Changes saved. You should reboot your board now";
  24. messages[7] = "Passwords do not match!";
  25. messages[8] = "Changes saved";
  26. messages[9] = "No changes detected";
  27. messages[10] = "Session expired, please reload page...";
  28. }
  29. function sensorName(id) {
  30. var names = [
  31. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  32. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  33. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  34. "SHT3X I2C", "BH1750"
  35. ];
  36. if (1 <= id && id <= names.length) {
  37. return names[id - 1];
  38. }
  39. return null;
  40. }
  41. function magnitudeType(type) {
  42. var types = [
  43. "Temperature", "Humidity", "Pressure",
  44. "Current", "Voltage", "Active Power", "Apparent Power",
  45. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  46. "Analog", "Digital", "Events",
  47. "PM1.0", "PM2.5", "PM10", "CO2", "Lux"
  48. ];
  49. if (1 <= type && type <= types.length) {
  50. return types[type - 1];
  51. }
  52. return null;
  53. }
  54. function magnitudeError(error) {
  55. var errors = [
  56. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  57. "Data Error", "I2C Error", "GPIO Error"
  58. ];
  59. if (0 <= error && error < errors.length) {
  60. return errors[error];
  61. }
  62. return "Error " + error;
  63. }
  64. // -----------------------------------------------------------------------------
  65. // Utils
  66. // -----------------------------------------------------------------------------
  67. function keepTime() {
  68. if (0 === now) { return; }
  69. var date = new Date(now * 1000);
  70. var text = date.toISOString().substring(0, 19).replace("T", " ");
  71. $("input[name='now']").val(text);
  72. $("span[name='now']").html(text);
  73. $("span[name='ago']").html(ago);
  74. now++;
  75. ago++;
  76. }
  77. // http://www.the-art-of-web.com/javascript/validate-password/
  78. function checkPassword(str) {
  79. // at least one lowercase and one uppercase letter or number
  80. // at least five characters (letters, numbers or special characters)
  81. var re = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{5,}$/;
  82. return re.test(str);
  83. }
  84. function zeroPad(number, positions) {
  85. var zeros = "";
  86. for (var i = 0; i < positions; i++) {
  87. zeros += "0";
  88. }
  89. return (zeros + number).slice(-positions);
  90. }
  91. function loadTimeZones() {
  92. var time_zones = [
  93. -720, -660, -600, -570, -540,
  94. -480, -420, -360, -300, -240,
  95. -210, -180, -120, -60, 0,
  96. 60, 120, 180, 210, 240,
  97. 270, 300, 330, 345, 360,
  98. 390, 420, 480, 510, 525,
  99. 540, 570, 600, 630, 660,
  100. 720, 765, 780, 840
  101. ];
  102. for (var i in time_zones) {
  103. var value = time_zones[i];
  104. var offset = value >= 0 ? value : -value;
  105. var text = "GMT" + (value >= 0 ? "+" : "-") +
  106. zeroPad(parseInt(offset / 60, 10), 2) + ":" +
  107. zeroPad(offset % 60, 2);
  108. $("select[name='ntpOffset']").append(
  109. $("<option></option>").
  110. attr("value",value).
  111. text(text));
  112. }
  113. }
  114. function validateForm(form) {
  115. // password
  116. var adminPass1 = $("input[name='adminPass']", form).first().val();
  117. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  118. alert("The password you have entered is not valid, it must have at least 5 characters, 1 lowercase and 1 uppercase or number!");
  119. return false;
  120. }
  121. var adminPass2 = $("input[name='adminPass']", form).last().val();
  122. if (adminPass1 !== adminPass2) {
  123. alert("Passwords are different!");
  124. return false;
  125. }
  126. return true;
  127. }
  128. function getValue(element) {
  129. if ($(element).attr("type") === "checkbox") {
  130. return $(element).is(":checked") ? 1 : 0;
  131. } else if ($(element).attr("type") === "radio") {
  132. if (!$(element).is(":checked")) {
  133. return null;
  134. }
  135. }
  136. return $(element).val();
  137. }
  138. function addValue(data, name, value) {
  139. // These fields will always be a list of values
  140. var is_group = [
  141. "ssid", "pass", "gw", "mask", "ip", "dns",
  142. "schEnabled", "schSwitch","schAction","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. function doHAConfig() {
  417. $("#haConfig").html("");
  418. sendAction("haconfig", {});
  419. return false;
  420. }
  421. // -----------------------------------------------------------------------------
  422. // Visualization
  423. // -----------------------------------------------------------------------------
  424. function toggleMenu() {
  425. $("#layout").toggleClass("active");
  426. $("#menu").toggleClass("active");
  427. $("#menuLink").toggleClass("active");
  428. }
  429. function showPanel() {
  430. $(".panel").hide();
  431. $("#" + $(this).attr("data")).show();
  432. if ($("#layout").hasClass("active")) { toggleMenu(); }
  433. $("input[type='checkbox']").
  434. iphoneStyle("calculateDimensions").
  435. iphoneStyle("refresh");
  436. }
  437. // -----------------------------------------------------------------------------
  438. // Relays & magnitudes mapping
  439. // -----------------------------------------------------------------------------
  440. function createRelayList(data, container, template_name) {
  441. var current = $("#" + container + " > div").length;
  442. if (current > 0) { return; }
  443. var template = $("#" + template_name + " .pure-g")[0];
  444. for (var i in data) {
  445. var line = $(template).clone();
  446. $("label", line).html("Switch #" + i);
  447. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  448. line.appendTo("#" + container);
  449. }
  450. }
  451. function createMagnitudeList(data, container, template_name) {
  452. var current = $("#" + container + " > div").length;
  453. if (current > 0) { return; }
  454. var template = $("#" + template_name + " .pure-g")[0];
  455. for (var i in data) {
  456. var magnitude = data[i];
  457. var line = $(template).clone();
  458. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  459. $("div.hint", line).html(magnitude.name);
  460. $("input", line).attr("tabindex", 40 + i).val(magnitude.idx);
  461. line.appendTo("#" + container);
  462. }
  463. }
  464. // -----------------------------------------------------------------------------
  465. // Wifi
  466. // -----------------------------------------------------------------------------
  467. function delNetwork() {
  468. var parent = $(this).parents(".pure-g");
  469. $(parent).remove();
  470. }
  471. function moreNetwork() {
  472. var parent = $(this).parents(".pure-g");
  473. $(".more", parent).toggle();
  474. }
  475. function addNetwork() {
  476. var numNetworks = $("#networks > div").length;
  477. if (numNetworks >= maxNetworks) {
  478. alert("Max number of networks reached");
  479. return null;
  480. }
  481. var tabindex = 200 + numNetworks * 10;
  482. var template = $("#networkTemplate").children();
  483. var line = $(template).clone();
  484. $(line).find("input").each(function() {
  485. $(this).attr("tabindex", tabindex);
  486. tabindex++;
  487. });
  488. $(line).find(".button-del-network").on("click", delNetwork);
  489. $(line).find(".button-more-network").on("click", moreNetwork);
  490. line.appendTo("#networks");
  491. return line;
  492. }
  493. // -----------------------------------------------------------------------------
  494. // Relays scheduler
  495. // -----------------------------------------------------------------------------
  496. function delSchedule() {
  497. var parent = $(this).parents(".pure-g");
  498. $(parent).remove();
  499. }
  500. function moreSchedule() {
  501. var parent = $(this).parents(".pure-g");
  502. $("div.more", parent).toggle();
  503. }
  504. function addSchedule() {
  505. var numSchedules = $("#schedules > div").length;
  506. if (numSchedules >= maxSchedules) {
  507. alert("Max number of schedules reached");
  508. return null;
  509. }
  510. var tabindex = 200 + numSchedules * 10;
  511. var template = $("#scheduleTemplate").children();
  512. var line = $(template).clone();
  513. $(line).find("input").each(function() {
  514. $(this).attr("tabindex", tabindex);
  515. tabindex++;
  516. });
  517. $(line).find(".button-del-schedule").on("click", delSchedule);
  518. $(line).find(".button-more-schedule").on("click", moreSchedule);
  519. line.appendTo("#schedules");
  520. return line;
  521. }
  522. // -----------------------------------------------------------------------------
  523. // Relays
  524. // -----------------------------------------------------------------------------
  525. function initRelays(data) {
  526. var current = $("#relays > div").length;
  527. if (current > 0) { return; }
  528. var template = $("#relayTemplate .pure-g")[0];
  529. for (var i=0; i<data.length; i++) {
  530. // Add relay fields
  531. var line = $(template).clone();
  532. $(".id", line).html(i);
  533. $("input", line).attr("data", i);
  534. line.appendTo("#relays");
  535. $(":checkbox", line).iphoneStyle({
  536. onChange: doToggle,
  537. resizeContainer: true,
  538. resizeHandle: true,
  539. checkedLabel: "ON",
  540. uncheckedLabel: "OFF"
  541. });
  542. // Populate the relay SELECTs
  543. $("select.isrelay").append(
  544. $("<option></option>").attr("value",i).text("Switch #" + i));
  545. }
  546. }
  547. function initRelayConfig(data) {
  548. var current = $("#relayConfig > div").length;
  549. if (current > 0) { return; }
  550. var template = $("#relayConfigTemplate").children();
  551. for (var i in data) {
  552. var relay = data[i];
  553. var line = $(template).clone();
  554. $("span.gpio", line).html(relay.gpio);
  555. $("span.id", line).html(i);
  556. $("select[name='relayBoot']", line).val(relay.boot);
  557. $("select[name='relayPulse']", line).val(relay.pulse);
  558. $("input[name='relayTime']", line).val(relay.pulse_ms);
  559. $("input[name='mqttGroup']", line).val(relay.group);
  560. $("select[name='mqttGroupInv']", line).val(relay.group_inv);
  561. line.appendTo("#relayConfig");
  562. }
  563. }
  564. // -----------------------------------------------------------------------------
  565. // Sensors & Magnitudes
  566. // -----------------------------------------------------------------------------
  567. function initMagnitudes(data) {
  568. // check if already initialized
  569. var done = $("#magnitudes > div").length;
  570. if (done > 0) { return; }
  571. // add templates
  572. var template = $("#magnitudeTemplate").children();
  573. for (var i in data) {
  574. var magnitude = data[i];
  575. var line = $(template).clone();
  576. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  577. $("div.hint", line).html(magnitude.description);
  578. $("input", line).attr("data", i);
  579. line.appendTo("#magnitudes");
  580. }
  581. }
  582. // -----------------------------------------------------------------------------
  583. // Lights
  584. // -----------------------------------------------------------------------------
  585. function initColorRGB() {
  586. // check if already initialized
  587. var done = $("#colors > div").length;
  588. if (done > 0) { return; }
  589. // add template
  590. var template = $("#colorRGBTemplate").children();
  591. var line = $(template).clone();
  592. line.appendTo("#colors");
  593. // init color wheel
  594. $("input[name='color']").wheelColorPicker({
  595. sliders: "wrgbp"
  596. }).on("sliderup", function() {
  597. var value = $(this).wheelColorPicker("getValue", "css");
  598. sendAction("color", {rgb: value});
  599. });
  600. // init bright slider
  601. $("#brightness").on("change", function() {
  602. var value = $(this).val();
  603. var parent = $(this).parents(".pure-g");
  604. $("span", parent).html(value);
  605. sendAction("color", {brightness: value});
  606. });
  607. }
  608. function initColorHSV() {
  609. // check if already initialized
  610. var done = $("#colors > div").length;
  611. if (done > 0) { return; }
  612. // add template
  613. var template = $("#colorHSVTemplate").children();
  614. var line = $(template).clone();
  615. line.appendTo("#colors");
  616. // init color wheel
  617. $("input[name='color']").wheelColorPicker({
  618. sliders: "whsvp"
  619. }).on("sliderup", function() {
  620. var color = $(this).wheelColorPicker("getColor");
  621. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  622. sendAction("color", {hsv: value});
  623. });
  624. }
  625. function initChannels(num) {
  626. // check if already initialized
  627. var done = $("#channels > div").length > 0;
  628. if (done) { return; }
  629. // does it have color channels?
  630. var colors = $("#colors > div").length > 0;
  631. // calculate channels to create
  632. var max = num;
  633. if (colors) {
  634. max = num % 3;
  635. if ((max > 0) & useWhite) {
  636. max--;
  637. }
  638. }
  639. var start = num - max;
  640. var onChannelSliderChange = function() {
  641. var id = $(this).attr("data");
  642. var value = $(this).val();
  643. var parent = $(this).parents(".pure-g");
  644. $("span", parent).html(value);
  645. sendAction("channel", {id: id, value: value});
  646. };
  647. // add templates
  648. var template = $("#channelTemplate").children();
  649. for (var i=0; i<max; i++) {
  650. var channel_id = start + i;
  651. var line = $(template).clone();
  652. $("span.slider", line).attr("data", channel_id);
  653. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  654. $("label", line).html("Channel " + (channel_id + 1));
  655. line.appendTo("#channels");
  656. }
  657. }
  658. // -----------------------------------------------------------------------------
  659. // RFBridge
  660. // -----------------------------------------------------------------------------
  661. function rfbLearn() {
  662. var parent = $(this).parents(".pure-g");
  663. var input = $("input", parent);
  664. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  665. }
  666. function rfbForget() {
  667. var parent = $(this).parents(".pure-g");
  668. var input = $("input", parent);
  669. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  670. }
  671. function rfbSend() {
  672. var parent = $(this).parents(".pure-g");
  673. var input = $("input", parent);
  674. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  675. }
  676. function addRfbNode() {
  677. var numNodes = $("#rfbNodes > legend").length;
  678. var template = $("#rfbNodeTemplate").children();
  679. var line = $(template).clone();
  680. var status = true;
  681. $("span", line).html(numNodes);
  682. $(line).find("input").each(function() {
  683. $(this).attr("data-id", numNodes);
  684. $(this).attr("data-status", status ? 1 : 0);
  685. status = !status;
  686. });
  687. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  688. $(line).find(".button-rfb-forget").on("click", rfbForget);
  689. $(line).find(".button-rfb-send").on("click", rfbSend);
  690. line.appendTo("#rfbNodes");
  691. return line;
  692. }
  693. // -----------------------------------------------------------------------------
  694. // Processing
  695. // -----------------------------------------------------------------------------
  696. function processData(data) {
  697. // title
  698. if ("app_name" in data) {
  699. var title = data.app_name;
  700. if ("app_version" in data) {
  701. title = title + " " + data.app_version;
  702. }
  703. $("span[name=title]").html(title);
  704. if ("hostname" in data) {
  705. title = data.hostname + " - " + title;
  706. }
  707. document.title = title;
  708. }
  709. Object.keys(data).forEach(function(key) {
  710. var i;
  711. var value = data[key];
  712. // ---------------------------------------------------------------------
  713. // Web mode
  714. // ---------------------------------------------------------------------
  715. if ("webMode" === key) {
  716. password = (1 === value);
  717. $("#layout").toggle(!password);
  718. $("#password").toggle(password);
  719. }
  720. // ---------------------------------------------------------------------
  721. // Actions
  722. // ---------------------------------------------------------------------
  723. if ("action" === key) {
  724. if ("reload" === data.action) { doReload(1000); }
  725. return;
  726. }
  727. // ---------------------------------------------------------------------
  728. // RFBridge
  729. // ---------------------------------------------------------------------
  730. if ("rfbCount" === key) {
  731. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  732. return;
  733. }
  734. if ("rfbrawVisible" === key) {
  735. $("input[name='rfbcode']").attr("maxlength", 116);
  736. }
  737. if ("rfb" === key) {
  738. var nodes = data.rfb;
  739. for (i in nodes) {
  740. var node = nodes[i];
  741. $("input[name='rfbcode'][data-id='" + node.id + "'][data-status='" + node.status + "']").val(node.data);
  742. }
  743. return;
  744. }
  745. // ---------------------------------------------------------------------
  746. // Lights
  747. // ---------------------------------------------------------------------
  748. if ("rgb" === key) {
  749. initColorRGB();
  750. $("input[name='color']").wheelColorPicker("setValue", value, true);
  751. return;
  752. }
  753. if ("hsv" === key) {
  754. initColorHSV();
  755. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  756. var chunks = value.split(",");
  757. var obj = {};
  758. obj.h = chunks[0] / 360;
  759. obj.s = chunks[1] / 100;
  760. obj.v = chunks[2] / 100;
  761. $("input[name='color']").wheelColorPicker("setColor", obj);
  762. return;
  763. }
  764. if ("brightness" === key) {
  765. $("#brightness").val(value);
  766. $("span.brightness").html(value);
  767. return;
  768. }
  769. if ("channels" === key) {
  770. var len = value.length;
  771. initChannels(len);
  772. for (i in value) {
  773. var ch = value[i];
  774. $("input.slider[data=" + i + "]").val(ch);
  775. $("span.slider[data=" + i + "]").html(ch);
  776. }
  777. return;
  778. }
  779. if ("useWhite" === key) {
  780. useWhite = value;
  781. }
  782. // ---------------------------------------------------------------------
  783. // Sensors & Magnitudes
  784. // ---------------------------------------------------------------------
  785. if ("magnitudes" === key) {
  786. initMagnitudes(value);
  787. for (i in value) {
  788. var magnitude = value[i];
  789. var error = magnitude.error || 0;
  790. var text = (0 === error) ?
  791. magnitude.value + magnitude.units :
  792. magnitudeError(error);
  793. $("input[name='magnitude'][data='" + i + "']").val(text);
  794. }
  795. return;
  796. }
  797. // ---------------------------------------------------------------------
  798. // WiFi
  799. // ---------------------------------------------------------------------
  800. if ("maxNetworks" === key) {
  801. maxNetworks = parseInt(value, 10);
  802. return;
  803. }
  804. if ("wifi" === key) {
  805. for (i in value) {
  806. var wifi = value[i];
  807. var nwk_line = addNetwork();
  808. Object.keys(wifi).forEach(function(key) {
  809. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  810. });
  811. }
  812. return;
  813. }
  814. if ("scanResult" === key) {
  815. $("div.scan.loading").hide();
  816. }
  817. // -----------------------------------------------------------------------------
  818. // Relays scheduler
  819. // -----------------------------------------------------------------------------
  820. if ("maxSchedules" === key) {
  821. maxSchedules = parseInt(value, 10);
  822. return;
  823. }
  824. if ("schedule" === key) {
  825. for (i in value) {
  826. var schedule = value[i];
  827. var sch_line = addSchedule();
  828. Object.keys(schedule).forEach(function(key) {
  829. var sch_value = schedule[key];
  830. $("input[name='" + key + "']", sch_line).val(sch_value);
  831. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  832. $(":checkbox[name='" + key + "']", sch_line).
  833. prop("checked", sch_value).
  834. iphoneStyle("refresh");
  835. });
  836. }
  837. return;
  838. }
  839. // ---------------------------------------------------------------------
  840. // Relays
  841. // ---------------------------------------------------------------------
  842. if ("relayStatus" === key) {
  843. initRelays(value);
  844. for (i in value) {
  845. // Set the status for each relay
  846. $("input.relayStatus[data='" + i + "']").
  847. prop("checked", value[i]).
  848. iphoneStyle("refresh");
  849. }
  850. return;
  851. }
  852. // Relay configuration
  853. if ("relayConfig" === key) {
  854. initRelayConfig(value);
  855. return;
  856. }
  857. // ---------------------------------------------------------------------
  858. // Domoticz
  859. // ---------------------------------------------------------------------
  860. // Domoticz - Relays
  861. if ("dczRelays" === key) {
  862. createRelayList(value, "dczRelays", "dczRelayTemplate");
  863. return;
  864. }
  865. // Domoticz - Magnitudes
  866. if ("dczMagnitudes" === key) {
  867. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  868. return;
  869. }
  870. // ---------------------------------------------------------------------
  871. // Thingspeak
  872. // ---------------------------------------------------------------------
  873. // Thingspeak - Relays
  874. if ("tspkRelays" === key) {
  875. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  876. return;
  877. }
  878. // Thingspeak - Magnitudes
  879. if ("tspkMagnitudes" === key) {
  880. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  881. return;
  882. }
  883. // ---------------------------------------------------------------------
  884. // General
  885. // ---------------------------------------------------------------------
  886. // Messages
  887. if ("message" === key) {
  888. window.alert(messages[value]);
  889. return;
  890. }
  891. // Enable options
  892. var position = key.indexOf("Visible");
  893. if (position > 0 && position === key.length - 7) {
  894. var module = key.slice(0,-7);
  895. $(".module-" + module).show();
  896. return;
  897. }
  898. if ("now" === key) {
  899. now = value;
  900. ago = 0;
  901. return;
  902. }
  903. if ("free_size" === key) {
  904. free_size = parseInt(value, 10);
  905. }
  906. // Pre-process
  907. if ("network" === key) {
  908. value = value.toUpperCase();
  909. }
  910. if ("mqttStatus" === key) {
  911. value = value ? "CONNECTED" : "NOT CONNECTED";
  912. }
  913. if ("ntpStatus" === key) {
  914. value = value ? "SYNC'D" : "NOT SYNC'D";
  915. }
  916. if ("uptime" === key) {
  917. var uptime = parseInt(value, 10);
  918. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  919. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  920. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  921. var days = uptime;
  922. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  923. }
  924. // ---------------------------------------------------------------------
  925. // Matching
  926. // ---------------------------------------------------------------------
  927. var pre;
  928. var post;
  929. // Look for INPUTs
  930. var input = $("input[name='" + key + "']");
  931. if (input.length > 0) {
  932. if (input.attr("type") === "checkbox") {
  933. input.
  934. prop("checked", value).
  935. iphoneStyle("refresh");
  936. } else if (input.attr("type") === "radio") {
  937. input.val([value]);
  938. } else {
  939. pre = input.attr("pre") || "";
  940. post = input.attr("post") || "";
  941. input.val(pre + value + post);
  942. }
  943. }
  944. // Look for SPANs
  945. var span = $("span[name='" + key + "']");
  946. if (span.length > 0) {
  947. pre = span.attr("pre") || "";
  948. post = span.attr("post") || "";
  949. span.html(pre + value + post);
  950. }
  951. // Look for SELECTs
  952. var select = $("select[name='" + key + "']");
  953. if (select.length > 0) {
  954. select.val(value);
  955. }
  956. });
  957. // Auto generate an APIKey if none defined yet
  958. if ($("input[name='apiKey']").val() === "") {
  959. generateAPIKey();
  960. }
  961. resetOriginals();
  962. }
  963. function hasChanged() {
  964. var newValue, originalValue;
  965. if ($(this).attr("type") === "checkbox") {
  966. newValue = $(this).prop("checked");
  967. originalValue = ($(this).attr("original") === "true");
  968. } else {
  969. newValue = $(this).val();
  970. originalValue = $(this).attr("original");
  971. }
  972. var hasChanged = $(this).attr("hasChanged") || 0;
  973. var action = $(this).attr("action");
  974. if (typeof originalValue === "undefined") { return; }
  975. if ("none" === action) { return; }
  976. if (newValue !== originalValue) {
  977. if (0 === hasChanged) {
  978. ++numChanged;
  979. if ("reconnect" === action) { ++numReconnect; }
  980. if ("reboot" === action) { ++numReboot; }
  981. if ("reload" === action) { ++numReload; }
  982. $(this).attr("hasChanged", 1);
  983. }
  984. } else {
  985. if (1 === hasChanged) {
  986. --numChanged;
  987. if ("reconnect" === action) { --numReconnect; }
  988. if ("reboot" === action) { --numReboot; }
  989. if ("reload" === action) { --numReload; }
  990. $(this).attr("hasChanged", 0);
  991. }
  992. }
  993. }
  994. // -----------------------------------------------------------------------------
  995. // Init & connect
  996. // -----------------------------------------------------------------------------
  997. function connect(host) {
  998. if (typeof host === "undefined") {
  999. host = window.location.href.replace("#", "");
  1000. } else {
  1001. if (host.indexOf("http") !== 0) {
  1002. host = "http://" + host + "/";
  1003. }
  1004. }
  1005. if (host.indexOf("http") !== 0) { return; }
  1006. webhost = host;
  1007. wshost = host.replace("http", "ws") + "ws";
  1008. if (websock) { websock.close(); }
  1009. websock = new WebSocket(wshost);
  1010. websock.onmessage = function(evt) {
  1011. var data = getJson(evt.data);
  1012. if (data) { processData(data); }
  1013. };
  1014. }
  1015. $(function() {
  1016. initMessages();
  1017. loadTimeZones();
  1018. setInterval(function() { keepTime(); }, 1000);
  1019. $("#menuLink").on("click", toggleMenu);
  1020. $(".pure-menu-link").on("click", showPanel);
  1021. $("progress").attr({ value: 0, max: 100 });
  1022. $(".button-update").on("click", doUpdate);
  1023. $(".button-update-password").on("click", doUpdatePassword);
  1024. $(".button-reboot").on("click", doReboot);
  1025. $(".button-reconnect").on("click", doReconnect);
  1026. $(".button-wifi-scan").on("click", doScan);
  1027. $(".button-ha-config").on("click", doHAConfig);
  1028. $(".button-settings-backup").on("click", doBackup);
  1029. $(".button-settings-restore").on("click", doRestore);
  1030. $(".button-settings-factory").on("click", doFactoryReset);
  1031. $("#uploader").on("change", onFileUpload);
  1032. $(".button-upgrade").on("click", doUpgrade);
  1033. $(".button-apikey").on("click", generateAPIKey);
  1034. $(".button-upgrade-browse").on("click", function() {
  1035. $("input[name='upgrade']")[0].click();
  1036. return false;
  1037. });
  1038. $("input[name='upgrade']").change(function (){
  1039. var file = this.files[0];
  1040. $("input[name='filename']").val(file.name);
  1041. });
  1042. $(".button-add-network").on("click", function() {
  1043. $(".more", addNetwork()).toggle();
  1044. });
  1045. $(".button-add-schedule").on("click", addSchedule);
  1046. $(document).on("change", "input", hasChanged);
  1047. $(document).on("change", "select", hasChanged);
  1048. connect();
  1049. });