-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth-classic.service.ts
278 lines (250 loc) · 8.78 KB
/
bluetooth-classic.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
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnModuleInit
} from '@nestjs/common';
import { ConfigService } from '../../config/config.service';
import { EntitiesService } from '../../entities/entities.service';
import { ClusterService } from '../../cluster/cluster.service';
import { BluetoothClassicConfig } from './bluetooth-classic.config';
import * as util from 'util';
import { exec } from 'child_process';
import { Node } from 'democracy';
import { NewRssiEvent } from './new-rssi.event';
import _ from 'lodash';
import { Interval, SchedulerRegistry } from '@nestjs/schedule';
import { EntityCustomization } from '../../entities/entity-customization.interface';
import { SensorConfig } from '../home-assistant/sensor-config';
import {
NEW_RSSI_CHANNEL,
REQUEST_RSSI_CHANNEL
} from './bluetooth-classic.const';
import { RoomPresenceDistanceSensor } from '../room-presence/room-presence-distance.sensor';
import { KalmanFilterable } from '../../util/filters';
import { makeId } from '../../util/id';
@Injectable()
export class BluetoothClassicService extends KalmanFilterable(Object, 1.4, 0.8)
implements OnModuleInit, OnApplicationBootstrap {
private readonly config: BluetoothClassicConfig;
private rotationOffset = 0;
private logger: Logger;
constructor(
private readonly configService: ConfigService,
private readonly entitiesService: EntitiesService,
private readonly clusterService: ClusterService,
private readonly schedulerRegistry: SchedulerRegistry
) {
super();
this.config = this.configService.get('bluetoothClassic');
this.logger = new Logger(BluetoothClassicService.name);
}
/**
* Lifecycle hook, called once the host module has been initialized.
*/
async onModuleInit(): Promise<void> {
const execPromise = util.promisify(exec);
try {
await execPromise('hcitool -h');
} catch (e) {
this.logger.error(
'The Bluetooth Classic integration requires hcitool to be installed, which could not be found.'
);
}
}
/**
* Lifecycle hook, called once the application has started.
*/
onApplicationBootstrap(): void {
this.clusterService.on(
REQUEST_RSSI_CHANNEL,
this.handleRssiRequest.bind(this)
);
this.clusterService.on(NEW_RSSI_CHANNEL, this.handleNewRssi.bind(this));
this.clusterService.subscribe(NEW_RSSI_CHANNEL);
}
/**
* Takes a Bluetooth MAC address, determines the current RSSI and then publishes it across the cluster.
*
* @param address - Bluetooth MAC address
*/
async handleRssiRequest(address: string): Promise<void> {
let rssi = await this.inquireRssi(address);
if (rssi !== undefined) {
rssi = _.round(this.filterRssi(address, rssi), 1);
const event = new NewRssiEvent(
this.configService.get('global').instanceName,
address,
rssi
);
this.clusterService.publish(NEW_RSSI_CHANNEL, event);
this.handleNewRssi(event);
}
}
/**
* Processes an event with a new RSSI event by passing it along to the corresponding to sensor.
* If no sensor matching the given address was found it will create a new one.
*
* @param event - Event that contains a new RSSI value
*/
async handleNewRssi(event: NewRssiEvent): Promise<void> {
this.logger.debug(
`Received RSSI of ${event.rssi} for ${event.address} from ${event.instanceName}`
);
const sensorId = makeId(`bluetooth-classic ${event.address}`);
let sensor: RoomPresenceDistanceSensor;
if (this.entitiesService.has(sensorId)) {
sensor = this.entitiesService.get(sensorId) as RoomPresenceDistanceSensor;
} else {
sensor = await this.createSensor(sensorId, event.address);
}
sensor.timeout = this.calculateCurrentTimeout();
sensor.handleNewDistance(event.instanceName, event.rssi * -1);
}
/**
* Sends out RSSI requests to the connected nodes in the cluster by matching each one with a MAC address.
* Rotates the mapping on each call.
*/
@Interval(10 * 1000)
distributeInquiries(): void {
if (this.clusterService.isLeader()) {
const nodes = this.getParticipatingNodes();
const addresses = Object.values(this.config.addresses);
if (this.rotationOffset >= Math.max(nodes.length, addresses.length)) {
this.rotationOffset = 0;
}
const [nodeSubset, addressSubset]: [Node[], string[]] = this.mapArrays(
nodes,
addresses,
this.rotationOffset
);
nodeSubset.forEach((node, index) => {
// only remote nodes have a timestamp of last contact attached
if (node.last === undefined) {
this.handleRssiRequest(addressSubset[index]);
} else {
this.clusterService.send(
REQUEST_RSSI_CHANNEL,
addressSubset[index],
node.id
);
}
});
this.rotationOffset++;
}
}
/**
* Queries for the RSSI of a Bluetooth device using the hcitool shell command.
*
* @param address - Bluetooth MAC address
* @returns RSSI value
*/
async inquireRssi(address: string): Promise<number> {
const execPromise = util.promisify(exec);
this.logger.debug(`Querying for RSSI of ${address} using hcitool`);
const output = await execPromise(
`hcitool cc "${address}" && hcitool rssi "${address}"`
);
const regex = new RegExp(/-?[0-9]+/);
const matches = output.stdout.match(regex);
return matches?.length > 0 ? parseInt(matches[0], 10) : undefined;
}
/**
* Applies the Kalman filter based on the historic values with the same address.
*
* @param address - Bluetooth MAC address
* @param rssi - Signal strength measurement for the given address
* @returns Smoothed signal strength value
*/
filterRssi(address: string, rssi: number): number {
return this.kalmanFilter(rssi, address);
}
/**
* Queries for the name of a Bluetooth device using the hcitool shell command.
*
* @param address - Bluetooth MAC address
* @returns Bluetooth device name or undefined if not found
*/
async inquireDeviceName(address: string): Promise<string> {
const execPromise = util.promisify(exec);
try {
const output = await execPromise(`hcitool name "${address}"`);
return output.stdout ? output.stdout.trim() : undefined;
} catch (e) {
this.logger.error(e.message);
return undefined;
}
}
/**
* Filters the nodes in the cluster to those who have this integration loaded.
*
* @returns List of nodes with the Bluetooth Classic integration enabled
*/
getParticipatingNodes(): Node[] {
const nodes = Object.values(this.clusterService.nodes());
return nodes.filter(node => node.channels?.includes(NEW_RSSI_CHANNEL));
}
/**
* Creates and registers a new room presence sensor.
*
* @param sensorId - Entity ID for the new sensor
* @param address - Bluetooth MAC address of the matching device
* @returns Registered sensor
*/
protected async createSensor(
sensorId: string,
address: string
): Promise<RoomPresenceDistanceSensor> {
const deviceName = (await this.inquireDeviceName(address)) || address;
const customizations: Array<EntityCustomization<any>> = [
{
for: SensorConfig,
overrides: {
icon: 'mdi:bluetooth'
}
}
];
const sensor = this.entitiesService.add(
new RoomPresenceDistanceSensor(
sensorId,
`${deviceName} Room Presence`,
0
),
customizations
) as RoomPresenceDistanceSensor;
const interval = setInterval(
sensor.checkForTimeout.bind(sensor),
10 * 1000
);
this.schedulerRegistry.addInterval(`${sensorId}_timeout_check`, interval);
return sensor;
}
/**
* Calculates the current timeout value based on the time it takes for a full rotation.
*
* @returns Timeout in seconds
*/
protected calculateCurrentTimeout(): number {
const nodes = this.getParticipatingNodes();
const addresses = Object.values(this.config.addresses); // workaround for node-config deserializing to an Array-like object
return (Math.max(nodes.length, addresses.length) + 1.5) * 10;
}
/**
* Maps the values of two arrays based on a numeric offset.
*
* @param a1 - The first array
* @param a2 - The second array
* @param offset - Index offset for the larger of both arrays
* @returns A tuple with subsets of both input arrays with matching size
*/
protected mapArrays(a1: any[], a2: any[], offset: number): [any[], any[]] {
const [small, large] = a1.length > a2.length ? [a2, a1] : [a1, a2];
const largeSubset = large.slice(offset, offset + small.length);
if (offset + small.length > large.length) {
largeSubset.push(
...large.slice(0, small.length - this.rotationOffset + 1)
);
}
return a1.length > a2.length ? [largeSubset, a2] : [a1, largeSubset];
}
}