@onekeyfe/hd-transport-react-native 1.2.8-alpha.13 → 1.2.8-alpha.131

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/src/index.ts CHANGED
@@ -8,8 +8,9 @@ import {
8
8
  ScanMode,
9
9
  } from 'react-native-ble-plx';
10
10
  import ByteBuffer from 'bytebuffer';
11
- import transport, {
11
+ import transportModule, {
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';
@@ -67,6 +69,9 @@ type FirmwareInstallBleAcquireInput = BleAcquireInput & {
67
69
  skipProtocolProbe?: boolean;
68
70
  };
69
71
 
72
+ const transport: typeof transportModule =
73
+ (transportModule as typeof transportModule & { default?: typeof transportModule }).default ??
74
+ transportModule;
70
75
  const { check, ProtocolV1, parseConfigure } = transport;
71
76
 
72
77
  const Log = bleLogger;
@@ -166,6 +171,11 @@ const isWedgedWriteError = (error: unknown): boolean =>
166
171
  (error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
167
172
  typeof (error as { message?: unknown })?.message === 'string' &&
168
173
  (error as { message: string }).message.startsWith(WEDGED_WRITE_MESSAGE);
174
+ const createWedgedWriteError = () =>
175
+ ERRORS.TypedError(
176
+ HardwareErrorCode.BleWriteCharacteristicError,
177
+ `${WEDGED_WRITE_MESSAGE} ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
178
+ );
169
179
  const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
170
180
  const code = (error as { errorCode?: unknown })?.errorCode;
171
181
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
@@ -190,6 +200,16 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
190
200
  export type ProtocolV2BleTuning = {
191
201
  iosPacketLength?: number;
192
202
  androidPacketLength?: number;
203
+ /**
204
+ * Write each multi-packet high-throughput frame with one native call when the native
205
+ * BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
206
+ */
207
+ nativeFrameWrite?: boolean;
208
+ /**
209
+ * Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
210
+ * default) requests it below Android 17 only; true or false forces it on every version.
211
+ */
212
+ androidHighConnectionPriority?: boolean | 'auto';
193
213
  };
194
214
 
195
215
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -197,6 +217,8 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
197
217
  const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
198
218
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
199
219
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
220
+ nativeFrameWrite: true,
221
+ androidHighConnectionPriority: 'auto',
200
222
  };
201
223
 
202
224
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -217,6 +239,15 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
217
239
  tuning.androidPacketLength,
218
240
  protocolV2BleTuning.androidPacketLength
219
241
  ),
242
+ nativeFrameWrite:
243
+ typeof tuning.nativeFrameWrite === 'boolean'
244
+ ? tuning.nativeFrameWrite
245
+ : protocolV2BleTuning.nativeFrameWrite,
246
+ androidHighConnectionPriority:
247
+ typeof tuning.androidHighConnectionPriority === 'boolean' ||
248
+ tuning.androidHighConnectionPriority === 'auto'
249
+ ? tuning.androidHighConnectionPriority
250
+ : protocolV2BleTuning.androidHighConnectionPriority,
220
251
  };
221
252
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
222
253
  }
@@ -230,13 +261,193 @@ export function getProtocolV2BleTuning() {
230
261
  return { ...protocolV2BleTuning };
231
262
  }
232
263
 
264
+ /**
265
+ * Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
266
+ * the unpatched release, so the shape is declared here and probed at runtime.
267
+ */
268
+ type ProtocolV2NativeFrameWriteExtension = {
269
+ isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
270
+ writeCharacteristicWithoutResponseFrame?: (
271
+ characteristicIdentifier: number,
272
+ base64Frame: string,
273
+ packetSize: number,
274
+ transactionId: string
275
+ ) => Promise<void>;
276
+ };
277
+
278
+ type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
279
+
280
+ type ActiveProtocolV2FrameWrite = {
281
+ generation: number;
282
+ cancel: (error: Error) => void;
283
+ };
284
+
285
+ /**
286
+ * A newer JS bundle can run on an older native binary that ships the JS wrapper without the
287
+ * native method, so support comes from the wrapper's native check, never from its presence.
288
+ */
289
+ const getProtocolV2NativeFrameWriter = (
290
+ manager: BlePlxManager | undefined
291
+ ): ProtocolV2NativeFrameWriter | undefined => {
292
+ const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
293
+ if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
294
+ return undefined;
295
+ }
296
+ try {
297
+ return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
298
+ ? (candidate as ProtocolV2NativeFrameWriter)
299
+ : undefined;
300
+ } catch {
301
+ return undefined;
302
+ }
303
+ };
304
+
305
+ const getNativeBleErrorReason = (error: unknown): string | undefined => {
306
+ const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
307
+ if (typeof reason === 'string' && reason) return reason;
308
+ return typeof message === 'string' && message ? message : undefined;
309
+ };
310
+
311
+ type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
312
+
313
+ const nowMs = () =>
314
+ typeof performance !== 'undefined' && typeof performance.now === 'function'
315
+ ? performance.now()
316
+ : Date.now();
317
+
318
+ const roundMs = (ms: number) => Math.round(ms * 10) / 10;
319
+
320
+ /** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
321
+ const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
322
+
323
+ const createDurationStats = () => {
324
+ let total = 0;
325
+ let count = 0;
326
+ let max = 0;
327
+ return {
328
+ add(ms: number) {
329
+ total += ms;
330
+ count += 1;
331
+ max = Math.max(max, ms);
332
+ },
333
+ summarize: () => ({
334
+ total: roundMs(total),
335
+ avg: count ? roundMs(total / count) : 0,
336
+ max: roundMs(max),
337
+ }),
338
+ };
339
+ };
340
+
341
+ /** Scalar-only timing of one pipelined FilesystemFileWrite call. */
342
+ const createProtocolV2FileWritePerf = () => {
343
+ const startedAt = nowMs();
344
+ let nativeFrames = 0;
345
+ let frames = 0;
346
+ let packets = 0;
347
+ let frameBytes = 0;
348
+ const write = createDurationStats();
349
+ const readWait = createDurationStats();
350
+ const packet = createDurationStats();
351
+ const packetHistogram = Array.from(
352
+ { length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 },
353
+ () => 0
354
+ );
355
+
356
+ return {
357
+ /** Called before each frame write so a frame that fails still reports its mode. */
358
+ startFrame(mode: ProtocolV2FrameWriteMode) {
359
+ if (mode === 'native-frame') nativeFrames += 1;
360
+ },
361
+ recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
362
+ frames += 1;
363
+ packets += framePackets;
364
+ frameBytes += bytes;
365
+ write.add(elapsedMs);
366
+ },
367
+ recordPacket(elapsedMs: number) {
368
+ packet.add(elapsedMs);
369
+ const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
370
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
371
+ },
372
+ recordReadWait(elapsedMs: number) {
373
+ readWait.add(elapsedMs);
374
+ },
375
+ summarize(ok: boolean) {
376
+ const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
377
+ const packetStats = packet.summarize();
378
+ return {
379
+ platform: Platform.OS,
380
+ mode,
381
+ ok,
382
+ frames,
383
+ packets,
384
+ frameBytes,
385
+ elapsedMs: roundMs(nowMs() - startedAt),
386
+ writeMs: write.summarize(),
387
+ readWaitMs: readWait.summarize(),
388
+ ...(mode === 'per-packet'
389
+ ? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
390
+ : {}),
391
+ };
392
+ },
393
+ };
394
+ };
395
+
396
+ type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
397
+
233
398
  function getDeviceDisplayName(device?: Device | null) {
234
399
  return device?.name || device?.localName || null;
235
400
  }
236
401
 
402
+ // The color is only in the primary advertisement, and the name only in the scan
403
+ // response, so the callback a scan keeps may not carry it. A connected device stops
404
+ // advertising. Keep the last valid color per device for the life of the process.
405
+ // iOS reports connected peripherals with lowercased ids, so key case-insensitively.
406
+ const bleColorCodesById = new Map<string, string>();
407
+
408
+ function getManufacturerDataLength(device?: Device | null) {
409
+ return device?.manufacturerData ? Buffer.from(device.manufacturerData, 'base64').length : 0;
410
+ }
411
+
412
+ function rememberBleColorCode(device?: Device | null) {
413
+ if (!device?.id || !device.manufacturerData) return;
414
+ const colorCode = parseOnekeyBleColorCode(Buffer.from(device.manufacturerData, 'base64'));
415
+ const key = device.id.toLowerCase();
416
+ if (colorCode && bleColorCodesById.get(key) !== colorCode) {
417
+ bleColorCodesById.set(key, colorCode);
418
+ Log?.debug('[ReactNativeBleTransport] BLE color code', {
419
+ deviceId: device.id,
420
+ bleColorCode: colorCode,
421
+ });
422
+ }
423
+ }
424
+
425
+ function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
426
+ const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
427
+ return bleColorCode ? ({ ...device, bleColorCode } as IOneKeyDevice) : device;
428
+ }
429
+
237
430
  const IOS_REQUEST_MTU = 247;
238
431
  const ANDROID_REQUEST_MTU = 517;
239
432
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
433
+ /**
434
+ * Android 17 maps CONNECTION_PRIORITY_HIGH to 11.25-15 ms with peripheral latency 1. OneKey BLE
435
+ * firmware accepts any latency at its 15 ms interval, and latency 1 roughly halves Protocol V2
436
+ * FileWrite throughput. BLE 1.0.23 requests 15 ms with latency 0 by itself; older BLE firmware
437
+ * asks for 15-30 ms or nothing and has not been measured on Android 17 without HIGH.
438
+ */
439
+ const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
440
+
441
+ const shouldRequestAndroidHighConnectionPriority = () => {
442
+ if (Platform.OS !== 'android') return false;
443
+ const { androidHighConnectionPriority } = protocolV2BleTuning;
444
+ if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
445
+ const apiLevel = Number(Platform.Version);
446
+ // Unknown versions keep the long-standing HIGH request.
447
+ return (
448
+ !Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
449
+ );
450
+ };
240
451
 
241
452
  const getRequestedBleMtu = () =>
242
453
  Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
@@ -356,7 +567,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
356
567
 
357
568
  type NegotiatedMtuResult = { device: Device; timedOut: boolean };
358
569
 
359
- export type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
570
+ export type IOneKeyDevice = OneKeyDeviceInfoBase &
571
+ Device &
572
+ Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
360
573
 
361
574
  const tryToGetConfiguration = (device: Device) => {
362
575
  if (!device || !device.serviceUUIDs) return null;
@@ -560,6 +773,13 @@ export default class ReactNativeBleTransport {
560
773
 
561
774
  private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
562
775
 
776
+ /** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
777
+ private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
778
+
779
+ private protocolV2FrameWriteCounter = 0;
780
+
781
+ private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
782
+
563
783
  private nextMonitorToken = 1;
564
784
 
565
785
  /** Serializes transport lifecycle changes for the same physical device. */
@@ -855,7 +1075,7 @@ export default class ReactNativeBleTransport {
855
1075
  }).then(() => {
856
1076
  this.scanCleanups.delete(cancelScan);
857
1077
  if (error) reject(error);
858
- else resolve(deviceList);
1078
+ else resolve(deviceList.map(withBleColorCode));
859
1079
  });
860
1080
  return scanCleanup;
861
1081
  };
@@ -900,6 +1120,9 @@ export default class ReactNativeBleTransport {
900
1120
  return;
901
1121
  }
902
1122
 
1123
+ // The native scan is filtered to the OneKey communication service, so an
1124
+ // unnamed iOS advertisement rejected below can still carry the color.
1125
+ rememberBleColorCode(device);
903
1126
  const displayName = getDeviceDisplayName(device);
904
1127
  // iOS may report a service-only advertisement before the named scan response.
905
1128
  // Do not cache that incomplete advertisement as an unknown device.
@@ -965,6 +1188,9 @@ export default class ReactNativeBleTransport {
965
1188
  deviceId: device.id,
966
1189
  name: displayName,
967
1190
  serviceUUIDs: device.serviceUUIDs,
1191
+ // 5 = advertises a color slot; 4 = BLE firmware before 1.0.23.
1192
+ manufacturerDataLength: getManufacturerDataLength(device),
1193
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
968
1194
  });
969
1195
  }
970
1196
  };
@@ -1524,16 +1750,34 @@ export default class ReactNativeBleTransport {
1524
1750
  return subscription;
1525
1751
  }
1526
1752
 
1527
- async release(uuid: string, onclose = false) {
1528
- return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose));
1753
+ async release(uuid: string, onclose = false, keepSession = false) {
1754
+ return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose, keepSession));
1529
1755
  }
1530
1756
 
1531
- private async releaseUnlocked(uuid: string, onclose = false) {
1532
- await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1757
+ private async releaseUnlocked(uuid: string, onclose = false, keepSession = false) {
1758
+ const transport = transportCache[uuid];
1759
+ if (
1760
+ keepSession &&
1761
+ !onclose &&
1762
+ transport &&
1763
+ this.deviceProtocol.get(uuid) === 'V2' &&
1764
+ !this.protocolV2FrameWrites.has(uuid) &&
1765
+ !this.protocolV2FramePromises.has(uuid)
1766
+ ) {
1767
+ // Keep the monitor generation and V2 session together when reusing the link.
1768
+ await this.runNativeTeardown(uuid, this.blePlxManager, () =>
1769
+ this.restoreAndroidConnectionPriority(uuid, transport)
1770
+ );
1771
+ return true;
1772
+ }
1773
+ const reason = 'React Native BLE transport released';
1774
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
1775
+ await this.protocolV2Links.invalidateLink(uuid, reason);
1533
1776
  return this.releaseNative(uuid, onclose);
1534
1777
  }
1535
1778
 
1536
1779
  private async releaseNative(uuid: string, onclose = false) {
1780
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1537
1781
  const transport = transportCache[uuid];
1538
1782
  const manager = this.blePlxManager;
1539
1783
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1954,7 +2198,13 @@ export default class ReactNativeBleTransport {
1954
2198
  }
1955
2199
 
1956
2200
  private async disconnectUnlocked(session: string) {
1957
- await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
2201
+ // The next link starts at the stack's default priority; a cached HIGH or a pending
2202
+ // Balanced restore from this link must not carry over to it.
2203
+ this.clearAndroidPriorityResetTimer(session);
2204
+ this.androidHighPriorityDevices.delete(session);
2205
+ const reason = 'React Native BLE transport disconnected';
2206
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
2207
+ await this.protocolV2Links.invalidateLink(session, reason);
1958
2208
  const transport = transportCache[session];
1959
2209
  const manager = this.blePlxManager;
1960
2210
  const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
@@ -2392,12 +2642,7 @@ export default class ReactNativeBleTransport {
2392
2642
  new Promise<never>((_, reject) => {
2393
2643
  timer = setTimeout(() => {
2394
2644
  timedOut = true;
2395
- reject(
2396
- ERRORS.TypedError(
2397
- HardwareErrorCode.BleWriteCharacteristicError,
2398
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2399
- )
2400
- );
2645
+ reject(createWedgedWriteError());
2401
2646
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2402
2647
  }),
2403
2648
  ]);
@@ -2431,6 +2676,7 @@ export default class ReactNativeBleTransport {
2431
2676
  consecutiveWriteTimeouts: timeouts,
2432
2677
  });
2433
2678
 
2679
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2434
2680
  const wedged = transportCache[uuid];
2435
2681
  this.disconnect(uuid).catch(error => {
2436
2682
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2458,6 +2704,8 @@ export default class ReactNativeBleTransport {
2458
2704
  const manager = this.blePlxManager;
2459
2705
  this.blePlxManager = undefined;
2460
2706
  const reason = 'React Native BLE manager reset';
2707
+ // Cancel through the manager that started each frame before destroy() drops its queue.
2708
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2461
2709
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2462
2710
  // each cached session before clearing generations so Core cannot retain a
2463
2711
  // silently stale connection for an unrelated device.
@@ -2520,17 +2768,13 @@ export default class ReactNativeBleTransport {
2520
2768
  private createProtocolMismatchError(expected: ProtocolType) {
2521
2769
  // A protocol probe miss alone does not prove that the OS bond is stale.
2522
2770
  // Native authentication/encryption failures are mapped separately.
2523
- return ERRORS.TypedError(
2524
- HardwareErrorCode.RuntimeError,
2525
- `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`
2526
- );
2771
+ return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed, undefined, {
2772
+ expectedProtocol: expected,
2773
+ });
2527
2774
  }
2528
2775
 
2529
2776
  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
- );
2777
+ return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed);
2534
2778
  }
2535
2779
 
2536
2780
  private clearProbeProtocol(uuid: string, protocol: ProtocolType) {
@@ -2933,22 +3177,204 @@ export default class ReactNativeBleTransport {
2933
3177
  androidPacketLength: tuning.androidPacketLength,
2934
3178
  mtu: transport.mtuSize,
2935
3179
  });
2936
- await writeProtocolV2BleFrame({
2937
- frame,
2938
- packetCapacity,
2939
- assertActive: assertCurrentGeneration,
2940
- signal: context.signal,
2941
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2942
- wait: delay,
2943
- writePacket: packet =>
2944
- this.writeProtocolV2Packet(
2945
- uuid,
2946
- transport,
2947
- Buffer.from(packet).toString('base64'),
2948
- context,
2949
- assertCurrentGeneration
2950
- ),
3180
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3181
+ const startedAt = perf ? nowMs() : 0;
3182
+ const nativeFrameWriter =
3183
+ frame.length > packetCapacity
3184
+ ? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
3185
+ : undefined;
3186
+ perf?.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
3187
+ if (nativeFrameWriter) {
3188
+ await this.writeProtocolV2NativeFrame(
3189
+ uuid,
3190
+ transport,
3191
+ nativeFrameWriter,
3192
+ frame,
3193
+ packetCapacity,
3194
+ context,
3195
+ assertCurrentGeneration
3196
+ );
3197
+ } else {
3198
+ await writeProtocolV2BleFrame({
3199
+ frame,
3200
+ packetCapacity,
3201
+ assertActive: assertCurrentGeneration,
3202
+ signal: context.signal,
3203
+ abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
3204
+ wait: delay,
3205
+ writePacket: async packet => {
3206
+ const packetStartedAt = perf ? nowMs() : 0;
3207
+ await this.writeProtocolV2Packet(
3208
+ uuid,
3209
+ transport,
3210
+ Buffer.from(packet).toString('base64'),
3211
+ context,
3212
+ assertCurrentGeneration
3213
+ );
3214
+ perf?.recordPacket(nowMs() - packetStartedAt);
3215
+ },
3216
+ });
3217
+ }
3218
+ perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
3219
+ }
3220
+
3221
+ /**
3222
+ * The native frame write only replaces the per-packet loop where its JS<->native round trips
3223
+ * dominate: multi-packet (checked by the caller) high-throughput frames written without response.
3224
+ */
3225
+ private resolveProtocolV2NativeFrameWriter(
3226
+ transport: BleTransport,
3227
+ context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
3228
+ nativeFrameWrite: boolean
3229
+ ): ProtocolV2NativeFrameWriter | undefined {
3230
+ if (!context.highThroughput || !nativeFrameWrite) return undefined;
3231
+ if (
3232
+ shouldWriteProtocolV2WithResponse({
3233
+ platform: Platform.OS,
3234
+ highThroughput: context.highThroughput,
3235
+ requestedWithResponse: context.writeWithResponse,
3236
+ characteristic: transport.writeCharacteristic,
3237
+ })
3238
+ ) {
3239
+ return undefined;
3240
+ }
3241
+ if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
3242
+ return getProtocolV2NativeFrameWriter(this.blePlxManager);
3243
+ }
3244
+
3245
+ /**
3246
+ * Writes one frame with a single native call that sends its packets in order without response.
3247
+ * Nothing here retries it: a resend could duplicate bytes the device already received. The
3248
+ * native transaction is cancelled on abort, watchdog expiry and link teardown so the native
3249
+ * side stops writing a frame nobody waits for any more; a generation change detected after
3250
+ * the frame completes still fails the write.
3251
+ */
3252
+ private async writeProtocolV2NativeFrame(
3253
+ uuid: string,
3254
+ transport: BleTransport,
3255
+ manager: ProtocolV2NativeFrameWriter,
3256
+ frame: Uint8Array,
3257
+ packetCapacity: number,
3258
+ context: ProtocolV2CallContext,
3259
+ assertCurrentGeneration: () => void
3260
+ ) {
3261
+ const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
3262
+ assertCurrentGeneration();
3263
+ if (context.signal.aborted) {
3264
+ throw new Error(abortMessage);
3265
+ }
3266
+
3267
+ this.protocolV2FrameWriteCounter += 1;
3268
+ const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
3269
+ let cancelError: Error | undefined;
3270
+ let rejectCancelled: (error: Error) => void = () => undefined;
3271
+ const cancelled = new Promise<never>((_, reject) => {
3272
+ rejectCancelled = reject;
2951
3273
  });
3274
+ const active: ActiveProtocolV2FrameWrite = {
3275
+ generation: context.generation,
3276
+ cancel: error => {
3277
+ if (cancelError) return;
3278
+ cancelError = error;
3279
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3280
+ this.protocolV2FrameWrites.delete(uuid);
3281
+ }
3282
+ rejectCancelled(error);
3283
+ this.cancelNativeTransaction(manager, transactionId);
3284
+ },
3285
+ };
3286
+ // Same rule as writeBlePacket: a superseded generation must not tear down the current link.
3287
+ const isCurrentOwner = () => {
3288
+ try {
3289
+ assertCurrentGeneration();
3290
+ return !context.signal.aborted;
3291
+ } catch {
3292
+ return false;
3293
+ }
3294
+ };
3295
+ const onAbort = () => active.cancel(new Error(abortMessage));
3296
+ let timer: ReturnType<typeof setTimeout> | undefined;
3297
+ try {
3298
+ const nativeWrite = Promise.resolve(
3299
+ manager.writeCharacteristicWithoutResponseFrame(
3300
+ transport.writeCharacteristic.id,
3301
+ Buffer.from(frame).toString('base64'),
3302
+ packetCapacity,
3303
+ transactionId
3304
+ )
3305
+ );
3306
+ // A cancelled or timed-out frame still settles natively later; that outcome is ignored.
3307
+ nativeWrite.catch(() => undefined);
3308
+ this.protocolV2FrameWrites.set(uuid, active);
3309
+ context.signal.addEventListener('abort', onAbort);
3310
+ timer = setTimeout(() => {
3311
+ const owner = isCurrentOwner();
3312
+ active.cancel(createWedgedWriteError());
3313
+ if (owner) {
3314
+ this.tearDownWedgedLink(uuid);
3315
+ } else {
3316
+ Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3317
+ }
3318
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
3319
+ await Promise.race([nativeWrite, cancelled]);
3320
+ } catch (error) {
3321
+ if (cancelError) throw cancelError;
3322
+ if (isNativeBleDisconnectError(error)) {
3323
+ throw toBleDisconnectHardwareError(error);
3324
+ }
3325
+ throw ERRORS.TypedError(
3326
+ HardwareErrorCode.BleWriteCharacteristicError,
3327
+ getNativeBleErrorReason(error)
3328
+ );
3329
+ } finally {
3330
+ if (timer) clearTimeout(timer);
3331
+ context.signal.removeEventListener('abort', onAbort);
3332
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3333
+ this.protocolV2FrameWrites.delete(uuid);
3334
+ }
3335
+ }
3336
+
3337
+ this.writeTimeoutCounts.delete(uuid);
3338
+ try {
3339
+ assertCurrentGeneration();
3340
+ } catch (error) {
3341
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
3342
+ }
3343
+ if (cancelError) throw cancelError;
3344
+ }
3345
+
3346
+ /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
3347
+ private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
3348
+ const active = this.protocolV2FrameWrites.get(uuid);
3349
+ if (!active || (generation !== undefined && active.generation !== generation)) return;
3350
+ active.cancel(error);
3351
+ }
3352
+
3353
+ private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
3354
+ const logFailure = (error: unknown) =>
3355
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
3356
+ error: error instanceof Error ? error.message : String(error),
3357
+ });
3358
+ try {
3359
+ Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
3360
+ } catch (error) {
3361
+ logFailure(error);
3362
+ }
3363
+ }
3364
+
3365
+ private getProtocolV2FileWritePerf(uuid: string, context: ProtocolV2CallContext) {
3366
+ return context.messageName === 'FilesystemFileWrite'
3367
+ ? this.protocolV2FileWritePerfs.get(uuid)
3368
+ : undefined;
3369
+ }
3370
+
3371
+ /** Returns true the first time `signature` is seen for `uuid` on this link. */
3372
+ private markProtocolV2LogSignature(uuid: string, signature: string): boolean {
3373
+ const signatures = this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3374
+ if (signatures.has(signature)) return false;
3375
+ signatures.add(signature);
3376
+ this.protocolV2HighVolumeLogSignatures.set(uuid, signatures);
3377
+ return true;
2952
3378
  }
2953
3379
 
2954
3380
  private async callProtocolV2(
@@ -2985,11 +3411,7 @@ export default class ReactNativeBleTransport {
2985
3411
  const logSignature = `${name}:${writeMode}:${String(
2986
3412
  currentTransport.mtuSize
2987
3413
  )}:${packetCapacity}`;
2988
- const loggedSignatures =
2989
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
2990
- if (!loggedSignatures.has(logSignature)) {
2991
- loggedSignatures.add(logSignature);
2992
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3414
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
2993
3415
  Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
2994
3416
  name,
2995
3417
  writeMode,
@@ -2997,20 +3419,47 @@ export default class ReactNativeBleTransport {
2997
3419
  packetCapacity,
2998
3420
  });
2999
3421
  }
3422
+ const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
3423
+ currentTransport,
3424
+ { highThroughput: true, writeWithResponse: options?.writeWithResponse },
3425
+ tuning.nativeFrameWrite
3426
+ )
3427
+ ? 'native-frame'
3428
+ : 'per-packet';
3429
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
3430
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
3431
+ platform: Platform.OS,
3432
+ mode: frameWriteMode,
3433
+ nativeFrameWrite: tuning.nativeFrameWrite,
3434
+ nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
3435
+ packetCapacity,
3436
+ });
3437
+ }
3000
3438
  }
3001
3439
 
3002
3440
  if (highThroughputWrite) {
3003
3441
  await this.enableAndroidHighConnectionPriority(uuid);
3004
3442
  }
3005
3443
 
3444
+ const fileWritePerf =
3445
+ name === 'FilesystemFileWrite' && options?.fileWritePipeline
3446
+ ? createProtocolV2FileWritePerf()
3447
+ : undefined;
3448
+ if (fileWritePerf) {
3449
+ this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
3450
+ }
3451
+ let fileWriteOk = false;
3452
+
3006
3453
  try {
3007
- return await this.protocolV2Links.call(
3454
+ const response = await this.protocolV2Links.call(
3008
3455
  uuid,
3009
3456
  () => this.createProtocolV2Adapter(uuid),
3010
3457
  name,
3011
3458
  data,
3012
3459
  callOptions
3013
3460
  );
3461
+ fileWriteOk = response.type !== 'Failure';
3462
+ return response;
3014
3463
  } catch (e) {
3015
3464
  Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
3016
3465
  if (
@@ -3031,6 +3480,15 @@ export default class ReactNativeBleTransport {
3031
3480
  if (highThroughputWrite) {
3032
3481
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3033
3482
  }
3483
+ if (fileWritePerf) {
3484
+ if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
3485
+ this.protocolV2FileWritePerfs.delete(uuid);
3486
+ }
3487
+ Log?.debug(
3488
+ '[ReactNativeBleTransport] FileWrite perf',
3489
+ fileWritePerf.summarize(fileWriteOk)
3490
+ );
3491
+ }
3034
3492
  }
3035
3493
  }
3036
3494
 
@@ -3069,6 +3527,15 @@ export default class ReactNativeBleTransport {
3069
3527
 
3070
3528
  this.clearAndroidPriorityResetTimer(uuid);
3071
3529
  if (this.androidHighPriorityDevices.has(uuid)) return;
3530
+ if (!shouldRequestAndroidHighConnectionPriority()) {
3531
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
3532
+ Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
3533
+ apiLevel: Platform.Version,
3534
+ setting: protocolV2BleTuning.androidHighConnectionPriority,
3535
+ });
3536
+ }
3537
+ return;
3538
+ }
3072
3539
 
3073
3540
  const transport = transportCache[uuid];
3074
3541
  if (!transport) return;
@@ -3147,15 +3614,20 @@ export default class ReactNativeBleTransport {
3147
3614
  assertCurrentGeneration
3148
3615
  );
3149
3616
  },
3150
- readFrame: async () => {
3617
+ readFrame: async (context: ProtocolV2CallContext) => {
3151
3618
  assertCurrentGeneration();
3619
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3620
+ const startedAt = perf ? nowMs() : 0;
3152
3621
  const rxFrame = await this.readProtocolV2Frame(uuid);
3622
+ perf?.recordReadWait(nowMs() - startedAt);
3153
3623
  if (!(rxFrame instanceof Uint8Array)) {
3154
3624
  throw new Error('Protocol V2 response is not Uint8Array');
3155
3625
  }
3156
3626
  return rxFrame;
3157
3627
  },
3158
3628
  reset: (reason: string) => {
3629
+ // The frame belongs to this link even after a newer monitor generation took over.
3630
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
3159
3631
  if (this.monitorTokens.get(uuid) !== generation) return;
3160
3632
  this.protocolV2Assemblers.get(uuid)?.reset();
3161
3633
  this.rejectProtocolV2Frames(uuid, new Error(reason));