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.

1335 lines
38 KiB

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