@onekeyfe/hd-transport-react-native 1.2.8-alpha.121 → 1.2.8-alpha.123

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
@@ -168,6 +168,11 @@ const isWedgedWriteError = (error: unknown): boolean =>
168
168
  (error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
169
169
  typeof (error as { message?: unknown })?.message === 'string' &&
170
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
+ );
171
176
  const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
172
177
  const code = (error as { errorCode?: unknown })?.errorCode;
173
178
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
@@ -192,6 +197,16 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
192
197
  export type ProtocolV2BleTuning = {
193
198
  iosPacketLength?: number;
194
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';
195
210
  };
196
211
 
197
212
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -199,6 +214,8 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
199
214
  const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
200
215
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
201
216
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
217
+ nativeFrameWrite: true,
218
+ androidHighConnectionPriority: 'auto',
202
219
  };
203
220
 
204
221
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -219,6 +236,15 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
219
236
  tuning.androidPacketLength,
220
237
  protocolV2BleTuning.androidPacketLength
221
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,
222
248
  };
223
249
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
224
250
  }
@@ -232,6 +258,140 @@ export function getProtocolV2BleTuning() {
232
258
  return { ...protocolV2BleTuning };
233
259
  }
234
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
+
235
395
  function getDeviceDisplayName(device?: Device | null) {
236
396
  return device?.name || device?.localName || null;
237
397
  }
@@ -267,6 +427,24 @@ function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
267
427
  const IOS_REQUEST_MTU = 247;
268
428
  const ANDROID_REQUEST_MTU = 517;
269
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
+ };
270
448
 
271
449
  const getRequestedBleMtu = () =>
272
450
  Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
@@ -592,6 +770,13 @@ export default class ReactNativeBleTransport {
592
770
 
593
771
  private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
594
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
+
595
780
  private nextMonitorToken = 1;
596
781
 
597
782
  /** Serializes transport lifecycle changes for the same physical device. */
@@ -1567,11 +1752,14 @@ export default class ReactNativeBleTransport {
1567
1752
  }
1568
1753
 
1569
1754
  private async releaseUnlocked(uuid: string, onclose = false) {
1570
- await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1755
+ const reason = 'React Native BLE transport released';
1756
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
1757
+ await this.protocolV2Links.invalidateLink(uuid, reason);
1571
1758
  return this.releaseNative(uuid, onclose);
1572
1759
  }
1573
1760
 
1574
1761
  private async releaseNative(uuid: string, onclose = false) {
1762
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1575
1763
  const transport = transportCache[uuid];
1576
1764
  const manager = this.blePlxManager;
1577
1765
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1992,7 +2180,13 @@ export default class ReactNativeBleTransport {
1992
2180
  }
1993
2181
 
1994
2182
  private async disconnectUnlocked(session: string) {
1995
- await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
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);
1996
2190
  const transport = transportCache[session];
1997
2191
  const manager = this.blePlxManager;
1998
2192
  const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
@@ -2430,12 +2624,7 @@ export default class ReactNativeBleTransport {
2430
2624
  new Promise<never>((_, reject) => {
2431
2625
  timer = setTimeout(() => {
2432
2626
  timedOut = true;
2433
- reject(
2434
- ERRORS.TypedError(
2435
- HardwareErrorCode.BleWriteCharacteristicError,
2436
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2437
- )
2438
- );
2627
+ reject(createWedgedWriteError());
2439
2628
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2440
2629
  }),
2441
2630
  ]);
@@ -2469,6 +2658,7 @@ export default class ReactNativeBleTransport {
2469
2658
  consecutiveWriteTimeouts: timeouts,
2470
2659
  });
2471
2660
 
2661
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2472
2662
  const wedged = transportCache[uuid];
2473
2663
  this.disconnect(uuid).catch(error => {
2474
2664
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2496,6 +2686,8 @@ export default class ReactNativeBleTransport {
2496
2686
  const manager = this.blePlxManager;
2497
2687
  this.blePlxManager = undefined;
2498
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)));
2499
2691
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2500
2692
  // each cached session before clearing generations so Core cannot retain a
2501
2693
  // silently stale connection for an unrelated device.
@@ -2967,22 +3159,204 @@ export default class ReactNativeBleTransport {
2967
3159
  androidPacketLength: tuning.androidPacketLength,
2968
3160
  mtu: transport.mtuSize,
2969
3161
  });
2970
- await writeProtocolV2BleFrame({
2971
- frame,
2972
- packetCapacity,
2973
- assertActive: assertCurrentGeneration,
2974
- signal: context.signal,
2975
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2976
- wait: delay,
2977
- writePacket: packet =>
2978
- this.writeProtocolV2Packet(
2979
- uuid,
2980
- transport,
2981
- Buffer.from(packet).toString('base64'),
2982
- context,
2983
- assertCurrentGeneration
2984
- ),
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;
2985
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;
2986
3360
  }
2987
3361
 
2988
3362
  private async callProtocolV2(
@@ -3019,11 +3393,7 @@ export default class ReactNativeBleTransport {
3019
3393
  const logSignature = `${name}:${writeMode}:${String(
3020
3394
  currentTransport.mtuSize
3021
3395
  )}:${packetCapacity}`;
3022
- const loggedSignatures =
3023
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3024
- if (!loggedSignatures.has(logSignature)) {
3025
- loggedSignatures.add(logSignature);
3026
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3396
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
3027
3397
  Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
3028
3398
  name,
3029
3399
  writeMode,
@@ -3031,20 +3401,47 @@ export default class ReactNativeBleTransport {
3031
3401
  packetCapacity,
3032
3402
  });
3033
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
+ }
3034
3420
  }
3035
3421
 
3036
3422
  if (highThroughputWrite) {
3037
3423
  await this.enableAndroidHighConnectionPriority(uuid);
3038
3424
  }
3039
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
+
3040
3435
  try {
3041
- return await this.protocolV2Links.call(
3436
+ const response = await this.protocolV2Links.call(
3042
3437
  uuid,
3043
3438
  () => this.createProtocolV2Adapter(uuid),
3044
3439
  name,
3045
3440
  data,
3046
3441
  callOptions
3047
3442
  );
3443
+ fileWriteOk = response.type !== 'Failure';
3444
+ return response;
3048
3445
  } catch (e) {
3049
3446
  Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
3050
3447
  if (
@@ -3065,6 +3462,15 @@ export default class ReactNativeBleTransport {
3065
3462
  if (highThroughputWrite) {
3066
3463
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3067
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
+ }
3068
3474
  }
3069
3475
  }
3070
3476
 
@@ -3103,6 +3509,15 @@ export default class ReactNativeBleTransport {
3103
3509
 
3104
3510
  this.clearAndroidPriorityResetTimer(uuid);
3105
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
+ }
3106
3521
 
3107
3522
  const transport = transportCache[uuid];
3108
3523
  if (!transport) return;
@@ -3181,15 +3596,20 @@ export default class ReactNativeBleTransport {
3181
3596
  assertCurrentGeneration
3182
3597
  );
3183
3598
  },
3184
- readFrame: async () => {
3599
+ readFrame: async (context: ProtocolV2CallContext) => {
3185
3600
  assertCurrentGeneration();
3601
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3602
+ const startedAt = perf ? nowMs() : 0;
3186
3603
  const rxFrame = await this.readProtocolV2Frame(uuid);
3604
+ perf?.recordReadWait(nowMs() - startedAt);
3187
3605
  if (!(rxFrame instanceof Uint8Array)) {
3188
3606
  throw new Error('Protocol V2 response is not Uint8Array');
3189
3607
  }
3190
3608
  return rxFrame;
3191
3609
  },
3192
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);
3193
3613
  if (this.monitorTokens.get(uuid) !== generation) return;
3194
3614
  this.protocolV2Assemblers.get(uuid)?.reset();
3195
3615
  this.rejectProtocolV2Frames(uuid, new Error(reason));