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.

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