-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.service.ts
210 lines (185 loc) · 6.09 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
import { Injectable, Logger } from '@nestjs/common';
import noble, { Peripheral } from '@abandonware/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';
type BluetoothAdapterState = 'inquiry' | 'scan' | 'inactive';
const execPromise = util.promisify(exec);
const rssiRegex = new RegExp(/-?[0-9]+/);
@Injectable()
export class BluetoothService {
private readonly logger: Logger = new Logger(BluetoothService.name);
private readonly classicConfig: BluetoothClassicConfig;
private readonly adapterStates = new Map<number, BluetoothAdapterState>();
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);
}
/**
* 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> {
await this.lockAdapter(adapterId);
this.logger.debug(`Querying for RSSI of ${address} using hcitool`);
try {
const output = await execPromise(
`hcitool -i hci${adapterId} cc "${address}" && hcitool -i hci${adapterId} rssi "${address}"`,
{
timeout: this.classicConfig.scanTimeLimit * 1000,
killSignal: 'SIGKILL',
}
);
const matches = output.stdout.match(rssiRegex);
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 {
this.logger.error(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> {
await this.lockAdapter(adapterId);
try {
const output = await execPromise(
`hcitool -i hci${adapterId} info "${address}"`
);
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
*/
async lockAdapter(adapterId: number): Promise<void> {
switch (this.adapterStates.get(adapterId)) {
case 'inquiry':
throw new Error(
`Trying to lock adapter ${adapterId} even though it is already locked`
);
case 'scan':
noble.stopScanning();
}
this.adapterStates.set(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.adapterStates.set(adapterId, 'inactive');
if (adapterId == this.lowEnergyAdapterId) {
await this.handleAdapterStateChange(noble.state);
}
}
/**
* 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.adapterStates.get(this.lowEnergyAdapterId) != 'inquiry') {
if (state === 'poweredOn') {
await noble.startScanningAsync([], true);
this.adapterStates.set(this.lowEnergyAdapterId, 'scan');
} else {
await noble.stopScanning();
this.adapterStates.set(this.lowEnergyAdapterId, 'inactive');
}
}
}
}