@onekeyfe/hd-transport-react-native 1.2.2-alpha.105 → 1.2.2-alpha.107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/BleManager.ts CHANGED
@@ -7,6 +7,19 @@ import type { Peripheral } from '@onekeyfe/react-native-ble-utils';
7
7
 
8
8
  const Logger = bleLogger;
9
9
 
10
+ // Android BluetoothDevice.EXTRA_UNBOND_REASON values.
11
+ const bondFailureReasons: Record<number, string> = {
12
+ 1: 'authentication_failed',
13
+ 2: 'rejected',
14
+ 3: 'canceled',
15
+ 4: 'device_unreachable',
16
+ 5: 'discovery_in_progress',
17
+ 6: 'timeout',
18
+ 7: 'repeated_attempts',
19
+ 8: 'remote_canceled',
20
+ 9: 'removed',
21
+ };
22
+
10
23
  /**
11
24
  * get the device basic info of connected devices
12
25
  * @param serviceUuids
@@ -30,7 +43,12 @@ export const onDeviceBondState = (bleMacAddress: string): Promise<Peripheral | u
30
43
 
31
44
  const timeout = setTimeout(() => {
32
45
  cleanup();
33
- reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded'));
46
+ reject(
47
+ ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing timed out', {
48
+ phase: 'bond',
49
+ reason: 'timeout',
50
+ })
51
+ );
34
52
  }, 60 * 1000);
35
53
 
36
54
  const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
@@ -40,14 +58,50 @@ export const onDeviceBondState = (bleMacAddress: string): Promise<Peripheral | u
40
58
  const { bondState } = peripheral;
41
59
 
42
60
  const hasBonded = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_BONDED';
43
- const hasCanceled = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_NONE';
61
+ const hasFailed = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_NONE';
44
62
  Logger.debug('onDeviceBondState bondState:', bondState);
45
63
  if (hasBonded) {
46
64
  cleanup();
47
65
  resolve(peripheral);
48
- } else if (hasCanceled) {
66
+ } else if (hasFailed) {
49
67
  cleanup();
50
- reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceBondedCanceled, 'bonding canceled'));
68
+ const nativeReason =
69
+ 'reason' in bondState && typeof bondState.reason === 'number'
70
+ ? bondState.reason
71
+ : undefined;
72
+ const reason =
73
+ nativeReason === undefined ? 'unknown' : bondFailureReasons[nativeReason] ?? 'unknown';
74
+ const params = {
75
+ phase: 'bond',
76
+ reason,
77
+ ...(nativeReason === undefined ? {} : { nativeReason }),
78
+ };
79
+ if (reason === 'timeout') {
80
+ // Connection timeouts are retried by Core; pairing requires a new user attempt.
81
+ reject(
82
+ ERRORS.TypedError(
83
+ HardwareErrorCode.BleDeviceNotBonded,
84
+ 'Bluetooth pairing timed out',
85
+ params
86
+ )
87
+ );
88
+ } else if (reason === 'canceled') {
89
+ reject(
90
+ ERRORS.TypedError(
91
+ HardwareErrorCode.BleDeviceBondedCanceled,
92
+ 'Bluetooth pairing canceled',
93
+ params
94
+ )
95
+ );
96
+ } else {
97
+ reject(
98
+ ERRORS.TypedError(
99
+ HardwareErrorCode.BleDeviceNotBonded,
100
+ 'Bluetooth pairing failed',
101
+ params
102
+ )
103
+ );
104
+ }
51
105
  }
52
106
  });
53
107
  });
@@ -0,0 +1,33 @@
1
+ import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from '../bleNativeDisconnect';
4
+
5
+ describe('native BLE disconnect mapping', () => {
6
+ test.each([
7
+ [{ errorCode: 201, reason: 'The specified device has disconnected from us.' }],
8
+ [{ errorCode: 201, iosErrorCode: 7, reason: 'The specified device has disconnected from us.' }],
9
+ [{ iosErrorCode: 7, reason: 'Peripheral disconnected' }],
10
+ ])('recognizes %j as a native disconnect', nativeError => {
11
+ expect(isNativeBleDisconnectError(nativeError)).toBe(true);
12
+ expect(toBleDisconnectHardwareError(nativeError)).toMatchObject({
13
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
14
+ });
15
+ });
16
+
17
+ test('does not treat a stale-bond iOS code as a disconnect', () => {
18
+ expect(
19
+ isNativeBleDisconnectError({
20
+ iosErrorCode: 14,
21
+ reason: 'Peer removed pairing information',
22
+ })
23
+ ).toBe(false);
24
+ });
25
+
26
+ test('does not treat an already-canonical unpaired error as a native disconnect', () => {
27
+ expect(
28
+ isNativeBleDisconnectError({
29
+ errorCode: HardwareErrorCode.BleDeviceNotBonded,
30
+ })
31
+ ).toBe(false);
32
+ });
33
+ });
@@ -1,7 +1,10 @@
1
1
  import { EventEmitter } from 'events';
2
- import { BleErrorCode } from 'react-native-ble-plx';
3
- import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+ import { Platform } from 'react-native';
3
+ import { BleErrorCode, BleManager } from 'react-native-ble-plx';
4
+ import BleUtils from '@onekeyfe/react-native-ble-utils';
5
+ import { ERRORS, HardwareErrorCode, createDeferred } from '@onekeyfe/hd-shared';
4
6
 
7
+ import { onDeviceBondState } from '../BleManager';
5
8
  import ReactNativeBleTransport, {
6
9
  BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD,
7
10
  BLE_CONNECT_TIMEOUT_MS,
@@ -10,6 +13,8 @@ import ReactNativeBleTransport, {
10
13
  } from '../index';
11
14
  import protocolV1Schema from './protocolV1SchemaFixture';
12
15
 
16
+ import type { Peripheral } from '@onekeyfe/react-native-ble-utils';
17
+
13
18
  jest.mock(
14
19
  'react-native',
15
20
  () => ({
@@ -44,12 +49,105 @@ jest.mock('@onekeyfe/react-native-ble-utils', () => ({
44
49
  default: {
45
50
  getConnectedPeripherals: jest.fn(() => Promise.resolve([])),
46
51
  getBondedPeripherals: jest.fn(() => Promise.resolve([])),
47
- pairDevice: jest.fn(() => Promise.resolve()),
52
+ pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
53
+ onDeviceBondState: jest.fn(),
48
54
  },
49
55
  }));
50
56
 
51
57
  const UUID = 'stalled-connect-device';
52
58
 
59
+ describe('Android bond failure reasons', () => {
60
+ let emitBondState: (peripheral: Peripheral) => void;
61
+ const cleanup = jest.fn();
62
+
63
+ beforeEach(() => {
64
+ jest.useFakeTimers({ doNotFake: ['performance'] });
65
+ cleanup.mockClear();
66
+ jest.spyOn(BleUtils, 'onDeviceBondState').mockImplementation(listener => {
67
+ emitBondState = listener;
68
+ return cleanup;
69
+ });
70
+ });
71
+
72
+ afterEach(() => {
73
+ jest.restoreAllMocks();
74
+ jest.useRealTimers();
75
+ });
76
+
77
+ test.each([
78
+ [6, 'timeout', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing timed out'],
79
+ [3, 'canceled', HardwareErrorCode.BleDeviceBondedCanceled, 'Bluetooth pairing canceled'],
80
+ [1, 'authentication_failed', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
81
+ [2, 'rejected', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
82
+ [4, 'device_unreachable', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
83
+ [5, 'discovery_in_progress', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
84
+ [7, 'repeated_attempts', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
85
+ [8, 'remote_canceled', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
86
+ [9, 'removed', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
87
+ [undefined, 'unknown', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
88
+ [999, 'unknown', HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed'],
89
+ ] as const)(
90
+ 'preserves Android reason %s as %s across serialization',
91
+ async (nativeReason, reason, code, message) => {
92
+ const result = onDeviceBondState(UUID).catch(error =>
93
+ JSON.parse(JSON.stringify(ERRORS.serializeError({ error })))
94
+ );
95
+ emitBondState({
96
+ id: UUID,
97
+ advertising: {},
98
+ bondState: {
99
+ preState: 'BOND_BONDING',
100
+ state: 'BOND_NONE',
101
+ ...(nativeReason === undefined ? {} : { reason: nativeReason }),
102
+ },
103
+ });
104
+
105
+ await expect(result).resolves.toEqual({
106
+ code,
107
+ error: message,
108
+ params: {
109
+ phase: 'bond',
110
+ reason,
111
+ ...(nativeReason === undefined ? {} : { nativeReason }),
112
+ },
113
+ });
114
+ expect(cleanup).toHaveBeenCalledTimes(1);
115
+ expect(jest.getTimerCount()).toBe(0);
116
+ }
117
+ );
118
+
119
+ test('reports a timeout if no bond event arrives within the SDK deadline', async () => {
120
+ const result = onDeviceBondState(UUID);
121
+ const rejection = expect(result).rejects.toMatchObject({
122
+ errorCode: HardwareErrorCode.BleDeviceNotBonded,
123
+ params: { phase: 'bond', reason: 'timeout' },
124
+ });
125
+ jest.advanceTimersByTime(60_000);
126
+ await rejection;
127
+ expect(cleanup).toHaveBeenCalledTimes(1);
128
+ });
129
+
130
+ test('ignores other devices and clears the deadline after bonding succeeds', async () => {
131
+ const result = onDeviceBondState(UUID);
132
+ const otherPeripheral = {
133
+ id: 'another-device',
134
+ advertising: {},
135
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 6 },
136
+ };
137
+ emitBondState(otherPeripheral);
138
+ expect(cleanup).not.toHaveBeenCalled();
139
+ const peripheral: Peripheral = {
140
+ id: UUID.toUpperCase(),
141
+ advertising: {},
142
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_BONDED' },
143
+ };
144
+ emitBondState(peripheral);
145
+ await expect(result).resolves.toBe(peripheral);
146
+ expect(cleanup).toHaveBeenCalledTimes(1);
147
+ expect(jest.getTimerCount()).toBe(0);
148
+ });
149
+ });
150
+
53
151
  const flush = () =>
54
152
  new Promise(resolve => {
55
153
  setImmediate(resolve);
@@ -129,6 +227,60 @@ describe('BLE connect timeout', () => {
129
227
  afterEach(() => {
130
228
  jest.clearAllTimers();
131
229
  jest.restoreAllMocks();
230
+ Object.assign(Platform, { OS: 'ios' });
231
+ });
232
+
233
+ test('waits for singleton destruction before creating the next manager', async () => {
234
+ const { transport, bleManager } = createHarness(() => Promise.resolve());
235
+ const destruction = createDeferred<void>();
236
+ Object.assign(bleManager, { destroy: jest.fn(() => destruction.promise) });
237
+ const createManager = jest.mocked(BleManager);
238
+ createManager.mockClear();
239
+ (transport as unknown as { resetPlxManager(): void }).resetPlxManager();
240
+ const first = transport.getPlxManager();
241
+ const second = transport.getPlxManager();
242
+ await flush();
243
+ expect(createManager).not.toHaveBeenCalled();
244
+ destruction.resolve();
245
+ expect(await first).toBe(await second);
246
+ expect(createManager).toHaveBeenCalledTimes(1);
247
+ });
248
+
249
+ test('does not reuse a manager after asynchronous destruction fails', async () => {
250
+ const { bleManager } = createHarness(() => Promise.resolve());
251
+ let transport!: ReactNativeBleTransport;
252
+ jest.isolateModules(() => {
253
+ const { default: Transport } = jest.requireActual<typeof import('../index')>('../index');
254
+ transport = new Transport({});
255
+ });
256
+ transport.blePlxManager = bleManager as never;
257
+ const destruction = createDeferred<void>();
258
+ Object.assign(bleManager, { destroy: jest.fn(() => destruction.promise) });
259
+ (transport as unknown as { resetPlxManager(): void }).resetPlxManager();
260
+ const result = transport.getPlxManager();
261
+ const failure = expect(result).rejects.toMatchObject({
262
+ errorCode: HardwareErrorCode.PollingTimeout,
263
+ });
264
+ destruction.reject(new Error('Native destruction failed'));
265
+ await failure;
266
+ });
267
+
268
+ test('bounds reset waiting without letting a new transport bypass unfinished destruction', async () => {
269
+ const { transport, bleManager } = createHarness(() => Promise.resolve());
270
+ const destruction = createDeferred<void>();
271
+ Object.assign(bleManager, { destroy: jest.fn(() => destruction.promise) });
272
+ const createManager = jest.mocked(BleManager);
273
+ createManager.mockClear();
274
+ (transport as unknown as { resetPlxManager(): void }).resetPlxManager();
275
+ const nextTransport = new ReactNativeBleTransport({});
276
+ const result = nextTransport.getPlxManager().catch(error => error);
277
+ await flush();
278
+ jest.advanceTimersByTime(BLE_CONNECT_TIMEOUT_MS);
279
+ await expect(result).resolves.toMatchObject({ errorCode: HardwareErrorCode.PollingTimeout });
280
+ expect(createManager).not.toHaveBeenCalled();
281
+ destruction.resolve();
282
+ await nextTransport.getPlxManager();
283
+ expect(createManager).toHaveBeenCalledTimes(1);
132
284
  });
133
285
 
134
286
  test('a native connect that never settles is bounded instead of blocking forever', async () => {
@@ -155,6 +307,61 @@ describe('BLE connect timeout', () => {
155
307
  expect(errors[0]?.errorCode).toBe(HardwareErrorCode.BleConnectedError);
156
308
  });
157
309
 
310
+ test('stop drains its scan and removes the timer before another transport scans', async () => {
311
+ const { transport, bleManager } = createHarness(() => Promise.resolve());
312
+ const nativeStop = createDeferred<void>();
313
+ bleManager.stopDeviceScan.mockImplementation(() => nativeStop.promise);
314
+ const scanned = transport.enumerate().catch(error => error);
315
+ await flush();
316
+ await flush();
317
+ expect(bleManager.startDeviceScan).toHaveBeenCalledTimes(1);
318
+ const stopping = transport.stop();
319
+ expect(transport.stop()).toBe(stopping);
320
+ let stopped = false;
321
+ stopping.then(() => {
322
+ stopped = true;
323
+ });
324
+ await flush();
325
+ expect(stopped).toBe(false);
326
+ nativeStop.resolve();
327
+ await stopping;
328
+ await expect(scanned).resolves.toMatchObject({
329
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
330
+ });
331
+ jest.advanceTimersByTime(transport.scanTimeout);
332
+ await flush();
333
+ expect(bleManager.stopDeviceScan).toHaveBeenCalledTimes(1);
334
+ await expect(transport.getPlxManager()).rejects.toMatchObject({
335
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
336
+ });
337
+ });
338
+
339
+ test('stop rejects a pending read and waits for native disconnection without destroying the shared manager', async () => {
340
+ const { transport, bleManager } = createHarness(() => Promise.resolve());
341
+ const nativeDisconnect = createDeferred<void>();
342
+ bleManager.cancelDeviceConnection.mockImplementation(() => nativeDisconnect.promise);
343
+ const destroy = jest.fn();
344
+ Object.assign(bleManager, { destroy });
345
+ const read = createDeferred<void>();
346
+ transport.runPromise = read;
347
+ Object.assign(transport, { runPromiseDeviceId: UUID });
348
+ const readResult = read.promise.catch(error => error);
349
+ let stopped = false;
350
+ const stopping = transport.stop().then(() => {
351
+ stopped = true;
352
+ });
353
+ await flush();
354
+ await expect(readResult).resolves.toMatchObject({
355
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
356
+ });
357
+ expect(stopped).toBe(false);
358
+ nativeDisconnect.resolve();
359
+ await advanceUntil(() => stopped, 1000);
360
+ await stopping;
361
+ expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
362
+ expect(destroy).not.toHaveBeenCalled();
363
+ });
364
+
158
365
  test('the connect budget leaves generous headroom over a healthy connect', () => {
159
366
  // Healthy connects finish in ~2-3s (the native budget is 3s); this backstop only
160
367
  // fires when the native timeout itself fails to.
@@ -162,6 +369,78 @@ describe('BLE connect timeout', () => {
162
369
  expect(BLE_CONNECT_TIMEOUT_MS).toBeLessThanOrEqual(12000);
163
370
  });
164
371
 
372
+ test.each(
373
+ (['ios', 'android'] as const).flatMap(platform =>
374
+ (['connect', 'mtu', 'gatt'] as const).flatMap(stage =>
375
+ (['reject', 'resolve'] as const).map(completion => ({ platform, stage, completion }))
376
+ )
377
+ )
378
+ )(
379
+ 'stop cancels $platform $stage before draining a late $completion',
380
+ async ({ platform, stage, completion }) => {
381
+ Object.assign(Platform, { OS: platform });
382
+ const { transport, device, bleManager, connect } = createHarness(
383
+ () => nativeOperation.promise
384
+ );
385
+ const nativeOperation = createDeferred<typeof device>();
386
+ const nativeDisconnect = createDeferred<void>();
387
+ const requestMtu = jest.fn(() => Promise.resolve(device));
388
+ Object.assign(device, { mtu: 247, requestMTU: requestMtu });
389
+ device.isConnected.mockResolvedValue(true);
390
+ if (stage === 'connect') device.isConnected.mockResolvedValueOnce(false);
391
+ if (stage === 'mtu') requestMtu.mockImplementationOnce(() => nativeOperation.promise);
392
+ if (stage === 'gatt') {
393
+ device.discoverAllServicesAndCharacteristics.mockImplementationOnce(() =>
394
+ nativeOperation.promise.then(() => undefined)
395
+ );
396
+ }
397
+ const destroy = jest.fn();
398
+ Object.assign(bleManager, { destroy });
399
+ const monitor = jest.spyOn(transport, '_monitorCharacteristic');
400
+ const acquire = transport.acquire({ uuid: UUID }).catch(error => error);
401
+ await flush();
402
+ await flush();
403
+ const pending = {
404
+ connect,
405
+ mtu: requestMtu,
406
+ gatt: device.discoverAllServicesAndCharacteristics,
407
+ }[stage];
408
+ expect(pending).toHaveBeenCalledTimes(1);
409
+
410
+ bleManager.cancelDeviceConnection.mockImplementation(() => nativeDisconnect.promise);
411
+ let stopped = false;
412
+ const stopping = transport.stop().then(() => {
413
+ stopped = true;
414
+ });
415
+ try {
416
+ await flush();
417
+ expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
418
+ expect(stopped).toBe(false);
419
+ } finally {
420
+ // Native completion can race cancellation; neither outcome may restart setup.
421
+ if (completion === 'resolve') nativeOperation.resolve(device);
422
+ else
423
+ nativeOperation.reject(
424
+ Object.assign(new Error('Operation was cancelled'), {
425
+ errorCode: BleErrorCode.OperationCancelled,
426
+ })
427
+ );
428
+ nativeDisconnect.resolve();
429
+ await advanceUntil(() => stopped, BLE_CONNECT_TIMEOUT_MS + BLE_GATT_SETUP_TIMEOUT_MS);
430
+ await stopping;
431
+ }
432
+ await expect(acquire).resolves.toBeInstanceOf(Error);
433
+ expect(connect).toHaveBeenCalledTimes(stage === 'connect' ? 1 : 0);
434
+ expect(monitor).not.toHaveBeenCalled();
435
+ if (stage === 'mtu')
436
+ expect(device.discoverAllServicesAndCharacteristics).not.toHaveBeenCalled();
437
+ expect(bleManager.cancelDeviceConnection.mock.calls).toEqual(
438
+ Array.from({ length: bleManager.cancelDeviceConnection.mock.calls.length }, () => [UUID])
439
+ );
440
+ expect(destroy).not.toHaveBeenCalled();
441
+ }
442
+ );
443
+
165
444
  test('a stalled connect is abandoned natively so the next attempt is not cancelled by it', async () => {
166
445
  const { transport, bleManager } = createHarness(
167
446
  () =>