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

3
const BASE_URL = "http://193.196.39.91:8080/frost-icity-tp31/v1.1";
4

5
6
/**
 * Retrieve the datastream ID that corresponds to a particular building
7
8
9
 * @param {Number | String} buildingNumber Integer representing the building ID
 * @param {String} phenomenon String representing the phenomenon of interest
 * @param {String} samplingRate String representing the sampling rate of the observations
10
11
 * @returns {Number} Datastream corresponding to the input building
 */
12
const getDatastreamIdFromBuildingNumber = function (
13
14
15
16
17
18
19
20
  buildingNumber,
  phenomenon,
  samplingRate
) {
  const buildingToDatastreamMapping = {
    101: {
      vl: { "15min": "69", "60min": "75" },
      rl: { "15min": "81", "60min": "87" },
21
22
23
24
25
26

      // These Datastreams do not yet have Observations
      // flow: { "15min": "93", "60min": "99" },
      // power: { "15min": "105", "60min": "111" },
      // energy: { "15min": "117", "60min": "123" },
      // energy_verb: { "15min": "129", "60min": "135" },
27
    },
28

29
30
31
    102: {
      vl: { "15min": "70", "60min": "76" },
      rl: { "15min": "82", "60min": "88" },
32
33
34
35
36
37

      // These Datastreams do not yet have Observations
      // flow: { "15min": "94", "60min": "100" },
      // power: { "15min": "106", "60min": "112" },
      // energy: { "15min": "118", "60min": "124" },
      // energy_verb: { "15min": "130", "60min": "136" },
38
    },
39

40
41
42
    107: {
      vl: { "15min": "71", "60min": "77" },
      rl: { "15min": "83", "60min": "89" },
43
44
45
46
47
48

      // These Datastreams do not yet have Observations
      // flow: { "15min": "95", "60min": "101" },
      // power: { "15min": "107", "60min": "113" },
      // energy: { "15min": "119", "60min": "125" },
      // energy_verb: { "15min": "131", "60min": "137" },
49
    },
50

51
    "112, 118": {
52
53
      vl: { "15min": "72", "60min": "78" },
      rl: { "15min": "84", "60min": "90" },
54
55
56
57
58
59

      // These Datastreams do not yet have Observations
      // flow: { "15min": "96", "60min": "102" },
      // power: { "15min": "108", "60min": "114" },
      // energy: { "15min": "120", "60min": "126" },
      // energy_verb: { "15min": "132", "60min": "138" },
60
    },
61

62
63
64
    125: {
      vl: { "15min": "73", "60min": "79" },
      rl: { "15min": "85", "60min": "91" },
65
66
67
68
69
70

      // These Datastreams do not yet have Observations
      // flow: { "15min": "97", "60min": "103" },
      // power: { "15min": "109", "60min": "115" },
      // energy: { "15min": "121", "60min": "127" },
      // energy_verb: { "15min": "133", "60min": "139" },
71
    },
72

73
74
75
76
77
78
79
80
81
82
    225: {
      vl: { "15min": "74", "60min": "80" },
      rl: { "15min": "86", "60min": "92" },
      flow: { "15min": "98", "60min": "104" },
      power: { "15min": "110", "60min": "116" },
      energy: { "15min": "122", "60min": "128" },
      energy_verb: { "15min": "134", "60min": "140" },
    },
  };

83
84
85
86
87
88
  if (
    buildingToDatastreamMapping?.[buildingNumber]?.[phenomenon]?.[
      samplingRate
    ] === undefined
  )
    return;
89

90
91
92
93
94
95
96
  const datastreamIdMatched = Number(
    buildingToDatastreamMapping[buildingNumber][phenomenon][samplingRate]
  );

  return datastreamIdMatched;
};

97
98
99
100
101
102
/**
 * Create URL to fetch the details of single Datastream
 * @param {String} baseUrl Base URL of the STA server
 * @param {Number} datastreamID Integer representing the Datastream ID
 * @returns {String} URL string for fetching a single Datastream
 */
103
const getDatastreamUrl = function (baseUrl, datastreamID) {
104
105
106
107
108
  if (!datastreamID) return;
  const fullDatastreamURL = `${baseUrl}/Datastreams(${datastreamID})`;
  return fullDatastreamURL;
};

109
/**
110
 * Create URL to fetch Observations
111
 * @param {String} baseUrl Base URL of the STA server
112
113
 * @param {Number} datastreamID Integer representing the Datastream ID
 * @returns {String} URL string for fetching Observations
114
 */
115
const getObservationsUrl = function (baseUrl, datastreamID) {
116
  if (!datastreamID) return;
117
118
  const fullObservationsURL = `${baseUrl}/Datastreams(${datastreamID})/Observations`;
  return fullObservationsURL;
119
120
121
122
};

/**
 * Create a temporal filter string for the fetched Observations
123
124
125
 * @param {String} dateStart Start date in YYYY-MM-DD format
 * @param {String} dateStop Stop date in YYYY-MM-DD format
 * @returns {String} Temporal filter string
126
 */
127
const createTemporalFilterString = function (dateStart, dateStop) {
128
129
130
131
132
  if (!dateStart || !dateStop) return;
  const filterString = `resultTime ge ${dateStart}T00:00:00.000Z and resultTime le ${dateStop}T00:00:00.000Z`;
  return filterString;
};

133
// const BASE_URL_OBSERVATIONS = getObservationsUrl(80);
134
135
136
137
138
139
140
const QUERY_PARAM_RESULT_FORMAT = "dataArray";
const QUERY_PARAM_ORDER_BY = "phenomenonTime asc";
const QUERY_PARAM_FILTER = createTemporalFilterString(
  "2020-01-01",
  "2021-01-01"
);
const QUERY_PARAM_SELECT = "result,phenomenonTime";
141
const QUERY_PARAMS_COMBINED = {
142
143
144
145
  "$resultFormat": QUERY_PARAM_RESULT_FORMAT,
  "$orderBy": QUERY_PARAM_ORDER_BY,
  "$filter": QUERY_PARAM_FILTER,
  "$select": QUERY_PARAM_SELECT,
146
};
Pithon Kabiro's avatar
Pithon Kabiro committed
147

148
149
/**
 * Perform a GET request using the Axios library
150
 * @param {String} urlObservations A URL that fetches Observations from an STA instance
151
 * @param {Object} urlParamObj The URL parameters to be sent together with the GET request
152
 * @returns {Promise} A promise that contains the first page of results when fulfilled
153
 */
154
const axiosGetRequest = function (urlObservations, urlParamObj) {
155
156
157
158
  return axios.get(urlObservations, {
    params: urlParamObj,
  });
};
159

160
161
162
163
164
165
/**
 * Retrieve the metadata for a single datastream
 * @async
 * @param {String} urlDatastream A URL that fetches a Datastream from an STA instance
 * @returns {Promise} A promise that contains a metadata object for a Datastream when fulfilled
 */
166
const getDatastreamMetadata = async function (urlDatastream) {
167
168
169
170
171
172
173
174
  try {
    // Extract properties of interest
    const {
      data: { description, name, unitOfMeasurement },
    } = await axiosGetRequest(urlDatastream);

    return { description, name, unitOfMeasurement };
  } catch (err) {
175
    console.error(err);
176
177
178
  }
};

179
180
181
182
183
/**
 * Format the response containing a Datastream's metadata from Sensorthings API
 * @param {Object} datastreamMetadata An object containing a Datastream's metadata
 * @returns {Object} An object containing the formatted metadata that is suitable for use in a line chart or heatmap
 */
184
const formatDatastreamMetadataForChart = function (datastreamMetadata) {
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
  const {
    description: datastreamDescription,
    name: datastreamName,
    unitOfMeasurement,
  } = datastreamMetadata;

  // Extract phenomenon name from Datastream name
  const regex = /\/ (.*) DS/;
  const phenomenonName = datastreamName.match(regex)[1]; // use second element in array

  // Match the unitOfMeasurement's string representation of a symbol
  // to an actual symbol, where necessary
  const unitOfMeasurementSymbol = (() => {
    if (unitOfMeasurement.symbol === "degC") {
      return "";
    } else if (unitOfMeasurement.symbol === "m3/h") {
      return "m<sup>3</sup>/h";
    } else {
      return unitOfMeasurement.symbol;
    }
  })();

  return {
    datastreamDescription,
    datastreamName,
    phenomenonName,
    unitOfMeasurementSymbol,
  };
};

215
/**
216
 * Format the response from SensorThings API to make it suitable for heatmap
217
218
 * @param {Array} obsArray Response from SensorThings API as array
 * @returns {Array} Array of formatted observations suitable for use in a heatmap
219
 */
220
const formatSTAResponseForHeatMap = function (obsArray) {
Pithon Kabiro's avatar
Pithon Kabiro committed
221
  if (!obsArray) return;
222
223

  const dataSTAFormatted = obsArray.map((obs) => {
224
225
226
227
228
229
230
231
232
233
234
235
236
    // 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];
237
    return [timestamp, hourOfDay, value];
238
  });
239

240
241
242
243
244
  return dataSTAFormatted;
};

/**
 * Draw a heatmap using Highcharts library
245
 * @param {Array} formattedObsArrayForHeatmap Response from SensorThings API formatted for use in a heatmap
246
 * @param {Object} formattedDatastreamMetadata Object containing Datastream metadata
247
 * @returns {undefined} undefined
248
 */
249
const drawHeatMapHC = function (
250
  formattedObsArrayForHeatmap,
251
  formattedDatastreamMetadata
252
) {
253
254
255
256
257
258
259
  const {
    datastreamDescription: DATASTREAM_DESCRIPTION,
    datastreamName: DATASTREAM_NAME,
    phenomenonName: PHENOMENON_NAME,
    unitOfMeasurementSymbol: PHENOMENON_SYMBOL,
  } = formattedDatastreamMetadata;

Pithon Kabiro's avatar
Pithon Kabiro committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
  // Function returns the min and max observation values
  const {
    minObsValue: MINIMUM_VALUE_COLOR_AXIS,
    maxObsValue: MAXIMUM_VALUE_COLOR_AXIS,
  } = (() => {
    // The observation value is the third element in array
    const obsValueArr = formattedObsArrayForHeatmap.map((obs) => obs[2]);

    // Extract integer part
    const minValue = Math.trunc(Math.min(...obsValueArr));
    const maxValue = Math.trunc(Math.max(...obsValueArr));

    // Calculate the closest multiple of 5
    const minObsValue = minValue - (minValue % 5);
    const maxObsValue = maxValue + (5 - (maxValue % 5));

    return { minObsValue, maxObsValue };
  })();

279
280
281
282
283
284
285
286
287
288
289
  Highcharts.chart("chart-heatmap", {
    chart: {
      type: "heatmap",
      zoomType: "x",
    },

    boost: {
      useGPUTranslations: true,
    },

    title: {
290
      text: DATASTREAM_DESCRIPTION,
291
292
293
294
295
      align: "left",
      x: 40,
    },

    subtitle: {
296
      text: DATASTREAM_NAME,
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
      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, 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"],
      ],
Pithon Kabiro's avatar
Pithon Kabiro committed
340
341
      min: MINIMUM_VALUE_COLOR_AXIS,
      max: MAXIMUM_VALUE_COLOR_AXIS,
342
343
344
      startOnTick: false,
      endOnTick: false,
      labels: {
345
346
        // format: "{value}℃",
        format: `{value}${PHENOMENON_SYMBOL}`,
347
348
349
350
351
      },
    },

    series: [
      {
352
        data: formattedObsArrayForHeatmap,
353
354
355
356
357
        boostThreshold: 100,
        borderWidth: 0,
        nullColor: "#525252",
        colsize: 24 * 36e5, // one day
        tooltip: {
358
359
          headerFormat: `${PHENOMENON_NAME}<br/>`,
          valueDecimals: 2,
360
          pointFormat:
361
362
            // "{point.x:%e %b, %Y} {point.y}:00: <b>{point.value} ℃</b>",
            `{point.x:%e %b, %Y} {point.y}:00: <b>{point.value} ${PHENOMENON_SYMBOL}</b>`,
Pithon Kabiro's avatar
Pithon Kabiro committed
363
          nullFormat: `{point.x:%e %b, %Y} {point.y}:00: <b>null</b>`,
364
365
366
367
368
369
370
        },
        turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
      },
    ],
  });
};

Pithon Kabiro's avatar
Pithon Kabiro committed
371
372
/**
 * Convert the observations' phenomenonTime from an ISO 8601 string to Unix epoch
373
374
 * @param {Array} obsArray Response from SensorThings API as array
 * @returns {Array} Array of formatted observations suitable for use in a line chart
Pithon Kabiro's avatar
Pithon Kabiro committed
375
 */
376
const formatSTAResponseForLineChart = function (obsArray) {
Pithon Kabiro's avatar
Pithon Kabiro committed
377
  if (!obsArray) return;
378
379

  const dataSTAFormatted = obsArray.map((result) => {
Pithon Kabiro's avatar
Pithon Kabiro committed
380
381
    const timestampObs = new Date(result[0].slice(0, -1)).getTime(); // slice() removes trailing "Z" character in timestamp
    const valueObs = result[1];
382
    return [timestampObs, valueObs];
Pithon Kabiro's avatar
Pithon Kabiro committed
383
  });
384

Pithon Kabiro's avatar
Pithon Kabiro committed
385
386
387
388
389
  return dataSTAFormatted;
};

/**
 * Draw a line chart using Highcharts library
390
 * @param {Array} formattedObsArrayForLineChart Response from SensorThings API formatted for use in a line chart
391
 * @param {Object} formattedDatastreamMetadata Object containing Datastream metadata
392
 * @returns {undefined} undefined
Pithon Kabiro's avatar
Pithon Kabiro committed
393
 */
394
const drawLineChartHC = function (
395
  formattedObsArrayForLineChart,
396
  formattedDatastreamMetadata
397
) {
398
399
400
401
402
403
404
  const {
    datastreamDescription: DATASTREAM_DESCRIPTION,
    datastreamName: DATASTREAM_NAME,
    phenomenonName: PHENOMENON_NAME,
    unitOfMeasurementSymbol: PHENOMENON_SYMBOL,
  } = formattedDatastreamMetadata;

Pithon Kabiro's avatar
Pithon Kabiro committed
405
406
407
408
409
410
  Highcharts.stockChart("chart-line", {
    chart: {
      zoomType: "x",
    },

    rangeSelector: {
411
      selected: 5,
Pithon Kabiro's avatar
Pithon Kabiro committed
412
413
414
    },

    title: {
415
      text: DATASTREAM_DESCRIPTION,
416
417
418
419
      "align": "left",
    },

    subtitle: {
420
      text: DATASTREAM_NAME,
421
      align: "left",
Pithon Kabiro's avatar
Pithon Kabiro committed
422
423
424
425
    },

    series: [
      {
426
        name: `${PHENOMENON_NAME} (${PHENOMENON_SYMBOL})`,
427
        data: formattedObsArrayForLineChart,
Pithon Kabiro's avatar
Pithon Kabiro committed
428
429
430
431
432
433
434
435
436
        tooltip: {
          valueDecimals: 2,
        },
        turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
      },
    ],
  });
};

Pithon Kabiro's avatar
Pithon Kabiro committed
437
/**
Pithon Kabiro's avatar
Pithon Kabiro committed
438
 * Follows "@iot.nextLink" links in SensorThingsAPI's response
Pithon Kabiro's avatar
Pithon Kabiro committed
439
 * Appends new results to existing results
Pithon Kabiro's avatar
Pithon Kabiro committed
440
 * @async
441
442
 * @param {Promise} responsePromise Promise object resulting from an Axios GET request
 * @returns {Object} Object containing results from all the "@iot.nextLink" links
Pithon Kabiro's avatar
Pithon Kabiro committed
443
 */
444
const followNextLink = function (responsePromise) {
Pithon Kabiro's avatar
Pithon Kabiro committed
445
  if (!responsePromise) return;
Pithon Kabiro's avatar
Pithon Kabiro committed
446
  return responsePromise
447
    .then((lastSuccess) => {
Pithon Kabiro's avatar
Pithon Kabiro committed
448
449
450
      if (lastSuccess.data["@iot.nextLink"]) {
        return followNextLink(
          axios.get(lastSuccess.data["@iot.nextLink"])
451
        ).then((nextLinkSuccess) => {
Pithon Kabiro's avatar
Pithon Kabiro committed
452
453
454
455
456
457
458
459
460
          nextLinkSuccess.data.value = lastSuccess.data.value.concat(
            nextLinkSuccess.data.value
          );
          return nextLinkSuccess;
        });
      } else {
        return lastSuccess;
      }
    })
461
    .catch((err) => {
462
      console.error(err);
Pithon Kabiro's avatar
Pithon Kabiro committed
463
464
465
    });
};

466
467
468
/**
 * Retrieve all the Observations from a Datastream after traversing all the "@iot.nextLink" links
 * @async
469
470
 * @param {Promise} httpGetRequestPromise Promise object resulting from an Axios GET request
 * @returns {Promise} A promise that contains an array of Observations from a single Datastream when fulfilled
471
 */
472
const getCombinedObservationsFromAllNextLinks = function (
473
  httpGetRequestPromise
474
) {
475
  return followNextLink(httpGetRequestPromise)
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    .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);
      });

      return new Promise((resolve, reject) => {
        resolve(combinedObservations);
      });
    })
    .catch((err) => {
491
      console.error(err);
492
493
    });
};
494

495
496
497
498
499
500
/**
 * Retrieve the metadata for a Datastream as well as the Observations corresponding to it
 * @async
 * @param {Promise} metadataPlusObsPromiseArray An array that contains two promises, one for datastream metadata, the other for observations
 * @returns {Promise} A promise that contains two arrays when fulfilled, one for datastream metadata and the other for observations
 */
501
const getMetadataPlusObservationsForChart = async function (
502
  metadataPlusObsPromiseArray
503
) {
504
  // Array to store our final result
505
506
  const combinedResolvedPromises = [];

507
508
  // Use for/of loop - we need to maintain the order of execution of the async operations
  for (const promise of metadataPlusObsPromiseArray) {
509
    try {
510
      // Resolved value of a single promise
511
512
513
      const resolvedPromise = await promise;
      combinedResolvedPromises.push(resolvedPromise);
    } catch (err) {
514
      console.error(err);
515
516
517
518
519
    }
  }
  return combinedResolvedPromises;
};

520
521
522
/**
 * Retrieve all the Observations from an array of Observations promises
 * @async
523
 * @param {Promise} observationPromiseArray An array that contains N observation promises
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
 * @returns {Promise} A promise that contains an array of Observations from multiple Datastreams when fulfilled
 */
const getObservationsFromMultipleDatastreams = async function (
  observationPromiseArray
) {
  // Array to store our final result
  const observationsAllDatastreamsArr = [];

  // Use for/of loop - we need to maintain the order of execution of the async operations
  for (const observationPromise of observationPromiseArray) {
    try {
      // Observations from a single Datastream
      const observations = await observationPromise;
      observationsAllDatastreamsArr.push(observations);
    } catch (err) {
539
      console.error(err);
540
541
542
543
    }
  }
  return observationsAllDatastreamsArr;
};
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574

// Building + phenomenon + sampling rate
const buildingsSensorSamplingRateRLArr = [
  ["101", "rl", "60min"],
  ["102", "rl", "60min"],
  ["107", "rl", "60min"],
  ["112, 118", "rl", "60min"],
  ["125", "rl", "60min"],
  ["225", "rl", "60min"],
];

// Datastreams IDs
const datastreamsRLArr = buildingsSensorSamplingRateRLArr.map((bldg) =>
  getDatastreamIdFromBuildingNumber(...bldg)
);

// Datastreams URLs
const datastreamsUrlRLArr = datastreamsRLArr.map((datastreamId) =>
  getObservationsUrl(BASE_URL, datastreamId)
);

// Promise objects - Observations / RL
const observationsPromisesRLArr = datastreamsUrlRLArr.map((obsUrl) =>
  getCombinedObservationsFromAllNextLinks(
    axiosGetRequest(obsUrl, QUERY_PARAMS_COMBINED)
  )
);

// getObservationsFromMultipleDatastreams(observationsPromisesRLArr).then((x) =>
//   console.log(x)
// );
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

export {
  BASE_URL,
  QUERY_PARAMS_COMBINED,
  getDatastreamIdFromBuildingNumber,
  getDatastreamUrl,
  getObservationsUrl,
  createTemporalFilterString,
  axiosGetRequest,
  getDatastreamMetadata,
  formatDatastreamMetadataForChart,
  formatSTAResponseForHeatMap,
  drawHeatMapHC,
  formatSTAResponseForLineChart,
  drawLineChartHC,
  getCombinedObservationsFromAllNextLinks,
  getMetadataPlusObservationsForChart,
};