@onekeyfe/hd-transport-react-native 1.2.8-alpha.1 → 1.2.8-alpha.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"subscribeBleOn.d.ts","sourceRoot":"","sources":["../src/subscribeBleOn.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,eAAO,MAAM,cAAc,eAAgB,aAAa,kBAAc,QAAQ,IAAI,CAmB9E,CAAC"}
1
+ {"version":3,"file":"subscribeBleOn.d.ts","sourceRoot":"","sources":["../src/subscribeBleOn.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,eAAO,MAAM,cAAc,eAAgB,aAAa,kBAAc,QAAQ,IAAI,CAsC9E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-react-native",
3
- "version": "1.2.8-alpha.1",
3
+ "version": "1.2.8-alpha.3",
4
4
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -20,11 +20,11 @@
20
20
  "lint:fix": "eslint . --fix"
21
21
  },
22
22
  "dependencies": {
23
- "@onekeyfe/hd-core": "1.2.8-alpha.1",
24
- "@onekeyfe/hd-shared": "1.2.8-alpha.1",
25
- "@onekeyfe/hd-transport": "1.2.8-alpha.1",
23
+ "@onekeyfe/hd-core": "1.2.8-alpha.3",
24
+ "@onekeyfe/hd-shared": "1.2.8-alpha.3",
25
+ "@onekeyfe/hd-transport": "1.2.8-alpha.3",
26
26
  "@onekeyfe/react-native-ble-utils": "0.1.9",
27
27
  "react-native-ble-plx": "3.5.1"
28
28
  },
29
- "gitHead": "df614dc773e3e1075e5fbcdaee62d10a7a641eed"
29
+ "gitHead": "18c57239359413a079fffa730b36149c8516aa85"
30
30
  }
package/src/BleManager.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import BleUtils from '@onekeyfe/react-native-ble-utils';
2
2
  import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
3
3
 
4
- import { onBleKeyMissing, startBleKeyMissingTracking } from './bleKeyMissing';
5
4
  import { bleLogger } from './logger';
6
5
 
7
6
  import type { Peripheral } from '@onekeyfe/react-native-ble-utils';
@@ -33,20 +32,7 @@ export const getBondedDevices = () => BleUtils.getBondedPeripherals();
33
32
 
34
33
  export const pairDevice = (macAddress: string) => BleUtils.pairDevice(macAddress);
35
34
 
36
- /**
37
- * Android replaces a bond as BONDING -> NONE, then NONE -> BONDING within milliseconds.
38
- * The window covers slow broadcast delivery before the first half counts as a failure.
39
- */
40
- export const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
41
-
42
- export type DeviceBondStateOptions = {
43
- /**
44
- * The system, not this transport, started the bonding in progress. Android 16+ re-pairs
45
- * by itself after it detects a lost bond, and a successful re-pair replaces the old bond
46
- * instead of going straight to BONDED.
47
- */
48
- systemInitiated?: boolean;
49
- };
35
+ const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
50
36
 
51
37
  const createBondFailureError = (bondState: Peripheral['bondState']) => {
52
38
  const nativeReason =
@@ -83,7 +69,7 @@ const createBondFailureError = (bondState: Peripheral['bondState']) => {
83
69
  export const onDeviceBondState = (
84
70
  bleMacAddress: string,
85
71
  signal?: AbortSignal,
86
- options?: DeviceBondStateOptions
72
+ options?: { systemInitiated?: boolean }
87
73
  ): Promise<Peripheral | undefined> =>
88
74
  new Promise((resolve, reject) => {
89
75
  if (signal?.aborted) {
@@ -97,7 +83,6 @@ export const onDeviceBondState = (
97
83
  }
98
84
  if (pendingFailure) clearTimeout(pendingFailure);
99
85
  if (cleanupListener) cleanupListener();
100
- cleanupKeyMissing?.();
101
86
  signal?.removeEventListener('abort', onAbort);
102
87
  };
103
88
  const onAbort = () => {
@@ -117,20 +102,6 @@ export const onDeviceBondState = (
117
102
  );
118
103
  }, 60 * 1000);
119
104
 
120
- // A failed system re-pair restores the old bond, so it also ends in BONDED. Key
121
- // missing is what tells it apart from a bond that now works.
122
- const cleanupKeyMissing = startBleKeyMissingTracking()
123
- ? onBleKeyMissing(bleMacAddress, () => {
124
- cleanup();
125
- reject(
126
- ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
127
- phase: 'bond',
128
- reason: 'key_missing',
129
- })
130
- );
131
- })
132
- : undefined;
133
-
134
105
  const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
135
106
  if (peripheral.id?.toLowerCase() !== bleMacAddress.toLowerCase()) {
136
107
  return;
@@ -148,6 +119,8 @@ export const onDeviceBondState = (
148
119
  clearTimeout(pendingFailure);
149
120
  pendingFailure = undefined;
150
121
  } else if (hasFailed && options?.systemInitiated) {
122
+ // Android can briefly remove the old bond before continuing an
123
+ // already-running system pairing. The original overall deadline stays.
151
124
  if (pendingFailure) clearTimeout(pendingFailure);
152
125
  pendingFailure = setTimeout(() => {
153
126
  cleanup();
@@ -14,7 +14,7 @@ describe('native BLE disconnect mapping', () => {
14
14
  });
15
15
  });
16
16
 
17
- test('does not treat a stale-bond iOS code as a disconnect', () => {
17
+ test('does not treat an unrelated iOS code as a disconnect', () => {
18
18
  expect(
19
19
  isNativeBleDisconnectError({
20
20
  iosErrorCode: 14,
@@ -30,4 +30,25 @@ describe('native BLE disconnect mapping', () => {
30
30
  })
31
31
  ).toBe(false);
32
32
  });
33
+
34
+ test('recognizes the unstructured ble-plx disconnect observed during GATT discovery', () => {
35
+ const nativeError = {
36
+ errorCode: 0,
37
+ message: 'BleError: Device stalled-connect-device was disconnected',
38
+ };
39
+
40
+ expect(isNativeBleDisconnectError(nativeError)).toBe(true);
41
+ expect(toBleDisconnectHardwareError(nativeError)).toMatchObject({
42
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
43
+ });
44
+ });
45
+
46
+ test('does not infer a disconnect from an unrelated discovery failure', () => {
47
+ expect(
48
+ isNativeBleDisconnectError({
49
+ errorCode: 0,
50
+ message: 'Known OneKey service UUID not found',
51
+ })
52
+ ).toBe(false);
53
+ });
33
54
  });
@@ -129,6 +129,102 @@ describe('Android bond failure reasons', () => {
129
129
  expect(cleanup).toHaveBeenCalledTimes(1);
130
130
  });
131
131
 
132
+ test('lets system-initiated bonding restart before accepting the replacement bond', async () => {
133
+ const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
134
+ const outcome = result.catch(error => error);
135
+ emitBondState({
136
+ id: UUID,
137
+ advertising: {},
138
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
139
+ });
140
+ jest.advanceTimersByTime(1499);
141
+ expect(cleanup).not.toHaveBeenCalled();
142
+
143
+ emitBondState({
144
+ id: UUID,
145
+ advertising: {},
146
+ bondState: { preState: 'BOND_NONE', state: 'BOND_BONDING' },
147
+ });
148
+ jest.advanceTimersByTime(1500);
149
+ expect(cleanup).not.toHaveBeenCalled();
150
+ const bonded: Peripheral = {
151
+ id: UUID,
152
+ advertising: {},
153
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_BONDED' },
154
+ };
155
+ emitBondState(bonded);
156
+
157
+ await expect(outcome).resolves.toBe(bonded);
158
+ expect(cleanup).toHaveBeenCalledTimes(1);
159
+ expect(jest.getTimerCount()).toBe(0);
160
+ });
161
+
162
+ test('rejects a genuine system bond failure when the restart window expires', async () => {
163
+ const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
164
+ const rejection = expect(result).rejects.toMatchObject({
165
+ errorCode: HardwareErrorCode.BleDeviceNotBonded,
166
+ params: { phase: 'bond', reason: 'authentication_failed', nativeReason: 1 },
167
+ });
168
+ emitBondState({
169
+ id: UUID,
170
+ advertising: {},
171
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 1 },
172
+ });
173
+ jest.advanceTimersByTime(1499);
174
+ expect(cleanup).not.toHaveBeenCalled();
175
+ jest.advanceTimersByTime(1);
176
+
177
+ await rejection;
178
+ expect(cleanup).toHaveBeenCalledTimes(1);
179
+ expect(jest.getTimerCount()).toBe(0);
180
+ });
181
+
182
+ test('aborts a pending system restart without leaving either timer or listener', async () => {
183
+ const controller = new AbortController();
184
+ const result = onDeviceBondState(UUID, controller.signal, { systemInitiated: true });
185
+ const outcome = result.catch(error => error);
186
+ emitBondState({
187
+ id: UUID,
188
+ advertising: {},
189
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
190
+ });
191
+ expect(cleanup).not.toHaveBeenCalled();
192
+
193
+ controller.abort();
194
+ await expect(outcome).resolves.toMatchObject({
195
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
196
+ });
197
+ expect(cleanup).toHaveBeenCalledTimes(1);
198
+ expect(jest.getTimerCount()).toBe(0);
199
+ });
200
+
201
+ test('keeps the overall deadline when system bonding repeatedly restarts', async () => {
202
+ const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
203
+ const outcome = result.catch(error => error);
204
+ for (let index = 0; index < 40; index += 1) {
205
+ emitBondState({
206
+ id: UUID,
207
+ advertising: {},
208
+ bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
209
+ });
210
+ emitBondState({
211
+ id: UUID,
212
+ advertising: {},
213
+ bondState: { preState: 'BOND_NONE', state: 'BOND_BONDING' },
214
+ });
215
+ jest.advanceTimersByTime(1000);
216
+ }
217
+ expect(cleanup).not.toHaveBeenCalled();
218
+ jest.advanceTimersByTime(20_000);
219
+
220
+ await expect(outcome).resolves.toMatchObject({
221
+ errorCode: HardwareErrorCode.BleDeviceNotBonded,
222
+ params: { phase: 'bond', reason: 'timeout' },
223
+ });
224
+ expect(cleanup).toHaveBeenCalledTimes(1);
225
+ expect(jest.getTimerCount()).toBe(0);
226
+ });
227
+
132
228
  test('aborts the bond wait and removes its listener and deadline', async () => {
133
229
  const controller = new AbortController();
134
230
  const result = onDeviceBondState(UUID, controller.signal);
@@ -623,6 +719,20 @@ describe('BLE connect timeout', () => {
623
719
  expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
624
720
  });
625
721
 
722
+ test('normalizes an unstructured GATT disconnect instead of leaking an unknown error', async () => {
723
+ const { transport, device } = createHarness(() => Promise.resolve());
724
+ const nativeError = Object.assign(new Error(`BleError: Device ${UUID} was disconnected`), {
725
+ errorCode: 0,
726
+ });
727
+ device.discoverAllServicesAndCharacteristics.mockRejectedValueOnce(nativeError);
728
+
729
+ await expect(
730
+ (transport as any).resolveCharacteristicsWithTimeout(UUID, device)
731
+ ).rejects.toMatchObject({
732
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
733
+ });
734
+ });
735
+
626
736
  test('a successful GATT retry clears the timeout budget before an abandoned call settles', async () => {
627
737
  const { transport, device, bleManager } = createHarness(() => Promise.resolve());
628
738
  let resolveAbandonedDiscovery: (() => void) | undefined;
@@ -1,12 +1,22 @@
1
1
  import { EventEmitter } from 'events';
2
+ import { PermissionsAndroid, Platform } from 'react-native';
3
+ import { BleErrorCode } from 'react-native-ble-plx';
4
+ import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
5
 
3
6
  import { getConnectedDeviceIds } from '../BleManager';
4
7
  import ReactNativeBleTransport from '../index';
8
+ import { subscribeBleOn } from '../subscribeBleOn';
5
9
 
6
10
  jest.mock(
7
11
  'react-native',
8
12
  () => ({
9
- PermissionsAndroid: {},
13
+ PermissionsAndroid: {
14
+ PERMISSIONS: {
15
+ BLUETOOTH_CONNECT: 'android.permission.BLUETOOTH_CONNECT',
16
+ BLUETOOTH_SCAN: 'android.permission.BLUETOOTH_SCAN',
17
+ },
18
+ requestMultiple: jest.fn(),
19
+ },
10
20
  Platform: { OS: 'ios' },
11
21
  }),
12
22
  { virtual: true }
@@ -14,7 +24,14 @@ jest.mock(
14
24
 
15
25
  jest.mock('react-native-ble-plx', () => ({
16
26
  BleError: class BleError extends Error {},
17
- BleErrorCode: {},
27
+ BleErrorCode: {
28
+ BluetoothUnsupported: 100,
29
+ BluetoothUnauthorized: 101,
30
+ BluetoothPoweredOff: 102,
31
+ BluetoothInUnknownState: 103,
32
+ ScanStartFailed: 600,
33
+ LocationServicesDisabled: 601,
34
+ },
18
35
  BleManager: jest.fn(),
19
36
  ScanMode: { LowLatency: 2 },
20
37
  }));
@@ -25,27 +42,61 @@ jest.mock('../BleManager', () => ({
25
42
  pairDevice: jest.fn(),
26
43
  }));
27
44
 
28
- // The native facade is replaced wholesale above; key missing and link encryption are covered
29
- // by their own suites.
30
- jest.mock('../bleKeyMissing', () => ({
31
- isBleKeyMissingSupported: jest.fn(() => false),
32
- startBleKeyMissingTracking: jest.fn(() => false),
33
- stopBleKeyMissingTracking: jest.fn(),
34
- waitForBleKeyMissing: jest.fn(() => Promise.resolve(false)),
35
- }));
36
- jest.mock('../bleEncryption', () => ({
37
- markBleLinkEncrypted: jest.fn(),
38
- startBleEncryptionTracking: jest.fn(() => false),
39
- stopBleEncryptionTracking: jest.fn(),
40
- waitForAndroidLinkEncryption: jest.fn(() => Promise.resolve('unresolved')),
41
- }));
42
-
43
45
  jest.mock('../subscribeBleOn', () => ({
44
46
  subscribeBleOn: jest.fn(() => Promise.resolve()),
45
47
  }));
46
48
 
47
49
  const ONEKEY_SERVICE_UUID = '00000001-0000-1000-8000-00805f9b34fb';
48
50
 
51
+ describe('ReactNativeBleTransport scan error mapping', () => {
52
+ beforeEach(() => {
53
+ jest.clearAllMocks();
54
+ });
55
+
56
+ afterEach(() => {
57
+ Object.assign(Platform, { OS: 'ios', Version: undefined });
58
+ });
59
+
60
+ test('checks Android Bluetooth permissions before waiting for adapter state', async () => {
61
+ Object.assign(Platform, { OS: 'android', Version: 31 });
62
+ jest.mocked(PermissionsAndroid).requestMultiple.mockResolvedValueOnce({
63
+ [PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT]: 'denied',
64
+ [PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN]: 'denied',
65
+ });
66
+ const transport = new ReactNativeBleTransport({});
67
+ transport.blePlxManager = {} as never;
68
+ transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
69
+
70
+ await expect(transport.enumerate()).rejects.toMatchObject({
71
+ errorCode: HardwareErrorCode.BleLocationError,
72
+ });
73
+ expect(subscribeBleOn).not.toHaveBeenCalled();
74
+ });
75
+
76
+ test.each([
77
+ [BleErrorCode.BluetoothPoweredOff, HardwareErrorCode.BlePoweredOff],
78
+ [BleErrorCode.BluetoothUnsupported, HardwareErrorCode.BleUnsupported],
79
+ [BleErrorCode.BluetoothInUnknownState, HardwareErrorCode.BleScanError],
80
+ [BleErrorCode.BluetoothUnauthorized, HardwareErrorCode.BleLocationError],
81
+ ])('maps native BLE error %s to hardware error %s', async (nativeCode, errorCode) => {
82
+ jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([]);
83
+ const blePlxManager = {
84
+ startDeviceScan: jest.fn((_serviceUUIDs, _options, listener) => {
85
+ queueMicrotask(() => {
86
+ listener({ errorCode: nativeCode, reason: 'native scan failure' }, null);
87
+ });
88
+ }),
89
+ stopDeviceScan: jest.fn(() => Promise.resolve()),
90
+ };
91
+ const transport = new ReactNativeBleTransport({ scanTimeout: 10_000 });
92
+ transport.blePlxManager = blePlxManager as never;
93
+ transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
94
+
95
+ await expect(transport.enumerate()).rejects.toMatchObject({ errorCode });
96
+ expect(blePlxManager.stopDeviceScan).toHaveBeenCalledTimes(1);
97
+ });
98
+ });
99
+
49
100
  describe('ReactNativeBleTransport iOS discovery', () => {
50
101
  test('keeps a bonded Pro2 communication peripheral after Find My changes its name', async () => {
51
102
  jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([
@@ -45,21 +45,6 @@ jest.mock('../BleManager', () => ({
45
45
  pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
46
46
  }));
47
47
 
48
- // The native facade is replaced wholesale above; key missing and link encryption are covered
49
- // by their own suites.
50
- jest.mock('../bleKeyMissing', () => ({
51
- isBleKeyMissingSupported: jest.fn(() => false),
52
- startBleKeyMissingTracking: jest.fn(() => false),
53
- stopBleKeyMissingTracking: jest.fn(),
54
- waitForBleKeyMissing: jest.fn(() => Promise.resolve(false)),
55
- }));
56
- jest.mock('../bleEncryption', () => ({
57
- markBleLinkEncrypted: jest.fn(),
58
- startBleEncryptionTracking: jest.fn(() => false),
59
- stopBleEncryptionTracking: jest.fn(),
60
- waitForAndroidLinkEncryption: jest.fn(() => Promise.resolve('unresolved')),
61
- }));
62
-
63
48
  jest.mock('../subscribeBleOn', () => ({
64
49
  subscribeBleOn: jest.fn(() => Promise.resolve()),
65
50
  }));
@@ -318,6 +303,45 @@ const createV1Harness = ({
318
303
  };
319
304
 
320
305
  describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
306
+ test.each(['ios', 'android'] as const)(
307
+ 'identifies MTU logs for concurrent devices and reconnects on %s',
308
+ async platform => {
309
+ setPlatformOS(platform);
310
+ const { transport, uuid, device, bleManager, logger } = createHarness();
311
+ const otherUuid = 'rn-pro2-other-id';
312
+ const otherDevice = { ...device, id: otherUuid };
313
+
314
+ try {
315
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
316
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
317
+ bleManager.devices.mockResolvedValue([otherDevice]);
318
+ await transport.acquire({ uuid: otherUuid, expectedProtocol: 'V2' });
319
+ await transport.release(uuid, true);
320
+ bleManager.devices.mockResolvedValue([device]);
321
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
322
+
323
+ const mtuLogs = logger.debug.mock.calls
324
+ .filter(([message]) => message === '[ReactNativeBleTransport] BLE MTU ready')
325
+ .map(([, params]) => params as { connectionId: number; actual: number });
326
+ expect(mtuLogs).toHaveLength(3);
327
+ expect(new Set(mtuLogs.map(({ connectionId }) => connectionId)).size).toBe(3);
328
+ for (const params of mtuLogs) {
329
+ expect(params).toEqual({
330
+ platform,
331
+ requested: expect.any(Number),
332
+ actual: device.mtu,
333
+ connectionId: expect.any(Number),
334
+ });
335
+ expect(Number.isSafeInteger(params.connectionId)).toBe(true);
336
+ expect(params.connectionId).toBeGreaterThan(0);
337
+ }
338
+ } finally {
339
+ await transport.release(uuid, true);
340
+ await transport.release(otherUuid, true);
341
+ }
342
+ }
343
+ );
344
+
321
345
  test('does not classify disconnects as retryable firmware writes', () => {
322
346
  expect(
323
347
  getFirmwareUploadWriteRetryType({
@@ -378,9 +402,16 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
378
402
  expect(new ReactNativeBleTransport({}).scanTimeout).toBe(3000);
379
403
  });
380
404
 
381
- test.each(['V1', 'V2'] as const)(
382
- 'waits for Android bonding before connecting the %s GATT link',
383
- async protocol => {
405
+ test.each([
406
+ { protocol: 'V1', initiated: true },
407
+ { protocol: 'V1', initiated: false },
408
+ { protocol: 'V1', initiated: undefined },
409
+ { protocol: 'V2', initiated: true },
410
+ { protocol: 'V2', initiated: false },
411
+ { protocol: 'V2', initiated: undefined },
412
+ ] as const)(
413
+ 'waits for Android bonding before connecting $protocol GATT, initiated=$initiated',
414
+ async ({ protocol, initiated }) => {
384
415
  setPlatformOS('android');
385
416
  const { transport, uuid, device } = protocol === 'V1' ? createV1Harness() : createHarness();
386
417
  const operationOrder: string[] = [];
@@ -395,7 +426,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
395
426
  });
396
427
  pairDeviceMock.mockImplementationOnce(() => {
397
428
  operationOrder.push('bond');
398
- return Promise.resolve({ bonded: false, bonding: true });
429
+ return Promise.resolve({ bonded: false, bonding: true, initiated });
399
430
  });
400
431
  bondStateMock.mockImplementationOnce(() => bonding.promise);
401
432
 
@@ -405,6 +436,9 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
405
436
  });
406
437
  expect(operationOrder).toEqual(['bond']);
407
438
  expect(device.connect).not.toHaveBeenCalled();
439
+ expect(bondStateMock).toHaveBeenLastCalledWith(uuid, expect.any(AbortSignal), {
440
+ systemInitiated: initiated === false,
441
+ });
408
442
 
409
443
  bonding.resolve();
410
444
  await expect(acquiring).resolves.toEqual({
@@ -447,6 +481,42 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
447
481
  expect(pairDeviceMock).toHaveBeenCalledTimes(1);
448
482
  });
449
483
 
484
+ test.each([
485
+ ['ios', 'V1'],
486
+ ['ios', 'V2'],
487
+ ['android', 'V1'],
488
+ ['android', 'V2'],
489
+ ] as const)(
490
+ 'uses connection or disconnect errors instead of a legacy bond error for ATT 22 on %s %s',
491
+ async (platform, expectedProtocol) => {
492
+ setPlatformOS(platform);
493
+ const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
494
+ message: string
495
+ ) => Error;
496
+
497
+ for (const [nativeCode, expectedCode] of [
498
+ [205, HardwareErrorCode.BleConnectedError],
499
+ [201, HardwareErrorCode.BleDeviceDisconnected],
500
+ ]) {
501
+ const { transport, uuid, device } = createHarness();
502
+ const nativeError = Object.assign(new BleErrorMock('GATT connect failed'), {
503
+ errorCode: nativeCode,
504
+ attErrorCode: 22,
505
+ reason: 'GATT connect failed',
506
+ });
507
+ device.isConnected.mockResolvedValueOnce(false);
508
+ device.connect.mockRejectedValueOnce(nativeError);
509
+
510
+ await expect(transport.acquire({ uuid, expectedProtocol })).rejects.toMatchObject({
511
+ errorCode: expectedCode,
512
+ message: expect.stringContaining('GATT connect failed'),
513
+ });
514
+ expect(device.connect).toHaveBeenCalledTimes(1);
515
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
516
+ }
517
+ }
518
+ );
519
+
450
520
  test('does not connect Android GATT when the system cannot start bonding', async () => {
451
521
  setPlatformOS('android');
452
522
  const { transport, uuid, device, bleManager } = createHarness();
@@ -478,27 +548,11 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
478
548
  });
479
549
 
480
550
  test.each([
481
- [
482
- 'ios',
483
- 'OneKey Neo',
484
- {
485
- iosErrorCode: 14,
486
- reason: 'Peer removed pairing information',
487
- },
488
- HardwareErrorCode.BlePeerRemovedPairingInformation,
489
- ],
490
- [
491
- 'android',
492
- 'OneKey Pro 2',
493
- {
494
- androidErrorCode: 5,
495
- reason: 'Connection state changed with status 5',
496
- },
497
- HardwareErrorCode.BleDeviceBondError,
498
- ],
551
+ ['ios', 'OneKey Neo', { iosErrorCode: 14, reason: 'Native connection failed' }],
552
+ ['android', 'OneKey Pro 2', { androidErrorCode: 5, reason: 'Native connection failed' }],
499
553
  ] as const)(
500
- 'maps a %s %s stale bond during connect before protocol detection',
501
- async (platform, deviceName, nativeError, errorCode) => {
554
+ 'keeps a %s %s native connect failure generic before protocol detection',
555
+ async (platform, deviceName, nativeError) => {
502
556
  setPlatformOS(platform);
503
557
  const { transport, uuid, device } = createHarness({ deviceName });
504
558
  const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
@@ -512,7 +566,9 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
512
566
  .fn()
513
567
  .mockRejectedValue(Object.assign(new BleErrorMock(nativeError.reason), nativeError));
514
568
 
515
- await expect(transport.acquire({ uuid })).rejects.toMatchObject({ errorCode });
569
+ await expect(transport.acquire({ uuid })).rejects.toMatchObject({
570
+ errorCode: HardwareErrorCode.BleConnectedError,
571
+ });
516
572
  expect(pairDeviceMock).toHaveBeenCalledTimes(platform === 'android' ? 1 : 0);
517
573
  expect(transport.getProtocolType(uuid)).toBeUndefined();
518
574
  }
@@ -608,7 +664,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
608
664
  await transport.release(uuid, true);
609
665
  });
610
666
 
611
- test('keeps native stale-bond write mapping out of Protocol V1 calls', async () => {
667
+ test('maps native Protocol V1 write failures to the generic write error', async () => {
612
668
  const { transport, uuid, writeCharacteristic } = createV1Harness();
613
669
  const nativeError = Object.assign(new Error('Encryption is insufficient'), {
614
670
  attErrorCode: 15,
@@ -831,35 +887,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
831
887
  }
832
888
  );
833
889
 
834
- test.each([
835
- [
836
- 'Encryption is insufficient',
837
- { reason: 'Encryption is insufficient', attErrorCode: 15 },
838
- HardwareErrorCode.BleDeviceBondError,
839
- ],
840
- [
841
- 'Peer removed pairing information',
842
- { reason: 'Peer removed pairing information', iosErrorCode: 14 },
843
- HardwareErrorCode.BlePeerRemovedPairingInformation,
844
- ],
845
- ] as const)(
846
- 'fails Protocol V2 acquire immediately on %s instead of waiting for Ping',
847
- async (_label, nativeError, errorCode) => {
848
- const { transport, uuid, device } = createHarness({
849
- monitorError: Object.assign(new Error(nativeError.reason), nativeError),
850
- });
851
- const probe = jest.spyOn(transport as any, 'probeProtocolV2');
852
-
853
- await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
854
- errorCode,
855
- });
856
-
857
- expect(probe).not.toHaveBeenCalled();
858
- expect(device.cancelConnection).toHaveBeenCalled();
859
- expect(transport.getProtocolType(uuid)).toBeUndefined();
860
- }
861
- );
862
-
863
890
  test.each(['ios', 'android'] as const)(
864
891
  'disconnects after a confirmed Protocol V2 probe miss on %s without reporting a bond error',
865
892
  async platform => {
@@ -1029,7 +1056,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1029
1056
  for (const errorCode of [
1030
1057
  HardwareErrorCode.BleDeviceNotBonded,
1031
1058
  HardwareErrorCode.BleDeviceBondedCanceled,
1032
- HardwareErrorCode.BlePeerRemovedPairingInformation,
1033
1059
  HardwareErrorCode.BleDeviceDisconnected,
1034
1060
  HardwareErrorCode.BleCharacteristicNotifyError,
1035
1061
  HardwareErrorCode.BleCharacteristicNotifyChangeFailure,
@@ -1210,20 +1236,20 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1210
1236
  await transport.release(uuid, true);
1211
1237
  }, 10_000);
1212
1238
 
1213
- test('maps a stale bond from the iOS MTU-timeout reconnect', async () => {
1239
+ test('keeps an iOS MTU-timeout reconnect failure generic', async () => {
1214
1240
  const { BleError: BleErrorMock } = jest.requireMock('react-native-ble-plx');
1215
1241
  const { transport, uuid, device } = createHarness();
1216
1242
  device.mtu = 23;
1217
1243
  device.requestMTU.mockImplementationOnce(() => new Promise(() => {}));
1218
1244
  device.connect.mockRejectedValueOnce(
1219
- Object.assign(new BleErrorMock('Peer removed pairing information'), {
1245
+ Object.assign(new BleErrorMock('Native connection failed'), {
1220
1246
  errorCode: 200,
1221
1247
  iosErrorCode: 14,
1222
1248
  })
1223
1249
  );
1224
1250
 
1225
1251
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1226
- errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
1252
+ errorCode: HardwareErrorCode.BleConnectedError,
1227
1253
  });
1228
1254
  await transport.release(uuid, true).catch(() => undefined);
1229
1255
  }, 10_000);