@onekeyfe/hd-transport-react-native 1.2.8-alpha.12 → 1.2.8-alpha.120
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/index.d.ts +37 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +344 -21
- package/package.json +5 -5
- package/src/__tests__/enumerate.test.ts +139 -0
- package/src/__tests__/nativeFrameWrite.test.ts +910 -0
- package/src/__tests__/protocolV2Link.test.ts +107 -7
- package/src/index.ts +494 -40
package/src/index.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
import ByteBuffer from 'bytebuffer';
|
|
11
11
|
import transport, {
|
|
12
12
|
type OneKeyDeviceInfoBase,
|
|
13
|
+
type OneKeyMobileDeviceInfo,
|
|
13
14
|
PROTOCOL_V1_MESSAGE_HEADER_SIZE,
|
|
14
15
|
PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
|
|
15
16
|
PROTOCOL_V2_CHANNEL_BLE_UART,
|
|
@@ -28,6 +29,7 @@ import {
|
|
|
28
29
|
HardwareErrorCode,
|
|
29
30
|
createDeferred,
|
|
30
31
|
isOnekeyBluetoothDevice,
|
|
32
|
+
parseOnekeyBleColorCode,
|
|
31
33
|
} from '@onekeyfe/hd-shared';
|
|
32
34
|
|
|
33
35
|
import { getConnectedDeviceIds, onDeviceBondState, pairDevice } from './BleManager';
|
|
@@ -166,6 +168,11 @@ const isWedgedWriteError = (error: unknown): boolean =>
|
|
|
166
168
|
(error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
|
|
167
169
|
typeof (error as { message?: unknown })?.message === 'string' &&
|
|
168
170
|
(error as { message: string }).message.startsWith(WEDGED_WRITE_MESSAGE);
|
|
171
|
+
const createWedgedWriteError = () =>
|
|
172
|
+
ERRORS.TypedError(
|
|
173
|
+
HardwareErrorCode.BleWriteCharacteristicError,
|
|
174
|
+
`${WEDGED_WRITE_MESSAGE} ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
|
|
175
|
+
);
|
|
169
176
|
const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
|
|
170
177
|
const code = (error as { errorCode?: unknown })?.errorCode;
|
|
171
178
|
// Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
|
|
@@ -190,6 +197,16 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
|
|
|
190
197
|
export type ProtocolV2BleTuning = {
|
|
191
198
|
iosPacketLength?: number;
|
|
192
199
|
androidPacketLength?: number;
|
|
200
|
+
/**
|
|
201
|
+
* Write each multi-packet high-throughput frame with one native call when the native
|
|
202
|
+
* BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
|
|
203
|
+
*/
|
|
204
|
+
nativeFrameWrite?: boolean;
|
|
205
|
+
/**
|
|
206
|
+
* Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
|
|
207
|
+
* default) requests it below Android 17 only; true or false forces it on every version.
|
|
208
|
+
*/
|
|
209
|
+
androidHighConnectionPriority?: boolean | 'auto';
|
|
193
210
|
};
|
|
194
211
|
|
|
195
212
|
type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
@@ -197,6 +214,8 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
|
197
214
|
const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
|
|
198
215
|
iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
|
|
199
216
|
androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
|
|
217
|
+
nativeFrameWrite: true,
|
|
218
|
+
androidHighConnectionPriority: 'auto',
|
|
200
219
|
};
|
|
201
220
|
|
|
202
221
|
let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
|
|
@@ -217,6 +236,15 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
|
|
|
217
236
|
tuning.androidPacketLength,
|
|
218
237
|
protocolV2BleTuning.androidPacketLength
|
|
219
238
|
),
|
|
239
|
+
nativeFrameWrite:
|
|
240
|
+
typeof tuning.nativeFrameWrite === 'boolean'
|
|
241
|
+
? tuning.nativeFrameWrite
|
|
242
|
+
: protocolV2BleTuning.nativeFrameWrite,
|
|
243
|
+
androidHighConnectionPriority:
|
|
244
|
+
typeof tuning.androidHighConnectionPriority === 'boolean' ||
|
|
245
|
+
tuning.androidHighConnectionPriority === 'auto'
|
|
246
|
+
? tuning.androidHighConnectionPriority
|
|
247
|
+
: protocolV2BleTuning.androidHighConnectionPriority,
|
|
220
248
|
};
|
|
221
249
|
Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
|
|
222
250
|
}
|
|
@@ -230,13 +258,193 @@ export function getProtocolV2BleTuning() {
|
|
|
230
258
|
return { ...protocolV2BleTuning };
|
|
231
259
|
}
|
|
232
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
|
|
263
|
+
* the unpatched release, so the shape is declared here and probed at runtime.
|
|
264
|
+
*/
|
|
265
|
+
type ProtocolV2NativeFrameWriteExtension = {
|
|
266
|
+
isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
|
|
267
|
+
writeCharacteristicWithoutResponseFrame?: (
|
|
268
|
+
characteristicIdentifier: number,
|
|
269
|
+
base64Frame: string,
|
|
270
|
+
packetSize: number,
|
|
271
|
+
transactionId: string
|
|
272
|
+
) => Promise<void>;
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
|
|
276
|
+
|
|
277
|
+
type ActiveProtocolV2FrameWrite = {
|
|
278
|
+
generation: number;
|
|
279
|
+
cancel: (error: Error) => void;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* A newer JS bundle can run on an older native binary that ships the JS wrapper without the
|
|
284
|
+
* native method, so support comes from the wrapper's native check, never from its presence.
|
|
285
|
+
*/
|
|
286
|
+
const getProtocolV2NativeFrameWriter = (
|
|
287
|
+
manager: BlePlxManager | undefined
|
|
288
|
+
): ProtocolV2NativeFrameWriter | undefined => {
|
|
289
|
+
const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
|
|
290
|
+
if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
|
|
295
|
+
? (candidate as ProtocolV2NativeFrameWriter)
|
|
296
|
+
: undefined;
|
|
297
|
+
} catch {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
const getNativeBleErrorReason = (error: unknown): string | undefined => {
|
|
303
|
+
const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
|
|
304
|
+
if (typeof reason === 'string' && reason) return reason;
|
|
305
|
+
return typeof message === 'string' && message ? message : undefined;
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
|
|
309
|
+
|
|
310
|
+
const nowMs = () =>
|
|
311
|
+
typeof performance !== 'undefined' && typeof performance.now === 'function'
|
|
312
|
+
? performance.now()
|
|
313
|
+
: Date.now();
|
|
314
|
+
|
|
315
|
+
const roundMs = (ms: number) => Math.round(ms * 10) / 10;
|
|
316
|
+
|
|
317
|
+
/** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
|
|
318
|
+
const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
|
|
319
|
+
|
|
320
|
+
const createDurationStats = () => {
|
|
321
|
+
let total = 0;
|
|
322
|
+
let count = 0;
|
|
323
|
+
let max = 0;
|
|
324
|
+
return {
|
|
325
|
+
add(ms: number) {
|
|
326
|
+
total += ms;
|
|
327
|
+
count += 1;
|
|
328
|
+
max = Math.max(max, ms);
|
|
329
|
+
},
|
|
330
|
+
summarize: () => ({
|
|
331
|
+
total: roundMs(total),
|
|
332
|
+
avg: count ? roundMs(total / count) : 0,
|
|
333
|
+
max: roundMs(max),
|
|
334
|
+
}),
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
/** Scalar-only timing of one pipelined FilesystemFileWrite call. */
|
|
339
|
+
const createProtocolV2FileWritePerf = () => {
|
|
340
|
+
const startedAt = nowMs();
|
|
341
|
+
let nativeFrames = 0;
|
|
342
|
+
let frames = 0;
|
|
343
|
+
let packets = 0;
|
|
344
|
+
let frameBytes = 0;
|
|
345
|
+
const write = createDurationStats();
|
|
346
|
+
const readWait = createDurationStats();
|
|
347
|
+
const packet = createDurationStats();
|
|
348
|
+
const packetHistogram = Array.from(
|
|
349
|
+
{ length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 },
|
|
350
|
+
() => 0
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
/** Called before each frame write so a frame that fails still reports its mode. */
|
|
355
|
+
startFrame(mode: ProtocolV2FrameWriteMode) {
|
|
356
|
+
if (mode === 'native-frame') nativeFrames += 1;
|
|
357
|
+
},
|
|
358
|
+
recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
|
|
359
|
+
frames += 1;
|
|
360
|
+
packets += framePackets;
|
|
361
|
+
frameBytes += bytes;
|
|
362
|
+
write.add(elapsedMs);
|
|
363
|
+
},
|
|
364
|
+
recordPacket(elapsedMs: number) {
|
|
365
|
+
packet.add(elapsedMs);
|
|
366
|
+
const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
|
|
367
|
+
packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
|
|
368
|
+
},
|
|
369
|
+
recordReadWait(elapsedMs: number) {
|
|
370
|
+
readWait.add(elapsedMs);
|
|
371
|
+
},
|
|
372
|
+
summarize(ok: boolean) {
|
|
373
|
+
const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
|
|
374
|
+
const packetStats = packet.summarize();
|
|
375
|
+
return {
|
|
376
|
+
platform: Platform.OS,
|
|
377
|
+
mode,
|
|
378
|
+
ok,
|
|
379
|
+
frames,
|
|
380
|
+
packets,
|
|
381
|
+
frameBytes,
|
|
382
|
+
elapsedMs: roundMs(nowMs() - startedAt),
|
|
383
|
+
writeMs: write.summarize(),
|
|
384
|
+
readWaitMs: readWait.summarize(),
|
|
385
|
+
...(mode === 'per-packet'
|
|
386
|
+
? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
|
|
387
|
+
: {}),
|
|
388
|
+
};
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
|
|
394
|
+
|
|
233
395
|
function getDeviceDisplayName(device?: Device | null) {
|
|
234
396
|
return device?.name || device?.localName || null;
|
|
235
397
|
}
|
|
236
398
|
|
|
399
|
+
// The color is only in the primary advertisement, and the name only in the scan
|
|
400
|
+
// response, so the callback a scan keeps may not carry it. A connected device stops
|
|
401
|
+
// advertising. Keep the last valid color per device for the life of the process.
|
|
402
|
+
// iOS reports connected peripherals with lowercased ids, so key case-insensitively.
|
|
403
|
+
const bleColorCodesById = new Map<string, string>();
|
|
404
|
+
|
|
405
|
+
function getManufacturerDataLength(device?: Device | null) {
|
|
406
|
+
return device?.manufacturerData ? Buffer.from(device.manufacturerData, 'base64').length : 0;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function rememberBleColorCode(device?: Device | null) {
|
|
410
|
+
if (!device?.id || !device.manufacturerData) return;
|
|
411
|
+
const colorCode = parseOnekeyBleColorCode(Buffer.from(device.manufacturerData, 'base64'));
|
|
412
|
+
const key = device.id.toLowerCase();
|
|
413
|
+
if (colorCode && bleColorCodesById.get(key) !== colorCode) {
|
|
414
|
+
bleColorCodesById.set(key, colorCode);
|
|
415
|
+
Log?.debug('[ReactNativeBleTransport] BLE color code', {
|
|
416
|
+
deviceId: device.id,
|
|
417
|
+
bleColorCode: colorCode,
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
|
|
423
|
+
const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
|
|
424
|
+
return bleColorCode ? ({ ...device, bleColorCode } as IOneKeyDevice) : device;
|
|
425
|
+
}
|
|
426
|
+
|
|
237
427
|
const IOS_REQUEST_MTU = 247;
|
|
238
428
|
const ANDROID_REQUEST_MTU = 517;
|
|
239
429
|
const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
|
|
430
|
+
/**
|
|
431
|
+
* Android 17 maps CONNECTION_PRIORITY_HIGH to 11.25-15 ms with peripheral latency 1. OneKey BLE
|
|
432
|
+
* firmware accepts any latency at its 15 ms interval, and latency 1 roughly halves Protocol V2
|
|
433
|
+
* FileWrite throughput. BLE 1.0.23 requests 15 ms with latency 0 by itself; older BLE firmware
|
|
434
|
+
* asks for 15-30 ms or nothing and has not been measured on Android 17 without HIGH.
|
|
435
|
+
*/
|
|
436
|
+
const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
|
|
437
|
+
|
|
438
|
+
const shouldRequestAndroidHighConnectionPriority = () => {
|
|
439
|
+
if (Platform.OS !== 'android') return false;
|
|
440
|
+
const { androidHighConnectionPriority } = protocolV2BleTuning;
|
|
441
|
+
if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
|
|
442
|
+
const apiLevel = Number(Platform.Version);
|
|
443
|
+
// Unknown versions keep the long-standing HIGH request.
|
|
444
|
+
return (
|
|
445
|
+
!Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
|
|
446
|
+
);
|
|
447
|
+
};
|
|
240
448
|
|
|
241
449
|
const getRequestedBleMtu = () =>
|
|
242
450
|
Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
|
|
@@ -356,7 +564,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
|
|
|
356
564
|
|
|
357
565
|
type NegotiatedMtuResult = { device: Device; timedOut: boolean };
|
|
358
566
|
|
|
359
|
-
export type IOneKeyDevice = OneKeyDeviceInfoBase &
|
|
567
|
+
export type IOneKeyDevice = OneKeyDeviceInfoBase &
|
|
568
|
+
Device &
|
|
569
|
+
Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
|
|
360
570
|
|
|
361
571
|
const tryToGetConfiguration = (device: Device) => {
|
|
362
572
|
if (!device || !device.serviceUUIDs) return null;
|
|
@@ -560,6 +770,13 @@ export default class ReactNativeBleTransport {
|
|
|
560
770
|
|
|
561
771
|
private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
|
|
562
772
|
|
|
773
|
+
/** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
|
|
774
|
+
private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
|
|
775
|
+
|
|
776
|
+
private protocolV2FrameWriteCounter = 0;
|
|
777
|
+
|
|
778
|
+
private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
|
|
779
|
+
|
|
563
780
|
private nextMonitorToken = 1;
|
|
564
781
|
|
|
565
782
|
/** Serializes transport lifecycle changes for the same physical device. */
|
|
@@ -855,7 +1072,7 @@ export default class ReactNativeBleTransport {
|
|
|
855
1072
|
}).then(() => {
|
|
856
1073
|
this.scanCleanups.delete(cancelScan);
|
|
857
1074
|
if (error) reject(error);
|
|
858
|
-
else resolve(deviceList);
|
|
1075
|
+
else resolve(deviceList.map(withBleColorCode));
|
|
859
1076
|
});
|
|
860
1077
|
return scanCleanup;
|
|
861
1078
|
};
|
|
@@ -900,6 +1117,9 @@ export default class ReactNativeBleTransport {
|
|
|
900
1117
|
return;
|
|
901
1118
|
}
|
|
902
1119
|
|
|
1120
|
+
// The native scan is filtered to the OneKey communication service, so an
|
|
1121
|
+
// unnamed iOS advertisement rejected below can still carry the color.
|
|
1122
|
+
rememberBleColorCode(device);
|
|
903
1123
|
const displayName = getDeviceDisplayName(device);
|
|
904
1124
|
// iOS may report a service-only advertisement before the named scan response.
|
|
905
1125
|
// Do not cache that incomplete advertisement as an unknown device.
|
|
@@ -965,6 +1185,9 @@ export default class ReactNativeBleTransport {
|
|
|
965
1185
|
deviceId: device.id,
|
|
966
1186
|
name: displayName,
|
|
967
1187
|
serviceUUIDs: device.serviceUUIDs,
|
|
1188
|
+
// 5 = advertises a color slot; 4 = BLE firmware before 1.0.23.
|
|
1189
|
+
manufacturerDataLength: getManufacturerDataLength(device),
|
|
1190
|
+
bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
|
|
968
1191
|
});
|
|
969
1192
|
}
|
|
970
1193
|
};
|
|
@@ -1529,11 +1752,14 @@ export default class ReactNativeBleTransport {
|
|
|
1529
1752
|
}
|
|
1530
1753
|
|
|
1531
1754
|
private async releaseUnlocked(uuid: string, onclose = false) {
|
|
1532
|
-
|
|
1755
|
+
const reason = 'React Native BLE transport released';
|
|
1756
|
+
this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
|
|
1757
|
+
await this.protocolV2Links.invalidateLink(uuid, reason);
|
|
1533
1758
|
return this.releaseNative(uuid, onclose);
|
|
1534
1759
|
}
|
|
1535
1760
|
|
|
1536
1761
|
private async releaseNative(uuid: string, onclose = false) {
|
|
1762
|
+
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1537
1763
|
const transport = transportCache[uuid];
|
|
1538
1764
|
const manager = this.blePlxManager;
|
|
1539
1765
|
if (this.runPromise && this.runPromiseDeviceId === uuid) {
|
|
@@ -1954,7 +2180,13 @@ export default class ReactNativeBleTransport {
|
|
|
1954
2180
|
}
|
|
1955
2181
|
|
|
1956
2182
|
private async disconnectUnlocked(session: string) {
|
|
1957
|
-
|
|
2183
|
+
// The next link starts at the stack's default priority; a cached HIGH or a pending
|
|
2184
|
+
// Balanced restore from this link must not carry over to it.
|
|
2185
|
+
this.clearAndroidPriorityResetTimer(session);
|
|
2186
|
+
this.androidHighPriorityDevices.delete(session);
|
|
2187
|
+
const reason = 'React Native BLE transport disconnected';
|
|
2188
|
+
this.cancelProtocolV2FrameWrite(session, new Error(reason));
|
|
2189
|
+
await this.protocolV2Links.invalidateLink(session, reason);
|
|
1958
2190
|
const transport = transportCache[session];
|
|
1959
2191
|
const manager = this.blePlxManager;
|
|
1960
2192
|
const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
|
|
@@ -2392,12 +2624,7 @@ export default class ReactNativeBleTransport {
|
|
|
2392
2624
|
new Promise<never>((_, reject) => {
|
|
2393
2625
|
timer = setTimeout(() => {
|
|
2394
2626
|
timedOut = true;
|
|
2395
|
-
reject(
|
|
2396
|
-
ERRORS.TypedError(
|
|
2397
|
-
HardwareErrorCode.BleWriteCharacteristicError,
|
|
2398
|
-
`BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
|
|
2399
|
-
)
|
|
2400
|
-
);
|
|
2627
|
+
reject(createWedgedWriteError());
|
|
2401
2628
|
}, BLE_WRITE_PACKET_TIMEOUT_MS);
|
|
2402
2629
|
}),
|
|
2403
2630
|
]);
|
|
@@ -2431,6 +2658,7 @@ export default class ReactNativeBleTransport {
|
|
|
2431
2658
|
consecutiveWriteTimeouts: timeouts,
|
|
2432
2659
|
});
|
|
2433
2660
|
|
|
2661
|
+
this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
|
|
2434
2662
|
const wedged = transportCache[uuid];
|
|
2435
2663
|
this.disconnect(uuid).catch(error => {
|
|
2436
2664
|
Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
|
|
@@ -2458,6 +2686,8 @@ export default class ReactNativeBleTransport {
|
|
|
2458
2686
|
const manager = this.blePlxManager;
|
|
2459
2687
|
this.blePlxManager = undefined;
|
|
2460
2688
|
const reason = 'React Native BLE manager reset';
|
|
2689
|
+
// Cancel through the manager that started each frame before destroy() drops its queue.
|
|
2690
|
+
this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
|
|
2461
2691
|
// Destroying the shared manager invalidates every peripheral it owns. Notify
|
|
2462
2692
|
// each cached session before clearing generations so Core cannot retain a
|
|
2463
2693
|
// silently stale connection for an unrelated device.
|
|
@@ -2520,17 +2750,13 @@ export default class ReactNativeBleTransport {
|
|
|
2520
2750
|
private createProtocolMismatchError(expected: ProtocolType) {
|
|
2521
2751
|
// A protocol probe miss alone does not prove that the OS bond is stale.
|
|
2522
2752
|
// Native authentication/encryption failures are mapped separately.
|
|
2523
|
-
return ERRORS.TypedError(
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
);
|
|
2753
|
+
return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed, undefined, {
|
|
2754
|
+
expectedProtocol: expected,
|
|
2755
|
+
});
|
|
2527
2756
|
}
|
|
2528
2757
|
|
|
2529
2758
|
private createProtocolDetectionError() {
|
|
2530
|
-
return ERRORS.TypedError(
|
|
2531
|
-
HardwareErrorCode.BleTimeoutError,
|
|
2532
|
-
'Unable to detect BLE protocol: device did not respond to Protocol V1 GetFeatures or Protocol V2 Ping'
|
|
2533
|
-
);
|
|
2759
|
+
return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed);
|
|
2534
2760
|
}
|
|
2535
2761
|
|
|
2536
2762
|
private clearProbeProtocol(uuid: string, protocol: ProtocolType) {
|
|
@@ -2933,22 +3159,204 @@ export default class ReactNativeBleTransport {
|
|
|
2933
3159
|
androidPacketLength: tuning.androidPacketLength,
|
|
2934
3160
|
mtu: transport.mtuSize,
|
|
2935
3161
|
});
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
3162
|
+
const perf = this.getProtocolV2FileWritePerf(uuid, context);
|
|
3163
|
+
const startedAt = perf ? nowMs() : 0;
|
|
3164
|
+
const nativeFrameWriter =
|
|
3165
|
+
frame.length > packetCapacity
|
|
3166
|
+
? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
|
|
3167
|
+
: undefined;
|
|
3168
|
+
perf?.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
|
|
3169
|
+
if (nativeFrameWriter) {
|
|
3170
|
+
await this.writeProtocolV2NativeFrame(
|
|
3171
|
+
uuid,
|
|
3172
|
+
transport,
|
|
3173
|
+
nativeFrameWriter,
|
|
3174
|
+
frame,
|
|
3175
|
+
packetCapacity,
|
|
3176
|
+
context,
|
|
3177
|
+
assertCurrentGeneration
|
|
3178
|
+
);
|
|
3179
|
+
} else {
|
|
3180
|
+
await writeProtocolV2BleFrame({
|
|
3181
|
+
frame,
|
|
3182
|
+
packetCapacity,
|
|
3183
|
+
assertActive: assertCurrentGeneration,
|
|
3184
|
+
signal: context.signal,
|
|
3185
|
+
abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
|
|
3186
|
+
wait: delay,
|
|
3187
|
+
writePacket: async packet => {
|
|
3188
|
+
const packetStartedAt = perf ? nowMs() : 0;
|
|
3189
|
+
await this.writeProtocolV2Packet(
|
|
3190
|
+
uuid,
|
|
3191
|
+
transport,
|
|
3192
|
+
Buffer.from(packet).toString('base64'),
|
|
3193
|
+
context,
|
|
3194
|
+
assertCurrentGeneration
|
|
3195
|
+
);
|
|
3196
|
+
perf?.recordPacket(nowMs() - packetStartedAt);
|
|
3197
|
+
},
|
|
3198
|
+
});
|
|
3199
|
+
}
|
|
3200
|
+
perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
|
|
3201
|
+
}
|
|
3202
|
+
|
|
3203
|
+
/**
|
|
3204
|
+
* The native frame write only replaces the per-packet loop where its JS<->native round trips
|
|
3205
|
+
* dominate: multi-packet (checked by the caller) high-throughput frames written without response.
|
|
3206
|
+
*/
|
|
3207
|
+
private resolveProtocolV2NativeFrameWriter(
|
|
3208
|
+
transport: BleTransport,
|
|
3209
|
+
context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
|
|
3210
|
+
nativeFrameWrite: boolean
|
|
3211
|
+
): ProtocolV2NativeFrameWriter | undefined {
|
|
3212
|
+
if (!context.highThroughput || !nativeFrameWrite) return undefined;
|
|
3213
|
+
if (
|
|
3214
|
+
shouldWriteProtocolV2WithResponse({
|
|
3215
|
+
platform: Platform.OS,
|
|
3216
|
+
highThroughput: context.highThroughput,
|
|
3217
|
+
requestedWithResponse: context.writeWithResponse,
|
|
3218
|
+
characteristic: transport.writeCharacteristic,
|
|
3219
|
+
})
|
|
3220
|
+
) {
|
|
3221
|
+
return undefined;
|
|
3222
|
+
}
|
|
3223
|
+
if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
|
|
3224
|
+
return getProtocolV2NativeFrameWriter(this.blePlxManager);
|
|
3225
|
+
}
|
|
3226
|
+
|
|
3227
|
+
/**
|
|
3228
|
+
* Writes one frame with a single native call that sends its packets in order without response.
|
|
3229
|
+
* Nothing here retries it: a resend could duplicate bytes the device already received. The
|
|
3230
|
+
* native transaction is cancelled on abort, watchdog expiry and link teardown so the native
|
|
3231
|
+
* side stops writing a frame nobody waits for any more; a generation change detected after
|
|
3232
|
+
* the frame completes still fails the write.
|
|
3233
|
+
*/
|
|
3234
|
+
private async writeProtocolV2NativeFrame(
|
|
3235
|
+
uuid: string,
|
|
3236
|
+
transport: BleTransport,
|
|
3237
|
+
manager: ProtocolV2NativeFrameWriter,
|
|
3238
|
+
frame: Uint8Array,
|
|
3239
|
+
packetCapacity: number,
|
|
3240
|
+
context: ProtocolV2CallContext,
|
|
3241
|
+
assertCurrentGeneration: () => void
|
|
3242
|
+
) {
|
|
3243
|
+
const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
|
|
3244
|
+
assertCurrentGeneration();
|
|
3245
|
+
if (context.signal.aborted) {
|
|
3246
|
+
throw new Error(abortMessage);
|
|
3247
|
+
}
|
|
3248
|
+
|
|
3249
|
+
this.protocolV2FrameWriteCounter += 1;
|
|
3250
|
+
const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
|
|
3251
|
+
let cancelError: Error | undefined;
|
|
3252
|
+
let rejectCancelled: (error: Error) => void = () => undefined;
|
|
3253
|
+
const cancelled = new Promise<never>((_, reject) => {
|
|
3254
|
+
rejectCancelled = reject;
|
|
2951
3255
|
});
|
|
3256
|
+
const active: ActiveProtocolV2FrameWrite = {
|
|
3257
|
+
generation: context.generation,
|
|
3258
|
+
cancel: error => {
|
|
3259
|
+
if (cancelError) return;
|
|
3260
|
+
cancelError = error;
|
|
3261
|
+
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3262
|
+
this.protocolV2FrameWrites.delete(uuid);
|
|
3263
|
+
}
|
|
3264
|
+
rejectCancelled(error);
|
|
3265
|
+
this.cancelNativeTransaction(manager, transactionId);
|
|
3266
|
+
},
|
|
3267
|
+
};
|
|
3268
|
+
// Same rule as writeBlePacket: a superseded generation must not tear down the current link.
|
|
3269
|
+
const isCurrentOwner = () => {
|
|
3270
|
+
try {
|
|
3271
|
+
assertCurrentGeneration();
|
|
3272
|
+
return !context.signal.aborted;
|
|
3273
|
+
} catch {
|
|
3274
|
+
return false;
|
|
3275
|
+
}
|
|
3276
|
+
};
|
|
3277
|
+
const onAbort = () => active.cancel(new Error(abortMessage));
|
|
3278
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
3279
|
+
try {
|
|
3280
|
+
const nativeWrite = Promise.resolve(
|
|
3281
|
+
manager.writeCharacteristicWithoutResponseFrame(
|
|
3282
|
+
transport.writeCharacteristic.id,
|
|
3283
|
+
Buffer.from(frame).toString('base64'),
|
|
3284
|
+
packetCapacity,
|
|
3285
|
+
transactionId
|
|
3286
|
+
)
|
|
3287
|
+
);
|
|
3288
|
+
// A cancelled or timed-out frame still settles natively later; that outcome is ignored.
|
|
3289
|
+
nativeWrite.catch(() => undefined);
|
|
3290
|
+
this.protocolV2FrameWrites.set(uuid, active);
|
|
3291
|
+
context.signal.addEventListener('abort', onAbort);
|
|
3292
|
+
timer = setTimeout(() => {
|
|
3293
|
+
const owner = isCurrentOwner();
|
|
3294
|
+
active.cancel(createWedgedWriteError());
|
|
3295
|
+
if (owner) {
|
|
3296
|
+
this.tearDownWedgedLink(uuid);
|
|
3297
|
+
} else {
|
|
3298
|
+
Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
|
|
3299
|
+
}
|
|
3300
|
+
}, BLE_WRITE_PACKET_TIMEOUT_MS);
|
|
3301
|
+
await Promise.race([nativeWrite, cancelled]);
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
if (cancelError) throw cancelError;
|
|
3304
|
+
if (isNativeBleDisconnectError(error)) {
|
|
3305
|
+
throw toBleDisconnectHardwareError(error);
|
|
3306
|
+
}
|
|
3307
|
+
throw ERRORS.TypedError(
|
|
3308
|
+
HardwareErrorCode.BleWriteCharacteristicError,
|
|
3309
|
+
getNativeBleErrorReason(error)
|
|
3310
|
+
);
|
|
3311
|
+
} finally {
|
|
3312
|
+
if (timer) clearTimeout(timer);
|
|
3313
|
+
context.signal.removeEventListener('abort', onAbort);
|
|
3314
|
+
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3315
|
+
this.protocolV2FrameWrites.delete(uuid);
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
this.writeTimeoutCounts.delete(uuid);
|
|
3320
|
+
try {
|
|
3321
|
+
assertCurrentGeneration();
|
|
3322
|
+
} catch (error) {
|
|
3323
|
+
active.cancel(error instanceof Error ? error : new Error(String(error)));
|
|
3324
|
+
}
|
|
3325
|
+
if (cancelError) throw cancelError;
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
/** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
|
|
3329
|
+
private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
|
|
3330
|
+
const active = this.protocolV2FrameWrites.get(uuid);
|
|
3331
|
+
if (!active || (generation !== undefined && active.generation !== generation)) return;
|
|
3332
|
+
active.cancel(error);
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
|
|
3336
|
+
const logFailure = (error: unknown) =>
|
|
3337
|
+
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
|
|
3338
|
+
error: error instanceof Error ? error.message : String(error),
|
|
3339
|
+
});
|
|
3340
|
+
try {
|
|
3341
|
+
Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
|
|
3342
|
+
} catch (error) {
|
|
3343
|
+
logFailure(error);
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
|
|
3347
|
+
private getProtocolV2FileWritePerf(uuid: string, context: ProtocolV2CallContext) {
|
|
3348
|
+
return context.messageName === 'FilesystemFileWrite'
|
|
3349
|
+
? this.protocolV2FileWritePerfs.get(uuid)
|
|
3350
|
+
: undefined;
|
|
3351
|
+
}
|
|
3352
|
+
|
|
3353
|
+
/** Returns true the first time `signature` is seen for `uuid` on this link. */
|
|
3354
|
+
private markProtocolV2LogSignature(uuid: string, signature: string): boolean {
|
|
3355
|
+
const signatures = this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
|
|
3356
|
+
if (signatures.has(signature)) return false;
|
|
3357
|
+
signatures.add(signature);
|
|
3358
|
+
this.protocolV2HighVolumeLogSignatures.set(uuid, signatures);
|
|
3359
|
+
return true;
|
|
2952
3360
|
}
|
|
2953
3361
|
|
|
2954
3362
|
private async callProtocolV2(
|
|
@@ -2985,11 +3393,7 @@ export default class ReactNativeBleTransport {
|
|
|
2985
3393
|
const logSignature = `${name}:${writeMode}:${String(
|
|
2986
3394
|
currentTransport.mtuSize
|
|
2987
3395
|
)}:${packetCapacity}`;
|
|
2988
|
-
|
|
2989
|
-
this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
|
|
2990
|
-
if (!loggedSignatures.has(logSignature)) {
|
|
2991
|
-
loggedSignatures.add(logSignature);
|
|
2992
|
-
this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
|
|
3396
|
+
if (this.markProtocolV2LogSignature(uuid, logSignature)) {
|
|
2993
3397
|
Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
|
|
2994
3398
|
name,
|
|
2995
3399
|
writeMode,
|
|
@@ -2997,20 +3401,47 @@ export default class ReactNativeBleTransport {
|
|
|
2997
3401
|
packetCapacity,
|
|
2998
3402
|
});
|
|
2999
3403
|
}
|
|
3404
|
+
const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
|
|
3405
|
+
currentTransport,
|
|
3406
|
+
{ highThroughput: true, writeWithResponse: options?.writeWithResponse },
|
|
3407
|
+
tuning.nativeFrameWrite
|
|
3408
|
+
)
|
|
3409
|
+
? 'native-frame'
|
|
3410
|
+
: 'per-packet';
|
|
3411
|
+
if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
|
|
3412
|
+
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
|
|
3413
|
+
platform: Platform.OS,
|
|
3414
|
+
mode: frameWriteMode,
|
|
3415
|
+
nativeFrameWrite: tuning.nativeFrameWrite,
|
|
3416
|
+
nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
|
|
3417
|
+
packetCapacity,
|
|
3418
|
+
});
|
|
3419
|
+
}
|
|
3000
3420
|
}
|
|
3001
3421
|
|
|
3002
3422
|
if (highThroughputWrite) {
|
|
3003
3423
|
await this.enableAndroidHighConnectionPriority(uuid);
|
|
3004
3424
|
}
|
|
3005
3425
|
|
|
3426
|
+
const fileWritePerf =
|
|
3427
|
+
name === 'FilesystemFileWrite' && options?.fileWritePipeline
|
|
3428
|
+
? createProtocolV2FileWritePerf()
|
|
3429
|
+
: undefined;
|
|
3430
|
+
if (fileWritePerf) {
|
|
3431
|
+
this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
|
|
3432
|
+
}
|
|
3433
|
+
let fileWriteOk = false;
|
|
3434
|
+
|
|
3006
3435
|
try {
|
|
3007
|
-
|
|
3436
|
+
const response = await this.protocolV2Links.call(
|
|
3008
3437
|
uuid,
|
|
3009
3438
|
() => this.createProtocolV2Adapter(uuid),
|
|
3010
3439
|
name,
|
|
3011
3440
|
data,
|
|
3012
3441
|
callOptions
|
|
3013
3442
|
);
|
|
3443
|
+
fileWriteOk = response.type !== 'Failure';
|
|
3444
|
+
return response;
|
|
3014
3445
|
} catch (e) {
|
|
3015
3446
|
Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
|
|
3016
3447
|
if (
|
|
@@ -3031,6 +3462,15 @@ export default class ReactNativeBleTransport {
|
|
|
3031
3462
|
if (highThroughputWrite) {
|
|
3032
3463
|
this.scheduleAndroidBalancedConnectionPriority(uuid);
|
|
3033
3464
|
}
|
|
3465
|
+
if (fileWritePerf) {
|
|
3466
|
+
if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
|
|
3467
|
+
this.protocolV2FileWritePerfs.delete(uuid);
|
|
3468
|
+
}
|
|
3469
|
+
Log?.debug(
|
|
3470
|
+
'[ReactNativeBleTransport] FileWrite perf',
|
|
3471
|
+
fileWritePerf.summarize(fileWriteOk)
|
|
3472
|
+
);
|
|
3473
|
+
}
|
|
3034
3474
|
}
|
|
3035
3475
|
}
|
|
3036
3476
|
|
|
@@ -3069,6 +3509,15 @@ export default class ReactNativeBleTransport {
|
|
|
3069
3509
|
|
|
3070
3510
|
this.clearAndroidPriorityResetTimer(uuid);
|
|
3071
3511
|
if (this.androidHighPriorityDevices.has(uuid)) return;
|
|
3512
|
+
if (!shouldRequestAndroidHighConnectionPriority()) {
|
|
3513
|
+
if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
|
|
3514
|
+
Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
|
|
3515
|
+
apiLevel: Platform.Version,
|
|
3516
|
+
setting: protocolV2BleTuning.androidHighConnectionPriority,
|
|
3517
|
+
});
|
|
3518
|
+
}
|
|
3519
|
+
return;
|
|
3520
|
+
}
|
|
3072
3521
|
|
|
3073
3522
|
const transport = transportCache[uuid];
|
|
3074
3523
|
if (!transport) return;
|
|
@@ -3147,15 +3596,20 @@ export default class ReactNativeBleTransport {
|
|
|
3147
3596
|
assertCurrentGeneration
|
|
3148
3597
|
);
|
|
3149
3598
|
},
|
|
3150
|
-
readFrame: async () => {
|
|
3599
|
+
readFrame: async (context: ProtocolV2CallContext) => {
|
|
3151
3600
|
assertCurrentGeneration();
|
|
3601
|
+
const perf = this.getProtocolV2FileWritePerf(uuid, context);
|
|
3602
|
+
const startedAt = perf ? nowMs() : 0;
|
|
3152
3603
|
const rxFrame = await this.readProtocolV2Frame(uuid);
|
|
3604
|
+
perf?.recordReadWait(nowMs() - startedAt);
|
|
3153
3605
|
if (!(rxFrame instanceof Uint8Array)) {
|
|
3154
3606
|
throw new Error('Protocol V2 response is not Uint8Array');
|
|
3155
3607
|
}
|
|
3156
3608
|
return rxFrame;
|
|
3157
3609
|
},
|
|
3158
3610
|
reset: (reason: string) => {
|
|
3611
|
+
// The frame belongs to this link even after a newer monitor generation took over.
|
|
3612
|
+
this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
|
|
3159
3613
|
if (this.monitorTokens.get(uuid) !== generation) return;
|
|
3160
3614
|
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3161
3615
|
this.rejectProtocolV2Frames(uuid, new Error(reason));
|