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.

1135 lines
34 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
  1. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var maxSchedules;
  5. var messages = [];
  6. var webhost;
  7. var numChanged = 0;
  8. var numReboot = 0;
  9. var numReconnect = 0;
  10. var numReload = 0;
  11. var useWhite = false;
  12. var manifest;
  13. // -----------------------------------------------------------------------------
  14. // Messages
  15. // -----------------------------------------------------------------------------
  16. function initMessages() {
  17. messages[ 1] = "Remote update started";
  18. messages[ 2] = "OTA update started";
  19. messages[ 3] = "Error parsing data!";
  20. messages[ 4] = "The file does not look like a valid configuration backup or is corrupted";
  21. messages[ 5] = "Changes saved. You should reboot your board now";
  22. messages[ 7] = "Passwords do not match!";
  23. messages[ 8] = "Changes saved";
  24. messages[ 9] = "No changes detected";
  25. messages[10] = "Session expired, please reload page...";
  26. }
  27. function sensorName(id) {
  28. var names = [
  29. "DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
  30. "HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
  31. "Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
  32. "SHT3X I2C", "BH1750"
  33. ];
  34. if (1 <= id && id <= names.length) return names[id-1];
  35. return null;
  36. }
  37. function magnitudeType(type) {
  38. var types = [
  39. "Temperature", "Humidity", "Pressure",
  40. "Current", "Voltage", "Active Power", "Apparent Power",
  41. "Reactive Power", "Power Factor", "Energy", "Energy (delta)",
  42. "Analog", "Digital", "Events",
  43. "PM1.0", "PM2.5", "PM10", "CO2", "Lux"
  44. ];
  45. if (1 <= type && type <= types.length) return types[type-1];
  46. return null;
  47. }
  48. function magnitudeError(error) {
  49. var errors = [
  50. "OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
  51. "CRC Error", "I2C Error", "GPIO Error"
  52. ];
  53. if (0 <= error && error < errors.length) return errors[error];
  54. return "Error " + error;
  55. }
  56. // -----------------------------------------------------------------------------
  57. // Utils
  58. // -----------------------------------------------------------------------------
  59. // http://www.the-art-of-web.com/javascript/validate-password/
  60. function checkPassword(str) {
  61. // at least one lowercase and one uppercase letter or number
  62. // at least five characters (letters, numbers or special characters)
  63. var re = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{5,}$/;
  64. return re.test(str);
  65. }
  66. function zeroPad(number, positions) {
  67. var zeros = '';
  68. for (var i = 0; i < positions; i++) zeros += "0";
  69. return (zeros + number).slice(-positions);
  70. }
  71. function validateForm(form) {
  72. // password
  73. var adminPass1 = $("input[name='adminPass']", form).first().val();
  74. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  75. alert("The password you have entered is not valid, it must have at least 5 characters, 1 lowercase and 1 uppercase or number!");
  76. return false;
  77. }
  78. var adminPass2 = $("input[name='adminPass']", form).last().val();
  79. if (adminPass1 != adminPass2) {
  80. alert("Passwords are different!");
  81. return false;
  82. }
  83. return true;
  84. }
  85. // These fields will always be a list of values
  86. var is_group = [
  87. "ssid", "pass", "gw", "mask", "ip", "dns",
  88. "schSwitch","schAction","schHour","schMinute","schWDs",
  89. "relayBoot", "relayPulse", "relayTime",
  90. "mqttGroup", "mqttGroupInv",
  91. "dczRelayIdx", "dczMagnitude",
  92. "tspkRelay", "tspkMagnitude",
  93. "ledMode",
  94. "adminPass"
  95. ];
  96. function getData(form) {
  97. var data = {};
  98. // Populate data
  99. $("input,select", form).each(function() {
  100. var name = $(this).attr("name");
  101. if (name) {
  102. // Do not report these fields
  103. if (name == "filename") return;
  104. if (name == "rfbcode") return;
  105. // Grab the value
  106. if ($(this).attr('type') == 'checkbox') {
  107. value = $(this).is(':checked') ? 1 : 0;
  108. } else if ($(this).attr('type') == 'radio') {
  109. if (!$(this).is(':checked')) return;
  110. value = $(this).val();
  111. } else {
  112. value = $(this).val();
  113. }
  114. // Build the object
  115. if (name in data) {
  116. if (!Array.isArray(data[name])) data[name] = [data[name]];
  117. data[name].push(value);
  118. } else if (is_group.indexOf(name) >= 0) {
  119. data[name] = [value];
  120. } else {
  121. data[name] = value;
  122. }
  123. }
  124. });
  125. // Post process
  126. if ("schSwitch" in data) data["schSwitch"].push(0xFF);
  127. return data;
  128. }
  129. function randomString(length, chars) {
  130. var mask = '';
  131. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  132. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  133. if (chars.indexOf('#') > -1) mask += '0123456789';
  134. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  135. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  136. var result = '';
  137. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  138. return result;
  139. }
  140. function generateAPIKey() {
  141. var apikey = randomString(16, '@#');
  142. $("input[name=\"apiKey\"]").val(apikey);
  143. return false;
  144. }
  145. function getJson(str) {
  146. try {
  147. return JSON.parse(str);
  148. } catch (e) {
  149. return false;
  150. }
  151. }
  152. // -----------------------------------------------------------------------------
  153. // Actions
  154. // -----------------------------------------------------------------------------
  155. function doReload(milliseconds) {
  156. milliseconds = (typeof milliseconds == 'undefined') ? 0 : parseInt(milliseconds);
  157. setTimeout(function() {
  158. window.location.reload();
  159. }, milliseconds);
  160. }
  161. function doUpdate() {
  162. var form = $("#formSave");
  163. if (validateForm(form)) {
  164. // Get data
  165. var data = getData(form);
  166. websock.send(JSON.stringify({'config': data}));
  167. // Empty special fields
  168. $(".pwrExpected").val(0);
  169. $("input[name='pwrResetCalibration']")
  170. .prop("checked", false)
  171. .iphoneStyle("refresh");
  172. // Change handling
  173. numChanged = 0;
  174. setTimeout(function() {
  175. if (numReboot > 0) {
  176. var response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  177. if (response == true) doReboot(false);
  178. } else if (numReconnect > 0) {
  179. var response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  180. if (response == true) doReconnect(false);
  181. } else if (numReload > 0) {
  182. var response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  183. if (response == true) doReload();
  184. }
  185. resetOriginals();
  186. }, 1000);
  187. }
  188. return false;
  189. }
  190. function doUpgrade() {
  191. var contents = $("input[name='upgrade']")[0].files[0];
  192. if (typeof contents == 'undefined') {
  193. alert("First you have to select a file from your computer.");
  194. return false;
  195. }
  196. var filename = $("input[name='upgrade']").val().split('\\').pop();
  197. var data = new FormData();
  198. data.append('upgrade', contents, filename);
  199. $.ajax({
  200. // Your server script to process the upload
  201. url: webhost + 'upgrade',
  202. type: 'POST',
  203. // Form data
  204. data: data,
  205. // Tell jQuery not to process data or worry about content-type
  206. // You *must* include these options!
  207. cache: false,
  208. contentType: false,
  209. processData: false,
  210. success: function(data, text) {
  211. $("#upgrade-progress").hide();
  212. if (data == 'OK') {
  213. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  214. doReload(5000);
  215. } else {
  216. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  217. }
  218. },
  219. // Custom XMLHttpRequest
  220. xhr: function() {
  221. $("#upgrade-progress").show();
  222. var myXhr = $.ajaxSettings.xhr();
  223. if (myXhr.upload) {
  224. // For handling the progress of the upload
  225. myXhr.upload.addEventListener('progress', function(e) {
  226. if (e.lengthComputable) {
  227. $('progress').attr({ value: e.loaded, max: e.total });
  228. }
  229. } , false);
  230. }
  231. return myXhr;
  232. },
  233. });
  234. return false;
  235. }
  236. function doUpdatePassword() {
  237. var form = $("#formPassword");
  238. if (validateForm(form)) {
  239. var data = getData(form);
  240. websock.send(JSON.stringify({'config': data}));
  241. }
  242. return false;
  243. }
  244. function doReboot(ask) {
  245. ask = (typeof ask == 'undefined') ? true : ask;
  246. if (numChanged > 0) {
  247. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  248. if (response == true) return doUpdate();
  249. }
  250. if (ask) {
  251. var response = window.confirm("Are you sure you want to reboot the device?");
  252. if (response == false) return false;
  253. }
  254. websock.send(JSON.stringify({'action': 'reboot'}));
  255. doReload(5000);
  256. return false;
  257. }
  258. function doReconnect(ask) {
  259. ask = (typeof ask == 'undefined') ? true : ask;
  260. if (numChanged > 0) {
  261. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  262. if (response == true) return doUpdate();
  263. }
  264. if (ask) {
  265. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  266. if (response == false) return false;
  267. }
  268. websock.send(JSON.stringify({'action': 'reconnect'}));
  269. doReload(5000);
  270. return false;
  271. }
  272. function doBackup() {
  273. document.getElementById('downloader').src = webhost + 'config';
  274. return false;
  275. }
  276. function onFileUpload(event) {
  277. var inputFiles = this.files;
  278. if (inputFiles == undefined || inputFiles.length == 0) return false;
  279. var inputFile = inputFiles[0];
  280. this.value = "";
  281. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  282. if (response == false) return false;
  283. var reader = new FileReader();
  284. reader.onload = function(e) {
  285. var data = getJson(e.target.result);
  286. if (data) {
  287. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  288. } else {
  289. alert(messages[4]);
  290. }
  291. };
  292. reader.readAsText(inputFile);
  293. return false;
  294. }
  295. function doRestore() {
  296. if (typeof window.FileReader !== 'function') {
  297. alert("The file API isn't supported on this browser yet.");
  298. } else {
  299. $("#uploader").click();
  300. }
  301. return false;
  302. }
  303. function doToggle(element, value) {
  304. var relayID = parseInt(element.attr("data"));
  305. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  306. return false;
  307. }
  308. // -----------------------------------------------------------------------------
  309. // Visualization
  310. // -----------------------------------------------------------------------------
  311. function showPanel() {
  312. $(".panel").hide();
  313. $("#" + $(this).attr("data")).show();
  314. if ($("#layout").hasClass('active')) toggleMenu();
  315. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  316. };
  317. function toggleMenu() {
  318. $("#layout").toggleClass('active');
  319. $("#menu").toggleClass('active');
  320. $("#menuLink").toggleClass('active');
  321. }
  322. // -----------------------------------------------------------------------------
  323. // Relays & magnitudes mapping
  324. // -----------------------------------------------------------------------------
  325. function createRelayList(data, container, template) {
  326. var current = $("#" + container + " > div").length;
  327. if (current > 0) return;
  328. var template = $("#" + template + " .pure-g")[0];
  329. for (var i=0; i<data.length; i++) {
  330. var line = $(template).clone();
  331. $("label", line).html("Switch #" + i);
  332. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  333. line.appendTo("#" + container);
  334. }
  335. }
  336. function createMagnitudeList(data, container, template) {
  337. var current = $("#" + container + " > div").length;
  338. if (current > 0) return;
  339. var template = $("#" + template + " .pure-g")[0];
  340. for (var i=0; i<data.length; i++) {
  341. var line = $(template).clone();
  342. $("label", line).html(magnitudeType(data[i].type) + " #" + parseInt(data[i].index));
  343. $("div.hint", line).html(data[i].name);
  344. $("input", line).attr("tabindex", 40 + i).val(data[i].idx);
  345. line.appendTo("#" + container);
  346. }
  347. }
  348. // -----------------------------------------------------------------------------
  349. // Wifi
  350. // -----------------------------------------------------------------------------
  351. function addNetwork() {
  352. var numNetworks = $("#networks > div").length;
  353. if (numNetworks >= maxNetworks) {
  354. alert("Max number of networks reached");
  355. return;
  356. }
  357. var tabindex = 200 + numNetworks * 10;
  358. var template = $("#networkTemplate").children();
  359. var line = $(template).clone();
  360. $(line).find("input").each(function() {
  361. $(this).attr("tabindex", tabindex++);
  362. });
  363. $(line).find(".button-del-network").on('click', delNetwork);
  364. $(line).find(".button-more-network").on('click', moreNetwork);
  365. line.appendTo("#networks");
  366. return line;
  367. }
  368. function delNetwork() {
  369. var parent = $(this).parents(".pure-g");
  370. $(parent).remove();
  371. }
  372. function moreNetwork() {
  373. var parent = $(this).parents(".pure-g");
  374. $(".more", parent).toggle();
  375. }
  376. // -----------------------------------------------------------------------------
  377. // Relays scheduler
  378. // -----------------------------------------------------------------------------
  379. function delSchedule() {
  380. var parent = $(this).parents(".pure-g");
  381. $(parent).remove();
  382. }
  383. function moreSchedule() {
  384. var parent = $(this).parents(".pure-g");
  385. $("div.more", parent).toggle();
  386. }
  387. function addSchedule() {
  388. var numSchedules = $("#schedules > div").length;
  389. if (numSchedules >= maxSchedules) {
  390. alert("Max number of schedules reached");
  391. return;
  392. }
  393. var tabindex = 200 + numSchedules * 10;
  394. var template = $("#scheduleTemplate").children();
  395. var line = $(template).clone();
  396. $(line).find("input").each(function() {
  397. $(this).attr("tabindex", tabindex++);
  398. });
  399. $(line).find(".button-del-schedule").on('click', delSchedule);
  400. $(line).find(".button-more-schedule").on('click', moreSchedule);
  401. line.appendTo("#schedules");
  402. return line;
  403. }
  404. // -----------------------------------------------------------------------------
  405. // Relays
  406. // -----------------------------------------------------------------------------
  407. function initRelays(data) {
  408. var current = $("#relays > div").length;
  409. if (current > 0) return;
  410. var template = $("#relayTemplate .pure-g")[0];
  411. for (var i=0; i<data.length; i++) {
  412. var line = $(template).clone();
  413. $(".id", line).html(i);
  414. $("input", line).attr("data", i);
  415. line.appendTo("#relays");
  416. $(":checkbox", line).iphoneStyle({
  417. onChange: doToggle,
  418. resizeContainer: true,
  419. resizeHandle: true,
  420. checkedLabel: 'ON',
  421. uncheckedLabel: 'OFF'
  422. });
  423. }
  424. }
  425. function initRelayConfig(data) {
  426. var current = $("#relayConfig > div").length;
  427. if (current > 0) return;
  428. var template = $("#relayConfigTemplate").children();
  429. for (var i=0; i < data.length; i++) {
  430. var line = $(template).clone();
  431. $("span.gpio", line).html(data[i].gpio);
  432. $("span.id", line).html(i);
  433. $("select[name='relayBoot']", line).val(data[i].boot);
  434. $("select[name='relayPulse']", line).val(data[i].pulse);
  435. $("input[name='relayTime']", line).val(data[i].pulse_ms);
  436. $("input[name='mqttGroup']", line).val(data[i].group);
  437. $("select[name='mqttGroupInv']", line).val(data[i].group_inv);
  438. line.appendTo("#relayConfig");
  439. }
  440. }
  441. // -----------------------------------------------------------------------------
  442. // Sensors & Magnitudes
  443. // -----------------------------------------------------------------------------
  444. function initMagnitudes(data) {
  445. // check if already initialized
  446. var done = $("#magnitudes > div").length;
  447. if (done > 0) return;
  448. // add templates
  449. var template = $("#magnitudeTemplate").children();
  450. for (var i=0; i<data.length; i++) {
  451. var line = $(template).clone();
  452. $("label", line).html(magnitudeType(data[i].type) + " #" + parseInt(data[i].index));
  453. $("div.hint", line).html(data[i].description);
  454. $("input", line).attr("data", i);
  455. line.appendTo("#magnitudes");
  456. }
  457. }
  458. function getManifest(sensor_id) {
  459. for (i in manifest) {
  460. if (manifest[i].sensor_id == sensor_id) return manifest[i];
  461. }
  462. return null;
  463. }
  464. // -----------------------------------------------------------------------------
  465. // Lights
  466. // -----------------------------------------------------------------------------
  467. function initColorRGB() {
  468. // check if already initialized
  469. var done = $("#colors > div").length;
  470. if (done > 0) return;
  471. // add template
  472. var template = $("#colorRGBTemplate").children();
  473. var line = $(template).clone();
  474. line.appendTo("#colors");
  475. // init color wheel
  476. $('input[name="color"]').wheelColorPicker({
  477. sliders: 'wrgbp'
  478. }).on('sliderup', function() {
  479. var value = $(this).wheelColorPicker('getValue', 'css');
  480. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  481. });
  482. // init bright slider
  483. $('#brightness').on("change", function() {
  484. var value = $(this).val();
  485. var parent = $(this).parents(".pure-g");
  486. $("span", parent).html(value);
  487. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  488. });
  489. }
  490. function initColorHSV() {
  491. // check if already initialized
  492. var done = $("#colors > div").length;
  493. if (done > 0) return;
  494. // add template
  495. var template = $("#colorHSVTemplate").children();
  496. var line = $(template).clone();
  497. line.appendTo("#colors");
  498. // init color wheel
  499. $('input[name="color"]').wheelColorPicker({
  500. sliders: 'whsvp'
  501. }).on('sliderup', function() {
  502. var color = $(this).wheelColorPicker('getColor');
  503. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  504. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  505. });
  506. }
  507. function initChannels(num) {
  508. // check if already initialized
  509. var done = $("#channels > div").length > 0;
  510. if (done) return;
  511. // does it have color channels?
  512. var colors = $("#colors > div").length > 0;
  513. // calculate channels to create
  514. var max = num;
  515. if (colors) {
  516. max = num % 3;
  517. if ((max > 0) & useWhite) max--;
  518. }
  519. var start = num - max;
  520. // add templates
  521. var template = $("#channelTemplate").children();
  522. for (var i=0; i<max; i++) {
  523. var channel_id = start + i;
  524. var line = $(template).clone();
  525. $("span.slider", line).attr("data", channel_id);
  526. $("input.slider", line).attr("data", channel_id).on("change", function() {
  527. var id = $(this).attr("data");
  528. var value = $(this).val();
  529. var parent = $(this).parents(".pure-g");
  530. $("span", parent).html(value);
  531. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  532. });
  533. $("label", line).html("Channel " + (channel_id + 1));
  534. line.appendTo("#channels");
  535. }
  536. }
  537. // -----------------------------------------------------------------------------
  538. // RFBridge
  539. // -----------------------------------------------------------------------------
  540. function addRfbNode() {
  541. var numNodes = $("#rfbNodes > legend").length;
  542. var template = $("#rfbNodeTemplate").children();
  543. var line = $(template).clone();
  544. var status = true;
  545. $("span", line).html(numNodes);
  546. $(line).find("input").each(function() {
  547. $(this).attr("data-id", numNodes);
  548. $(this).attr("data-status", status ? 1 : 0);
  549. status = !status;
  550. });
  551. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  552. $(line).find(".button-rfb-forget").on('click', rfbForget);
  553. $(line).find(".button-rfb-send").on('click', rfbSend);
  554. line.appendTo("#rfbNodes");
  555. return line;
  556. }
  557. function rfbLearn() {
  558. var parent = $(this).parents(".pure-g");
  559. var input = $("input", parent);
  560. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  561. }
  562. function rfbForget() {
  563. var parent = $(this).parents(".pure-g");
  564. var input = $("input", parent);
  565. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  566. }
  567. function rfbSend() {
  568. var parent = $(this).parents(".pure-g");
  569. var input = $("input", parent);
  570. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  571. }
  572. // -----------------------------------------------------------------------------
  573. // Processing
  574. // -----------------------------------------------------------------------------
  575. function processData(data) {
  576. console.log(data);
  577. // title
  578. if ("app_name" in data) {
  579. var title = data.app_name;
  580. if ("app_version" in data) {
  581. title = title + " " + data.app_version;
  582. }
  583. $(".pure-menu-heading").html(title);
  584. if ("hostname" in data) {
  585. title = data.hostname + " - " + title;
  586. }
  587. document.title = title;
  588. }
  589. Object.keys(data).forEach(function(key) {
  590. // ---------------------------------------------------------------------
  591. // Web mode
  592. // ---------------------------------------------------------------------
  593. if (key == "webMode") {
  594. password = data.webMode == 1;
  595. $("#layout").toggle(data.webMode == 0);
  596. $("#password").toggle(data.webMode == 1);
  597. }
  598. // ---------------------------------------------------------------------
  599. // Actions
  600. // ---------------------------------------------------------------------
  601. if (key == "action") {
  602. if (data.action == "reload") doReload(1000);
  603. return;
  604. }
  605. // ---------------------------------------------------------------------
  606. // RFBridge
  607. // ---------------------------------------------------------------------
  608. if (key == "rfbCount") {
  609. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  610. return;
  611. }
  612. if (key == "rfb") {
  613. var nodes = data.rfb;
  614. for (var i in nodes) {
  615. var node = nodes[i];
  616. $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]").val(node["data"]);
  617. }
  618. return;
  619. }
  620. // ---------------------------------------------------------------------
  621. // Lights
  622. // ---------------------------------------------------------------------
  623. if (key == "rgb") {
  624. initColorRGB();
  625. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  626. return;
  627. }
  628. if (key == "hsv") {
  629. initColorHSV();
  630. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  631. var chunks = data[key].split(",");
  632. var obj = {};
  633. obj.h = chunks[0] / 360;
  634. obj.s = chunks[1] / 100;
  635. obj.v = chunks[2] / 100;
  636. $("input[name='color']").wheelColorPicker('setColor', obj);
  637. return;
  638. }
  639. if (key == "brightness") {
  640. $("#brightness").val(data[key]);
  641. $("span.brightness").html(data[key]);
  642. return;
  643. }
  644. if (key == "channels") {
  645. var len = data[key].length;
  646. initChannels(len);
  647. for (var i=0; i<len; i++) {
  648. $("input.slider[data=" + i + "]").val(data[key][i]);
  649. $("span.slider[data=" + i + "]").html(data[key][i]);
  650. }
  651. return;
  652. }
  653. if (key == "useWhite") {
  654. useWhite = data[key];
  655. }
  656. // ---------------------------------------------------------------------
  657. // Sensors & Magnitudes
  658. // ---------------------------------------------------------------------
  659. if (key == "magnitudes") {
  660. initMagnitudes(data[key]);
  661. for (var i=0; i<data[key].length; i++) {
  662. var error = data[key][i].error || 0;
  663. var text = (error == 0) ?
  664. data[key][i].value + data[key][i].units
  665. : magnitudeError(error);
  666. $("input[name=magnitude][data=" + i + "]").val(text);
  667. }
  668. return;
  669. }
  670. if (key == "manifest") {
  671. manifest = data[key];
  672. }
  673. // ---------------------------------------------------------------------
  674. // WiFi
  675. // ---------------------------------------------------------------------
  676. if (key == "maxNetworks") {
  677. maxNetworks = parseInt(data.maxNetworks);
  678. return;
  679. }
  680. if (key == "wifi") {
  681. for (var i in data.wifi) {
  682. var line = addNetwork();
  683. var wifi = data.wifi[i];
  684. Object.keys(wifi).forEach(function(key) {
  685. $("input[name=" + key + "]", line).val(wifi[key]);
  686. });
  687. }
  688. return;
  689. }
  690. // -----------------------------------------------------------------------------
  691. // Relays scheduler
  692. // -----------------------------------------------------------------------------
  693. if (key == "maxSchedules") {
  694. maxSchedules = parseInt(data.maxSchedules);
  695. return;
  696. }
  697. if (key == "schedule") {
  698. var schedule = data.schedule;
  699. for (var i in schedule) {
  700. var line = addSchedule();
  701. var schedule = data.schedule[i];
  702. Object.keys(schedule).forEach(function(key) {
  703. $("input[name=" + key + "]", line).val(schedule[key]);
  704. $("select[name=" + key + "]", line).prop("value", schedule[key]);
  705. });
  706. }
  707. return;
  708. }
  709. // ---------------------------------------------------------------------
  710. // Relays
  711. // ---------------------------------------------------------------------
  712. if (key == "relayStatus") {
  713. initRelays(data[key]);
  714. for (var i in data[key]) {
  715. // Set the status for each relay
  716. $("input.relayStatus[data='" + i + "']")
  717. .prop("checked", data[key][i])
  718. .iphoneStyle("refresh");
  719. // Populate the relay SELECTs
  720. $("select.isrelay").append(
  721. $("<option></option>").attr("value",i).text("Switch #" + i)
  722. );
  723. }
  724. return;
  725. }
  726. // Relay configuration
  727. if (key == "relayConfig") {
  728. initRelayConfig(data[key]);
  729. return;
  730. }
  731. // ---------------------------------------------------------------------
  732. // Domoticz
  733. // ---------------------------------------------------------------------
  734. // Domoticz - Relays
  735. if (key == "dczRelays") {
  736. createRelayList(data[key], "dczRelays", "dczRelayTemplate");
  737. return;
  738. }
  739. // Domoticz - Magnitudes
  740. if (key == "dczMagnitudes") {
  741. createMagnitudeList(data[key], "dczMagnitudes", "dczMagnitudeTemplate");
  742. return;
  743. }
  744. // ---------------------------------------------------------------------
  745. // Thingspeak
  746. // ---------------------------------------------------------------------
  747. // Thingspeak - Relays
  748. if (key == "tspkRelays") {
  749. createRelayList(data[key], "tspkRelays", "tspkRelayTemplate");
  750. return;
  751. }
  752. // Thingspeak - Magnitudes
  753. if (key == "tspkMagnitudes") {
  754. createMagnitudeList(data[key], "tspkMagnitudes", "tspkMagnitudeTemplate");
  755. return;
  756. }
  757. // ---------------------------------------------------------------------
  758. // General
  759. // ---------------------------------------------------------------------
  760. // Messages
  761. if (key == "message") {
  762. window.alert(messages[data.message]);
  763. return;
  764. }
  765. // Enable options
  766. var position = key.indexOf("Visible");
  767. if (position > 0 && position == key.length - 7) {
  768. var module = key.slice(0,-7);
  769. $(".module-" + module).show();
  770. return;
  771. }
  772. // Pre-process
  773. if (key == "network") {
  774. data.network = data.network.toUpperCase();
  775. }
  776. if (key == "mqttStatus") {
  777. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  778. }
  779. if (key == "ntpStatus") {
  780. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  781. }
  782. if (key == "uptime") {
  783. var uptime = parseInt(data[key]);
  784. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  785. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  786. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  787. var days = uptime;
  788. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  789. }
  790. // ---------------------------------------------------------------------
  791. // Matching
  792. // ---------------------------------------------------------------------
  793. // Look for INPUTs
  794. var element = $("input[name=" + key + "]");
  795. if (element.length > 0) {
  796. if (element.attr('type') == 'checkbox') {
  797. element
  798. .prop("checked", data[key])
  799. .iphoneStyle("refresh");
  800. } else if (element.attr('type') == 'radio') {
  801. element.val([data[key]]);
  802. } else {
  803. var pre = element.attr("pre") || "";
  804. var post = element.attr("post") || "";
  805. element.val(pre + data[key] + post);
  806. }
  807. return;
  808. }
  809. // Look for SPANs
  810. var element = $("span[name=" + key + "]");
  811. if (element.length > 0) {
  812. var pre = element.attr("pre") || "";
  813. var post = element.attr("post") || "";
  814. element.html(pre + data[key] + post);
  815. return;
  816. }
  817. // Look for SELECTs
  818. var element = $("select[name=" + key + "]");
  819. if (element.length > 0) {
  820. element.val(data[key]);
  821. return;
  822. }
  823. });
  824. // Auto generate an APIKey if none defined yet
  825. if ($("input[name='apiKey']").val() == "") {
  826. generateAPIKey();
  827. }
  828. resetOriginals();
  829. }
  830. function hasChanged() {
  831. var newValue, originalValue;
  832. if ($(this).attr('type') == 'checkbox') {
  833. newValue = $(this).prop("checked")
  834. originalValue = $(this).attr("original") == "true";
  835. } else {
  836. newValue = $(this).val();
  837. originalValue = $(this).attr("original");
  838. }
  839. var hasChanged = $(this).attr("hasChanged") || 0;
  840. var action = $(this).attr("action");
  841. if (typeof originalValue == 'undefined') return;
  842. if (action == 'none') return;
  843. if (newValue != originalValue) {
  844. if (hasChanged == 0) {
  845. ++numChanged;
  846. if (action == "reconnect") ++numReconnect;
  847. if (action == "reboot") ++numReboot;
  848. if (action == "reload") ++numReload;
  849. $(this).attr("hasChanged", 1);
  850. }
  851. } else {
  852. if (hasChanged == 1) {
  853. --numChanged;
  854. if (action == "reconnect") --numReconnect;
  855. if (action == "reboot") --numReboot;
  856. if (action == "reload") --numReload;
  857. $(this).attr("hasChanged", 0);
  858. }
  859. }
  860. }
  861. function resetOriginals() {
  862. $("input,select").each(function() {
  863. $(this).attr("original", $(this).val());
  864. })
  865. numReboot = numReconnect = numReload = 0;
  866. }
  867. // -----------------------------------------------------------------------------
  868. // Init & connect
  869. // -----------------------------------------------------------------------------
  870. function connect(host) {
  871. if (typeof host === 'undefined') {
  872. host = window.location.href.replace('#', '');
  873. } else {
  874. if (host.indexOf("http") != 0) {
  875. host = 'http://' + host + '/';
  876. }
  877. }
  878. if (host.indexOf("http") != 0) return;
  879. webhost = host;
  880. wshost = host.replace('http', 'ws') + 'ws';
  881. if (websock) websock.close();
  882. websock = new WebSocket(wshost);
  883. websock.onmessage = function(evt) {
  884. var data = getJson(evt.data);
  885. if (data) processData(data);
  886. };
  887. }
  888. $(function() {
  889. initMessages();
  890. $("#menuLink").on('click', toggleMenu);
  891. $(".pure-menu-link").on('click', showPanel);
  892. $('progress').attr({ value: 0, max: 100 });
  893. $(".button-update").on('click', doUpdate);
  894. $(".button-update-password").on('click', doUpdatePassword);
  895. $(".button-reboot").on('click', doReboot);
  896. $(".button-reconnect").on('click', doReconnect);
  897. $(".button-settings-backup").on('click', doBackup);
  898. $(".button-settings-restore").on('click', doRestore);
  899. $('#uploader').on('change', onFileUpload);
  900. $(".button-upgrade").on('click', doUpgrade);
  901. $(".button-apikey").on('click', generateAPIKey);
  902. $(".button-upgrade-browse").on('click', function() {
  903. $("input[name='upgrade']")[0].click();
  904. return false;
  905. });
  906. $("input[name='upgrade']").change(function (){
  907. var fileName = $(this).val();
  908. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  909. });
  910. $(".button-add-network").on('click', function() {
  911. $(".more", addNetwork()).toggle();
  912. });
  913. $(".button-add-schedule").on('click', function() {
  914. $("div.more", addSchedule()).toggle();
  915. });
  916. $(document).on('change', 'input', hasChanged);
  917. $(document).on('change', 'select', hasChanged);
  918. connect();
  919. });