-
Notifications
You must be signed in to change notification settings - Fork 0
/
RealtimeDataContainer.ts
496 lines (449 loc) · 16.4 KB
/
RealtimeDataContainer.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
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
377
378
379
380
381
382
383
384
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
import cloneDeep from "lodash.clonedeep";
import merge from "lodash.merge";
import { TypedEmitter } from "tiny-typed-emitter";
import {
VantInterface,
VantPro2Interface,
VantVueInterface,
VantProInterface,
} from "../interfaces";
import { defaultUnitSettings } from "vant-environment/units";
import {
RealtimeDataContainerSettings,
MinimumRealtimeDataContainerSettings,
DeviceModel,
} from "./settings";
import { RealtimeDataContainerEvents } from "./events";
import { OnContainerCreate } from "./settings/OnContainerCreate";
import { OnInterfaceCreate } from "../interfaces/settings";
/**
* Base class for the {@link SmallRealtimeDataContainer} and the {@link BigRealtimeDataContainer}.
*/
export default abstract class RealtimeDataContainer<
Interface extends VantInterface,
SupportedDeviceModels extends DeviceModel
> extends TypedEmitter<RealtimeDataContainerEvents> {
/**
* By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual realtime data container instances using the {@link setMaxListeners} method.
*
* To change the default for all instances, this property can be used. If this value is not a positive number, a RangeError is thrown.
*/
public static defaultMaxListeners: number;
/**
* Adds an event listener. Possible events are described {@link RealtimeDataContainerEvents here}.
* @param eventName The event to listen for
* @param listener The listener to add
* @returns this (for chaining calls)
*/
public addListener<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.addListener(eventName, listener);
}
/**
* Removes the specified listener from the listener array for the event named `eventName`.
* @param eventName the event the listener listens to
* @param listener the listener to remove
* @returns this (for chaining calls)
*/
public removeListener<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.removeListener(eventName, listener);
}
/**
* Synchronously calls each of the listeners registered for the event `eventName`, in the order they were registered, passing the supplied arguments to each.
* Returns `true` if the event had listeners, `false` otherwise.
* @param eventName
* @param args
* @returns whether the event had listeners
*/
public emit<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
...args: Parameters<RealtimeDataContainerEvents[U]>
): boolean {
return super.emit(eventName, ...args);
}
/**
* Returns an array listing the events for which the realtime data container has registered listeners.
* @returns an array listing the events for which the realtime data container has registered listeners
*/
public eventNames<U extends keyof RealtimeDataContainerEvents>(): U[] {
return super.eventNames();
}
/**
* Returns the current max listener value for the realtime data container which is either set by {@link setMaxListeners} or defaults to {@link defaultMaxListeners}.
* @returns the current max listener value for the current realtime data container instance
*/
public getMaxListeners(): number {
return super.getMaxListeners();
}
/**
* Returns the number of listeners listening to the event named `eventName`.
* @param eventName
* @returns the number of listeners listening to the event
*/
public listenerCount(type: keyof RealtimeDataContainerEvents): number {
return super.listenerCount(type);
}
/**
* Returns a copy of the array of listeners for the event named `eventName`.
* @param eventName
* @returns a copy of the array of listeners for the passed event
*/
public listeners<U extends keyof RealtimeDataContainerEvents>(
eventName: U
): RealtimeDataContainerEvents[U][] {
return super.listeners(eventName);
}
/**
* Alias for {@link removeListener}.
* @param eventName
* @param listener
* @returns this (for chaining calls)
*/
public off<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.off(eventName, listener);
}
/**
* Alias for {@link addListener}.
* @param eventName
* @param listener
* @returns this (for chaining calls)
*/
public on<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.on(eventName, listener);
}
/**
* Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
* @param eventName
* @param listener
* @returns this (for chaining calls)
*/
public once<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.once(eventName, listener);
}
/**
* By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual realtime data container instances using this method.
*
* To change the default for all EventEmitter instances, change {@link defaultMaxListeners}.
*
* @param maxListeners new limit for the amount of listeners for any single event on this realtime data container instance
* @returns this (for chaining calls)
*/
public setMaxListeners(maxListeners: number): this {
return super.setMaxListeners(maxListeners);
}
/**
* Adds the listener function to the beginning of the listeners array for the event named `eventName`.
* No checks are made to see if the listener has already been added. Multiple calls passing the same combination of `eventName`
* and listener will result in the listener being added, and called, multiple times.
* @param eventName
* @param listener
* @returns this (for chaining calls)
*/
public prependListener<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.prependListener(eventName, listener);
}
/**
* Adds a one-time listener function for the event named `eventName` to the beginning of the listeners array.
* The next time `eventName` is triggered, this listener is removed, and then invoked.
* @param eventName
* @param listener
* @returns this (for chaining calls)
*/
public prependOnceListener<U extends keyof RealtimeDataContainerEvents>(
eventName: U,
listener: RealtimeDataContainerEvents[U]
): this {
return super.prependOnceListener(eventName, listener);
}
/**
* Removes all listeners, or those of the specified `eventName`.
* @param eventName
* @returns this (for chaining calls)
*/
public removeAllListeners(
eventName?: keyof RealtimeDataContainerEvents
): this {
return super.removeAllListeners(eventName);
}
/**
* The default realtime data container settings.
*/
private static defaultSettings = {
baudRate: 19200,
updateInterval: 60,
onCreate: OnContainerCreate.WaitForFirstValidUpdate,
units: defaultUnitSettings,
};
/**
* The realtime data container's settings. Immutable.
*/
public readonly settings: RealtimeDataContainerSettings<SupportedDeviceModels>;
/**
* The currently internally used interface
*/
protected currentDevice: Interface | null = null;
/**
* The currently active update interval
*/
private currentUpdateInterval: NodeJS.Timeout | null = null;
/**
* Whether the serial port connection to the console is open.
*/
public isPortOpen() {
if (!this.currentDevice) {
return false;
}
return this.currentDevice.isPortOpen;
}
/**
* Whether the realtime data container is running.
*/
public isRunning() {
return this.currentUpdateInterval !== null;
}
/**
* Creates a new instance and merges the passed settings with the default settings.
* @param settings the realtime data container's settings
*/
protected constructor(
settings: MinimumRealtimeDataContainerSettings<SupportedDeviceModels>
) {
super();
this.settings = merge(
cloneDeep(RealtimeDataContainer.defaultSettings),
settings
);
}
/**
* Performs the {@link OnContainerCreate onCreate} action on the passed container.
* @param container
* @returns the container
*/
protected static async performOnCreateAction<
W extends RealtimeDataContainer<any, any>
>(container: W): Promise<W> {
switch (container.settings.onCreate) {
case OnContainerCreate.DoNothing:
break;
case OnContainerCreate.Start:
await container.start();
break;
case OnContainerCreate.StartAndWaitUntilOpen:
await container.startAndWaitUntilOpen();
break;
case OnContainerCreate.WaitForFirstUpdate:
container.start();
await container.waitForUpdate();
break;
case OnContainerCreate.WaitForFirstValidUpdate:
container.start();
await container.waitForValidUpdate();
break;
}
return container;
}
/**
* Stops the realtime data container, fires a `"close"` event. The update cycle is stopped and the connection to the
* weather station gets closed.
*
* If the realtime data container already got closed no `"close"` event is thrown.
*/
public stop = () => {
return new Promise<void>((resolve) => {
if (this.currentUpdateInterval) {
clearInterval(this.currentUpdateInterval);
this.currentUpdateInterval = null;
}
if (this.currentDevice) {
this.currentDevice.close().then(() => {
this.currentDevice = null;
this.emit("stop");
resolve();
});
} else {
this.currentDevice = null;
resolve();
}
});
};
/**
* Starts the realtime data container. Fires a `"start"` event. Doesn't wait for the serial port connection to be opened.
*
* Starts the update cycle and tries to connect to the weather station console. If connecting fails,
* the realtime data container tries to reconnect every `settings.updateInterval` seconds.
*
* If the container already got started it is stopped first.
*/
public start = () => {
return new Promise<void>((resolve) => {
this.stop().then(async () => {
await this.setupInterface();
const currentDevice = this.currentDevice as Interface;
this.startUpdateCycle(currentDevice);
currentDevice.on("open", () => {
this.emit("device-open");
});
currentDevice.on("close", () => {
this.emit("device-close");
});
currentDevice.open();
this.emit("start");
resolve();
});
});
};
/**
* Starts the realtime data container and waits for the serial port connection to be opened.
*
* Starts the update cycle and tries to connect to the weather station console. If connecting fails,
* the realtime data container tries to reconnect every `settings.updateInterval` seconds.
*
* If the container got already started it is stopped first.
*/
public startAndWaitUntilOpen = () => {
return new Promise<void>((resolve) => {
this.stop().then(async () => {
await this.setupInterface();
const currentDevice = this.currentDevice as Interface;
this.startUpdateCycle(currentDevice);
currentDevice.on("open", () => {
this.emit("device-open");
});
currentDevice.on("close", () => {
this.emit("device-close");
});
await currentDevice.open();
this.emit("start");
resolve();
});
});
};
/**
* Waits for the next update on the realtime data container. If an error occurrs while updating
* the promise is rejected. This can be used to handle errors. See {@link RealtimeDataContainerEvents}.
*
* @example
* ```ts
* try{
* await container.waitForUpdate();
* // ...
* }catch(err){
* // handle error
* }
* ```
*/
public waitForUpdate = (): Promise<void | any> => {
return new Promise<void>((resolve, reject) => {
this.once("update", (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
/**
* Waits for the next valid update on the realtime data container. See {@link RealtimeDataContainerEvents}.
*/
public waitForValidUpdate = () => {
return new Promise<void>((resolve) => {
this.once("valid-update", async () => {
resolve();
});
});
};
/**
* Creates the internally used interface (dependent on the passed device model) and opens the connection to the weather station console.
*/
private setupInterface = async () => {
const { path, model, baudRate, rainCollectorSize, units } =
this.settings;
switch (model) {
case DeviceModel.VantagePro2:
this.currentDevice = (await VantPro2Interface.create({
path,
baudRate,
rainCollectorSize,
units,
onCreate: OnInterfaceCreate.DoNothing,
})) as any;
break;
case DeviceModel.VantageVue:
this.currentDevice = (await VantVueInterface.create({
path,
baudRate,
rainCollectorSize,
units,
onCreate: OnInterfaceCreate.DoNothing,
})) as any;
break;
case DeviceModel.VantagePro:
this.currentDevice = (await VantProInterface.create({
path,
baudRate,
rainCollectorSize,
units,
onCreate: OnInterfaceCreate.DoNothing,
})) as any;
break;
}
};
/**
* Starts the update cycle (using the passed interface).
* @param device the interface to the device
*/
private startUpdateCycle = (device: Interface) => {
const update = async () => {
try {
try {
await device.open();
await device.wakeUp();
} catch (err) {
await this.onConnectionError();
throw err;
}
try {
await this.onUpdate(device);
} catch (err) {
await this.onConnectionError();
throw err;
}
this.emit("update");
this.emit("valid-update");
} catch (err) {
this.emit("update", err);
}
};
update();
this.currentUpdateInterval = setInterval(
update,
this.settings.updateInterval * 1000
);
};
/**
* Gets called if an error occurrs while updating the weather data.
*/
protected abstract onConnectionError(): Promise<void>;
/**
* In this method an extending class should specify the update process of the realtime data container.
*/
protected abstract onUpdate(device: Interface): Promise<void>;
}