From 82d3c47d5eed682f4af83a215ac65f95741c59cb Mon Sep 17 00:00:00 2001
From: Pithon Kabiro <pithon.kabiro@hft-stuttgart.de>
Date: Wed, 2 Jun 2021 13:05:27 +0200
Subject: [PATCH] Add line chart / Highcharts

---
 index.html            |  4 +++-
 public/js/appChart.js | 49 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)

diff --git a/index.html b/index.html
index 46c5dc0..e525e37 100644
--- a/index.html
+++ b/index.html
@@ -28,7 +28,9 @@
     <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
 
     <!-- Higcharts lib -->
-    <script src="https://code.highcharts.com/highcharts.js"></script>
+    <!-- Does not play well with `Highstock`; see: https://www.highcharts.com/errors/16/
+    <script src="https://code.highcharts.com/highcharts.js"></script> -->
+    <script src="https://code.highcharts.com/stock/highstock.js"></script>
     <script src="https://code.highcharts.com/stock/modules/data.js"></script>
     <script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
     <script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
diff --git a/public/js/appChart.js b/public/js/appChart.js
index f1a1d08..64a5e30 100644
--- a/public/js/appChart.js
+++ b/public/js/appChart.js
@@ -139,6 +139,54 @@ const drawHeatMapHC = function (obsArray) {
   });
 };
 
+/**
+ * Convert the observations' phenomenonTime from an ISO 8601 string to Unix epoch
+ * @param {*} obsArray - Response from SensorThings API as array
+ * @returns {Array}
+ */
+const formatSTAResponseForLineChart = function (obsArray) {
+  const dataSTAFormatted = [];
+  obsArray.forEach((result) => {
+    const timestampObs = new Date(result[0].slice(0, -1)).getTime(); // slice() removes trailing "Z" character in timestamp
+    const valueObs = result[1];
+    dataSTAFormatted.push([timestampObs, valueObs]);
+  });
+  return dataSTAFormatted;
+};
+
+/**
+ * Draw a line chart using Highcharts library
+ * @param {*} obsArray - Response from SensorThings API
+ * @returns {void}
+ */
+const drawLineChartHC = function (obsArray) {
+  // Create the chart
+  Highcharts.stockChart("chart-line", {
+    chart: {
+      zoomType: "x",
+    },
+
+    rangeSelector: {
+      selected: 1,
+    },
+
+    title: {
+      text: "AAPL Stock Price",
+    },
+
+    series: [
+      {
+        name: "AAPL",
+        data: formatSTAResponseForLineChart(obsArray),
+        tooltip: {
+          valueDecimals: 2,
+        },
+        turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
+      },
+    ],
+  });
+};
+
 /**
  * Follows "@iot.nextLink" links in SensorThingsAPI's response
  * Appends new results to existing results
@@ -202,4 +250,5 @@ followNextLink(
   })
   .then((observationArr) => {
     drawHeatMapHC(observationArr);
+    drawLineChartHC(observationArr);
   });
-- 
GitLab