-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.service.ts
335 lines (298 loc) · 9.85 KB
/
bluetooth.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
import { Injectable, Logger } from '@nestjs/common';
import noble, { Peripheral } from '@mkerix/noble';
import util from 'util';
import { exec } from 'child_process';
import { BluetoothHealthIndicator } from './bluetooth.health';
import { BluetoothClassicConfig } from '../bluetooth-classic/bluetooth-classic.config';
import { ConfigService } from '../../config/config.service';
import { Device } from '../bluetooth-classic/device';
import { promiseWithTimeout } from '../../util/promises';
import { Interval } from '@nestjs/schedule';
const RSSI_REGEX = new RegExp(/-?[0-9]+/);
const INQUIRY_LOCK_TIMEOUT = 30 * 1000;
const execPromise = util.promisify(exec);
type BluetoothAdapterState = 'inquiry' | 'scan' | 'inactive';
type ExecOutput = { stdout: string; stderr: string };
class BluetoothAdapter {
state: BluetoothAdapterState;
startedAt: Date;
}
class BluetoothAdapterMap extends Map<number, BluetoothAdapter> {
getState(key: number): BluetoothAdapterState {
return this.get(key)?.state;
}
setState(key: number, state: BluetoothAdapterState): this {
return this.set(key, { state, startedAt: new Date() });
}
}
@Injectable()
export class BluetoothService {
private readonly logger: Logger = new Logger(BluetoothService.name);
private readonly classicConfig: BluetoothClassicConfig;
private readonly adapters = new BluetoothAdapterMap();
private lowEnergyAdapterId: number;
constructor(
private readonly configService: ConfigService,
private readonly healthIndicator: BluetoothHealthIndicator
) {
this.classicConfig = this.configService.get('bluetoothClassic');
}
/**
* Registers a callback function that will be invoked when a
* Bluetooth Low Energy peripheral advertisement was received.
*
* @param callback - Callback function that receives a peripheral
*/
onLowEnergyDiscovery(callback: (peripheral: Peripheral) => void): void {
if (this.lowEnergyAdapterId == undefined) {
this.setupNoble();
}
noble.on('discover', callback);
}
/**
* Locks the adapter and establishes a connection the given BLE peripheral.
* Connection attempts time out after 30s.
*
* @param peripheral - BLE peripheral to connect to
*/
async connectLowEnergyDevice(peripheral: Peripheral): Promise<Peripheral> {
if (!peripheral.connectable) {
throw new Error('Trying to connect to a non-connectable device');
}
this.logger.debug(
`Connecting to BLE device at address ${peripheral.address}`
);
this.lockAdapter(this.lowEnergyAdapterId);
peripheral.once('disconnect', (e) => {
if (e) {
this.logger.error(e);
} else {
this.logger.debug(
`Disconnected from BLE device at address ${peripheral.address}`
);
}
this.unlockAdapter(this.lowEnergyAdapterId);
});
try {
await promiseWithTimeout(peripheral.connectAsync(), 10 * 1000);
return peripheral;
} catch (e) {
this.logger.error(
`Failed to connect to ${peripheral.address}: ${e.message}`,
e.trace
);
peripheral.disconnect();
peripheral.removeAllListeners();
await this.resetHciDevice(this.lowEnergyAdapterId);
this.unlockAdapter(this.lowEnergyAdapterId);
throw e;
}
}
/**
* Disconnect from the given BLE peripheral and unlock the adapter.
*
* @param peripheral - BLE peripheral to disconnect from
*/
async disconnectLowEnergyDevice(peripheral: Peripheral): Promise<void> {
this.logger.debug(
`Disconnecting from BLE device at address ${peripheral.address}`
);
try {
await peripheral.disconnectAsync();
} catch (e) {
this.logger.error(
`Failed to disconnect from ${peripheral.address}: ${e.message}`,
e.trace
);
}
}
/**
* Queries for the RSSI of a Bluetooth device using the hcitool shell command.
*
* @param adapterId - HCI Adapter ID to use for queries
* @param address - Bluetooth MAC address
* @returns RSSI value
*/
async inquireClassicRssi(
adapterId: number,
address: string
): Promise<number> {
this.lockAdapter(adapterId);
this.logger.debug(`Querying for RSSI of ${address} using hcitool`);
try {
const output = await promiseWithTimeout<ExecOutput>(
execPromise(
`hcitool -i hci${adapterId} cc "${address}" && hcitool -i hci${adapterId} rssi "${address}"`,
{
timeout: this.classicConfig.scanTimeLimit * 1000,
killSignal: 'SIGKILL',
}
),
this.classicConfig.scanTimeLimit * 1000 * 1.1
);
const matches = output.stdout.match(RSSI_REGEX);
this.healthIndicator.reportSuccess();
return matches?.length > 0 ? parseInt(matches[0], 10) : undefined;
} catch (e) {
if (e.signal === 'SIGKILL') {
this.logger.debug(
`Query of ${address} reached scan time limit, resetting hci${this.classicConfig.hciDeviceId}`
);
await this.resetHciDevice(adapterId);
// when not reachable a scan runs for 6s, so lower time limits might not be an error
if (this.classicConfig.scanTimeLimit >= 6) {
this.healthIndicator.reportError();
}
} else if (
e.message?.includes('Input/output') ||
e.message?.includes('I/O')
) {
this.logger.debug(e.message);
} else if (e.message == 'timed out') {
this.logger.warn(
`Bluetooth adapter ${adapterId} seems stuck, resetting`
);
this.healthIndicator.reportError();
await this.resetHciDevice(adapterId);
} else {
this.logger.error(`Inquiring RSSI via BT Classic failed: ${e.message}`);
this.healthIndicator.reportError();
}
return undefined;
} finally {
this.unlockAdapter(adapterId);
}
}
/**
* Inquires device information of a Bluetooth peripheral.
*
* @param adapterId - HCI Adapter ID to use for queries
* @param address - Bluetooth MAC address
* @returns Device information
*/
async inquireClassicDeviceInfo(
adapterId: number,
address: string
): Promise<Device> {
this.lockAdapter(adapterId);
try {
const output = await promiseWithTimeout<ExecOutput>(
execPromise(`hcitool -i hci${adapterId} info "${address}"`),
6000
);
const nameMatches = /Device Name: (.+)/g.exec(output.stdout);
const manufacturerMatches = /OUI Company: (.+) \(.+\)/g.exec(
output.stdout
);
return {
address,
name: nameMatches ? nameMatches[1] : address,
manufacturer: manufacturerMatches ? manufacturerMatches[1] : undefined,
};
} catch (e) {
this.logger.error(e.message, e.stack);
return {
address,
name: address,
};
} finally {
this.unlockAdapter(adapterId);
}
}
/**
* Reset the hci (Bluetooth) device used for inquiries.
*/
protected async resetHciDevice(adapterId: number): Promise<void> {
try {
await execPromise(`hciconfig hci${adapterId} reset`);
} catch (e) {
this.logger.error(e.message);
}
}
/**
* Locks an adapter for an active inquiry.
*
* @param adapterId - HCI Device ID of the adapter to lock
*/
lockAdapter(adapterId: number): void {
this.logger.debug(`Locking adapter ${adapterId}`);
switch (this.adapters.getState(adapterId)) {
case 'inquiry':
throw new Error(
`Trying to lock adapter ${adapterId} even though it is already locked`
);
case 'scan':
this.logger.debug(
`Stop scanning for BLE peripherals on adapter ${this.lowEnergyAdapterId}`
);
noble.stopScanning();
}
this.adapters.setState(adapterId, 'inquiry');
}
/**
* Unlocks an adapter and returns it to scan or inactive state.
*
* @param adapterId - HCI Device ID of the adapter to unlock
*/
async unlockAdapter(adapterId: number): Promise<void> {
this.logger.debug(`Unlocking adapter ${adapterId}`);
this.adapters.setState(adapterId, 'inactive');
if (adapterId == this.lowEnergyAdapterId) {
await this.handleAdapterStateChange(noble.state);
}
}
/**
* Checks if any adapters had a lock acquired on them for longer than
* INQUIRY_LOCK_TIMEOUT and resets them before unlocking them again.
*/
@Interval(10 * 1000)
resetDeadlockedAdapters(): void {
this.adapters.forEach(async (adapter, adapterId) => {
if (
adapter.state === 'inquiry' &&
adapter.startedAt.getTime() < Date.now() - INQUIRY_LOCK_TIMEOUT
) {
this.logger.log(
`Detected unusually long lock on Bluetooth adapter ${adapterId}, resetting`
);
await this.resetHciDevice(adapterId);
await this.unlockAdapter(adapterId);
}
});
}
/**
* Sets up Noble hooks.
*/
private setupNoble(): void {
this.lowEnergyAdapterId = parseInt(process.env.NOBLE_HCI_DEVICE_ID) || 0;
noble.on('stateChange', this.handleAdapterStateChange.bind(this));
noble.on('warning', (message) => {
if (message == 'unknown peripheral undefined RSSI update!') {
return;
}
this.logger.warn(message);
});
}
/**
* Handles state adapter changes as reported by Noble.
*
* @param state - State of the HCI adapter
*/
private async handleAdapterStateChange(state: string): Promise<void> {
if (this.adapters.getState(this.lowEnergyAdapterId) != 'inquiry') {
if (state === 'poweredOn') {
this.logger.debug(
`Start scanning for BLE peripherals on adapter ${this.lowEnergyAdapterId}`
);
await noble.startScanningAsync([], true);
this.adapters.setState(this.lowEnergyAdapterId, 'scan');
} else {
this.logger.debug(
`Stop scanning for BLE peripherals on adapter ${this.lowEnergyAdapterId}`
);
await noble.stopScanning();
this.adapters.setState(this.lowEnergyAdapterId, 'inactive');
}
}
}
}