-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.service.spec.ts
570 lines (465 loc) · 17.5 KB
/
bluetooth.service.spec.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import { makeCounterProvider } from '@willsoto/nestjs-prometheus';
const mockExec = jest.fn();
const mockNoble = {
state: 'poweredOn',
on: jest.fn(),
startScanning: jest.fn(),
stopScanning: jest.fn(),
reset: jest.fn(),
resetBindings: jest.fn(),
};
jest.mock(
'@mkerix/noble',
() => {
return mockNoble;
},
{ virtual: true }
);
import { Test, TestingModule } from '@nestjs/testing';
import { BluetoothService } from './bluetooth.service';
import { ConfigModule } from '../../config/config.module';
import { BluetoothHealthIndicator } from './bluetooth.health';
import { Peripheral } from '@mkerix/noble';
import * as Promises from '../../util/promises';
jest.mock('util', () => ({
...jest.requireActual('util'),
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
promisify: () => mockExec,
}));
jest.useFakeTimers();
describe('BluetoothService', () => {
let service: BluetoothService;
const healthIndicator = {
reportError: jest.fn(),
reportSuccess: jest.fn(),
};
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
imports: [ConfigModule],
providers: [
BluetoothService,
BluetoothHealthIndicator,
makeCounterProvider({
name: 'bluetooth_le_advertisements_received_count',
help: 'help',
}),
],
})
.overrideProvider(BluetoothHealthIndicator)
.useValue(healthIndicator)
.compile();
service = module.get<BluetoothService>(BluetoothService);
});
describe('Bluetooth Classic', () => {
it('should return measured RSSI value from command output', async () => {
mockExec.mockResolvedValue({ stdout: 'RSSI return value: -4' });
const address = '77:50:fb:4d:ab:70';
expect(await service.inquireClassicRssi(1, address)).toBe(-4);
expect(mockExec).toHaveBeenCalledWith(
`hcitool -i hci1 cc \"${address}\" && hcitool -i hci1 rssi \"${address}\"`,
expect.anything()
);
});
it('should return undefined if no RSSI could be determined', async () => {
mockExec.mockResolvedValue({
stdout: "Can't create connection: Input/output error",
stderr: 'Not connected.',
});
expect(
await service.inquireClassicRssi(0, '08:05:90:ed:3b:60')
).toBeUndefined();
});
it('should return undefined if the command failed', async () => {
mockExec.mockRejectedValue({ message: 'Command failed' });
expect(
await service.inquireClassicRssi(0, '08:05:90:ed:3b:60')
).toBeUndefined();
});
it('should throw an exception if an inquiry is requested for a locked adapter', async () => {
service.lockAdapter(1);
await expect(
service.inquireClassicRssi(1, '77:50:fb:4d:ab:71')
).rejects.toThrow();
});
it('should cancel the connection if the query took too long', async () => {
mockExec
.mockRejectedValueOnce({ signal: 'SIGKILL' })
.mockResolvedValue({});
const result = await service.inquireClassicRssi(1, '08:05:90:ed:3b:60');
expect(result).toBeUndefined();
expect(mockExec).toHaveBeenCalledWith(
'hcitool -i hci1 cmd 0x01 0x0008',
expect.anything()
);
});
it('should stop scanning on an adapter while performing an inquiry', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
await stateChangeHandler('poweredOn');
const scanStartHandler = mockNoble.on.mock.calls[5][1];
scanStartHandler();
expect(mockNoble.startScanning).toHaveBeenCalledTimes(1);
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service.inquireClassicRssi(0, 'x').then(() => {
expect(mockNoble.startScanning).toHaveBeenCalledTimes(2);
});
expect(mockNoble.stopScanning).toHaveBeenCalledTimes(1);
execResolve({ stdout: '-1' });
return inquirePromise;
});
it('should start scanning again even after encountering an exception', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
await stateChangeHandler('poweredOn');
mockExec.mockRejectedValue({ stderr: 'error' });
await service.inquireClassicRssi(0, 'x');
expect(mockNoble.startScanning).toHaveBeenCalledTimes(2);
});
it('should stop scanning on an adapter while getting Classic device info', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
await stateChangeHandler('poweredOn');
const scanStartHandler = mockNoble.on.mock.calls[5][1];
scanStartHandler();
expect(mockNoble.startScanning).toHaveBeenCalledTimes(1);
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service
.inquireClassicDeviceInfo(0, 'x')
.then(() => {
expect(mockNoble.startScanning).toHaveBeenCalledTimes(2);
});
expect(mockNoble.stopScanning).toHaveBeenCalledTimes(1);
execResolve({ stdout: '' });
return inquirePromise;
});
it('should return device information based on parsed output', async () => {
mockExec.mockResolvedValue({
stdout: `
Requesting information ...
\tBD Address: F0:99:B6:12:34:AB
\tOUI Company: Apple, Inc. (F0-99-B6)
\tDevice Name: Test iPhone
\tLMP Version: 5.0 (0x9) LMP Subversion: 0x4307
\tManufacturer: Broadcom Corporation (15)
\tFeatures page 0:
\tFeatures page 1:
\tFeatures page 2:
`,
});
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:AB')
).toStrictEqual({
address: 'F0:99:B6:12:34:AB',
name: 'Test iPhone',
manufacturer: 'Apple, Inc.',
});
});
it('should return the address as device name if none was found', async () => {
mockExec.mockResolvedValue({
stdout: 'IO error',
});
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:AB')
).toStrictEqual({
address: 'F0:99:B6:12:34:AB',
name: 'F0:99:B6:12:34:AB',
manufacturer: undefined,
});
});
it('should return barebones information if request fails', async () => {
mockExec.mockRejectedValue({ stderr: 'I/O Error' });
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:CD')
).toStrictEqual({
address: 'F0:99:B6:12:34:CD',
name: 'F0:99:B6:12:34:CD',
});
});
it('should report success to the health indicator when queries are successful', async () => {
mockExec.mockResolvedValue({ stdout: 'RSSI return value: -4' });
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportSuccess).toHaveBeenCalledTimes(1);
});
it('should report an error to the health indicator when queries are unsuccessful', async () => {
mockExec.mockRejectedValue({ message: 'critical error' });
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportError).toHaveBeenCalledTimes(1);
});
it('should not report anything to the health indicator if the device was not reachable', async () => {
mockExec.mockRejectedValue({
message: 'Could not connect: Input/output error',
});
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportSuccess).not.toHaveBeenCalled();
expect(healthIndicator.reportError).not.toHaveBeenCalled();
});
it('should not report an error if the scan was stopped due to low time limits', async () => {
mockExec
.mockRejectedValueOnce({
message: 'killed',
signal: 'SIGKILL',
})
.mockResolvedValue({});
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportError).not.toHaveBeenCalled();
});
});
describe('Bluetooth Low Energy', () => {
it('should setup noble listeners on the first subscriber', () => {
const callback = () => undefined;
service.onLowEnergyDiscovery(callback);
expect(mockNoble.on).toHaveBeenCalledWith(
'stateChange',
expect.any(Function)
);
expect(mockNoble.on).toHaveBeenCalledWith('discover', callback);
});
it('should only setup noble listeners once', () => {
service.onLowEnergyDiscovery(() => undefined);
service.onLowEnergyDiscovery(() => undefined);
expect(mockNoble.on).toHaveBeenCalledTimes(10);
});
it('should enable scanning when the adapter is inactive', () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
stateChangeHandler('poweredOn');
expect(mockNoble.startScanning).toHaveBeenCalledTimes(1);
});
it('should not enable scanning when the adapter is performing a Classic inquiry', () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service.inquireClassicRssi(0, 'x').then(() => {
expect(mockNoble.startScanning).toHaveBeenCalledTimes(1);
});
stateChangeHandler('poweredOn');
expect(mockNoble.startScanning).not.toHaveBeenCalled();
execResolve({ stdout: '-1' });
return inquirePromise;
});
it('should continue scanning if Classic inquiries are performed on another adapter', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
stateChangeHandler('poweredOn');
const execPromise = Promise.resolve({ stdout: '-1' });
mockExec.mockReturnValue(execPromise);
await service.inquireClassicRssi(1, 'x');
expect(mockNoble.startScanning).toHaveBeenCalledTimes(1);
expect(mockNoble.stopScanning).not.toHaveBeenCalled();
});
it('should throw an exception if trying to connect to a non-connectable peripheral', async () => {
const peripheral = {
connectable: false,
} as Peripheral;
await expect(async () => {
await service.connectLowEnergyDevice(peripheral);
}).rejects.toThrow();
});
it('should throw an exception if trying to connect to an already connecting peripheral', async () => {
const peripheral = {
connectable: true,
state: 'connecting',
} as Peripheral;
await expect(async () => {
await service.connectLowEnergyDevice(peripheral);
}).rejects.toThrow();
});
it('should re-use connections for already connected peripherals', async () => {
const peripheral = {
connectable: true,
state: 'connected',
} as Peripheral;
const result = await service.connectLowEnergyDevice(peripheral);
expect(result).toBe(peripheral);
});
it('should only allow a single connection on an adapter', async () => {
let connectResolve;
const connectPromise = new Promise((r) => (connectResolve = r));
const peripheral = {
connectable: true,
connectAsync: jest.fn().mockReturnValue(connectPromise),
once: jest.fn(),
state: 'disconnected',
};
service.connectLowEnergyDevice((peripheral as unknown) as Peripheral);
await expect(
service.connectLowEnergyDevice((peripheral as unknown) as Peripheral)
).rejects.toThrow();
peripheral.state = 'connected';
connectResolve();
});
it('should unlock the adapter on disconnect', async () => {
jest.spyOn(Promises, 'sleep').mockResolvedValue();
const peripheral = {
connectable: true,
connectAsync: jest.fn().mockImplementation(() => {
peripheral.state = 'connected';
return Promise.resolve();
}),
once: jest.fn(),
state: 'disconnected',
};
await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
const disconnectListener = peripheral.once.mock.calls[0][1];
disconnectListener();
await expect(async () => {
await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
}).not.toThrow();
});
it('should clean up if an exception occurs while connecting', async () => {
const peripheral = {
connectable: true,
connectAsync: jest.fn().mockRejectedValue(new Error('expected')),
disconnect: jest.fn(),
removeAllListeners: jest.fn(),
once: jest.fn(),
};
await expect(async () => {
await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
}).rejects.toThrow();
expect(peripheral.removeAllListeners).toHaveBeenCalled();
});
it('should limit the connection attempt time', () => {
expect.assertions(1);
jest.useFakeTimers('modern');
const peripheral = {
connectable: true,
connectAsync: jest
.fn()
.mockReturnValue(
new Promise((resolve) => setTimeout(resolve, 11 * 1000))
),
disconnect: jest.fn(),
removeAllListeners: jest.fn(),
once: jest.fn(),
};
const promise = service
.connectLowEnergyDevice((peripheral as unknown) as Peripheral)
.catch((e) => {
expect(e).toStrictEqual(new Error('timed out'));
});
jest.advanceTimersByTime(10.5 * 1000);
return promise;
});
it('should return the peripheral after connecting', async () => {
jest.spyOn(Promises, 'sleep').mockResolvedValue();
const peripheral = {
connectable: true,
connectAsync: jest.fn().mockImplementation(() => {
peripheral.state = 'connected';
return Promise.resolve();
}),
once: jest.fn(),
state: 'disconnected',
};
const actual = await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
expect(actual).toBe(peripheral);
});
it('should retry connection attempts after immediate disconnects', async () => {
const peripheral = {
connectable: true,
connectAsync: jest
.fn()
.mockResolvedValueOnce(undefined)
.mockImplementation(() => {
peripheral.state = 'connected';
return Promise.resolve();
}),
once: jest.fn(),
state: 'disconnected',
};
const actual = await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
expect(actual).toBe(peripheral);
expect(peripheral.connectAsync).toHaveBeenCalledTimes(2);
});
it('should throw after multiple connection attempts', async () => {
jest.spyOn(Promises, 'sleep').mockResolvedValue();
const peripheral = {
connectable: true,
connectAsync: jest.fn().mockResolvedValue(undefined),
disconnect: jest.fn(),
once: jest.fn(),
removeAllListeners: jest.fn(),
state: 'disconnected',
};
await expect(async () => {
await service.connectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
}).rejects.toThrow();
expect(peripheral.connectAsync).toHaveBeenCalledTimes(5);
});
it('should disconnect from a peripheral', async () => {
const peripheral = {
state: 'connected',
disconnectAsync: jest.fn().mockResolvedValue(undefined),
};
await service.disconnectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
expect(peripheral.disconnectAsync).toHaveBeenCalled();
});
it('should reset the adapter if the disconnect fails', async () => {
service.onLowEnergyDiscovery(() => undefined);
const peripheral = {
state: 'connected',
disconnectAsync: jest.fn().mockRejectedValue({ message: '' }),
};
await service.disconnectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
expect(mockExec).toHaveBeenCalledWith(
'hciconfig hci0 reset',
expect.anything()
);
});
it('should not try to disconnect from a peripheral that is not connected', async () => {
const peripheral = {
state: 'disconnected',
disconnectAsync: jest.fn().mockResolvedValue(undefined),
};
await service.disconnectLowEnergyDevice(
(peripheral as unknown) as Peripheral
);
expect(peripheral.disconnectAsync).not.toHaveBeenCalled();
});
it('should reset adapter if nothing has been detected for a while', async () => {
jest.spyOn(Promises, 'sleep').mockResolvedValue();
jest.useFakeTimers('modern');
// eslint-disable-next-line @typescript-eslint/no-empty-function
service.onLowEnergyDiscovery(() => {});
const stateCallback = mockNoble.on.mock.calls.find(
(call) => call[0] === 'stateChange'
)[1];
const discoveryCallback = mockNoble.on.mock.calls.filter(
(call) => call[0] === 'discover'
)[1][1];
await stateCallback('poweredOn');
jest.resetAllMocks();
discoveryCallback();
jest.setSystemTime(Date.now() + 31 * 1000);
await service.verifyLowEnergyScanner();
expect(mockExec).toHaveBeenCalledWith(
'hciconfig hci0 reset',
expect.anything()
);
});
});
});