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.

1130 lines
34 KiB

8 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 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
6 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. // add a new row
  701. var line = addSchedule();
  702. // fill in the blanks
  703. var schedule = data.schedule[i];
  704. Object.keys(schedule).forEach(function(key) {
  705. var element = $("input[name=" + key + "]", line);
  706. if (element.length) element.val(schedule[key]);
  707. var elementsel = $("select[name=" + key + "]", line);
  708. if (elementsel.length) elementsel.prop("value", schedule[key]);
  709. });
  710. }
  711. return;
  712. }
  713. // ---------------------------------------------------------------------
  714. // Relays
  715. // ---------------------------------------------------------------------
  716. if (key == "relayStatus") {
  717. initRelays(data[key]);
  718. for (var i in data[key]) {
  719. $("input.relayStatus[data='" + i + "']")
  720. .prop("checked", data[key][i])
  721. .iphoneStyle("refresh");
  722. }
  723. return;
  724. }
  725. // Relay configuration
  726. if (key == "relayConfig") {
  727. initRelayConfig(data[key]);
  728. return;
  729. }
  730. // ---------------------------------------------------------------------
  731. // Domoticz
  732. // ---------------------------------------------------------------------
  733. // Domoticz - Relays
  734. if (key == "dczRelays") {
  735. createRelayList(data[key], "dczRelays", "dczRelayTemplate");
  736. return;
  737. }
  738. // Domoticz - Magnitudes
  739. if (key == "dczMagnitudes") {
  740. createMagnitudeList(data[key], "dczMagnitudes", "dczMagnitudeTemplate");
  741. return;
  742. }
  743. // ---------------------------------------------------------------------
  744. // Thingspeak
  745. // ---------------------------------------------------------------------
  746. // Thingspeak - Relays
  747. if (key == "tspkRelays") {
  748. createRelayList(data[key], "tspkRelays", "tspkRelayTemplate");
  749. return;
  750. }
  751. // Thingspeak - Magnitudes
  752. if (key == "tspkMagnitudes") {
  753. createMagnitudeList(data[key], "tspkMagnitudes", "tspkMagnitudeTemplate");
  754. return;
  755. }
  756. // ---------------------------------------------------------------------
  757. // General
  758. // ---------------------------------------------------------------------
  759. // Messages
  760. if (key == "message") {
  761. window.alert(messages[data.message]);
  762. return;
  763. }
  764. // Enable options
  765. var position = key.indexOf("Visible");
  766. if (position > 0 && position == key.length - 7) {
  767. var module = key.slice(0,-7);
  768. $(".module-" + module).show();
  769. return;
  770. }
  771. // Pre-process
  772. if (key == "network") {
  773. data.network = data.network.toUpperCase();
  774. }
  775. if (key == "mqttStatus") {
  776. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  777. }
  778. if (key == "ntpStatus") {
  779. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  780. }
  781. if (key == "uptime") {
  782. var uptime = parseInt(data[key]);
  783. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  784. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  785. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  786. var days = uptime;
  787. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  788. }
  789. // ---------------------------------------------------------------------
  790. // Matching
  791. // ---------------------------------------------------------------------
  792. // Look for INPUTs
  793. var element = $("input[name=" + key + "]");
  794. if (element.length > 0) {
  795. if (element.attr('type') == 'checkbox') {
  796. element
  797. .prop("checked", data[key])
  798. .iphoneStyle("refresh");
  799. } else if (element.attr('type') == 'radio') {
  800. element.val([data[key]]);
  801. } else {
  802. var pre = element.attr("pre") || "";
  803. var post = element.attr("post") || "";
  804. element.val(pre + data[key] + post);
  805. }
  806. return;
  807. }
  808. // Look for SPANs
  809. var element = $("span[name=" + key + "]");
  810. if (element.length > 0) {
  811. var pre = element.attr("pre") || "";
  812. var post = element.attr("post") || "";
  813. element.html(pre + data[key] + post);
  814. return;
  815. }
  816. // Look for SELECTs
  817. var element = $("select[name=" + key + "]");
  818. if (element.length > 0) {
  819. element.val(data[key]);
  820. return;
  821. }
  822. });
  823. // Auto generate an APIKey if none defined yet
  824. if ($("input[name='apiKey']").val() == "") {
  825. generateAPIKey();
  826. }
  827. resetOriginals();
  828. }
  829. function hasChanged() {
  830. var newValue, originalValue;
  831. if ($(this).attr('type') == 'checkbox') {
  832. newValue = $(this).prop("checked")
  833. originalValue = $(this).attr("original") == "true";
  834. } else {
  835. newValue = $(this).val();
  836. originalValue = $(this).attr("original");
  837. }
  838. var hasChanged = $(this).attr("hasChanged") || 0;
  839. var action = $(this).attr("action");
  840. if (typeof originalValue == 'undefined') return;
  841. if (action == 'none') return;
  842. if (newValue != originalValue) {
  843. if (hasChanged == 0) {
  844. ++numChanged;
  845. if (action == "reconnect") ++numReconnect;
  846. if (action == "reboot") ++numReboot;
  847. if (action == "reload") ++numReload;
  848. $(this).attr("hasChanged", 1);
  849. }
  850. } else {
  851. if (hasChanged == 1) {
  852. --numChanged;
  853. if (action == "reconnect") --numReconnect;
  854. if (action == "reboot") --numReboot;
  855. if (action == "reload") --numReload;
  856. $(this).attr("hasChanged", 0);
  857. }
  858. }
  859. }
  860. function resetOriginals() {
  861. $("input,select").each(function() {
  862. $(this).attr("original", $(this).val());
  863. })
  864. numReboot = numReconnect = numReload = 0;
  865. }
  866. // -----------------------------------------------------------------------------
  867. // Init & connect
  868. // -----------------------------------------------------------------------------
  869. function connect(host) {
  870. if (typeof host === 'undefined') {
  871. host = window.location.href.replace('#', '');
  872. } else {
  873. if (host.indexOf("http") != 0) {
  874. host = 'http://' + host + '/';
  875. }
  876. }
  877. if (host.indexOf("http") != 0) return;
  878. webhost = host;
  879. wshost = host.replace('http', 'ws') + 'ws';
  880. if (websock) websock.close();
  881. websock = new WebSocket(wshost);
  882. websock.onmessage = function(evt) {
  883. var data = getJson(evt.data);
  884. if (data) processData(data);
  885. };
  886. }
  887. $(function() {
  888. initMessages();
  889. $("#menuLink").on('click', toggleMenu);
  890. $(".pure-menu-link").on('click', showPanel);
  891. $('progress').attr({ value: 0, max: 100 });
  892. $(".button-update").on('click', doUpdate);
  893. $(".button-update-password").on('click', doUpdatePassword);
  894. $(".button-reboot").on('click', doReboot);
  895. $(".button-reconnect").on('click', doReconnect);
  896. $(".button-settings-backup").on('click', doBackup);
  897. $(".button-settings-restore").on('click', doRestore);
  898. $('#uploader').on('change', onFileUpload);
  899. $(".button-upgrade").on('click', doUpgrade);
  900. $(".button-apikey").on('click', generateAPIKey);
  901. $(".button-upgrade-browse").on('click', function() {
  902. $("input[name='upgrade']")[0].click();
  903. return false;
  904. });
  905. $("input[name='upgrade']").change(function (){
  906. var fileName = $(this).val();
  907. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  908. });
  909. $(".button-add-network").on('click', function() {
  910. $(".more", addNetwork()).toggle();
  911. });
  912. $(".button-add-schedule").on('click', function() {
  913. $("div.more", addSchedule()).toggle();
  914. });
  915. $(document).on('change', 'input', hasChanged);
  916. $(document).on('change', 'select', hasChanged);
  917. connect();
  918. });