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

// Request parameters
4
5

// Observations WITHOUT data gap - Bau 225
Pithon Kabiro's avatar
Pithon Kabiro committed
6
const BASE_URL =
Pithon Kabiro's avatar
Pithon Kabiro committed
7
  "http://193.196.39.91:8080/frost-icity-tp31/v1.1/Datastreams(80)/Observations";
8

Pithon Kabiro's avatar
Pithon Kabiro committed
9
10
11
const PARAM_RESULT_FORMAT = "dataArray";
const PARAM_ORDER_BY = "phenomenonTime asc";
const PARAM_FILTER =
12
  "resultTime ge 2020-01-01T00:00:00.000Z and resultTime le 2021-01-01T00:00:00.000Z";
Pithon Kabiro's avatar
Pithon Kabiro committed
13
14
const PARAM_SELECT = "result,phenomenonTime";

15
16
17
18
19
20
// Observations WITH data gap - Bau 112
const BASE_URL2 =
  "http://193.196.39.91:8080/frost-icity-tp31-v2/v1.1/Datastreams(78)/Observations";
const PARAM_FILTER2 =
  "resultTime ge 2020-06-01T00:00:00.000Z and resultTime le 2021-01-01T00:00:00.000Z";

Pithon Kabiro's avatar
Pithon Kabiro committed
21
/**
Pithon Kabiro's avatar
Pithon Kabiro committed
22
23
24
25
26
 * 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
27
 */
Pithon Kabiro's avatar
Pithon Kabiro committed
28
29
30
31
32
const drawEmptyLineChartAC = function (
  htmlElement,
  mainTitle = "Main Chart Title",
  yAxisTitle = "y-axis title"
) {
Pithon Kabiro's avatar
Pithon Kabiro committed
33
  // Chart constants
Pithon Kabiro's avatar
Pithon Kabiro committed
34
35
36
  const CHART_HTML_ELEMENT = htmlElement;
  const TITLE_TEXT = mainTitle;
  const Y_AXIS_TITLE = yAxisTitle;
Pithon Kabiro's avatar
Pithon Kabiro committed
37
38

  const options = {
Pithon Kabiro's avatar
Pithon Kabiro committed
39
    series: [],
Pithon Kabiro's avatar
Pithon Kabiro committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    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
63
64
65
    noData: {
      text: "Loading...",
    },
Pithon Kabiro's avatar
Pithon Kabiro committed
66
67
68
69
70
71
72
73
74
75
76
77
78
    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
79
          return val.toFixed(0);
Pithon Kabiro's avatar
Pithon Kabiro committed
80
        },
Pithon Kabiro's avatar
Pithon Kabiro committed
81
        forceNiceScale: true,
Pithon Kabiro's avatar
Pithon Kabiro committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
      },
      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
101
102
103
104
  return chart;
};

// Line chart 1 constants
105
const chart1LineHTML = document.querySelector("#chart-line");
Pithon Kabiro's avatar
Pithon Kabiro committed
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
370
371
372
373
374
375
376
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
377

Pithon Kabiro's avatar
Pithon Kabiro committed
378
  const chart = new ApexCharts(
379
    document.querySelector("#chart-heatmap"),
Pithon Kabiro's avatar
Pithon Kabiro committed
380
381
    options
  );
Pithon Kabiro's avatar
Pithon Kabiro committed
382
383
384
  chart.render();
};

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/**
 * Draw a heatmap using Highcharts library
 * @param {*} obsArray - Response from SensorThings API as array
 * @returns {void}
 */
const drawHeatMapHC = function (obsArray) {
  /**
   * Format the response from SensorThings API to make it suitable for heatmap
   * @returns {Array}
   */
  const formatSTAResponseForHeatMap = function () {
    const dataSTAFormatted = [];
    obsArray.forEach((obs) => {
      // Get the date/time string; first element in input array; remove trailing "Z"
      const obsDateTimeInput = obs[0].slice(0, -1);
      // Get the "date" part of an observation
      const obsDateInput = obs[0].slice(0, 10);
      // Create Date objects
      const obsDateTime = new Date(obsDateTimeInput);
      const obsDate = new Date(obsDateInput);
      // x-axis -> timestamp; will be the same for observations from the same date
      const timestamp = Date.parse(obsDate);
      // y-axis -> hourOfDay
      const hourOfDay = obsDateTime.getHours();
      // value -> the observation's value; second element in input array
      const value = obs[1];
      dataSTAFormatted.push([timestamp, hourOfDay, value]);
    });
    return dataSTAFormatted;
  };

  Highcharts.chart("chart-heatmap", {
    chart: {
      type: "heatmap",
      zoomType: "x",
    },

    boost: {
      useGPUTranslations: true,
    },

    title: {
      text: "Inlet flow (Vorlauf)",
      align: "left",
      x: 40,
    },

    subtitle: {
      text: "Temperature variation by day and hour in 2020",
      align: "left",
      x: 40,
    },

    xAxis: {
      type: "datetime",
      // min: Date.UTC(2017, 0, 1),
      // max: Date.UTC(2017, 11, 31, 23, 59, 59),
      labels: {
        align: "left",
        x: 5,
        y: 14,
        format: "{value:%B}", // long month
      },
      showLastLabel: false,
      tickLength: 16,
    },

    yAxis: {
      title: {
        text: null,
      },
      labels: {
        format: "{value}:00",
      },
      minPadding: 0,
      maxPadding: 0,
      startOnTick: false,
      endOnTick: false,
      // tickPositions: [0, 6, 12, 18, 24],
      tickPositions: [0, 3, 6, 9, 12, 15, 18, 21, 24],
      tickWidth: 1,
      min: 0,
      max: 23,
      reversed: true,
    },

    colorAxis: {
      stops: [
        [0, "#3060cf"],
        [0.5, "#fffbbc"],
        [0.9, "#c4463a"],
        [1, "#c4463a"],
      ],
      min: 60,
      max: 85,
      startOnTick: false,
      endOnTick: false,
      labels: {
        format: "{value}℃",
      },
    },

    series: [
      {
        data: formatSTAResponseForHeatMap(),
        boostThreshold: 100,
        borderWidth: 0,
        nullColor: "#525252",
        colsize: 24 * 36e5, // one day
        tooltip: {
          headerFormat: "Temperature<br/>",
          pointFormat:
            "{point.x:%e %b, %Y} {point.y}:00: <b>{point.value} ℃</b>",
        },
        turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
      },
    ],
  });
};

Pithon Kabiro's avatar
Pithon Kabiro committed
505
/**
Pithon Kabiro's avatar
Pithon Kabiro committed
506
 * Follows "@iot.nextLink" links in SensorThingsAPI's response
Pithon Kabiro's avatar
Pithon Kabiro committed
507
 * Appends new results to existing results
Pithon Kabiro's avatar
Pithon Kabiro committed
508
509
510
 * @async
 * @param {Object} responsePromise - Promise object
 * @returns {Object} - Object containing results from all the "@iot.nextLink" links
Pithon Kabiro's avatar
Pithon Kabiro committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
 */
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);
    });
};

// Get "ALL" the Observations that satisfy our query
followNextLink(
  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
558
559
    // DEBUG: Print the array of observations
    console.log(combinedObservations);
Pithon Kabiro's avatar
Pithon Kabiro committed
560
561
562
563
564
565
566

    return combinedObservations;
  })
  .catch((err) => {
    console.log(err);
  })
  .then((observationArr) => {
567
568
569
    // updateLineChartAC(chart1LineTitle, observationArr);
    // drawHeatMapAC2(observationArr);
    drawHeatMapHC(observationArr);
Pithon Kabiro's avatar
Pithon Kabiro committed
570
  });