@onekeyfe/hd-transport-react-native 1.2.7 → 1.2.8-alpha.2

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.7",
3
+ "version": "1.2.8-alpha.2",
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.7",
24
- "@onekeyfe/hd-shared": "1.2.7",
25
- "@onekeyfe/hd-transport": "1.2.7",
23
+ "@onekeyfe/hd-core": "1.2.8-alpha.2",
24
+ "@onekeyfe/hd-shared": "1.2.8-alpha.2",
25
+ "@onekeyfe/hd-transport": "1.2.8-alpha.2",
26
26
  "@onekeyfe/react-native-ble-utils": "0.1.9",
27
27
  "react-native-ble-plx": "3.5.1"
28
28
  },
29
- "gitHead": "6cf9b7d76b905f168169fd0442af8636afd2b469"
29
+ "gitHead": "74ac64464df3806ef44ad54d313378754c3eaed2"
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,21 +32,6 @@ 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
- };
50
-
51
35
  const createBondFailureError = (bondState: Peripheral['bondState']) => {
52
36
  const nativeReason =
53
37
  'reason' in bondState && typeof bondState.reason === 'number' ? bondState.reason : undefined;
@@ -82,22 +66,18 @@ const createBondFailureError = (bondState: Peripheral['bondState']) => {
82
66
 
83
67
  export const onDeviceBondState = (
84
68
  bleMacAddress: string,
85
- signal?: AbortSignal,
86
- options?: DeviceBondStateOptions
69
+ signal?: AbortSignal
87
70
  ): Promise<Peripheral | undefined> =>
88
71
  new Promise((resolve, reject) => {
89
72
  if (signal?.aborted) {
90
73
  reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
91
74
  return;
92
75
  }
93
- let pendingFailure: ReturnType<typeof setTimeout> | undefined;
94
76
  const cleanup = () => {
95
77
  if (timeout) {
96
78
  clearTimeout(timeout);
97
79
  }
98
- if (pendingFailure) clearTimeout(pendingFailure);
99
80
  if (cleanupListener) cleanupListener();
100
- cleanupKeyMissing?.();
101
81
  signal?.removeEventListener('abort', onAbort);
102
82
  };
103
83
  const onAbort = () => {
@@ -117,20 +97,6 @@ export const onDeviceBondState = (
117
97
  );
118
98
  }, 60 * 1000);
119
99
 
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
100
  const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
135
101
  if (peripheral.id?.toLowerCase() !== bleMacAddress.toLowerCase()) {
136
102
  return;
@@ -139,20 +105,10 @@ export const onDeviceBondState = (
139
105
 
140
106
  const hasBonded = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_BONDED';
141
107
  const hasFailed = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_NONE';
142
- const hasRestarted = bondState.preState === 'BOND_NONE' && bondState.state === 'BOND_BONDING';
143
108
  Logger.debug('onDeviceBondState bondState:', bondState);
144
109
  if (hasBonded) {
145
110
  cleanup();
146
111
  resolve(peripheral);
147
- } else if (hasRestarted && pendingFailure) {
148
- clearTimeout(pendingFailure);
149
- pendingFailure = undefined;
150
- } else if (hasFailed && options?.systemInitiated) {
151
- if (pendingFailure) clearTimeout(pendingFailure);
152
- pendingFailure = setTimeout(() => {
153
- cleanup();
154
- reject(createBondFailureError(bondState));
155
- }, SYSTEM_BONDING_RESTART_WINDOW_MS);
156
112
  } else if (hasFailed) {
157
113
  cleanup();
158
114
  reject(createBondFailureError(bondState));
@@ -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
  });
@@ -623,6 +623,20 @@ describe('BLE connect timeout', () => {
623
623
  expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
624
624
  });
625
625
 
626
+ test('normalizes an unstructured GATT disconnect instead of leaking an unknown error', async () => {
627
+ const { transport, device } = createHarness(() => Promise.resolve());
628
+ const nativeError = Object.assign(new Error(`BleError: Device ${UUID} was disconnected`), {
629
+ errorCode: 0,
630
+ });
631
+ device.discoverAllServicesAndCharacteristics.mockRejectedValueOnce(nativeError);
632
+
633
+ await expect(
634
+ (transport as any).resolveCharacteristicsWithTimeout(UUID, device)
635
+ ).rejects.toMatchObject({
636
+ errorCode: HardwareErrorCode.BleDeviceDisconnected,
637
+ });
638
+ });
639
+
626
640
  test('a successful GATT retry clears the timeout budget before an abandoned call settles', async () => {
627
641
  const { transport, device, bleManager } = createHarness(() => Promise.resolve());
628
642
  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.BlePermissionError,
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.BlePermissionError],
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
  }));
@@ -447,6 +432,42 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
447
432
  expect(pairDeviceMock).toHaveBeenCalledTimes(1);
448
433
  });
449
434
 
435
+ test.each([
436
+ ['ios', 'V1'],
437
+ ['ios', 'V2'],
438
+ ['android', 'V1'],
439
+ ['android', 'V2'],
440
+ ] as const)(
441
+ 'uses connection or disconnect errors instead of a legacy bond error for ATT 22 on %s %s',
442
+ async (platform, expectedProtocol) => {
443
+ setPlatformOS(platform);
444
+ const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
445
+ message: string
446
+ ) => Error;
447
+
448
+ for (const [nativeCode, expectedCode] of [
449
+ [205, HardwareErrorCode.BleConnectedError],
450
+ [201, HardwareErrorCode.BleDeviceDisconnected],
451
+ ]) {
452
+ const { transport, uuid, device } = createHarness();
453
+ const nativeError = Object.assign(new BleErrorMock('GATT connect failed'), {
454
+ errorCode: nativeCode,
455
+ attErrorCode: 22,
456
+ reason: 'GATT connect failed',
457
+ });
458
+ device.isConnected.mockResolvedValueOnce(false);
459
+ device.connect.mockRejectedValueOnce(nativeError);
460
+
461
+ await expect(transport.acquire({ uuid, expectedProtocol })).rejects.toMatchObject({
462
+ errorCode: expectedCode,
463
+ message: expect.stringContaining('GATT connect failed'),
464
+ });
465
+ expect(device.connect).toHaveBeenCalledTimes(1);
466
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
467
+ }
468
+ }
469
+ );
470
+
450
471
  test('does not connect Android GATT when the system cannot start bonding', async () => {
451
472
  setPlatformOS('android');
452
473
  const { transport, uuid, device, bleManager } = createHarness();
@@ -478,27 +499,11 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
478
499
  });
479
500
 
480
501
  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
- ],
502
+ ['ios', 'OneKey Neo', { iosErrorCode: 14, reason: 'Native connection failed' }],
503
+ ['android', 'OneKey Pro 2', { androidErrorCode: 5, reason: 'Native connection failed' }],
499
504
  ] as const)(
500
- 'maps a %s %s stale bond during connect before protocol detection',
501
- async (platform, deviceName, nativeError, errorCode) => {
505
+ 'keeps a %s %s native connect failure generic before protocol detection',
506
+ async (platform, deviceName, nativeError) => {
502
507
  setPlatformOS(platform);
503
508
  const { transport, uuid, device } = createHarness({ deviceName });
504
509
  const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
@@ -512,7 +517,9 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
512
517
  .fn()
513
518
  .mockRejectedValue(Object.assign(new BleErrorMock(nativeError.reason), nativeError));
514
519
 
515
- await expect(transport.acquire({ uuid })).rejects.toMatchObject({ errorCode });
520
+ await expect(transport.acquire({ uuid })).rejects.toMatchObject({
521
+ errorCode: HardwareErrorCode.BleConnectedError,
522
+ });
516
523
  expect(pairDeviceMock).toHaveBeenCalledTimes(platform === 'android' ? 1 : 0);
517
524
  expect(transport.getProtocolType(uuid)).toBeUndefined();
518
525
  }
@@ -608,7 +615,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
608
615
  await transport.release(uuid, true);
609
616
  });
610
617
 
611
- test('keeps native stale-bond write mapping out of Protocol V1 calls', async () => {
618
+ test('maps native Protocol V1 write failures to the generic write error', async () => {
612
619
  const { transport, uuid, writeCharacteristic } = createV1Harness();
613
620
  const nativeError = Object.assign(new Error('Encryption is insufficient'), {
614
621
  attErrorCode: 15,
@@ -831,35 +838,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
831
838
  }
832
839
  );
833
840
 
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
841
  test.each(['ios', 'android'] as const)(
864
842
  'disconnects after a confirmed Protocol V2 probe miss on %s without reporting a bond error',
865
843
  async platform => {
@@ -1029,7 +1007,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1029
1007
  for (const errorCode of [
1030
1008
  HardwareErrorCode.BleDeviceNotBonded,
1031
1009
  HardwareErrorCode.BleDeviceBondedCanceled,
1032
- HardwareErrorCode.BlePeerRemovedPairingInformation,
1033
1010
  HardwareErrorCode.BleDeviceDisconnected,
1034
1011
  HardwareErrorCode.BleCharacteristicNotifyError,
1035
1012
  HardwareErrorCode.BleCharacteristicNotifyChangeFailure,
@@ -1210,20 +1187,20 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1210
1187
  await transport.release(uuid, true);
1211
1188
  }, 10_000);
1212
1189
 
1213
- test('maps a stale bond from the iOS MTU-timeout reconnect', async () => {
1190
+ test('keeps an iOS MTU-timeout reconnect failure generic', async () => {
1214
1191
  const { BleError: BleErrorMock } = jest.requireMock('react-native-ble-plx');
1215
1192
  const { transport, uuid, device } = createHarness();
1216
1193
  device.mtu = 23;
1217
1194
  device.requestMTU.mockImplementationOnce(() => new Promise(() => {}));
1218
1195
  device.connect.mockRejectedValueOnce(
1219
- Object.assign(new BleErrorMock('Peer removed pairing information'), {
1196
+ Object.assign(new BleErrorMock('Native connection failed'), {
1220
1197
  errorCode: 200,
1221
1198
  iosErrorCode: 14,
1222
1199
  })
1223
1200
  );
1224
1201
 
1225
1202
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1226
- errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
1203
+ errorCode: HardwareErrorCode.BleConnectedError,
1227
1204
  });
1228
1205
  await transport.release(uuid, true).catch(() => undefined);
1229
1206
  }, 10_000);
@@ -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.BlePermissionError],
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