@onekeyfe/hd-transport-react-native 1.2.0-alpha.7 → 1.2.0-alpha.70
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/dist/BleTransport.d.ts +1 -3
- package/dist/BleTransport.d.ts.map +1 -1
- package/dist/bleStrategy.d.ts +0 -2
- package/dist/bleStrategy.d.ts.map +1 -1
- package/dist/constants.d.ts +0 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/index.d.ts +99 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +705 -387
- package/dist/subscribeBleOn.d.ts.map +1 -1
- package/dist/transportLog.d.ts +2 -0
- package/dist/transportLog.d.ts.map +1 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/jest.config.js +10 -0
- package/package.json +7 -6
- package/src/BleTransport.ts +6 -41
- package/src/__tests__/BleTransport.test.ts +93 -0
- package/src/__tests__/bleStrategy.test.ts +1 -6
- package/src/__tests__/connectTimeout.test.ts +281 -0
- package/src/__tests__/constants.test.ts +20 -0
- package/src/__tests__/enumerate.test.ts +132 -0
- package/src/__tests__/protocolReprobe.test.ts +132 -0
- package/src/__tests__/protocolV1SchemaFixture.ts +39 -0
- package/src/__tests__/protocolV2Link.test.ts +769 -0
- package/src/__tests__/staleCallTimeout.test.ts +210 -0
- package/src/__tests__/writePacketTimeout.test.ts +305 -0
- package/src/bleStrategy.ts +0 -25
- package/src/constants.ts +7 -13
- package/src/index.ts +931 -408
- package/src/subscribeBleOn.ts +0 -2
- package/src/transportLog.ts +1 -0
- package/src/types.ts +1 -0
|
@@ -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,
|
|
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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transportLog.d.ts","sourceRoot":"","sources":["../src/transportLog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC"}
|
package/dist/types.d.ts
CHANGED
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE3D,YAAY,EAAE,UAAU,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAExE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gBAAgB,CAAC,EAAE,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE3D,YAAY,EAAE,UAAU,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAExE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gBAAgB,CAAC,EAAE,YAAY,CAAC;IAChC,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC"}
|
package/jest.config.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
preset: '../../jest.config.js',
|
|
3
|
+
testEnvironment: 'node',
|
|
4
|
+
modulePathIgnorePatterns: ['node_modules', '<rootDir>/dist'],
|
|
5
|
+
moduleNameMapper: {
|
|
6
|
+
// The workspace symlinks resolve to prebuilt dist outputs that can lag behind src.
|
|
7
|
+
'^@onekeyfe/hd-transport$': '<rootDir>/../hd-transport/src/index.ts',
|
|
8
|
+
'^@onekeyfe/hd-shared$': '<rootDir>/../shared/src/index.ts',
|
|
9
|
+
},
|
|
10
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onekeyfe/hd-transport-react-native",
|
|
3
|
-
"version": "1.2.0-alpha.
|
|
3
|
+
"version": "1.2.0-alpha.70",
|
|
4
4
|
"homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -15,15 +15,16 @@
|
|
|
15
15
|
"scripts": {
|
|
16
16
|
"dev": "rimraf dist && rollup -c ../../build/rollup.config.js -w",
|
|
17
17
|
"build": "rimraf dist && rollup -c ../../build/rollup.config.js",
|
|
18
|
+
"test": "jest",
|
|
18
19
|
"lint": "eslint .",
|
|
19
20
|
"lint:fix": "eslint . --fix"
|
|
20
21
|
},
|
|
21
22
|
"dependencies": {
|
|
22
|
-
"@onekeyfe/hd-core": "1.2.0-alpha.
|
|
23
|
-
"@onekeyfe/hd-shared": "1.2.0-alpha.
|
|
24
|
-
"@onekeyfe/hd-transport": "1.2.0-alpha.
|
|
25
|
-
"@onekeyfe/react-native-ble-utils": "^0.1.
|
|
23
|
+
"@onekeyfe/hd-core": "1.2.0-alpha.70",
|
|
24
|
+
"@onekeyfe/hd-shared": "1.2.0-alpha.70",
|
|
25
|
+
"@onekeyfe/hd-transport": "1.2.0-alpha.70",
|
|
26
|
+
"@onekeyfe/react-native-ble-utils": "^0.1.6",
|
|
26
27
|
"react-native-ble-plx": "3.5.1"
|
|
27
28
|
},
|
|
28
|
-
"gitHead": "
|
|
29
|
+
"gitHead": "d86b033cf970f97e060c49fe4cf618f38b9ce666"
|
|
29
30
|
}
|
package/src/BleTransport.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { wait } from '@onekeyfe/hd-shared';
|
|
3
|
-
|
|
4
|
-
import { bleLogger } from './logger';
|
|
1
|
+
import { Platform } from 'react-native';
|
|
5
2
|
|
|
6
3
|
import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
|
|
7
4
|
|
|
8
|
-
const Log = bleLogger;
|
|
9
|
-
|
|
10
5
|
export default class BleTransport {
|
|
11
6
|
id: string;
|
|
12
7
|
|
|
@@ -28,10 +23,6 @@ export default class BleTransport {
|
|
|
28
23
|
|
|
29
24
|
monitorToken?: number;
|
|
30
25
|
|
|
31
|
-
static MAX_RETRIES = 5;
|
|
32
|
-
|
|
33
|
-
static RETRY_DELAY = 2000;
|
|
34
|
-
|
|
35
26
|
constructor(
|
|
36
27
|
device: Device,
|
|
37
28
|
writeCharacteristic: Characteristic,
|
|
@@ -43,37 +34,11 @@ export default class BleTransport {
|
|
|
43
34
|
this.notifyCharacteristic = notifyCharacteristic;
|
|
44
35
|
}
|
|
45
36
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
* @returns
|
|
51
|
-
*/
|
|
52
|
-
async writeWithRetry(data: string, retryCount = BleTransport.MAX_RETRIES): Promise<void> {
|
|
53
|
-
try {
|
|
54
|
-
await this.writeCharacteristic.writeWithoutResponse(data);
|
|
55
|
-
} catch (error) {
|
|
56
|
-
Log?.debug(
|
|
57
|
-
`Write retry attempt ${BleTransport.MAX_RETRIES - retryCount + 1}, error: ${error}`
|
|
58
|
-
);
|
|
59
|
-
if (retryCount > 0) {
|
|
60
|
-
await wait(BleTransport.RETRY_DELAY);
|
|
61
|
-
if (
|
|
62
|
-
error.errorCode === BleErrorCode.DeviceDisconnected ||
|
|
63
|
-
error.errorCode === BleErrorCode.CharacteristicNotFound
|
|
64
|
-
) {
|
|
65
|
-
try {
|
|
66
|
-
await this.device.connect();
|
|
67
|
-
await this.device.discoverAllServicesAndCharacteristics();
|
|
68
|
-
} catch (e) {
|
|
69
|
-
Log?.debug(`Connect or discoverAllServicesAndCharacteristics error: ${e}`);
|
|
70
|
-
}
|
|
71
|
-
} else {
|
|
72
|
-
Log?.debug(`writeCharacteristic error: ${error}`);
|
|
73
|
-
}
|
|
74
|
-
return this.writeWithRetry(data, retryCount - 1);
|
|
75
|
-
}
|
|
76
|
-
throw error;
|
|
37
|
+
async writeWithRetry(data: string): Promise<void> {
|
|
38
|
+
if (Platform.OS === 'ios' && this.writeCharacteristic.isWritableWithResponse) {
|
|
39
|
+
await this.writeCharacteristic.writeWithResponse(data);
|
|
40
|
+
return;
|
|
77
41
|
}
|
|
42
|
+
await this.writeCharacteristic.writeWithoutResponse(data);
|
|
78
43
|
}
|
|
79
44
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { BleErrorCode } from 'react-native-ble-plx';
|
|
2
|
+
import { Platform } from 'react-native';
|
|
3
|
+
|
|
4
|
+
import BleTransport from '../BleTransport';
|
|
5
|
+
|
|
6
|
+
jest.mock(
|
|
7
|
+
'react-native',
|
|
8
|
+
() => ({
|
|
9
|
+
Platform: { OS: 'ios' },
|
|
10
|
+
}),
|
|
11
|
+
{ virtual: true }
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
jest.mock(
|
|
15
|
+
'react-native-ble-plx',
|
|
16
|
+
() => ({
|
|
17
|
+
BleErrorCode: {
|
|
18
|
+
DeviceDisconnected: 205,
|
|
19
|
+
CharacteristicNotFound: 404,
|
|
20
|
+
},
|
|
21
|
+
}),
|
|
22
|
+
{ virtual: true }
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
jest.mock('@onekeyfe/hd-shared', () => ({
|
|
26
|
+
...jest.requireActual('@onekeyfe/hd-shared'),
|
|
27
|
+
wait: jest.fn(() => Promise.resolve()),
|
|
28
|
+
}));
|
|
29
|
+
|
|
30
|
+
describe('BleTransport side-effecting writes', () => {
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
Platform.OS = 'ios';
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('does not reconnect or replay after the device disconnects', async () => {
|
|
36
|
+
const error = Object.assign(new Error('device disconnected'), {
|
|
37
|
+
errorCode: BleErrorCode.DeviceDisconnected,
|
|
38
|
+
});
|
|
39
|
+
const writeCharacteristic = {
|
|
40
|
+
isWritableWithResponse: true,
|
|
41
|
+
writeWithResponse: jest.fn(() => Promise.reject(error)),
|
|
42
|
+
writeWithoutResponse: jest.fn(() => Promise.resolve()),
|
|
43
|
+
};
|
|
44
|
+
const device = {
|
|
45
|
+
id: 'classic-id',
|
|
46
|
+
connect: jest.fn(() => Promise.resolve()),
|
|
47
|
+
discoverAllServicesAndCharacteristics: jest.fn(() => Promise.resolve()),
|
|
48
|
+
};
|
|
49
|
+
const transport = new BleTransport(device as any, writeCharacteristic as any, {} as any);
|
|
50
|
+
|
|
51
|
+
await expect(transport.writeWithRetry('payload')).rejects.toBe(error);
|
|
52
|
+
|
|
53
|
+
expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(1);
|
|
54
|
+
expect(device.connect).not.toHaveBeenCalled();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('keeps Android Protocol V1 writes on writeWithoutResponse', async () => {
|
|
58
|
+
Platform.OS = 'android';
|
|
59
|
+
const writeCharacteristic = {
|
|
60
|
+
isWritableWithResponse: true,
|
|
61
|
+
writeWithResponse: jest.fn(() => Promise.resolve()),
|
|
62
|
+
writeWithoutResponse: jest.fn(() => Promise.resolve()),
|
|
63
|
+
};
|
|
64
|
+
const transport = new BleTransport(
|
|
65
|
+
{ id: 'classic-id' } as any,
|
|
66
|
+
writeCharacteristic as any,
|
|
67
|
+
{} as any
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
await transport.writeWithRetry('payload');
|
|
71
|
+
|
|
72
|
+
expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
|
|
73
|
+
expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledWith('payload');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('uses writeWithoutResponse on iOS when the characteristic lacks response support', async () => {
|
|
77
|
+
const writeCharacteristic = {
|
|
78
|
+
isWritableWithResponse: false,
|
|
79
|
+
writeWithResponse: jest.fn(() => Promise.resolve()),
|
|
80
|
+
writeWithoutResponse: jest.fn(() => Promise.resolve()),
|
|
81
|
+
};
|
|
82
|
+
const transport = new BleTransport(
|
|
83
|
+
{ id: 'classic-id' } as any,
|
|
84
|
+
writeCharacteristic as any,
|
|
85
|
+
{} as any
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
await transport.writeWithRetry('payload');
|
|
89
|
+
|
|
90
|
+
expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
|
|
91
|
+
expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledWith('payload');
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
hasWritableCapability,
|
|
3
|
-
resolveBleWriteMode,
|
|
4
|
-
resolveProtocolV2PacketCapacity,
|
|
5
|
-
} from '../bleStrategy';
|
|
1
|
+
import { hasWritableCapability, resolveProtocolV2PacketCapacity } from '../bleStrategy';
|
|
6
2
|
|
|
7
3
|
describe('React Native BLE strategy', () => {
|
|
8
4
|
test('accepts writeWithoutResponse-only characteristics', () => {
|
|
@@ -12,7 +8,6 @@ describe('React Native BLE strategy', () => {
|
|
|
12
8
|
};
|
|
13
9
|
|
|
14
10
|
expect(hasWritableCapability(characteristic)).toBe(true);
|
|
15
|
-
expect(resolveBleWriteMode(characteristic)).toBe('withoutResponse');
|
|
16
11
|
});
|
|
17
12
|
|
|
18
13
|
test('falls back to Android default ATT payload when MTU is unavailable', () => {
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import { BleErrorCode } from 'react-native-ble-plx';
|
|
3
|
+
|
|
4
|
+
import { HardwareErrorCode } from '@onekeyfe/hd-shared';
|
|
5
|
+
|
|
6
|
+
import ReactNativeBleTransport, {
|
|
7
|
+
BLE_CONNECT_TIMEOUT_MS,
|
|
8
|
+
BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD,
|
|
9
|
+
BLE_GATT_SETUP_TIMEOUT_MS,
|
|
10
|
+
} from '../index';
|
|
11
|
+
import protocolV1Schema from './protocolV1SchemaFixture';
|
|
12
|
+
|
|
13
|
+
jest.mock(
|
|
14
|
+
'react-native',
|
|
15
|
+
() => ({
|
|
16
|
+
Platform: { OS: 'ios', select: (spec: Record<string, unknown>) => spec.ios },
|
|
17
|
+
PermissionsAndroid: {
|
|
18
|
+
PERMISSIONS: {},
|
|
19
|
+
RESULTS: {},
|
|
20
|
+
request: jest.fn(),
|
|
21
|
+
requestMultiple: jest.fn(),
|
|
22
|
+
},
|
|
23
|
+
}),
|
|
24
|
+
{ virtual: true }
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
jest.mock('react-native-ble-plx', () => ({
|
|
28
|
+
BleATTErrorCode: { InvalidHandle: 1, UnlikelyError: 14 },
|
|
29
|
+
BleError: Error,
|
|
30
|
+
BleErrorCode: {
|
|
31
|
+
DeviceDisconnected: 201,
|
|
32
|
+
OperationStartFailed: 601,
|
|
33
|
+
DeviceMTUChangeFailed: 401,
|
|
34
|
+
OperationCancelled: 2,
|
|
35
|
+
OperationTimedOut: 3,
|
|
36
|
+
DeviceAlreadyConnected: 203,
|
|
37
|
+
},
|
|
38
|
+
BleManager: jest.fn(),
|
|
39
|
+
ScanMode: { LowLatency: 2 },
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
jest.mock('@onekeyfe/react-native-ble-utils', () => ({
|
|
43
|
+
__esModule: true,
|
|
44
|
+
default: {
|
|
45
|
+
getConnectedPeripherals: jest.fn(() => Promise.resolve([])),
|
|
46
|
+
getBondedPeripherals: jest.fn(() => Promise.resolve([])),
|
|
47
|
+
pairDevice: jest.fn(() => Promise.resolve()),
|
|
48
|
+
},
|
|
49
|
+
}));
|
|
50
|
+
|
|
51
|
+
const UUID = 'stalled-connect-device';
|
|
52
|
+
|
|
53
|
+
const flush = () =>
|
|
54
|
+
new Promise(resolve => {
|
|
55
|
+
setImmediate(resolve);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
async function advanceUntil(settled: () => boolean, totalMs: number, stepMs = 250) {
|
|
59
|
+
for (let elapsed = 0; elapsed < totalMs; elapsed += stepMs) {
|
|
60
|
+
jest.advanceTimersByTime(stepMs);
|
|
61
|
+
// eslint-disable-next-line no-await-in-loop
|
|
62
|
+
await flush();
|
|
63
|
+
if (settled()) return;
|
|
64
|
+
}
|
|
65
|
+
throw new Error(`fake timers exhausted after ${totalMs}ms before the connect settled`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A device whose native connect() never settles — the observed iOS failure mode. */
|
|
69
|
+
function createHarness(connectImpl: () => Promise<unknown>) {
|
|
70
|
+
const connect = jest.fn(connectImpl);
|
|
71
|
+
const writeCharacteristic = {
|
|
72
|
+
uuid: '00000002-0000-1000-8000-00805f9b34fb',
|
|
73
|
+
isWritableWithResponse: true,
|
|
74
|
+
};
|
|
75
|
+
const notifyCharacteristic = {
|
|
76
|
+
uuid: '00000003-0000-1000-8000-00805f9b34fb',
|
|
77
|
+
isNotifiable: true,
|
|
78
|
+
};
|
|
79
|
+
const device = {
|
|
80
|
+
id: UUID,
|
|
81
|
+
name: 'OneKey Classic',
|
|
82
|
+
localName: 'OneKey Classic',
|
|
83
|
+
serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
|
|
84
|
+
isConnected: jest.fn(() => Promise.resolve(false)),
|
|
85
|
+
cancelConnection: jest.fn(() => Promise.resolve()),
|
|
86
|
+
connect,
|
|
87
|
+
discoverAllServicesAndCharacteristics: jest.fn(() => Promise.resolve()),
|
|
88
|
+
characteristicsForService: jest.fn(() =>
|
|
89
|
+
Promise.resolve([writeCharacteristic, notifyCharacteristic])
|
|
90
|
+
),
|
|
91
|
+
services: jest.fn(() => Promise.resolve([])),
|
|
92
|
+
onDisconnected: jest.fn(() => ({ remove: jest.fn() })),
|
|
93
|
+
};
|
|
94
|
+
const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
|
|
95
|
+
const bleManager = {
|
|
96
|
+
devices: jest.fn(() => Promise.resolve([device])),
|
|
97
|
+
connectedDevices: jest.fn(() => Promise.resolve([])),
|
|
98
|
+
connectToDevice: jest.fn(connectImpl),
|
|
99
|
+
cancelTransaction: jest.fn(() => Promise.resolve()),
|
|
100
|
+
cancelDeviceConnection: jest.fn(() => Promise.resolve()),
|
|
101
|
+
onStateChange: jest.fn((listener: (state: string) => void) => {
|
|
102
|
+
// Dispatch asynchronously: subscribeBleOn wires its own cleanup after
|
|
103
|
+
// registering, so a synchronous callback would run before it is ready.
|
|
104
|
+
setImmediate(() => listener('PoweredOn'));
|
|
105
|
+
return { remove: jest.fn() };
|
|
106
|
+
}),
|
|
107
|
+
state: jest.fn(() => Promise.resolve('PoweredOn')),
|
|
108
|
+
startDeviceScan: jest.fn(),
|
|
109
|
+
stopDeviceScan: jest.fn(),
|
|
110
|
+
};
|
|
111
|
+
(transport as any).blePlxManager = bleManager;
|
|
112
|
+
transport.init(
|
|
113
|
+
{ debug: jest.fn(), error: jest.fn(), warn: jest.fn() } as any,
|
|
114
|
+
new EventEmitter()
|
|
115
|
+
);
|
|
116
|
+
transport.configure(protocolV1Schema);
|
|
117
|
+
return { transport, device, bleManager, connect };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
describe('BLE connect timeout', () => {
|
|
121
|
+
beforeAll(() => {
|
|
122
|
+
jest.useFakeTimers({ doNotFake: ['setImmediate', 'performance'] });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
afterAll(() => {
|
|
126
|
+
jest.useRealTimers();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
afterEach(() => {
|
|
130
|
+
jest.clearAllTimers();
|
|
131
|
+
jest.restoreAllMocks();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('a native connect that never settles is bounded instead of blocking forever', async () => {
|
|
135
|
+
// iOS applies its own connect timeout on a serial queue; when that queue is busy
|
|
136
|
+
// the timeout never fires and acquire() blocks until the app-level 60s timeout.
|
|
137
|
+
const { transport } = createHarness(
|
|
138
|
+
() =>
|
|
139
|
+
new Promise(() => {
|
|
140
|
+
// never settles
|
|
141
|
+
})
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
const errors: Array<{ errorCode?: unknown }> = [];
|
|
145
|
+
let settled = false;
|
|
146
|
+
transport.acquire({ uuid: UUID }).catch(e => {
|
|
147
|
+
errors.push(e);
|
|
148
|
+
settled = true;
|
|
149
|
+
});
|
|
150
|
+
await flush();
|
|
151
|
+
|
|
152
|
+
await advanceUntil(() => settled, BLE_CONNECT_TIMEOUT_MS + 5000);
|
|
153
|
+
|
|
154
|
+
expect(errors).toHaveLength(1);
|
|
155
|
+
expect(errors[0]?.errorCode).toBe(HardwareErrorCode.BleConnectedError);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test('the connect budget leaves generous headroom over a healthy connect', () => {
|
|
159
|
+
// Healthy connects finish in ~2-3s (the native budget is 3s); this backstop only
|
|
160
|
+
// fires when the native timeout itself fails to.
|
|
161
|
+
expect(BLE_CONNECT_TIMEOUT_MS).toBeGreaterThanOrEqual(6000);
|
|
162
|
+
expect(BLE_CONNECT_TIMEOUT_MS).toBeLessThanOrEqual(12000);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('a stalled connect is abandoned natively so the next attempt is not cancelled by it', async () => {
|
|
166
|
+
const { transport, bleManager } = createHarness(
|
|
167
|
+
() =>
|
|
168
|
+
new Promise(() => {
|
|
169
|
+
// never settles
|
|
170
|
+
})
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
let settled = false;
|
|
174
|
+
transport.acquire({ uuid: UUID }).catch(() => {
|
|
175
|
+
settled = true;
|
|
176
|
+
});
|
|
177
|
+
await flush();
|
|
178
|
+
await advanceUntil(() => settled, BLE_CONNECT_TIMEOUT_MS + 5000);
|
|
179
|
+
|
|
180
|
+
expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test('repeated stalled connects recreate the BLE manager', async () => {
|
|
184
|
+
const { transport, bleManager } = createHarness(
|
|
185
|
+
() =>
|
|
186
|
+
new Promise(() => {
|
|
187
|
+
// never settles
|
|
188
|
+
})
|
|
189
|
+
);
|
|
190
|
+
const destroy = jest.fn();
|
|
191
|
+
(bleManager as unknown as { destroy: jest.Mock }).destroy = destroy;
|
|
192
|
+
|
|
193
|
+
for (let attempt = 0; attempt < BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD; attempt += 1) {
|
|
194
|
+
let settled = false;
|
|
195
|
+
transport.acquire({ uuid: UUID }).catch(() => {
|
|
196
|
+
settled = true;
|
|
197
|
+
});
|
|
198
|
+
// eslint-disable-next-line no-await-in-loop
|
|
199
|
+
await flush();
|
|
200
|
+
// eslint-disable-next-line no-await-in-loop
|
|
201
|
+
await advanceUntil(() => settled, BLE_CONNECT_TIMEOUT_MS + 5000);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
expect(destroy).toHaveBeenCalledTimes(1);
|
|
205
|
+
expect((transport as unknown as { blePlxManager?: unknown }).blePlxManager).toBeUndefined();
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test('native connect timeouts contribute to the same manager reset budget', async () => {
|
|
209
|
+
const { transport, bleManager } = createHarness(() => Promise.resolve());
|
|
210
|
+
const destroy = jest.fn();
|
|
211
|
+
(bleManager as unknown as { destroy: jest.Mock }).destroy = destroy;
|
|
212
|
+
const nativeTimeout = Object.assign(new Error('Operation timed out'), {
|
|
213
|
+
errorCode: BleErrorCode.OperationTimedOut,
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
for (let attempt = 0; attempt < BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD; attempt += 1) {
|
|
217
|
+
// eslint-disable-next-line no-await-in-loop
|
|
218
|
+
await expect(
|
|
219
|
+
(transport as any).connectWithTimeout(UUID, () => Promise.reject(nativeTimeout))
|
|
220
|
+
).rejects.toBe(nativeTimeout);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
expect(destroy).toHaveBeenCalledTimes(1);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
test('GATT discovery is bounded and abandons the native connection', async () => {
|
|
227
|
+
const { transport, device, bleManager } = createHarness(() => Promise.resolve());
|
|
228
|
+
device.discoverAllServicesAndCharacteristics.mockImplementation(
|
|
229
|
+
() =>
|
|
230
|
+
new Promise(() => {
|
|
231
|
+
// never settles
|
|
232
|
+
})
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
const errors: Array<{ errorCode?: unknown }> = [];
|
|
236
|
+
let settled = false;
|
|
237
|
+
(transport as any).resolveCharacteristicsWithTimeout(UUID, device).catch((error: unknown) => {
|
|
238
|
+
errors.push(error as { errorCode?: unknown });
|
|
239
|
+
settled = true;
|
|
240
|
+
});
|
|
241
|
+
await flush();
|
|
242
|
+
await advanceUntil(() => settled, BLE_GATT_SETUP_TIMEOUT_MS + 5000);
|
|
243
|
+
|
|
244
|
+
expect(errors).toHaveLength(1);
|
|
245
|
+
expect(errors[0]?.errorCode).toBe(HardwareErrorCode.BleConnectedError);
|
|
246
|
+
expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test('a successful GATT retry clears the timeout budget before an abandoned call settles', async () => {
|
|
250
|
+
const { transport, device, bleManager } = createHarness(() => Promise.resolve());
|
|
251
|
+
let resolveAbandonedDiscovery: (() => void) | undefined;
|
|
252
|
+
device.discoverAllServicesAndCharacteristics
|
|
253
|
+
.mockImplementationOnce(
|
|
254
|
+
() =>
|
|
255
|
+
new Promise<void>(resolve => {
|
|
256
|
+
resolveAbandonedDiscovery = resolve;
|
|
257
|
+
})
|
|
258
|
+
)
|
|
259
|
+
.mockResolvedValueOnce(undefined);
|
|
260
|
+
|
|
261
|
+
let firstSettled = false;
|
|
262
|
+
(transport as any).resolveCharacteristicsWithTimeout(UUID, device).catch(() => {
|
|
263
|
+
firstSettled = true;
|
|
264
|
+
});
|
|
265
|
+
await flush();
|
|
266
|
+
await advanceUntil(() => firstSettled, BLE_GATT_SETUP_TIMEOUT_MS + 5000);
|
|
267
|
+
|
|
268
|
+
await expect(
|
|
269
|
+
(transport as any).resolveCharacteristicsWithTimeout(UUID, device)
|
|
270
|
+
).resolves.toMatchObject({
|
|
271
|
+
writeCharacteristic: expect.any(Object),
|
|
272
|
+
notifyCharacteristic: expect.any(Object),
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
resolveAbandonedDiscovery?.();
|
|
276
|
+
await flush();
|
|
277
|
+
|
|
278
|
+
expect(bleManager.cancelDeviceConnection).toHaveBeenCalledTimes(1);
|
|
279
|
+
expect((transport as any).connectionSetupTimeoutCounts.has(UUID)).toBe(false);
|
|
280
|
+
});
|
|
281
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { getBluetoothServiceUuids, getInfosForServiceUuid } from '../constants';
|
|
2
|
+
|
|
3
|
+
describe('React Native BLE service filters', () => {
|
|
4
|
+
test('does not scan or configure the ignored FFFD service', () => {
|
|
5
|
+
expect(getBluetoothServiceUuids()).not.toContain('fffd');
|
|
6
|
+
expect(getInfosForServiceUuid('fffd', 'classic')).toBeNull();
|
|
7
|
+
expect(getInfosForServiceUuid('0000fffd-0000-1000-8000-00805f9b34fb', 'classic')).toBeNull();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('keeps the OneKey communication service configured', () => {
|
|
11
|
+
expect(getBluetoothServiceUuids()).toContain('00000001-0000-1000-8000-00805f9b34fb');
|
|
12
|
+
expect(getInfosForServiceUuid('0001', 'classic')).toMatchObject({
|
|
13
|
+
serviceUuid: '00000001-0000-1000-8000-00805f9b34fb',
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('does not match a vendor-specific UUID containing the OneKey short key', () => {
|
|
18
|
+
expect(getInfosForServiceUuid('abcd0001-1234-5678-9012-abcdefabcdef', 'classic')).toBeNull();
|
|
19
|
+
});
|
|
20
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
import { getConnectedDeviceIds } from '../BleManager';
|
|
4
|
+
import ReactNativeBleTransport from '../index';
|
|
5
|
+
|
|
6
|
+
jest.mock(
|
|
7
|
+
'react-native',
|
|
8
|
+
() => ({
|
|
9
|
+
PermissionsAndroid: {},
|
|
10
|
+
Platform: { OS: 'ios' },
|
|
11
|
+
}),
|
|
12
|
+
{ virtual: true }
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
jest.mock('react-native-ble-plx', () => ({
|
|
16
|
+
BleError: class BleError extends Error {},
|
|
17
|
+
BleErrorCode: {},
|
|
18
|
+
BleManager: jest.fn(),
|
|
19
|
+
ScanMode: { LowLatency: 2 },
|
|
20
|
+
}));
|
|
21
|
+
|
|
22
|
+
jest.mock('../BleManager', () => ({
|
|
23
|
+
getConnectedDeviceIds: jest.fn(),
|
|
24
|
+
onDeviceBondState: jest.fn(),
|
|
25
|
+
pairDevice: jest.fn(),
|
|
26
|
+
}));
|
|
27
|
+
|
|
28
|
+
jest.mock('../subscribeBleOn', () => ({
|
|
29
|
+
subscribeBleOn: jest.fn(() => Promise.resolve()),
|
|
30
|
+
}));
|
|
31
|
+
|
|
32
|
+
const ONEKEY_SERVICE_UUID = '00000001-0000-1000-8000-00805f9b34fb';
|
|
33
|
+
|
|
34
|
+
describe('ReactNativeBleTransport iOS discovery', () => {
|
|
35
|
+
test('filters a bonded Pro2 Find My peripheral while keeping the wallet peripheral', async () => {
|
|
36
|
+
jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([
|
|
37
|
+
{
|
|
38
|
+
id: 'find-my-peripheral',
|
|
39
|
+
name: 'Pro2 6E9E - Find My',
|
|
40
|
+
localName: null,
|
|
41
|
+
serviceUUIDs: [ONEKEY_SERVICE_UUID],
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
id: 'wallet-peripheral',
|
|
45
|
+
name: 'Pro2 6E9E',
|
|
46
|
+
localName: 'Pro2 6E9E',
|
|
47
|
+
serviceUUIDs: [ONEKEY_SERVICE_UUID],
|
|
48
|
+
},
|
|
49
|
+
] as never);
|
|
50
|
+
const blePlxManager = {
|
|
51
|
+
startDeviceScan: jest.fn(),
|
|
52
|
+
stopDeviceScan: jest.fn(),
|
|
53
|
+
};
|
|
54
|
+
const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
|
|
55
|
+
transport.blePlxManager = blePlxManager as never;
|
|
56
|
+
transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
|
|
57
|
+
|
|
58
|
+
const devices = await transport.enumerate();
|
|
59
|
+
|
|
60
|
+
expect(devices.map(device => device.id)).toEqual(['wallet-peripheral']);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('filters a scanned Pro2 Find My peripheral by name when localName is null', async () => {
|
|
64
|
+
jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([]);
|
|
65
|
+
const blePlxManager = {
|
|
66
|
+
startDeviceScan: jest.fn((_serviceUUIDs, _options, listener) => {
|
|
67
|
+
queueMicrotask(() => {
|
|
68
|
+
listener(null, {
|
|
69
|
+
id: 'find-my-peripheral',
|
|
70
|
+
name: 'Pro2 6E9E - Find My',
|
|
71
|
+
localName: null,
|
|
72
|
+
serviceUUIDs: [ONEKEY_SERVICE_UUID],
|
|
73
|
+
});
|
|
74
|
+
listener(null, {
|
|
75
|
+
id: 'wallet-peripheral',
|
|
76
|
+
name: 'Pro2 6E9E',
|
|
77
|
+
localName: 'Pro2 6E9E',
|
|
78
|
+
serviceUUIDs: [ONEKEY_SERVICE_UUID],
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}),
|
|
82
|
+
stopDeviceScan: jest.fn(),
|
|
83
|
+
};
|
|
84
|
+
const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
|
|
85
|
+
transport.blePlxManager = blePlxManager as never;
|
|
86
|
+
transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
|
|
87
|
+
|
|
88
|
+
const devices = await transport.enumerate();
|
|
89
|
+
|
|
90
|
+
expect(devices.map(device => device.id)).toEqual(['wallet-peripheral']);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('ignores an unnamed scanned advertisement while keeping the named wallet peripheral', async () => {
|
|
94
|
+
jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([]);
|
|
95
|
+
const blePlxManager = {
|
|
96
|
+
startDeviceScan: jest.fn((_serviceUUIDs, _options, listener) => {
|
|
97
|
+
queueMicrotask(() => {
|
|
98
|
+
listener(null, {
|
|
99
|
+
id: 'unnamed-peripheral',
|
|
100
|
+
name: null,
|
|
101
|
+
localName: null,
|
|
102
|
+
serviceUUIDs: [
|
|
103
|
+
'0000180a-0000-1000-8000-00805f9b34fb',
|
|
104
|
+
'0000180f-0000-1000-8000-00805f9b34fb',
|
|
105
|
+
'0000fffd-0000-1000-8000-00805f9b34fb',
|
|
106
|
+
ONEKEY_SERVICE_UUID,
|
|
107
|
+
],
|
|
108
|
+
});
|
|
109
|
+
listener(null, {
|
|
110
|
+
id: 'wallet-peripheral',
|
|
111
|
+
name: 'Pro2 769D',
|
|
112
|
+
localName: 'Pro2 769D',
|
|
113
|
+
serviceUUIDs: [
|
|
114
|
+
'0000180a-0000-1000-8000-00805f9b34fb',
|
|
115
|
+
'0000180f-0000-1000-8000-00805f9b34fb',
|
|
116
|
+
'0000fffd-0000-1000-8000-00805f9b34fb',
|
|
117
|
+
ONEKEY_SERVICE_UUID,
|
|
118
|
+
],
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}),
|
|
122
|
+
stopDeviceScan: jest.fn(),
|
|
123
|
+
};
|
|
124
|
+
const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
|
|
125
|
+
transport.blePlxManager = blePlxManager as never;
|
|
126
|
+
transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
|
|
127
|
+
|
|
128
|
+
const devices = await transport.enumerate();
|
|
129
|
+
|
|
130
|
+
expect(devices.map(device => device.id)).toEqual(['wallet-peripheral']);
|
|
131
|
+
});
|
|
132
|
+
});
|