@onekeyfe/hd-transport-react-native 1.2.11-alpha.7 → 1.2.11-alpha.8

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.
@@ -0,0 +1,284 @@
1
+ import { EventEmitter } from 'events';
2
+ import transportPackage, { PROTOCOL_V2_CHANNEL_BLE_UART, ProtocolV2 } from '@onekeyfe/hd-transport';
3
+ import { ERRORS, HardwareErrorCode, createDeferred } from '@onekeyfe/hd-shared';
4
+ import DataManager from '@onekeyfe/hd-core/src/data-manager/DataManager';
5
+ import TransportManager from '@onekeyfe/hd-core/src/data-manager/TransportManager';
6
+ import { Device } from '@onekeyfe/hd-core/src/device/Device';
7
+ import DeviceConnector from '@onekeyfe/hd-core/src/device/DeviceConnector';
8
+
9
+ import ReactNativeBleTransport from '../index';
10
+
11
+ jest.mock(
12
+ 'react-native',
13
+ () => ({
14
+ PermissionsAndroid: {},
15
+ Platform: { OS: 'android' },
16
+ }),
17
+ { virtual: true }
18
+ );
19
+
20
+ jest.mock('react-native-ble-plx', () => ({
21
+ BleATTErrorCode: { UnlikelyError: 14 },
22
+ BleError: class BleError extends Error {},
23
+ BleErrorCode: {
24
+ DeviceAlreadyConnected: 203,
25
+ DeviceDisconnected: 201,
26
+ DeviceMTUChangeFailed: 206,
27
+ OperationCancelled: 2,
28
+ CharacteristicNotFound: 404,
29
+ },
30
+ BleManager: jest.fn(),
31
+ ConnectionPriority: { Balanced: 0, High: 1, LowPower: 2 },
32
+ ScanMode: { LowLatency: 2 },
33
+ }));
34
+
35
+ jest.mock('../BleManager', () => ({
36
+ getBondedDevices: jest.fn(() => Promise.resolve([])),
37
+ getConnectedDeviceIds: jest.fn(() => Promise.resolve([])),
38
+ onDeviceBondState: jest.fn(() => Promise.resolve()),
39
+ pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
40
+ }));
41
+
42
+ jest.mock('../subscribeBleOn', () => ({
43
+ subscribeBleOn: jest.fn(() => Promise.resolve()),
44
+ }));
45
+
46
+ jest.mock('../../../core/src/data/config', () => ({
47
+ getSDKVersion: () => '1.0.0-test',
48
+ DEFAULT_DOMAIN: 'https://jssdk.onekey.so/1.0.0-test/',
49
+ }));
50
+
51
+ const { parseConfigure } = transportPackage;
52
+
53
+ const protocolV1Schema = {
54
+ nested: {
55
+ Initialize: { fields: {} },
56
+ GetFeatures: { fields: {} },
57
+ Success: {
58
+ fields: {
59
+ message: { type: 'string', id: 1 },
60
+ },
61
+ },
62
+ MessageType: {
63
+ values: {
64
+ MessageType_Initialize: 1,
65
+ MessageType_Success: 2,
66
+ MessageType_GetFeatures: 55,
67
+ },
68
+ },
69
+ },
70
+ };
71
+
72
+ const protocolV2Schema = {
73
+ nested: {
74
+ ProtocolInfoRequest: { fields: {} },
75
+ Ping: {
76
+ fields: {
77
+ message: { type: 'string', id: 1 },
78
+ },
79
+ },
80
+ Success: {
81
+ fields: {
82
+ message: { type: 'string', id: 1 },
83
+ },
84
+ },
85
+ MessageType: {
86
+ values: {
87
+ MessageType_ProtocolInfoRequest: 60200,
88
+ MessageType_Ping: 60206,
89
+ MessageType_Success: 60207,
90
+ },
91
+ },
92
+ },
93
+ };
94
+
95
+ const schemas = {
96
+ protocolV1: parseConfigure(protocolV1Schema),
97
+ protocolV2: parseConfigure(protocolV2Schema),
98
+ };
99
+
100
+ const flush = () =>
101
+ new Promise(resolve => {
102
+ setImmediate(resolve);
103
+ });
104
+
105
+ const createSimulatedBleDevice = (uuid: string) => {
106
+ let notifyCallback:
107
+ | ((error: Error | null, characteristic: { value: string } | null) => void)
108
+ | undefined;
109
+ let responseSeq = 0;
110
+
111
+ const notifyCharacteristic = {
112
+ uuid: '0003',
113
+ deviceID: uuid,
114
+ isNotifiable: true,
115
+ monitor: jest.fn(callback => {
116
+ notifyCallback = callback;
117
+ return { remove: jest.fn() };
118
+ }),
119
+ };
120
+
121
+ const handleWrite = () => {
122
+ responseSeq += 1;
123
+ const response = ProtocolV2.encodeFrame(
124
+ schemas,
125
+ 'Success',
126
+ { message: 'ok' },
127
+ { router: PROTOCOL_V2_CHANNEL_BLE_UART, seq: responseSeq }
128
+ );
129
+ notifyCallback?.(null, { value: Buffer.from(response).toString('base64') });
130
+ return Promise.resolve();
131
+ };
132
+
133
+ const writeCharacteristic = {
134
+ uuid: '0002',
135
+ deviceID: uuid,
136
+ isWritableWithResponse: true,
137
+ isWritableWithoutResponse: true,
138
+ writeWithResponse: jest.fn(handleWrite),
139
+ writeWithoutResponse: jest.fn(handleWrite),
140
+ };
141
+
142
+ const device = {
143
+ id: uuid,
144
+ name: 'OneKey Pro 2',
145
+ localName: 'OneKey Pro 2',
146
+ mtu: 247,
147
+ serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
148
+ isConnected: jest.fn(() => Promise.resolve(true)),
149
+ cancelConnection: jest.fn(() => Promise.resolve()),
150
+ connect: jest.fn(),
151
+ onDisconnected: jest.fn(() => ({ remove: jest.fn() })),
152
+ } as any;
153
+ device.connect.mockResolvedValue(device);
154
+ device.requestMTU = jest.fn(() => Promise.resolve(device));
155
+ device.requestConnectionPriority = jest.fn(() => Promise.resolve(device));
156
+
157
+ return { device, writeCharacteristic, notifyCharacteristic };
158
+ };
159
+
160
+ describe('ReactNativeBleTransport concurrent release and Android bonding', () => {
161
+ afterEach(() => {
162
+ jest.restoreAllMocks();
163
+ });
164
+
165
+ test('normal Device.release() does not abort another device waiting on Android bonding', async () => {
166
+ const uuidA = 'rn-android-release-a';
167
+ const uuidB = 'rn-android-bonding-b';
168
+ const devA = createSimulatedBleDevice(uuidA);
169
+ const devB = createSimulatedBleDevice(uuidB);
170
+ const devicesById = new Map([
171
+ [uuidA, devA],
172
+ [uuidB, devB],
173
+ ]);
174
+
175
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
176
+ transport.blePlxManager = {
177
+ devices: jest.fn((ids: string[]) =>
178
+ Promise.resolve(ids.map(id => devicesById.get(id)?.device).filter(Boolean))
179
+ ),
180
+ connectedDevices: jest.fn(() => Promise.resolve([])),
181
+ cancelTransaction: jest.fn(() => Promise.resolve()),
182
+ cancelDeviceConnection: jest.fn(() => Promise.resolve()),
183
+ destroy: jest.fn(),
184
+ } as any;
185
+ transport.resolveCharacteristics = jest.fn((device: { id: string }) => {
186
+ const entry = devicesById.get(device.id);
187
+ if (!entry) throw new Error(`Unknown device ${device.id}`);
188
+ return Promise.resolve({
189
+ writeCharacteristic: entry.writeCharacteristic,
190
+ notifyCharacteristic: entry.notifyCharacteristic,
191
+ });
192
+ });
193
+ transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
194
+ transport.configure(protocolV1Schema);
195
+ transport.configureProtocolV2(protocolV2Schema);
196
+
197
+ jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
198
+ jest.spyOn(TransportManager, 'load').mockImplementation();
199
+ TransportManager.transport = transport as any;
200
+ const connector = new DeviceConnector();
201
+ const cancelSpy = jest.spyOn(transport, 'cancel');
202
+
203
+ const pairDeviceMock = jest.requireMock('../BleManager').pairDevice as jest.Mock;
204
+ const onDeviceBondStateMock = jest.requireMock('../BleManager').onDeviceBondState as jest.Mock;
205
+ const bondB = createDeferred<void>();
206
+
207
+ pairDeviceMock.mockImplementation((id: string) =>
208
+ id === uuidA
209
+ ? Promise.resolve({ bonded: true, bonding: false })
210
+ : Promise.resolve({ bonded: false, bonding: true, initiated: true })
211
+ );
212
+ onDeviceBondStateMock.mockImplementation((id: string, signal?: AbortSignal) => {
213
+ if (id !== uuidB) return Promise.resolve();
214
+ return new Promise<void>((resolve, reject) => {
215
+ if (signal?.aborted) {
216
+ reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
217
+ return;
218
+ }
219
+ const onAbort = () => reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
220
+ signal?.addEventListener('abort', onAbort, { once: true });
221
+ bondB.promise.then(
222
+ () => {
223
+ signal?.removeEventListener('abort', onAbort);
224
+ resolve();
225
+ },
226
+ err => {
227
+ signal?.removeEventListener('abort', onAbort);
228
+ reject(err);
229
+ }
230
+ );
231
+ });
232
+ });
233
+
234
+ const deviceA = Device.fromDescriptor({
235
+ id: uuidA,
236
+ path: uuidA,
237
+ name: 'OneKey Pro 2',
238
+ commType: 'ble',
239
+ protocolType: 'V2',
240
+ } as never);
241
+ deviceA.deviceConnector = connector;
242
+
243
+ const deviceB = Device.fromDescriptor({
244
+ id: uuidB,
245
+ path: uuidB,
246
+ name: 'OneKey Pro 2',
247
+ commType: 'ble',
248
+ protocolType: 'V2',
249
+ } as never);
250
+ deviceB.deviceConnector = connector;
251
+
252
+ await deviceA.acquire('V2');
253
+ await expect(deviceA.commands.typedCall('Ping', 'Success', { message: 'hi' })).resolves.toEqual(
254
+ {
255
+ type: 'Success',
256
+ message: { message: 'ok' },
257
+ }
258
+ );
259
+
260
+ const acquiringB = deviceB.acquire('V2');
261
+ for (let i = 0; i < 10 && onDeviceBondStateMock.mock.calls.length === 0; i += 1) {
262
+ // eslint-disable-next-line no-await-in-loop
263
+ await flush();
264
+ }
265
+ expect(onDeviceBondStateMock).toHaveBeenCalledWith(
266
+ uuidB,
267
+ expect.any(Object),
268
+ expect.objectContaining({ systemInitiated: false })
269
+ );
270
+
271
+ // Normal release goes through Device.release() -> DeviceCommands.dispose(false).
272
+ await deviceA.release();
273
+ expect(cancelSpy).not.toHaveBeenCalled();
274
+
275
+ // Device B must still complete Android bonding and acquire cleanly.
276
+ bondB.resolve();
277
+ await expect(acquiringB).resolves.toBeUndefined();
278
+ expect(deviceB.hasDeviceAcquire()).toBe(true);
279
+ expect(deviceB.mainId).toBe(uuidB);
280
+
281
+ await deviceB.release();
282
+ await transport.stop();
283
+ });
284
+ });
@@ -0,0 +1,39 @@
1
+ import { ERRORS, HardwareErrorCode, HardwareErrorCodeMessage } from '@onekeyfe/hd-shared';
2
+
3
+ /**
4
+ * CoreBluetooth reports a bond the device no longer holds as
5
+ * CBErrorPeerRemovedPairingInformation (14), either on the connect or on the
6
+ * first GATT operation. ble-plx exposes it as `iosErrorCode`; the localized
7
+ * `reason` is not used for matching.
8
+ */
9
+ const IOS_PEER_REMOVED_PAIRING_INFORMATION = 14;
10
+
11
+ type NativeBleErrorFields = {
12
+ iosErrorCode?: unknown;
13
+ reason?: unknown;
14
+ message?: unknown;
15
+ };
16
+
17
+ export const isIosPeerRemovedPairingInformation = (error: unknown): boolean => {
18
+ if (!error || typeof error !== 'object') {
19
+ return false;
20
+ }
21
+ return (error as NativeBleErrorFields).iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION;
22
+ };
23
+
24
+ export const toIosStaleBondError = (error: unknown) => {
25
+ const nativeError = (error ?? {}) as NativeBleErrorFields;
26
+ const nativeErrorMessage = [nativeError.reason, nativeError.message]
27
+ .filter((value): value is string => typeof value === 'string')
28
+ .join(' ')
29
+ .slice(0, 240);
30
+ return ERRORS.TypedError(
31
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
32
+ HardwareErrorCodeMessage[HardwareErrorCode.BlePeerRemovedPairingInformation],
33
+ {
34
+ phase: 'connect',
35
+ reason: 'peer_removed_pairing_information',
36
+ ...(nativeErrorMessage ? { nativeErrorMessage } : {}),
37
+ }
38
+ );
39
+ };