@onekeyfe/hd-transport-react-native 1.2.8-alpha.10 → 1.2.8-alpha.101

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.
@@ -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,
@@ -765,7 +821,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
765
821
 
766
822
  const acquiring = transport.acquire({ uuid });
767
823
  const failure = expect(acquiring).rejects.toMatchObject({
768
- errorCode: HardwareErrorCode.BleTimeoutError,
824
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
769
825
  });
770
826
  const reconnecting = transport.acquire({ uuid, expectedProtocol: 'V2' });
771
827
 
@@ -804,7 +860,8 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
804
860
  jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
805
861
 
806
862
  await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
807
- errorCode: HardwareErrorCode.RuntimeError,
863
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
864
+ params: { expectedProtocol: 'V2' },
808
865
  });
809
866
 
810
867
  expect(device.cancelConnection).toHaveBeenCalledTimes(1);
@@ -820,10 +877,12 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
820
877
  jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
821
878
 
822
879
  await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
823
- errorCode: HardwareErrorCode.RuntimeError,
880
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
881
+ params: { expectedProtocol: 'V2' },
824
882
  });
825
883
  await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
826
- errorCode: HardwareErrorCode.RuntimeError,
884
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
885
+ params: { expectedProtocol: 'V2' },
827
886
  });
828
887
 
829
888
  expect(device.cancelConnection).toHaveBeenCalledTimes(2);
@@ -831,35 +890,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
831
890
  }
832
891
  );
833
892
 
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
893
  test.each(['ios', 'android'] as const)(
864
894
  'disconnects after a confirmed Protocol V2 probe miss on %s without reporting a bond error',
865
895
  async platform => {
@@ -870,7 +900,8 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
870
900
  jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
871
901
 
872
902
  await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
873
- errorCode: HardwareErrorCode.RuntimeError,
903
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
904
+ params: { expectedProtocol: 'V2' },
874
905
  });
875
906
 
876
907
  expect(device.cancelConnection).toHaveBeenCalledTimes(1);
@@ -1029,7 +1060,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1029
1060
  for (const errorCode of [
1030
1061
  HardwareErrorCode.BleDeviceNotBonded,
1031
1062
  HardwareErrorCode.BleDeviceBondedCanceled,
1032
- HardwareErrorCode.BlePeerRemovedPairingInformation,
1033
1063
  HardwareErrorCode.BleDeviceDisconnected,
1034
1064
  HardwareErrorCode.BleCharacteristicNotifyError,
1035
1065
  HardwareErrorCode.BleCharacteristicNotifyChangeFailure,
@@ -1210,20 +1240,20 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1210
1240
  await transport.release(uuid, true);
1211
1241
  }, 10_000);
1212
1242
 
1213
- test('maps a stale bond from the iOS MTU-timeout reconnect', async () => {
1243
+ test('keeps an iOS MTU-timeout reconnect failure generic', async () => {
1214
1244
  const { BleError: BleErrorMock } = jest.requireMock('react-native-ble-plx');
1215
1245
  const { transport, uuid, device } = createHarness();
1216
1246
  device.mtu = 23;
1217
1247
  device.requestMTU.mockImplementationOnce(() => new Promise(() => {}));
1218
1248
  device.connect.mockRejectedValueOnce(
1219
- Object.assign(new BleErrorMock('Peer removed pairing information'), {
1249
+ Object.assign(new BleErrorMock('Native connection failed'), {
1220
1250
  errorCode: 200,
1221
1251
  iosErrorCode: 14,
1222
1252
  })
1223
1253
  );
1224
1254
 
1225
1255
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1226
- errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
1256
+ errorCode: HardwareErrorCode.BleConnectedError,
1227
1257
  });
1228
1258
  await transport.release(uuid, true).catch(() => undefined);
1229
1259
  }, 10_000);
@@ -1706,7 +1736,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1706
1736
 
1707
1737
  await expect(transport.acquire({ uuid })).rejects.toBeDefined();
1708
1738
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1709
- errorCode: HardwareErrorCode.BleTimeoutError,
1739
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
1710
1740
  });
1711
1741
  await transport.disconnect(uuid);
1712
1742
  await transport.stop();
@@ -1814,7 +1844,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1814
1844
  jest.spyOn(transport as any, 'probeProtocolV1').mockResolvedValue(false);
1815
1845
 
1816
1846
  await expect(transport.acquire({ uuid, protocolHint: 'V2' })).rejects.toMatchObject({
1817
- errorCode: HardwareErrorCode.BleTimeoutError,
1847
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
1818
1848
  });
1819
1849
 
1820
1850
  expect(device.onDisconnected).not.toHaveBeenCalled();
@@ -0,0 +1,114 @@
1
+ import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import { subscribeBleOn } from '../subscribeBleOn';
4
+
5
+ import type { BlePlxManager } from '../types';
6
+
7
+ type BleState = Parameters<Parameters<BlePlxManager['onStateChange']>[0]>[0];
8
+
9
+ const createBleManager = () => {
10
+ let stateListener: ((state: BleState) => void) | undefined;
11
+ const remove = jest.fn();
12
+ const bleManager = {
13
+ onStateChange: jest.fn(listener => {
14
+ stateListener = listener;
15
+ return { remove };
16
+ }),
17
+ } as unknown as BlePlxManager;
18
+
19
+ return {
20
+ bleManager,
21
+ emitState: (state: BleState) => stateListener?.(state),
22
+ remove,
23
+ };
24
+ };
25
+
26
+ describe('subscribeBleOn', () => {
27
+ beforeAll(() => {
28
+ jest.useFakeTimers({ doNotFake: ['performance'] });
29
+ });
30
+
31
+ afterAll(() => {
32
+ jest.useRealTimers();
33
+ });
34
+
35
+ afterEach(() => {
36
+ jest.clearAllTimers();
37
+ });
38
+
39
+ test('resolves when Bluetooth is powered on', async () => {
40
+ const { bleManager, emitState, remove } = createBleManager();
41
+ const result = subscribeBleOn(bleManager);
42
+
43
+ emitState('PoweredOn');
44
+
45
+ await expect(result).resolves.toBeUndefined();
46
+ expect(remove).toHaveBeenCalledTimes(1);
47
+ expect(jest.getTimerCount()).toBe(0);
48
+ });
49
+
50
+ test('cleans up when the current state is emitted synchronously', async () => {
51
+ const remove = jest.fn();
52
+ const bleManager = {
53
+ onStateChange: jest.fn(listener => {
54
+ listener('PoweredOn');
55
+ return { remove };
56
+ }),
57
+ } as unknown as BlePlxManager;
58
+
59
+ await expect(subscribeBleOn(bleManager)).resolves.toBeUndefined();
60
+ expect(remove).toHaveBeenCalledTimes(1);
61
+ expect(jest.getTimerCount()).toBe(0);
62
+ });
63
+
64
+ test.each([
65
+ ['PoweredOff', HardwareErrorCode.BlePoweredOff],
66
+ ['Unsupported', HardwareErrorCode.BleUnsupported],
67
+ ['Unauthorized', HardwareErrorCode.BleLocationError],
68
+ ] as const)('maps %s to hardware error %s', async (state, errorCode) => {
69
+ const { bleManager, emitState, remove } = createBleManager();
70
+ const result = subscribeBleOn(bleManager, 2000);
71
+ const rejection = expect(result).rejects.toMatchObject({ errorCode });
72
+
73
+ emitState(state);
74
+ jest.advanceTimersByTime(1999);
75
+ expect(remove).not.toHaveBeenCalled();
76
+ jest.advanceTimersByTime(1);
77
+
78
+ await rejection;
79
+ expect(remove).toHaveBeenCalledTimes(1);
80
+ expect(jest.getTimerCount()).toBe(0);
81
+ });
82
+
83
+ test('resolves if Bluetooth powers on during the readiness window', async () => {
84
+ const { bleManager, emitState, remove } = createBleManager();
85
+ const result = subscribeBleOn(bleManager);
86
+
87
+ emitState('PoweredOff');
88
+ jest.advanceTimersByTime(1999);
89
+ expect(remove).not.toHaveBeenCalled();
90
+ emitState('PoweredOn');
91
+
92
+ await expect(result).resolves.toBeUndefined();
93
+ expect(remove).toHaveBeenCalledTimes(1);
94
+ expect(jest.getTimerCount()).toBe(0);
95
+ });
96
+
97
+ test.each(['Unknown', 'Resetting'] as const)(
98
+ 'reports %s as a scan error if no stable state arrives before timeout',
99
+ async state => {
100
+ const { bleManager, emitState, remove } = createBleManager();
101
+ const result = subscribeBleOn(bleManager, 1000);
102
+ const rejection = expect(result).rejects.toMatchObject({
103
+ errorCode: HardwareErrorCode.BleScanError,
104
+ });
105
+
106
+ emitState('PoweredOff');
107
+ emitState(state);
108
+ jest.advanceTimersByTime(1000);
109
+
110
+ await rejection;
111
+ expect(remove).toHaveBeenCalledTimes(1);
112
+ }
113
+ );
114
+ });
@@ -23,7 +23,8 @@ export const isNativeBleDisconnectError = (error: unknown): boolean => {
23
23
  const nativeError = error as NativeBleErrorFields;
24
24
  return (
25
25
  nativeError.errorCode === BLE_PLX_DEVICE_DISCONNECTED ||
26
- nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED
26
+ nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED ||
27
+ nativeErrorText(nativeError).toLowerCase().includes('was disconnected')
27
28
  );
28
29
  };
29
30