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.

1127 lines
34 KiB

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