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.

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