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.

1363 lines
39 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
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
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
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", "PZEM004T", "AM2320 I2C", "GUVAS12SD"
  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", "UV"
  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 = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  71. if (13 === keycode) {
  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).prop("checked") ? 1 : 0;
  141. } else if ($(element).attr("type") === "radio") {
  142. if (!$(element).prop("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","schType","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. $("input[name='pwrResetE']").
  353. prop("checked", false).
  354. iphoneStyle("refresh");
  355. // Change handling
  356. numChanged = 0;
  357. setTimeout(function() {
  358. var response;
  359. if (numReboot > 0) {
  360. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  361. if (response) { doReboot(false); }
  362. } else if (numReconnect > 0) {
  363. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  364. if (response) { doReconnect(false); }
  365. } else if (numReload > 0) {
  366. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  367. if (response) { doReload(0); }
  368. }
  369. resetOriginals();
  370. }, 1000);
  371. }
  372. return false;
  373. }
  374. function doBackup() {
  375. document.getElementById("downloader").src = webhost + "config";
  376. return false;
  377. }
  378. function onFileUpload(event) {
  379. var inputFiles = this.files;
  380. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  381. return false;
  382. }
  383. var inputFile = inputFiles[0];
  384. this.value = "";
  385. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  386. if (!response) {
  387. return false;
  388. }
  389. var reader = new FileReader();
  390. reader.onload = function(e) {
  391. var data = getJson(e.target.result);
  392. if (data) {
  393. sendAction("restore", data);
  394. } else {
  395. alert(messages[4]);
  396. }
  397. };
  398. reader.readAsText(inputFile);
  399. return false;
  400. }
  401. function doRestore() {
  402. if (typeof window.FileReader !== "function") {
  403. alert("The file API isn't supported on this browser yet.");
  404. } else {
  405. $("#uploader").click();
  406. }
  407. return false;
  408. }
  409. function doFactoryReset() {
  410. var response = window.confirm("Are you sure you want to restore to factory settings?");
  411. if (response === false) {
  412. return false;
  413. }
  414. websock.send(JSON.stringify({"action": "factory_reset"}));
  415. doReload(5000);
  416. return false;
  417. }
  418. function doToggle(element, value) {
  419. var id = parseInt(element.attr("data"), 10);
  420. sendAction("relay", {id: id, status: value ? 1 : 0 });
  421. return false;
  422. }
  423. function doScan() {
  424. $("#scanResult").html("");
  425. $("div.scan.loading").show();
  426. sendAction("scan", {});
  427. return false;
  428. }
  429. function doHAConfig() {
  430. $("#haConfig").html("");
  431. sendAction("haconfig", {});
  432. return false;
  433. }
  434. function doDebugCommand() {
  435. var el = $("input[name='dbgcmd']");
  436. var command = el.val();
  437. el.val("");
  438. sendAction("dbgcmd", {command: command});
  439. return false;
  440. }
  441. function doDebugClear() {
  442. $("#weblog").text("");
  443. return false;
  444. }
  445. // -----------------------------------------------------------------------------
  446. // Visualization
  447. // -----------------------------------------------------------------------------
  448. function toggleMenu() {
  449. $("#layout").toggleClass("active");
  450. $("#menu").toggleClass("active");
  451. $("#menuLink").toggleClass("active");
  452. }
  453. function showPanel() {
  454. $(".panel").hide();
  455. if ($("#layout").hasClass("active")) { toggleMenu(); }
  456. $("#" + $(this).attr("data")).show().
  457. find("input[type='checkbox']").
  458. iphoneStyle("calculateDimensions").
  459. iphoneStyle("refresh");
  460. }
  461. // -----------------------------------------------------------------------------
  462. // Relays & magnitudes mapping
  463. // -----------------------------------------------------------------------------
  464. function createRelayList(data, container, template_name) {
  465. var current = $("#" + container + " > div").length;
  466. if (current > 0) { return; }
  467. var template = $("#" + template_name + " .pure-g")[0];
  468. for (var i in data) {
  469. var line = $(template).clone();
  470. $("label", line).html("Switch #" + i);
  471. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  472. line.appendTo("#" + container);
  473. }
  474. }
  475. function createMagnitudeList(data, container, template_name) {
  476. var current = $("#" + container + " > div").length;
  477. if (current > 0) { return; }
  478. var template = $("#" + template_name + " .pure-g")[0];
  479. for (var i in data) {
  480. var magnitude = data[i];
  481. var line = $(template).clone();
  482. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  483. $("div.hint", line).html(magnitude.name);
  484. $("input", line).attr("tabindex", 40 + i).val(magnitude.idx);
  485. line.appendTo("#" + container);
  486. }
  487. }
  488. // -----------------------------------------------------------------------------
  489. // Wifi
  490. // -----------------------------------------------------------------------------
  491. function delNetwork() {
  492. var parent = $(this).parents(".pure-g");
  493. $(parent).remove();
  494. }
  495. function moreNetwork() {
  496. var parent = $(this).parents(".pure-g");
  497. $(".more", parent).toggle();
  498. }
  499. function addNetwork() {
  500. var numNetworks = $("#networks > div").length;
  501. if (numNetworks >= maxNetworks) {
  502. alert("Max number of networks reached");
  503. return null;
  504. }
  505. var tabindex = 200 + numNetworks * 10;
  506. var template = $("#networkTemplate").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-network").on("click", delNetwork);
  513. $(line).find(".button-more-network").on("click", moreNetwork);
  514. line.appendTo("#networks");
  515. return line;
  516. }
  517. // -----------------------------------------------------------------------------
  518. // Relays scheduler
  519. // -----------------------------------------------------------------------------
  520. function delSchedule() {
  521. var parent = $(this).parents(".pure-g");
  522. $(parent).remove();
  523. }
  524. function moreSchedule() {
  525. var parent = $(this).parents(".pure-g");
  526. $("div.more", parent).toggle();
  527. }
  528. function addSchedule(event) {
  529. var numSchedules = $("#schedules > div").length;
  530. if (numSchedules >= maxSchedules) {
  531. alert("Max number of schedules reached");
  532. return null;
  533. }
  534. var tabindex = 200 + numSchedules * 10;
  535. var template = $("#scheduleTemplate").children();
  536. var line = $(template).clone();
  537. var type = (1 === event.data.schType) ? "switch" : "light";
  538. template = $("#" + type + "ActionTemplate").children();
  539. var actionLine = template.clone();
  540. $(line).find("#schActionDiv").append(actionLine);
  541. $(line).find("input").each(function() {
  542. $(this).attr("tabindex", tabindex);
  543. tabindex++;
  544. });
  545. $(line).find(".button-del-schedule").on("click", delSchedule);
  546. $(line).find(".button-more-schedule").on("click", moreSchedule);
  547. line.appendTo("#schedules");
  548. $(line).find("input[type='checkbox']").
  549. prop("checked", false).
  550. iphoneStyle("calculateDimensions").
  551. iphoneStyle("refresh");
  552. return line;
  553. }
  554. // -----------------------------------------------------------------------------
  555. // Relays
  556. // -----------------------------------------------------------------------------
  557. function initRelays(data) {
  558. var current = $("#relays > div").length;
  559. if (current > 0) { return; }
  560. var template = $("#relayTemplate .pure-g")[0];
  561. for (var i=0; i<data.length; i++) {
  562. // Add relay fields
  563. var line = $(template).clone();
  564. $(".id", line).html(i);
  565. $("input", line).attr("data", i);
  566. line.appendTo("#relays");
  567. $("input[type='checkbox']", line).iphoneStyle({
  568. onChange: doToggle,
  569. resizeContainer: true,
  570. resizeHandle: true,
  571. checkedLabel: "ON",
  572. uncheckedLabel: "OFF"
  573. });
  574. // Populate the relay SELECTs
  575. $("select.isrelay").append(
  576. $("<option></option>").attr("value",i).text("Switch #" + i));
  577. }
  578. }
  579. function initRelayConfig(data) {
  580. var current = $("#relayConfig > div").length;
  581. if (current > 0) { return; }
  582. var template = $("#relayConfigTemplate").children();
  583. for (var i in data) {
  584. var relay = data[i];
  585. var line = $(template).clone();
  586. $("span.gpio", line).html(relay.gpio);
  587. $("span.id", line).html(i);
  588. $("select[name='relayBoot']", line).val(relay.boot);
  589. $("select[name='relayPulse']", line).val(relay.pulse);
  590. $("input[name='relayTime']", line).val(relay.pulse_ms);
  591. $("input[name='mqttGroup']", line).val(relay.group);
  592. $("select[name='mqttGroupInv']", line).val(relay.group_inv);
  593. $("select[name='relayOnDisc']", line).val(relay.on_disc);
  594. line.appendTo("#relayConfig");
  595. }
  596. }
  597. // -----------------------------------------------------------------------------
  598. // Sensors & Magnitudes
  599. // -----------------------------------------------------------------------------
  600. function initMagnitudes(data) {
  601. // check if already initialized
  602. var done = $("#magnitudes > div").length;
  603. if (done > 0) { return; }
  604. // add templates
  605. var template = $("#magnitudeTemplate").children();
  606. for (var i in data) {
  607. var magnitude = data[i];
  608. var line = $(template).clone();
  609. $("label", line).html(magnitudeType(magnitude.type) + " #" + parseInt(magnitude.index, 10));
  610. $("div.hint", line).html(magnitude.description);
  611. $("input", line).attr("data", i);
  612. line.appendTo("#magnitudes");
  613. }
  614. }
  615. // -----------------------------------------------------------------------------
  616. // Lights
  617. // -----------------------------------------------------------------------------
  618. function initColorRGB() {
  619. // check if already initialized
  620. var done = $("#colors > div").length;
  621. if (done > 0) { return; }
  622. // add template
  623. var template = $("#colorRGBTemplate").children();
  624. var line = $(template).clone();
  625. line.appendTo("#colors");
  626. // init color wheel
  627. $("input[name='color']").wheelColorPicker({
  628. sliders: "wrgbp"
  629. }).on("sliderup", function() {
  630. var value = $(this).wheelColorPicker("getValue", "css");
  631. sendAction("color", {rgb: value});
  632. });
  633. // init bright slider
  634. $("#brightness").on("change", function() {
  635. var value = $(this).val();
  636. var parent = $(this).parents(".pure-g");
  637. $("span", parent).html(value);
  638. sendAction("color", {brightness: value});
  639. });
  640. }
  641. function initColorHSV() {
  642. // check if already initialized
  643. var done = $("#colors > div").length;
  644. if (done > 0) { return; }
  645. // add template
  646. var template = $("#colorHSVTemplate").children();
  647. var line = $(template).clone();
  648. line.appendTo("#colors");
  649. // init color wheel
  650. $("input[name='color']").wheelColorPicker({
  651. sliders: "whsvp"
  652. }).on("sliderup", function() {
  653. var color = $(this).wheelColorPicker("getColor");
  654. var value = parseInt(color.h * 360, 10) + "," + parseInt(color.s * 100, 10) + "," + parseInt(color.v * 100, 10);
  655. sendAction("color", {hsv: value});
  656. });
  657. }
  658. function initChannels(num) {
  659. // check if already initialized
  660. var done = $("#channels > div").length > 0;
  661. if (done) { return; }
  662. // does it have color channels?
  663. var colors = $("#colors > div").length > 0;
  664. // calculate channels to create
  665. var max = num;
  666. if (colors) {
  667. max = num % 3;
  668. if ((max > 0) & useWhite) {
  669. max--;
  670. }
  671. }
  672. var start = num - max;
  673. var onChannelSliderChange = function() {
  674. var id = $(this).attr("data");
  675. var value = $(this).val();
  676. var parent = $(this).parents(".pure-g");
  677. $("span", parent).html(value);
  678. sendAction("channel", {id: id, value: value});
  679. };
  680. // add templates
  681. var template = $("#channelTemplate").children();
  682. for (var i=0; i<max; i++) {
  683. var channel_id = start + i;
  684. var line = $(template).clone();
  685. $("span.slider", line).attr("data", channel_id);
  686. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  687. $("label", line).html("Channel " + (channel_id + 1));
  688. line.appendTo("#channels");
  689. $("select.islight").append(
  690. $("<option></option>").attr("value",i).text("Channel #" + i));
  691. }
  692. }
  693. // -----------------------------------------------------------------------------
  694. // RFBridge
  695. // -----------------------------------------------------------------------------
  696. function rfbLearn() {
  697. var parent = $(this).parents(".pure-g");
  698. var input = $("input", parent);
  699. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  700. }
  701. function rfbForget() {
  702. var parent = $(this).parents(".pure-g");
  703. var input = $("input", parent);
  704. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  705. }
  706. function rfbSend() {
  707. var parent = $(this).parents(".pure-g");
  708. var input = $("input", parent);
  709. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  710. }
  711. function addRfbNode() {
  712. var numNodes = $("#rfbNodes > legend").length;
  713. var template = $("#rfbNodeTemplate").children();
  714. var line = $(template).clone();
  715. var status = true;
  716. $("span", line).html(numNodes);
  717. $(line).find("input").each(function() {
  718. $(this).attr("data-id", numNodes);
  719. $(this).attr("data-status", status ? 1 : 0);
  720. status = !status;
  721. });
  722. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  723. $(line).find(".button-rfb-forget").on("click", rfbForget);
  724. $(line).find(".button-rfb-send").on("click", rfbSend);
  725. line.appendTo("#rfbNodes");
  726. return line;
  727. }
  728. // -----------------------------------------------------------------------------
  729. // Processing
  730. // -----------------------------------------------------------------------------
  731. function processData(data) {
  732. // title
  733. if ("app_name" in data) {
  734. var title = data.app_name;
  735. if ("app_version" in data) {
  736. title = title + " " + data.app_version;
  737. }
  738. $("span[name=title]").html(title);
  739. if ("hostname" in data) {
  740. title = data.hostname + " - " + title;
  741. }
  742. document.title = title;
  743. }
  744. Object.keys(data).forEach(function(key) {
  745. var i;
  746. var value = data[key];
  747. // ---------------------------------------------------------------------
  748. // Web mode
  749. // ---------------------------------------------------------------------
  750. if ("webMode" === key) {
  751. password = (1 === value);
  752. $("#layout").toggle(!password);
  753. $("#password").toggle(password);
  754. }
  755. // ---------------------------------------------------------------------
  756. // Actions
  757. // ---------------------------------------------------------------------
  758. if ("action" === key) {
  759. if ("reload" === data.action) { doReload(1000); }
  760. return;
  761. }
  762. // ---------------------------------------------------------------------
  763. // RFBridge
  764. // ---------------------------------------------------------------------
  765. if ("rfbCount" === key) {
  766. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  767. return;
  768. }
  769. if ("rfbrawVisible" === key) {
  770. $("input[name='rfbcode']").attr("maxlength", 116);
  771. }
  772. if ("rfb" === key) {
  773. var nodes = data.rfb;
  774. for (i in nodes) {
  775. var node = nodes[i];
  776. $("input[name='rfbcode'][data-id='" + node.id + "'][data-status='" + node.status + "']").val(node.data);
  777. }
  778. return;
  779. }
  780. // ---------------------------------------------------------------------
  781. // Lights
  782. // ---------------------------------------------------------------------
  783. if ("rgb" === key) {
  784. initColorRGB();
  785. $("input[name='color']").wheelColorPicker("setValue", value, true);
  786. return;
  787. }
  788. if ("hsv" === key) {
  789. initColorHSV();
  790. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  791. var chunks = value.split(",");
  792. var obj = {};
  793. obj.h = chunks[0] / 360;
  794. obj.s = chunks[1] / 100;
  795. obj.v = chunks[2] / 100;
  796. $("input[name='color']").wheelColorPicker("setColor", obj);
  797. return;
  798. }
  799. if ("brightness" === key) {
  800. $("#brightness").val(value);
  801. $("span.brightness").html(value);
  802. return;
  803. }
  804. if ("channels" === key) {
  805. var len = value.length;
  806. initChannels(len);
  807. for (i in value) {
  808. var ch = value[i];
  809. $("input.slider[data=" + i + "]").val(ch);
  810. $("span.slider[data=" + i + "]").html(ch);
  811. }
  812. return;
  813. }
  814. if ("useWhite" === key) {
  815. useWhite = value;
  816. }
  817. // ---------------------------------------------------------------------
  818. // Sensors & Magnitudes
  819. // ---------------------------------------------------------------------
  820. if ("magnitudes" === key) {
  821. initMagnitudes(value);
  822. for (i in value) {
  823. var magnitude = value[i];
  824. var error = magnitude.error || 0;
  825. var text = (0 === error) ?
  826. magnitude.value + magnitude.units :
  827. magnitudeError(error);
  828. $("input[name='magnitude'][data='" + i + "']").val(text);
  829. }
  830. return;
  831. }
  832. // ---------------------------------------------------------------------
  833. // WiFi
  834. // ---------------------------------------------------------------------
  835. if ("maxNetworks" === key) {
  836. maxNetworks = parseInt(value, 10);
  837. return;
  838. }
  839. if ("wifi" === key) {
  840. for (i in value) {
  841. var wifi = value[i];
  842. var nwk_line = addNetwork();
  843. Object.keys(wifi).forEach(function(key) {
  844. $("input[name='" + key + "']", nwk_line).val(wifi[key]);
  845. });
  846. }
  847. return;
  848. }
  849. if ("scanResult" === key) {
  850. $("div.scan.loading").hide();
  851. $("#scanResult").show();
  852. }
  853. // -----------------------------------------------------------------------------
  854. // Home Assistant
  855. // -----------------------------------------------------------------------------
  856. if ("haConfig" === key) {
  857. $("#haConfig").show();
  858. }
  859. // -----------------------------------------------------------------------------
  860. // Relays scheduler
  861. // -----------------------------------------------------------------------------
  862. if ("maxSchedules" === key) {
  863. maxSchedules = parseInt(value, 10);
  864. return;
  865. }
  866. if ("schedule" === key) {
  867. for (i in value) {
  868. var schedule = value[i];
  869. var sch_line = addSchedule({ data: {schType: schedule["schType"] }});
  870. Object.keys(schedule).forEach(function(key) {
  871. var sch_value = schedule[key];
  872. $("input[name='" + key + "']", sch_line).val(sch_value);
  873. $("select[name='" + key + "']", sch_line).prop("value", sch_value);
  874. $("input[type='checkbox'][name='" + key + "']", sch_line).
  875. prop("checked", sch_value).
  876. iphoneStyle("refresh");
  877. });
  878. }
  879. return;
  880. }
  881. // ---------------------------------------------------------------------
  882. // Relays
  883. // ---------------------------------------------------------------------
  884. if ("relayStatus" === key) {
  885. initRelays(value);
  886. for (i in value) {
  887. // Set the status for each relay
  888. $("input.relayStatus[data='" + i + "']").
  889. prop("checked", value[i]).
  890. iphoneStyle("refresh");
  891. }
  892. return;
  893. }
  894. // Relay configuration
  895. if ("relayConfig" === key) {
  896. initRelayConfig(value);
  897. return;
  898. }
  899. // ---------------------------------------------------------------------
  900. // Domoticz
  901. // ---------------------------------------------------------------------
  902. // Domoticz - Relays
  903. if ("dczRelays" === key) {
  904. createRelayList(value, "dczRelays", "dczRelayTemplate");
  905. return;
  906. }
  907. // Domoticz - Magnitudes
  908. if ("dczMagnitudes" === key) {
  909. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  910. return;
  911. }
  912. // ---------------------------------------------------------------------
  913. // Thingspeak
  914. // ---------------------------------------------------------------------
  915. // Thingspeak - Relays
  916. if ("tspkRelays" === key) {
  917. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  918. return;
  919. }
  920. // Thingspeak - Magnitudes
  921. if ("tspkMagnitudes" === key) {
  922. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  923. return;
  924. }
  925. // ---------------------------------------------------------------------
  926. // General
  927. // ---------------------------------------------------------------------
  928. // Messages
  929. if ("message" === key) {
  930. window.alert(messages[value]);
  931. return;
  932. }
  933. // Web log
  934. if ("weblog" === key) {
  935. $("#weblog").append(value);
  936. $("#weblog").scrollTop($("#weblog")[0].scrollHeight - $("#weblog").height());
  937. return;
  938. }
  939. // Enable options
  940. var position = key.indexOf("Visible");
  941. if (position > 0 && position === key.length - 7) {
  942. var module = key.slice(0,-7);
  943. $(".module-" + module).show();
  944. return;
  945. }
  946. if ("now" === key) {
  947. now = value;
  948. ago = 0;
  949. return;
  950. }
  951. if ("free_size" === key) {
  952. free_size = parseInt(value, 10);
  953. }
  954. // Pre-process
  955. if ("network" === key) {
  956. value = value.toUpperCase();
  957. }
  958. if ("mqttStatus" === key) {
  959. value = value ? "CONNECTED" : "NOT CONNECTED";
  960. }
  961. if ("ntpStatus" === key) {
  962. value = value ? "SYNC'D" : "NOT SYNC'D";
  963. }
  964. if ("uptime" === key) {
  965. var uptime = parseInt(value, 10);
  966. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  967. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  968. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  969. var days = uptime;
  970. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  971. }
  972. // ---------------------------------------------------------------------
  973. // Matching
  974. // ---------------------------------------------------------------------
  975. var pre;
  976. var post;
  977. // Look for INPUTs
  978. var input = $("input[name='" + key + "']");
  979. if (input.length > 0) {
  980. if (input.attr("type") === "checkbox") {
  981. input.
  982. prop("checked", value).
  983. iphoneStyle("refresh");
  984. } else if (input.attr("type") === "radio") {
  985. input.val([value]);
  986. } else {
  987. pre = input.attr("pre") || "";
  988. post = input.attr("post") || "";
  989. input.val(pre + value + post);
  990. }
  991. }
  992. // Look for SPANs
  993. var span = $("span[name='" + key + "']");
  994. if (span.length > 0) {
  995. pre = span.attr("pre") || "";
  996. post = span.attr("post") || "";
  997. span.html(pre + value + post);
  998. }
  999. // Look for SELECTs
  1000. var select = $("select[name='" + key + "']");
  1001. if (select.length > 0) {
  1002. select.val(value);
  1003. }
  1004. });
  1005. // Auto generate an APIKey if none defined yet
  1006. if ($("input[name='apiKey']").val() === "") {
  1007. generateAPIKey();
  1008. }
  1009. resetOriginals();
  1010. }
  1011. function hasChanged() {
  1012. var newValue, originalValue;
  1013. if ($(this).attr("type") === "checkbox") {
  1014. newValue = $(this).prop("checked");
  1015. originalValue = ($(this).attr("original") === "true");
  1016. } else {
  1017. newValue = $(this).val();
  1018. originalValue = $(this).attr("original");
  1019. }
  1020. var hasChanged = $(this).attr("hasChanged") || 0;
  1021. var action = $(this).attr("action");
  1022. if (typeof originalValue === "undefined") { return; }
  1023. if ("none" === action) { return; }
  1024. if (newValue !== originalValue) {
  1025. if (0 === hasChanged) {
  1026. ++numChanged;
  1027. if ("reconnect" === action) { ++numReconnect; }
  1028. if ("reboot" === action) { ++numReboot; }
  1029. if ("reload" === action) { ++numReload; }
  1030. $(this).attr("hasChanged", 1);
  1031. }
  1032. } else {
  1033. if (1 === hasChanged) {
  1034. --numChanged;
  1035. if ("reconnect" === action) { --numReconnect; }
  1036. if ("reboot" === action) { --numReboot; }
  1037. if ("reload" === action) { --numReload; }
  1038. $(this).attr("hasChanged", 0);
  1039. }
  1040. }
  1041. }
  1042. // -----------------------------------------------------------------------------
  1043. // Init & connect
  1044. // -----------------------------------------------------------------------------
  1045. function connect(host) {
  1046. if (typeof host === "undefined") {
  1047. host = window.location.href.replace("#", "");
  1048. } else {
  1049. if (host.indexOf("http") !== 0) {
  1050. host = "http://" + host + "/";
  1051. }
  1052. }
  1053. if (host.indexOf("http") !== 0) { return; }
  1054. webhost = host;
  1055. var wshost = host.replace("http", "ws") + "ws";
  1056. if (websock) { websock.close(); }
  1057. websock = new WebSocket(wshost);
  1058. websock.onmessage = function(evt) {
  1059. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1060. if (data) {
  1061. processData(data);
  1062. }
  1063. };
  1064. }
  1065. $(function() {
  1066. initMessages();
  1067. loadTimeZones();
  1068. setInterval(function() { keepTime(); }, 1000);
  1069. $("#menuLink").on("click", toggleMenu);
  1070. $(".pure-menu-link").on("click", showPanel);
  1071. $("progress").attr({ value: 0, max: 100 });
  1072. $(".button-update").on("click", doUpdate);
  1073. $(".button-update-password").on("click", doUpdatePassword);
  1074. $(".button-reboot").on("click", doReboot);
  1075. $(".button-reconnect").on("click", doReconnect);
  1076. $(".button-wifi-scan").on("click", doScan);
  1077. $(".button-ha-config").on("click", doHAConfig);
  1078. $(".button-dbgcmd").on("click", doDebugCommand);
  1079. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1080. $(".button-dbg-clear").on("click", doDebugClear);
  1081. $(".button-settings-backup").on("click", doBackup);
  1082. $(".button-settings-restore").on("click", doRestore);
  1083. $(".button-settings-factory").on("click", doFactoryReset);
  1084. $("#uploader").on("change", onFileUpload);
  1085. $(".button-upgrade").on("click", doUpgrade);
  1086. $(".button-apikey").on("click", generateAPIKey);
  1087. $(".button-upgrade-browse").on("click", function() {
  1088. $("input[name='upgrade']")[0].click();
  1089. return false;
  1090. });
  1091. $("input[name='upgrade']").change(function (){
  1092. var file = this.files[0];
  1093. $("input[name='filename']").val(file.name);
  1094. });
  1095. $(".button-add-network").on("click", function() {
  1096. $(".more", addNetwork()).toggle();
  1097. });
  1098. $(".button-add-switch-schedule").on("click", { schType: 1 }, addSchedule);
  1099. $(".button-add-light-schedule").on("click", { schType: 2 }, addSchedule);
  1100. $(document).on("change", "input", hasChanged);
  1101. $(document).on("change", "select", hasChanged);
  1102. connect();
  1103. });