-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth-low-energy.service.ts
409 lines (376 loc) · 12.1 KB
/
bluetooth-low-energy.service.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
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnModuleInit,
} from '@nestjs/common';
import { Peripheral } from '@abandonware/noble';
import { EntitiesService } from '../../entities/entities.service';
import { IBeacon } from './i-beacon';
import { Tag } from './tag';
import { ConfigService } from '../../config/config.service';
import { BluetoothLowEnergyConfig } from './bluetooth-low-energy.config';
import { ClusterService } from '../../cluster/cluster.service';
import { NewDistanceEvent } from './new-distance.event';
import { EntityCustomization } from '../../entities/entity-customization.interface';
import { SensorConfig } from '../home-assistant/sensor-config';
import { DeviceTrackerConfig } from '../home-assistant/device-tracker-config';
import { Device } from '../home-assistant/device';
import { RoomPresenceDistanceSensor } from '../room-presence/room-presence-distance.sensor';
import { SchedulerRegistry } from '@nestjs/schedule';
import { KalmanFilterable } from '../../util/filters';
import { makeId } from '../../util/id';
import { DISTRIBUTED_DEVICE_ID } from '../home-assistant/home-assistant.const';
import * as _ from 'lodash';
import { DeviceTracker } from '../../entities/device-tracker';
import { Sensor } from '../../entities/sensor';
import { RoomPresenceProxyHandler } from '../room-presence/room-presence.proxy';
import { BluetoothLowEnergyPresenceSensor } from './bluetooth-low-energy-presence.sensor';
import { BluetoothService } from '../bluetooth/bluetooth.service';
export const NEW_DISTANCE_CHANNEL = 'bluetooth-low-energy.new-distance';
@Injectable() // parameters determined experimentally
export class BluetoothLowEnergyService
extends KalmanFilterable(Object, 0.8, 15)
implements OnModuleInit, OnApplicationBootstrap {
private readonly config: BluetoothLowEnergyConfig;
private readonly logger: Logger;
private readonly seenIds = new Set<string>();
private tagUpdaters: {
[tagId: string]: (event: NewDistanceEvent) => void;
} = {};
constructor(
private readonly bluetoothService: BluetoothService,
private readonly entitiesService: EntitiesService,
private readonly configService: ConfigService,
private readonly clusterService: ClusterService,
private readonly schedulerRegistry: SchedulerRegistry
) {
super();
this.config = this.configService.get('bluetoothLowEnergy');
this.logger = new Logger(BluetoothLowEnergyService.name);
}
/**
* Lifecycle hook, called once the host module has been initialized.
*/
onModuleInit(): void {
if (!this.isWhitelistEnabled() && !this.isBlacklistEnabled()) {
this.logger.warn(
'The whitelist and blacklist are empty, no sensors will be created! Please add some of the discovered IDs below to your configuration.'
);
}
}
/**
* Lifecycle hook, called once the application has started.
*/
onApplicationBootstrap(): void {
this.bluetoothService.onLowEnergyDiscovery(this.handleDiscovery.bind(this));
this.clusterService.on(
NEW_DISTANCE_CHANNEL,
this.handleNewDistance.bind(this)
);
this.clusterService.subscribe(NEW_DISTANCE_CHANNEL);
}
/**
* Filters found BLE peripherals and publishes new distance data to sensors, depending on configuration.
*
* @param peripheral - BLE peripheral
*/
handleDiscovery(peripheral: Peripheral): void {
let tag = this.createTag(peripheral);
if (this.config.onlyIBeacon && !(tag instanceof IBeacon)) {
return;
}
if (!this.seenIds.has(tag.id)) {
this.logger.log(
`Discovered new BLE peripheral ${tag.name} with ID ${tag.id} and RSSI ${tag.rssi}`
);
this.seenIds.add(tag.id);
}
if (
(this.isOnWhitelist(tag.id) ||
(!this.isWhitelistEnabled() && this.isBlacklistEnabled())) &&
!this.isOnBlacklist(tag.id)
) {
tag = this.applyOverrides(tag);
tag.rssi = this.filterRssi(tag.id, tag.rssi);
const globalSettings = this.configService.get('global');
const event = new NewDistanceEvent(
globalSettings.instanceName,
tag.id,
tag.name,
tag.rssi,
tag.measuredPower,
tag.distance,
tag.distance > this.config.maxDistance,
tag instanceof IBeacon ? tag.batteryLevel : undefined
);
if (!this.tagUpdaters.hasOwnProperty(tag.id)) {
this.tagUpdaters[tag.id] = _.throttle((event: NewDistanceEvent) => {
this.handleNewDistance(event);
this.clusterService.publish(NEW_DISTANCE_CHANNEL, event);
}, this.config.updateFrequency * 1000);
}
this.tagUpdaters[tag.id](event);
}
}
/**
* Passes newly found discovery information to aggregated room presence sensors.
*
* @param event - Event with new distance/battery data
*/
handleNewDistance(event: NewDistanceEvent): void {
const sensorId = makeId(`ble ${event.tagId}`);
let sensor: BluetoothLowEnergyPresenceSensor;
const hasBattery = event.batteryLevel !== undefined;
if (this.entitiesService.has(sensorId)) {
sensor = this.entitiesService.get(
sensorId
) as BluetoothLowEnergyPresenceSensor;
} else {
sensor = this.createRoomPresenceSensor(
sensorId,
event.tagId,
event.tagName,
hasBattery
);
}
sensor.handleNewMeasurement(
event.instanceName,
event.rssi,
event.measuredPower,
event.distance,
event.outOfRange,
event.batteryLevel
);
}
/**
* Determines if the manufacturer data of a BLE peripheral belongs to an iBeacon or not.
*
* @param manufacturerData - Buffer of BLE peripheral manufacturer data
* @returns Whether the data belongs to an iBeacon or not
*/
isIBeacon(manufacturerData: Buffer): boolean {
return (
manufacturerData &&
25 <= manufacturerData.length && // expected data length
0x004c === manufacturerData.readUInt16LE(0) && // apple company identifier
0x02 === manufacturerData.readUInt8(2) && // ibeacon type
0x15 === manufacturerData.readUInt8(3)
); // expected ibeacon data length
}
/**
* Determines whether a whitelist has been configured or not.
*
* @returns Whitelist status
*/
isWhitelistEnabled(): boolean {
return this.config.whitelist?.length > 0;
}
/**
* Determines whether a blacklist has been configured or not.
*
* @returns Blacklist status
*/
isBlacklistEnabled(): boolean {
return this.config.blacklist?.length > 0;
}
/**
* Checks if an id is on the whitelist of this component.
*
* @param id - Device id
* @return Whether the id is on the whitelist or not
*/
isOnWhitelist(id: string): boolean {
const whitelist = this.config.whitelist;
if (whitelist === undefined || whitelist.length === 0) {
return false;
}
return this.config.whitelistRegex
? whitelist.some((regex) => id.match(regex))
: whitelist.includes(id);
}
/**
* Checks if an id is on the blacklist of this component.
*
* @param id - Device id
* @return Whether the id is on the blacklist or not
*/
isOnBlacklist(id: string): boolean {
const blacklist = this.config.blacklist;
if (blacklist === undefined || blacklist.length === 0) {
return false;
}
return this.config.blacklistRegex
? blacklist.some((regex) => id.match(regex))
: blacklist.includes(id);
}
/**
* Applies the Kalman filter based on the historic values with the same tag id.
*
* @param tagId - Tag id that matches the measured device
* @param rssi - Measured signal strength
* @returns Smoothed signal strength value
*/
filterRssi(tagId: string, rssi: number): number {
return this.kalmanFilter(rssi, tagId);
}
/**
* Creates and registers a new room presence sensor and device tracker.
*
* @param sensorId - Id that the sensor should receive
* @param deviceId - Id of the BLE peripheral
* @param deviceName - Name of the BLE peripheral
* @param hasBattery - Ability to report battery
* @returns Registered room presence sensor
*/
protected createRoomPresenceSensor(
sensorId: string,
deviceId: string,
deviceName: string,
hasBattery: boolean
): BluetoothLowEnergyPresenceSensor {
const deviceInfo: Device = {
identifiers: deviceId,
name: deviceName,
viaDevice: DISTRIBUTED_DEVICE_ID,
};
const deviceTracker = this.createDeviceTracker(
makeId(`${sensorId}-tracker`),
`${deviceName} Tracker`,
deviceInfo
);
let batterySensor: Sensor;
if (hasBattery) {
batterySensor = this.createBatterySensor(
makeId(`${sensorId}-battery`),
`${deviceName} Battery`,
deviceInfo
);
}
const sensorName = `${deviceName} Room Presence`;
const customizations: Array<EntityCustomization<any>> = [
{
for: SensorConfig,
overrides: {
icon: 'mdi:bluetooth',
device: deviceInfo,
},
},
];
const rawSensor = new BluetoothLowEnergyPresenceSensor(
sensorId,
sensorName,
this.config.timeout
);
const proxiedSensor = new Proxy<RoomPresenceDistanceSensor>(
rawSensor,
new RoomPresenceProxyHandler(deviceTracker, batterySensor)
);
const sensor = this.entitiesService.add(
proxiedSensor,
customizations
) as BluetoothLowEnergyPresenceSensor;
const interval = setInterval(
sensor.updateState.bind(sensor),
this.config.timeout * 1000
);
this.schedulerRegistry.addInterval(`${sensorId}_timeout_check`, interval);
return sensor;
}
/**
* Creates and registers a new device tracker.
*
* @param id - Entity ID for the new device tracker
* @param name - Name for the new device tracker
* @param deviceInfo - Reference information about the BLE device
* @returns Registered device tracker
*/
protected createDeviceTracker(
id: string,
name: string,
deviceInfo: Device
): DeviceTracker {
const trackerCustomizations: Array<EntityCustomization<any>> = [
{
for: DeviceTrackerConfig,
overrides: {
device: deviceInfo,
},
},
];
return this.entitiesService.add(
new DeviceTracker(id, name, true),
trackerCustomizations
) as DeviceTracker;
}
/**
* Creates and registers a new battery sensor.
*
* @param id - Entity ID for the new battery sensor
* @param name - Name for the new battery sensor
* @param deviceInfo - Reference information about the BLE device
* @returns Registered battery sensor
*/
protected createBatterySensor(
id: string,
name: string,
deviceInfo: Device
): Sensor {
const batteryCustomizations: Array<EntityCustomization<any>> = [
{
for: SensorConfig,
overrides: {
deviceClass: 'battery',
unitOfMeasurement: '%',
device: deviceInfo,
},
},
];
return this.entitiesService.add(
new Sensor(id, name, true),
batteryCustomizations
) as Sensor;
}
/**
* Creates a tag based on a given BLE peripheral.
*
* @param peripheral - Noble BLE peripheral
* @returns Tag or IBeacon
*/
protected createTag(peripheral: Peripheral): Tag {
if (
this.config.processIBeacon &&
this.isIBeacon(peripheral.advertisement.manufacturerData)
) {
return new IBeacon(
peripheral,
this.config.majorMask,
this.config.minorMask,
this.config.batteryMask
);
} else {
return new Tag(peripheral);
}
}
/**
* Checks if overrides have been configured for a tag and then applies them.
*
* @param tag - Tag that should be overridden
* @returns Same tag with potentially overridden data
*/
protected applyOverrides(tag: Tag): Tag {
if (this.config.tagOverrides.hasOwnProperty(tag.id)) {
const overrides = this.config.tagOverrides[tag.id];
if (overrides.name !== undefined) {
tag.name = overrides.name;
}
if (overrides.measuredPower !== undefined) {
tag.measuredPower = overrides.measuredPower;
}
if (overrides.batteryMask !== undefined && tag instanceof IBeacon) {
tag.batteryMask = overrides.batteryMask;
}
}
return tag;
}
}