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.

1064 lines
32 KiB

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