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.

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