-
Notifications
You must be signed in to change notification settings - Fork 9
/
NotehubDataProvider.ts
242 lines (207 loc) · 8.25 KB
/
NotehubDataProvider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable class-methods-use-this */
import { sub, formatDistanceToNow, parseISO } from "date-fns";
import { uniqBy } from "lodash";
import * as NotehubJs from "@blues-inc/notehub-js";
import { DeviceTracker, TrackerConfig } from "../AppModel";
import { DataProvider } from "../DataProvider";
import { FleetID, ProjectID } from "../DomainModel";
import NotehubDevice from "./models/NotehubDevice";
import NotehubEnvVars from "./models/NotehubEnvVars";
import { NotehubLocationAlternatives } from "./models/NotehubLocation";
import NotehubRoutedEvent from "./models/NotehubRoutedEvent";
import NotehubEnvVarsResponse from "./models/NotehubEnvVarsResponse";
interface HasDeviceId {
uid: string;
}
// N.B.: Notehub defines 'best' location with more nuance than we do here (e.g
// considering staleness). Also this algorithm is copy-pasted in a couple places.
export const getBestLocation = (object: NotehubLocationAlternatives) =>
object.gps_location || object.triangulated_location || object.tower_location;
export function notehubDeviceToIndoorTracker(device: NotehubDevice) {
return {
uid: device.uid,
name: device.serial_number,
lastActivity: device.last_activity,
...(getBestLocation(device) && {
location: getBestLocation(device)?.name,
}),
voltage: `${device.voltage}`,
};
}
export function filterEventsData(events: NotehubRoutedEvent[], file: string) {
const dataEvent = events.filter((event) => event.file === file).reverse();
return dataEvent;
}
export function extractRelevantEventBodyData(events: NotehubRoutedEvent[]) {
const relevantEventInfo = events.map((event) => ({
...event.body,
uid: event.device,
}));
return relevantEventInfo;
}
export function mergeObject<CombinedEventObj>(
A: any,
B: any
): CombinedEventObj {
const res: any = {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, array-callback-return
Object.keys({ ...A, ...B }).map((key) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
res[key] = A[key] || B[key];
});
return res as CombinedEventObj;
}
// merge latest event objects with the same device ID
// these are different readings from the same device
export function reducer<CombinedEventObj extends HasDeviceId>(
groups: Map<string, CombinedEventObj>,
event: CombinedEventObj
) {
// make id the map's key
const key = event.uid;
// fetch previous map values associated with that key
const previous = groups.get(key);
// combine the previous map event with new map event
const merged: CombinedEventObj = mergeObject(previous || {}, event);
// set the key and newly merged object as the value
groups.set(key, merged);
return groups;
}
export function formatDeviceTrackerData(deviceTrackerData: DeviceTracker[]) {
const formattedDeviceTrackerData = deviceTrackerData.map((data) => ({
...data,
lastActivity: formatDistanceToNow(parseISO(data.lastActivity), {
includeSeconds: true,
}),
...(data.altitude && { altitude: Number(data.altitude).toFixed(1) }),
voltage: `${Number(data.voltage).toFixed(1)}V`,
...(data.pressure && {
pressure: `${Number(data.pressure).toFixed(1)} hPa`,
}),
...(data.temperature && {
temp: `${Number(data.temperature).toFixed(1)}C`,
}),
}));
return formattedDeviceTrackerData;
}
export function trackerConfigToEnvironmentVariables(
trackerConfig: TrackerConfig
) {
const envVars = {} as NotehubEnvVars;
if (trackerConfig.baseFloor !== undefined) {
envVars.baseline_floor = String(trackerConfig.baseFloor);
}
if (trackerConfig.floorHeight !== undefined) {
envVars.floor_height = String(trackerConfig.floorHeight);
}
if (trackerConfig.live !== undefined) {
envVars.live = String(trackerConfig.live);
}
if (trackerConfig.noMovementThreshold !== undefined) {
// convert notehub no_move_threshold from seconds to mins for UI
envVars.no_movement_threshold = String(
trackerConfig.noMovementThreshold / 60
);
}
return envVars;
}
export function environmentVariablesToTrackerConfig(envVars: NotehubEnvVars) {
return {
live: envVars.live === "true",
baseFloor: Number(envVars.baseline_floor) || 1,
floorHeight: Number(envVars.floor_height) || 4.2672,
// convert UI no_move_threshold from minutes to seconds for Notehub
noMovementThreshold:
Number(Number(envVars.no_movement_threshold) * 60) || 300,
} as TrackerConfig;
}
export function epochStringMinutesAgo(minutesToConvert: number) {
const date = new Date();
const rawEpochDate = sub(date, { minutes: minutesToConvert });
const formattedEpochDate = Math.round(
rawEpochDate.getTime() / 1000
).toString();
return formattedEpochDate;
}
export default class NotehubDataProvider implements DataProvider {
constructor(
private readonly projectID: ProjectID,
private readonly fleetID: FleetID,
private readonly hubAuthToken: string,
private readonly notehubJsClient: any
) {}
async getDeviceTrackerData(): Promise<DeviceTracker[]> {
const trackerDevices: DeviceTracker[] = [];
let formattedDeviceTrackerData: DeviceTracker[] = [];
const { notehubJsClient } = this;
const { api_key } = notehubJsClient.authentications;
api_key.apiKey = this.hubAuthToken;
const projectApiInstance = new NotehubJs.ProjectApi();
const { projectUID } = this.projectID;
const { fleetUID } = this.fleetID;
const devicesByFleet = await projectApiInstance.getProjectFleetDevices(
projectUID,
fleetUID
);
// get all the devices by fleet ID
devicesByFleet.devices.forEach((device: NotehubDevice) => {
trackerDevices.push(notehubDeviceToIndoorTracker(device));
});
// fetch all events for the last X minutes from Notehub
const MINUTES_OF_NOTEHUB_DATA_TO_FETCH = 6;
const unixTimestampMinutesAgo = epochStringMinutesAgo(
MINUTES_OF_NOTEHUB_DATA_TO_FETCH
);
const eventOpts = { startDate: unixTimestampMinutesAgo };
const rawEvents = await projectApiInstance.getProjectEvents(
projectUID,
eventOpts
);
// filter down to only data.qo events and reverse the order to get the latest event first
const filteredEvents = filterEventsData(rawEvents.events, "floor.qo");
// get unique events by device ID
const uniqueEvents = uniqBy(filteredEvents, "device");
// pull out relevant device data from unique events
const mappedEvents: object[] = extractRelevantEventBodyData(uniqueEvents);
// concat the device info from fleet with latest device info
const combinedEventsDevices = [...trackerDevices, ...mappedEvents];
// combine events with matching device IDs with helper functions defined above
const reducedEventsIterator = combinedEventsDevices
.reduce(reducer, new Map())
.values();
// transform the Map iterator obj into plain array
const deviceTrackerData: any[] = Array.from(reducedEventsIterator);
// format the data to round the numbers to 2 decimal places
formattedDeviceTrackerData = formatDeviceTrackerData(deviceTrackerData);
const alarmEvents = filterEventsData(rawEvents.events, "alarm.qo");
const uniqueAlarmEvents = uniqBy(alarmEvents, "device");
this.appendAlarmData(uniqueAlarmEvents, formattedDeviceTrackerData);
return formattedDeviceTrackerData;
}
private appendAlarmData(
alarmEvents: NotehubRoutedEvent[],
trackers: DeviceTracker[]
) {
alarmEvents.forEach((event) => {
trackers
.filter((tracker) => event.device === tracker.uid)
.forEach((tracker) => {
// eslint-disable-next-line no-param-reassign
tracker.lastAlarm = `${event.when}`;
});
});
}
async getTrackerConfig(): Promise<TrackerConfig> {
const { notehubJsClient } = this;
const { api_key } = notehubJsClient.authentications;
api_key.apiKey = this.hubAuthToken;
const fleetApiInstance = new NotehubJs.FleetApi();
const { projectUID } = this.projectID;
const { fleetUID } = this.fleetID;
const envVarResponse: NotehubEnvVarsResponse =
await fleetApiInstance.getFleetEnvironmentVariables(projectUID, fleetUID);
const envVars = envVarResponse.environment_variables;
return environmentVariablesToTrackerConfig(envVars);
}
}