appChart.js 11.1 KB
Newer Older
Pithon Kabiro's avatar
Pithon Kabiro committed
1
"use strict";
Pithon Kabiro's avatar
Pithon Kabiro committed
2
3
4

// Request parameters
const BASE_URL =
Pithon Kabiro's avatar
Pithon Kabiro committed
5
6
7
  "http://193.196.39.91:8080/frost-icity-tp31/v1.1/Datastreams(80)/Observations";
const BASE_URL2 =
  "http://193.196.39.91:8080/frost-icity-tp31-v2/v1.1/Datastreams(41)/Observations";
Pithon Kabiro's avatar
Pithon Kabiro committed
8
9
10
const PARAM_RESULT_FORMAT = "dataArray";
const PARAM_ORDER_BY = "phenomenonTime asc";
const PARAM_FILTER =
Pithon Kabiro's avatar
Pithon Kabiro committed
11
  "resultTime ge 2020-01-01T00:00:00.000Z and resultTime le 2020-07-01T00:00:00.000Z";
Pithon Kabiro's avatar
Pithon Kabiro committed
12
13
14
const PARAM_SELECT = "result,phenomenonTime";

/**
Pithon Kabiro's avatar
Pithon Kabiro committed
15
16
17
18
19
 * Draw an EMPTY chart using Apexcharts library
 * @param {HTMLElement} htmlElement - HTML element where chart will be drawn
 * @param {String} mainTitle - Main chart title
 * @param {String} yAxisTitle - Y-axis title
 * @returns {Object} - An empty chart object
Pithon Kabiro's avatar
Pithon Kabiro committed
20
 */
Pithon Kabiro's avatar
Pithon Kabiro committed
21
22
23
24
25
const drawEmptyLineChartAC = function (
  htmlElement,
  mainTitle = "Main Chart Title",
  yAxisTitle = "y-axis title"
) {
Pithon Kabiro's avatar
Pithon Kabiro committed
26
  // Chart constants
Pithon Kabiro's avatar
Pithon Kabiro committed
27
28
29
  const CHART_HTML_ELEMENT = htmlElement;
  const TITLE_TEXT = mainTitle;
  const Y_AXIS_TITLE = yAxisTitle;
Pithon Kabiro's avatar
Pithon Kabiro committed
30
31

  const options = {
Pithon Kabiro's avatar
Pithon Kabiro committed
32
    series: [],
Pithon Kabiro's avatar
Pithon Kabiro committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    chart: {
      type: "area",
      stacked: false,
      height: 350,
      zoom: {
        type: "x",
        enabled: true,
        autoScaleYaxis: true,
      },
      toolbar: {
        autoSelected: "zoom",
      },
    },
    dataLabels: {
      enabled: false,
    },
    markers: {
      size: 0,
    },
    title: {
      text: TITLE_TEXT,
      align: "left",
    },
Pithon Kabiro's avatar
Pithon Kabiro committed
56
57
58
    noData: {
      text: "Loading...",
    },
Pithon Kabiro's avatar
Pithon Kabiro committed
59
60
61
62
63
64
65
66
67
68
69
70
71
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        inverseColors: false,
        opacityFrom: 0.5,
        opacityTo: 0,
        stops: [0, 90, 100],
      },
    },
    yaxis: {
      labels: {
        formatter: function (val) {
Pithon Kabiro's avatar
Pithon Kabiro committed
72
          return val.toFixed(0);
Pithon Kabiro's avatar
Pithon Kabiro committed
73
        },
Pithon Kabiro's avatar
Pithon Kabiro committed
74
        forceNiceScale: true,
Pithon Kabiro's avatar
Pithon Kabiro committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
      },
      title: {
        text: Y_AXIS_TITLE,
      },
    },
    xaxis: {
      type: "datetime",
    },
    tooltip: {
      shared: false,
      y: {
        formatter: function (val) {
          return val.toFixed(2);
        },
      },
    },
  };

  const chart = new ApexCharts(CHART_HTML_ELEMENT, options);
Pithon Kabiro's avatar
Pithon Kabiro committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
  return chart;
};

// Line chart 1 constants
const chart1LineHTML = document.querySelector("#chart-apex-line");
const chart1LineTitle = "Inlet flow (Vorlauf)";
const chart1LineYAxisTitle = "Temperature (°C)";

// Draw an empty line chart
const lineChartApex = drawEmptyLineChartAC(
  chart1LineHTML,
  chart1LineTitle,
  chart1LineYAxisTitle
);
lineChartApex.render();

/**
 * Update an empty chart created using Apexcharts library
 * @param {String} chartName
 * @param {Array} dataArr
 * @returns {void}
 */
const updateLineChartAC = function (chartName, dataArr) {
  const CHART_NAME = chartName;
  // Update the chart
  lineChartApex.updateSeries([
    {
      name: CHART_NAME,
      data: dataArr,
    },
  ]);
};

/**
 * Draw a heatmap using the ApexCharts library
 * ATTEMPT 1
 * @param {Array} obsArray - Response from SensorThings API as array
 * @returns {void}
 */
const drawHeatMapAC1 = function (obsArray) {
  // Chart constants
  const CHART_HEATMAP_TITLE = "HeatMap Chart";
  const CHART_HEATMAP_NAME_SERIES_1 = "VL-225";
  // const CHART_HEATMAP_NAME_SERIES_2 = "W2";

  /**
   * Convert SensorThings API response (an array) into an object
   * @returns {Object} - Chart series object
   */
  const generateHeatMapData = function () {
    const series = [];
    obsArray.forEach(([obsTime, obsValue]) => {
      series.push({
        x: obsTime.slice(0, -1), // remove trailing "Z" from timestamp
        y: obsValue,
      });
    });
    return series;
  };

  const data = [
    {
      name: CHART_HEATMAP_NAME_SERIES_1,
      data: generateHeatMapData(obsArray),
    },
    // {
    //   name: CHART_HEATMAP_NAME_SERIES_2,
    //   data: generateHeatMapData(obsArray),
    // },
  ];

  data.reverse();

  const colors = [
    "#F3B415",
    "#F27036",
    "#663F59",
    "#6A6E94",
    "#4E88B4",
    "#00A7C6",
    "#18D8D8",
    "#A9D794",
    "#46AF78",
    "#A93F55",
    "#8C5E58",
    "#2176FF",
    "#33A1FD",
    "#7A918D",
    "#BAFF29",
  ];

  // colors.reverse();

  const options = {
    series: data,
    chart: {
      height: 350,
      type: "heatmap",
    },
    dataLabels: {
      enabled: false,
    },
    colors: colors,

    title: {
      text: CHART_HEATMAP_TITLE,
    },
    grid: {
      padding: {
        right: 20,
      },
    },
    xaxis: {
      type: "datetime",
    },
    tooltip: {
      shared: false,
      x: {
        formatter: function (val) {
          return new Date(val).toLocaleString();
        },
      },
      y: {
        formatter: function (val) {
          return val.toFixed(2);
        },
      },
    },
    plotOptions: {
      heatmap: {
        useFillColorAsStroke: true, // we need this option for the chart to be visible
        // distributed: true,
        // enableShades: false,
      },
    },
  };

  const chart = new ApexCharts(
    document.querySelector("#chart-apex-heatmap"),
    options
  );
  chart.render();
};

/**
 * Draw a heatmap using the ApexCharts library
 * ATTEMPT 2
 * @param {Array} obsArray - Response from SensorThings API as array
 * @returns {void}
 */
const drawHeatMapAC2 = function (obsArray) {
  // Chart constants
  const CHART_HEATMAP_TITLE = "HeatMap Chart";
  const CHART_HEATMAP_NAME_SERIES_1 = "VL-225";

  /**
   * Convert SensorThings API response (an array) into an object
   * @returns {Object} - Chart series object
   */
  const generateHeatMapData = function () {
    const series = [];
    obsArray.forEach(([obsTime, obsValue]) => {
      series.push({
        x: obsTime.slice(0, -1), // remove trailing "Z" from timestamp
        y: obsValue,
      });
    });
    return series;
  };

  const data = [
    {
      name: CHART_HEATMAP_NAME_SERIES_1,
      data: generateHeatMapData(obsArray),
    },
    // {
    //   name: CHART_HEATMAP_NAME_SERIES_2,
    //   data: generateHeatMapData(obsArray),
    // },
  ];

  // Constants for our data range
  const LOW_FROM = 65;
  const LOW_TO = 70;
  const MEDIUM_FROM = 70;
  const MEDIUM_TO = 75;
  const HIGH_FROM = 75;
  const HIGH_TO = 80;
  const EXTREME_FROM = 80;
  const EXTREME_TO = 85;
  const options = {
    series: data,
    chart: {
      height: 450,
      type: "heatmap",
    },
    plotOptions: {
      heatmap: {
        shadeIntensity: 0.5,
        radius: 0,
        useFillColorAsStroke: true,
        colorScale: {
          ranges: [
            {
              from: null,
              to: null,
              name: "null",
              color: "#525252",
            },
            {
              from: LOW_FROM,
              to: LOW_TO,
              name: `${LOW_FROM}°C`,
              color: "#1a9641",
            },
            {
              from: MEDIUM_FROM,
              to: MEDIUM_TO,
              name: `${MEDIUM_FROM}°C`,
              color: "#a6d96a",
            },
            {
              from: HIGH_FROM,
              to: HIGH_TO,
              name: `${HIGH_FROM}°C`,
              color: "#fdae61",
            },
            {
              from: EXTREME_FROM,
              to: EXTREME_TO,
              name: `${EXTREME_FROM}°C`,
              color: "#d7191c",
            },
          ],
        },
      },
    },
    dataLabels: {
      enabled: false,
    },
    stroke: {
      width: 1,
    },
    title: {
      text: CHART_HEATMAP_TITLE,
    },
    grid: {
      padding: {
        right: 20,
      },
    },
    xaxis: {
      type: "datetime",
      // labels: {
      //   format: "MMM",
      // },
    },
    tooltip: {
      shared: false,
      x: {
        formatter: function (val) {
          return new Date(val).toLocaleString();
        },
      },
      y: {
        formatter: function (val) {
          if (val) {
            return val.toFixed(2);
          } else {
            return "null";
          }
        },
      },
    },
    // distributed: true,
  };
Pithon Kabiro's avatar
Pithon Kabiro committed
370

Pithon Kabiro's avatar
Pithon Kabiro committed
371
372
373
374
  const chart = new ApexCharts(
    document.querySelector("#chart-apex-heatmap"),
    options
  );
Pithon Kabiro's avatar
Pithon Kabiro committed
375
376
377
378
  chart.render();
};

/**
Pithon Kabiro's avatar
Pithon Kabiro committed
379
 * Follows "@iot.nextLink" links in SensorThingsAPI's response
Pithon Kabiro's avatar
Pithon Kabiro committed
380
 * Appends new results to existing results
Pithon Kabiro's avatar
Pithon Kabiro committed
381
382
383
 * @async
 * @param {Object} responsePromise - Promise object
 * @returns {Object} - Object containing results from all the "@iot.nextLink" links
Pithon Kabiro's avatar
Pithon Kabiro committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
 */
const followNextLink = function (responsePromise) {
  return responsePromise
    .then(function (lastSuccess) {
      if (lastSuccess.data["@iot.nextLink"]) {
        return followNextLink(
          axios.get(lastSuccess.data["@iot.nextLink"])
        ).then(function (nextLinkSuccess) {
          nextLinkSuccess.data.value = lastSuccess.data.value.concat(
            nextLinkSuccess.data.value
          );
          return nextLinkSuccess;
        });
      } else {
        return lastSuccess;
      }
    })
    .catch(function (err) {
      console.log(err);
    });
};

406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
///////////////////////////////////////////////////////////////
function getDataReadyForSimplifyJS(pts) {
  var val = [];
  
  for (var i = 0, len = pts.length; i < len; i++) 
    val.push(pts[i][1]);
  
  pts = val;

  let newPts = [];
  for (var i = 0, len = pts.length; i < len; i++) 
    newPts.push({ x: i, y: pts[i] });  
  return newPts;
}
///////////////////////////////////////////////////////////////
function getPointIndiciesFromXYjson(pts) {
  let newPts = [];
  for (var i = 0, len = pts.length; i < len; i++) 
    newPts.push(pts[i].x);    
  return newPts;
}

///////////////////////////////////////////////////////////////
function getReducedDataFromSimplifiedData(originalData, simplified_data) {    
  let red_data = [];
  let new_start = 0;
  for (var i = 0; i < originalData.length; i++) 
    for (var j=new_start; j < simplified_data.length; j++){
      if (i == simplified_data[j].x){
        red_data.push([originalData[i][0],originalData[i][1]]);
        new_start = j+1;
      }
    }
  return red_data;
}

Pithon Kabiro's avatar
Pithon Kabiro committed
442
// Get "ALL" the Observations that satisfy our query
443
var res = followNextLink(
Pithon Kabiro's avatar
Pithon Kabiro committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
  axios.get(BASE_URL, {
    params: {
      "$resultFormat": PARAM_RESULT_FORMAT,
      "$orderBy": PARAM_ORDER_BY,
      "$filter": PARAM_FILTER,
      "$select": PARAM_SELECT,
    },
  })
)
  .then((success) => {
    const successValue = success.data.value;

    // Array that will hold the combined observations
    const combinedObservations = [];

    successValue.forEach((dataObj) => {
      // Each page of results will have a dataArray that holds the observations
      const dataArrays = dataObj.dataArray;

      combinedObservations.push(...dataArrays);
    });
    // DEBUG: Check total number of observations
    console.log(combinedObservations.length);
Pithon Kabiro's avatar
Pithon Kabiro committed
467
468
    // DEBUG: Print the array of observations
    console.log(combinedObservations);
Pithon Kabiro's avatar
Pithon Kabiro committed
469
470
471
472
473
474
475

    return combinedObservations;
  })
  .catch((err) => {
    console.log(err);
  })
  .then((observationArr) => {
476
477
478
479
480
481
482
483
484
485
    // updateLineChartAC(chart1LineTitle, observationArr);
     
    let simplified_data = simplify(getDataReadyForSimplifyJS(observationArr),2,true);
    let reducedData =  getReducedDataFromSimplifiedData(observationArr, simplified_data);

    updateLineChartAC(chart1LineTitle, reducedData);
    // drawHeatMapAC2(observationArr);
    drawHeatMapAC2(reducedData);
    console.log(reducedData.length, observationArr.length);
    return reducedData;
Pithon Kabiro's avatar
Pithon Kabiro committed
486
  });
487