Advertisement
Shell_Casing

combinedTable

Dec 27th, 2018
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.11 KB | None | 0 0
  1.  
  2. const API = {
  3. access_token: "",
  4. tagsUrl: 'https://dev.sealu.net:4433/api/v1/forward?url=/historian-rest-api/v1/tagslist',
  5. dataUrl: "https://dev.sealu.net:4433/api/v1/forward?url=/historian-rest-api/v1/datapoints/calculated"
  6. };
  7.  
  8.  
  9. // user inputs
  10. const form = document.querySelector('#form');
  11. const tagSelector = document.querySelector('#tagSelector');
  12. const tagSelector2 = document.querySelector('#tagSelector2');
  13. const tagSelector3 = document.querySelector('#tagSelector3');
  14. const tagSelector4 = document.querySelector('#tagSelector4');
  15. const startDate = document.querySelector('#startDate');
  16. const endDate = document.querySelector('#endDate');
  17. const startTime = document.querySelector('#startTime');
  18. const endTime = document.querySelector('#endTime');
  19. const calcMode = document.querySelector('#calcMode');
  20. const count = document.querySelector('#count');
  21. const interval = document.querySelector('#interval');
  22. const plotType = document.querySelector('#plotType');
  23. const plotButton = document.querySelector('#plotButton');
  24. const warning = document.querySelector('#warning');
  25. const errorMessage = document.querySelector('#errorMessage');
  26.  
  27. // for the tables
  28. const tableContainer = document.querySelector('#tableContainer');
  29. const table = document.querySelector('#table');
  30. const table2 = document.querySelector('#table2');
  31. const table3 = document.querySelector('#table3');
  32. const table4 = document.querySelector('#table4');
  33. const tableCaption = document.querySelector('#tableCaption');
  34. const tableCaption2 = document.querySelector('#tableCaption2');
  35. const tableCaption3 = document.querySelector('#tableCaption3');
  36. const tableCaption4 = document.querySelector('#tableCaption4');
  37.  
  38.  
  39. const tagSelectorsArray = document.querySelectorAll('.tagSelectors');
  40.  
  41.  
  42. // grabs the canvas
  43. const ctx = document.querySelector('#chart').getContext('2d');
  44.  
  45. // holds the API tags
  46. const tagsArray = [];
  47.  
  48. // these arrays hold the charts values to be plotted
  49. const valuesArray = [];
  50. const timeArray = [];
  51.  
  52. const valuesArray2 = [];
  53. const timeArray2 = []; // for tabulation
  54.  
  55. const valuesArray3 = [];
  56. const timeArray3 = [];
  57.  
  58. const valuesArray4 = [];
  59. const timeArray4 = [];
  60.  
  61.  
  62. // array of tagSelector values
  63. const tagSelectorsValues = [];
  64.  
  65. // composite table for holding values for the CSV
  66. let combinedTable = new Map();
  67.  
  68.  
  69.  
  70. let data = {
  71. labels: timeArray,
  72. datasets: [
  73. {
  74. label: tagSelector.value,
  75. fillColor: "#FF0000",
  76. highlightFill: "#FF0000",
  77. backgroundColor: "#FF0000",
  78. data: valuesArray
  79. },
  80. {
  81. label: tagSelector2.value,
  82. fillColor: "#008080",
  83. highlightFill: "#008080",
  84. backgroundColor: "#008080",
  85. data: valuesArray2
  86. },
  87. {
  88. label: tagSelector3.value,
  89. fillColor: "#FFFF00",
  90. highlightFill: "#FFFF00",
  91. backgroundColor: "#FFFF00",
  92. data: valuesArray3
  93. },
  94. {
  95. label: tagSelector4.value,
  96. fillColor: "#800080",
  97. highlightFill: "#800080",
  98. backgroundColor: "#800080",
  99. data: valuesArray4
  100. }
  101. ]
  102. };
  103.  
  104.  
  105. // chart options
  106. const options = {
  107. scales: {
  108. yAxes: [{
  109. ticks: {
  110. beginAtZero:false
  111. }
  112. }]
  113. }
  114. };
  115.  
  116.  
  117. // gets tags
  118. async function getTags() {
  119.  
  120. const options = { headers: { 'Authorization': `Bearer ${ API.access_token }` } };
  121. let response = await fetch(API.tagsUrl, options);
  122.  
  123. // let response = await fetch(`./data/tags - verbose.json`);
  124.  
  125. let data = await response.json();
  126. let tags = data.Tags;
  127. // console.log(tags);
  128. tags.map(tag => {
  129. let allTags = tag.Tagname;
  130. tagsArray.push(allTags);
  131. populateTagsInput();
  132. });
  133. }
  134.  
  135.  
  136. // populates the tags dropdown menu
  137. function populateTagsInput() {
  138.  
  139. tagsArray.forEach(tag => {
  140. tagSelectorsArray.forEach(selector => {
  141. let tagOption = document.createElement('option');
  142. tagOption.textContent = tag;
  143. tagOption.setAttribute('value', tag);
  144. selector.append(tagOption);
  145. });
  146. });
  147. }
  148.  
  149.  
  150. plotButton.addEventListener('click', checkIfFormIsFullyFilled);
  151.  
  152.  
  153. function checkIfFormIsFullyFilled(e) {
  154. e.preventDefault();
  155. console.log('button clicked');
  156.  
  157. let formInputs = form.elements;
  158. let emptyFields = [...formInputs].some(input => input.value === ''); // boolean
  159. if (emptyFields) {
  160. warning.style.display = 'block';
  161. } else {
  162. getValuesThenPlotChartsAndTabulateData();
  163. }
  164. }
  165.  
  166.  
  167. async function getValuesThenPlotChartsAndTabulateData() {
  168.  
  169. let queryUrl = generateQueryUrl();
  170. console.log(queryUrl);
  171.  
  172. const options = { headers: { 'Authorization': `Bearer ${ API.access_token }` } };
  173. let response = await fetch(queryUrl, options);
  174.  
  175. let historianData = await response.json();
  176.  
  177. // display error message in case of Historian Error code 7: "Service call to central buffer server fail."
  178. if (historianData['Data'] === undefined) {
  179. errorMessage.style.display = 'block';
  180. }
  181.  
  182. let timeStampsAndValues = historianData['Data'][0].Samples;
  183. let timeStampsAndValues2 = historianData['Data'][1].Samples || [];
  184. let timeStampsAndValues3 = historianData['Data'][2].Samples || [];
  185. let timeStampsAndValues4 = historianData['Data'][3].Samples || [];
  186.  
  187. addToCombinedTable(timeStampsAndValues, 0);
  188. addToCombinedTable(timeStampsAndValues2, 1);
  189. addToCombinedTable(timeStampsAndValues3, 2);
  190. addToCombinedTable(timeStampsAndValues4, 3);
  191.  
  192. console.log(combinedTable);
  193.  
  194. downloadTagCSV('allTags', makeCSV(combinedTable));
  195.  
  196. // fill the chart arrays
  197. timeStampsAndValues.forEach(value => {
  198. timeArray.push(simplifyTime(value.TimeStamp));
  199. valuesArray.push((parseInt(value.Value)).toFixed(0)); // removing decimal fraction
  200. });
  201.  
  202. // tabulate the data
  203. tableCaption.textContent = `Tag ${tagSelector.value}`;
  204. timeStampsAndValues.forEach(dataItem => {
  205. let row = document.createElement('tr');
  206. row.innerHTML = `<td>${simplifyTime(dataItem.TimeStamp)}</td> <td>${(parseInt(dataItem.Value)).toFixed(0)}</td>`;
  207. table.append(row);
  208. });
  209.  
  210.  
  211. if (timeStampsAndValues2.length !== 0) {
  212. // fill the chart arrays
  213. timeStampsAndValues2.forEach(value => {
  214. timeArray2.push(simplifyTime(value.TimeStamp)); // for the table
  215. valuesArray2.push((parseInt(value.Value)).toFixed(0));
  216. });
  217.  
  218. // tabulate the data
  219. tableCaption2.textContent = `Tag ${tagSelector2.value}`;
  220. timeStampsAndValues2.forEach(dataItem => {
  221. let row = document.createElement('tr');
  222. row.innerHTML = `<td>${(parseInt(dataItem.Value)).toFixed(0)}</td> `;
  223. table2.append(row);
  224. });
  225. }
  226.  
  227. if (timeStampsAndValues3.length !== 0) {
  228. timeStampsAndValues3.forEach(value => {
  229. timeArray3.push(simplifyTime(value.TimeStamp));
  230. valuesArray3.push((parseInt(value.Value)).toFixed(0));
  231. });
  232.  
  233. // tabulate the data
  234. tableCaption3.textContent = `Tag ${tagSelector3.value}`;
  235. timeStampsAndValues3.forEach(dataItem => {
  236. let row = document.createElement('tr');
  237. row.innerHTML = `<td>${(parseInt(dataItem.Value)).toFixed(0)}</td> `;
  238. table3.append(row);
  239. });
  240. }
  241.  
  242. if (timeStampsAndValues4.length !== 0) {
  243. timeStampsAndValues4.forEach(value => {
  244. timeArray4.push(simplifyTime(value.TimeStamp));
  245. valuesArray4.push((parseInt(value.Value)).toFixed(0));
  246. });
  247.  
  248. // tabulate the data
  249. tableCaption4.textContent = `Tag ${tagSelector4.value}`;
  250. timeStampsAndValues4.forEach(dataItem => {
  251. let row = document.createElement('tr');
  252. row.innerHTML = `<td>${(parseInt(dataItem.Value)).toFixed(0)}</td> `;
  253. table4.append(row);
  254. });
  255. }
  256.  
  257. plotChart();
  258. tableContainer.style.display = 'block';
  259. }
  260.  
  261.  
  262. // grabs the form inputs and builds the API query URL
  263. function generateQueryUrl() {
  264. // change interval value to milliseconds
  265. const milliseconds = Math.ceil((parseInt(interval.value))*1000);
  266. tagSelectorsValues.push(`${tagSelector.value}%3B`, `${tagSelector2.value}%3B`, `${tagSelector3.value}%3B`, `${tagSelector4.value}`); // concatenates tagSelector values and separates them with semicolon
  267. return `${API.dataUrl}/${tagSelectorsValues.join('')}/${startDate.value}T${startTime.value}/${endDate.value}T${endTime.value}/${calcMode.value}/${count.value}/${milliseconds}`;
  268. }
  269.  
  270.  
  271.  
  272. // trims off the seconds
  273. function simplifyTime(timestamp) {
  274. return timestamp.slice(0, 16);
  275. }
  276.  
  277.  
  278. // adds values to combined table for the CSV file
  279. function addToCombinedTable(items, n) {
  280. items.forEach(item => {
  281. combinedTable[item.TimeStamp] = [];
  282. combinedTable[item.TimeStamp][n] = item.Value;
  283. // return combinedTable;
  284. });
  285. }
  286.  
  287.  
  288. // returns CSV of object array (duh)
  289. function makeCSV(objectArray) {
  290. let fields = Object.keys(objectArray[0]);
  291.  
  292. let csv = objectArray.map(row => {
  293. return fields.map(fieldName => {
  294. return JSON.stringify(row[fieldName], replacer)
  295. }).join(',')
  296. });
  297.  
  298. csv.unshift(fields.join(',')); // add header column
  299. return csv.join('\r\n');
  300. }
  301.  
  302.  
  303. // goes hand-in-hand with makeCSV function
  304. function replacer(key, value) {
  305. return value === null ? '' : value;
  306. }
  307.  
  308.  
  309. // creates the download link for the CSV file
  310. function downloadTagCSV(filename, csvFile) {
  311. let link = document.createElement('a');
  312. link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURI(csvFile)); // href is set to a "data URI"
  313. link.setAttribute('download', filename + '.csv');
  314. link.textContent = 'Download';
  315. link.click();
  316. }
  317.  
  318.  
  319. function plotChart() {
  320. const chart = new Chart(ctx, {
  321. type: plotType.value,
  322. data: data,
  323. options: options
  324. });
  325. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement