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.

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