Advertisement
Shell_Casing

current code

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