@onekeyfe/hd-transport-react-native 1.2.8-alpha.114 → 1.2.8-alpha.116

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
@@ -10,7 +10,6 @@ import {
10
10
  import ByteBuffer from 'bytebuffer';
11
11
  import transport, {
12
12
  type OneKeyDeviceInfoBase,
13
- type OneKeyMobileDeviceInfo,
14
13
  PROTOCOL_V1_MESSAGE_HEADER_SIZE,
15
14
  PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
16
15
  PROTOCOL_V2_CHANNEL_BLE_UART,
@@ -29,7 +28,6 @@ import {
29
28
  HardwareErrorCode,
30
29
  createDeferred,
31
30
  isOnekeyBluetoothDevice,
32
- parseOnekeyBleColorCode,
33
31
  } from '@onekeyfe/hd-shared';
34
32
 
35
33
  import { getConnectedDeviceIds, onDeviceBondState, pairDevice } from './BleManager';
@@ -192,6 +190,11 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
192
190
  export type ProtocolV2BleTuning = {
193
191
  iosPacketLength?: number;
194
192
  androidPacketLength?: number;
193
+ /**
194
+ * Write each multi-packet high-throughput frame with one native call when the native
195
+ * BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
196
+ */
197
+ nativeFrameWrite?: boolean;
195
198
  };
196
199
 
197
200
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -199,6 +202,7 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
199
202
  const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
200
203
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
201
204
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
205
+ nativeFrameWrite: true,
202
206
  };
203
207
 
204
208
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -219,6 +223,10 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
219
223
  tuning.androidPacketLength,
220
224
  protocolV2BleTuning.androidPacketLength
221
225
  ),
226
+ nativeFrameWrite:
227
+ typeof tuning.nativeFrameWrite === 'boolean'
228
+ ? tuning.nativeFrameWrite
229
+ : protocolV2BleTuning.nativeFrameWrite,
222
230
  };
223
231
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
224
232
  }
@@ -232,36 +240,140 @@ export function getProtocolV2BleTuning() {
232
240
  return { ...protocolV2BleTuning };
233
241
  }
234
242
 
235
- function getDeviceDisplayName(device?: Device | null) {
236
- return device?.name || device?.localName || null;
237
- }
243
+ /**
244
+ * Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
245
+ * the unpatched release, so the shape is declared here and probed at runtime.
246
+ */
247
+ type ProtocolV2NativeFrameWriteExtension = {
248
+ isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
249
+ writeCharacteristicWithoutResponseFrame?: (
250
+ characteristicIdentifier: number,
251
+ base64Frame: string,
252
+ packetSize: number,
253
+ transactionId: string
254
+ ) => Promise<void>;
255
+ };
238
256
 
239
- // The color is only in the primary advertisement, and the name only in the scan
240
- // response, so the callback a scan keeps may not carry it. A connected device stops
241
- // advertising. Keep the last valid color per device for the life of the process.
242
- // iOS reports connected peripherals with lowercased ids, so key case-insensitively.
243
- const bleColorCodesById = new Map<string, string>();
257
+ type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
244
258
 
245
- function getManufacturerDataLength(device?: Device | null) {
246
- return device?.manufacturerData ? Buffer.from(device.manufacturerData, 'base64').length : 0;
247
- }
259
+ type ActiveProtocolV2FrameWrite = {
260
+ transactionId: string;
261
+ generation: number;
262
+ cancel: (error: Error) => void;
263
+ };
248
264
 
249
- function rememberBleColorCode(device?: Device | null) {
250
- if (!device?.id || !device.manufacturerData) return;
251
- const colorCode = parseOnekeyBleColorCode(Buffer.from(device.manufacturerData, 'base64'));
252
- const key = device.id.toLowerCase();
253
- if (colorCode && bleColorCodesById.get(key) !== colorCode) {
254
- bleColorCodesById.set(key, colorCode);
255
- Log?.debug('[ReactNativeBleTransport] BLE color code', {
256
- deviceId: device.id,
257
- bleColorCode: colorCode,
258
- });
265
+ /**
266
+ * A newer JS bundle can run on an older native binary that ships the JS wrapper without the
267
+ * native method, so support comes from the wrapper's native check, never from its presence.
268
+ */
269
+ const getProtocolV2NativeFrameWriter = (
270
+ manager: BlePlxManager | undefined
271
+ ): ProtocolV2NativeFrameWriter | undefined => {
272
+ const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
273
+ if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
274
+ return undefined;
259
275
  }
260
- }
276
+ try {
277
+ return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
278
+ ? (candidate as ProtocolV2NativeFrameWriter)
279
+ : undefined;
280
+ } catch {
281
+ return undefined;
282
+ }
283
+ };
261
284
 
262
- function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
263
- const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
264
- return bleColorCode ? ({ ...device, bleColorCode } as IOneKeyDevice) : device;
285
+ const getNativeBleErrorReason = (error: unknown): string | undefined => {
286
+ const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
287
+ if (typeof reason === 'string' && reason) return reason;
288
+ return typeof message === 'string' && message ? message : undefined;
289
+ };
290
+
291
+ type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
292
+
293
+ const nowMs = () =>
294
+ typeof performance !== 'undefined' && typeof performance.now === 'function'
295
+ ? performance.now()
296
+ : Date.now();
297
+
298
+ const roundMs = (ms: number) => Math.round(ms * 10) / 10;
299
+
300
+ /** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
301
+ const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
302
+
303
+ const createDurationStats = () => {
304
+ let total = 0;
305
+ let count = 0;
306
+ let max = 0;
307
+ return {
308
+ add(ms: number) {
309
+ total += ms;
310
+ count += 1;
311
+ max = Math.max(max, ms);
312
+ },
313
+ summarize: () => ({
314
+ total: roundMs(total),
315
+ avg: count ? roundMs(total / count) : 0,
316
+ max: roundMs(max),
317
+ }),
318
+ };
319
+ };
320
+
321
+ /** Scalar-only timing of one pipelined FilesystemFileWrite call. */
322
+ const createProtocolV2FileWritePerf = () => {
323
+ const startedAt = nowMs();
324
+ let nativeFrames = 0;
325
+ let frames = 0;
326
+ let packets = 0;
327
+ let frameBytes = 0;
328
+ const write = createDurationStats();
329
+ const readWait = createDurationStats();
330
+ const packet = createDurationStats();
331
+ const packetHistogram = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.map(() => 0).concat(0);
332
+
333
+ return {
334
+ /** Called before each frame write so a frame that fails still reports its mode. */
335
+ startFrame(mode: ProtocolV2FrameWriteMode) {
336
+ if (mode === 'native-frame') nativeFrames += 1;
337
+ },
338
+ recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
339
+ frames += 1;
340
+ packets += framePackets;
341
+ frameBytes += bytes;
342
+ write.add(elapsedMs);
343
+ },
344
+ recordPacket(elapsedMs: number) {
345
+ packet.add(elapsedMs);
346
+ const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
347
+ packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
348
+ },
349
+ recordReadWait(elapsedMs: number) {
350
+ readWait.add(elapsedMs);
351
+ },
352
+ summarize(ok: boolean) {
353
+ const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
354
+ const packetStats = packet.summarize();
355
+ return {
356
+ platform: Platform.OS,
357
+ mode,
358
+ ok,
359
+ frames,
360
+ packets,
361
+ frameBytes,
362
+ elapsedMs: roundMs(nowMs() - startedAt),
363
+ writeMs: write.summarize(),
364
+ readWaitMs: readWait.summarize(),
365
+ ...(mode === 'per-packet'
366
+ ? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
367
+ : {}),
368
+ };
369
+ },
370
+ };
371
+ };
372
+
373
+ type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
374
+
375
+ function getDeviceDisplayName(device?: Device | null) {
376
+ return device?.name || device?.localName || null;
265
377
  }
266
378
 
267
379
  const IOS_REQUEST_MTU = 247;
@@ -386,9 +498,7 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
386
498
 
387
499
  type NegotiatedMtuResult = { device: Device; timedOut: boolean };
388
500
 
389
- export type IOneKeyDevice = OneKeyDeviceInfoBase &
390
- Device &
391
- Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
501
+ export type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
392
502
 
393
503
  const tryToGetConfiguration = (device: Device) => {
394
504
  if (!device || !device.serviceUUIDs) return null;
@@ -592,6 +702,13 @@ export default class ReactNativeBleTransport {
592
702
 
593
703
  private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
594
704
 
705
+ /** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
706
+ private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
707
+
708
+ private protocolV2FrameWriteCounter = 0;
709
+
710
+ private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
711
+
595
712
  private nextMonitorToken = 1;
596
713
 
597
714
  /** Serializes transport lifecycle changes for the same physical device. */
@@ -887,7 +1004,7 @@ export default class ReactNativeBleTransport {
887
1004
  }).then(() => {
888
1005
  this.scanCleanups.delete(cancelScan);
889
1006
  if (error) reject(error);
890
- else resolve(deviceList.map(withBleColorCode));
1007
+ else resolve(deviceList);
891
1008
  });
892
1009
  return scanCleanup;
893
1010
  };
@@ -932,9 +1049,6 @@ export default class ReactNativeBleTransport {
932
1049
  return;
933
1050
  }
934
1051
 
935
- // The native scan is filtered to the OneKey communication service, so an
936
- // unnamed iOS advertisement rejected below can still carry the color.
937
- rememberBleColorCode(device);
938
1052
  const displayName = getDeviceDisplayName(device);
939
1053
  // iOS may report a service-only advertisement before the named scan response.
940
1054
  // Do not cache that incomplete advertisement as an unknown device.
@@ -1000,9 +1114,6 @@ export default class ReactNativeBleTransport {
1000
1114
  deviceId: device.id,
1001
1115
  name: displayName,
1002
1116
  serviceUUIDs: device.serviceUUIDs,
1003
- // 5 = advertises a color slot; 4 = BLE firmware before 1.0.23.
1004
- manufacturerDataLength: getManufacturerDataLength(device),
1005
- bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
1006
1117
  });
1007
1118
  }
1008
1119
  };
@@ -1567,11 +1678,13 @@ export default class ReactNativeBleTransport {
1567
1678
  }
1568
1679
 
1569
1680
  private async releaseUnlocked(uuid: string, onclose = false) {
1681
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1570
1682
  await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1571
1683
  return this.releaseNative(uuid, onclose);
1572
1684
  }
1573
1685
 
1574
1686
  private async releaseNative(uuid: string, onclose = false) {
1687
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1575
1688
  const transport = transportCache[uuid];
1576
1689
  const manager = this.blePlxManager;
1577
1690
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1992,6 +2105,7 @@ export default class ReactNativeBleTransport {
1992
2105
  }
1993
2106
 
1994
2107
  private async disconnectUnlocked(session: string) {
2108
+ this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
1995
2109
  await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1996
2110
  const transport = transportCache[session];
1997
2111
  const manager = this.blePlxManager;
@@ -2469,6 +2583,13 @@ export default class ReactNativeBleTransport {
2469
2583
  consecutiveWriteTimeouts: timeouts,
2470
2584
  });
2471
2585
 
2586
+ this.cancelProtocolV2FrameWrite(
2587
+ uuid,
2588
+ ERRORS.TypedError(
2589
+ HardwareErrorCode.BleWriteCharacteristicError,
2590
+ `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2591
+ )
2592
+ );
2472
2593
  const wedged = transportCache[uuid];
2473
2594
  this.disconnect(uuid).catch(error => {
2474
2595
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2496,6 +2617,10 @@ export default class ReactNativeBleTransport {
2496
2617
  const manager = this.blePlxManager;
2497
2618
  this.blePlxManager = undefined;
2498
2619
  const reason = 'React Native BLE manager reset';
2620
+ // Cancel through the manager that started each frame before destroy() drops its queue.
2621
+ Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid =>
2622
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason))
2623
+ );
2499
2624
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2500
2625
  // each cached session before clearing generations so Core cannot retain a
2501
2626
  // silently stale connection for an unrelated device.
@@ -2967,22 +3092,208 @@ export default class ReactNativeBleTransport {
2967
3092
  androidPacketLength: tuning.androidPacketLength,
2968
3093
  mtu: transport.mtuSize,
2969
3094
  });
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
- ),
3095
+ const perf =
3096
+ context.messageName === 'FilesystemFileWrite'
3097
+ ? this.protocolV2FileWritePerfs.get(uuid)
3098
+ : undefined;
3099
+ const startedAt = perf ? nowMs() : 0;
3100
+ const nativeFrameWriter =
3101
+ frame.length > packetCapacity
3102
+ ? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
3103
+ : undefined;
3104
+ perf?.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
3105
+ if (nativeFrameWriter) {
3106
+ await this.writeProtocolV2NativeFrame(
3107
+ uuid,
3108
+ transport,
3109
+ nativeFrameWriter,
3110
+ frame,
3111
+ packetCapacity,
3112
+ context,
3113
+ assertCurrentGeneration
3114
+ );
3115
+ } else {
3116
+ await writeProtocolV2BleFrame({
3117
+ frame,
3118
+ packetCapacity,
3119
+ assertActive: assertCurrentGeneration,
3120
+ signal: context.signal,
3121
+ abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
3122
+ wait: delay,
3123
+ writePacket: async packet => {
3124
+ const packetStartedAt = perf ? nowMs() : 0;
3125
+ await this.writeProtocolV2Packet(
3126
+ uuid,
3127
+ transport,
3128
+ Buffer.from(packet).toString('base64'),
3129
+ context,
3130
+ assertCurrentGeneration
3131
+ );
3132
+ perf?.recordPacket(nowMs() - packetStartedAt);
3133
+ },
3134
+ });
3135
+ }
3136
+ perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
3137
+ }
3138
+
3139
+ /**
3140
+ * The native frame write only replaces the per-packet loop where its JS<->native round trips
3141
+ * dominate: multi-packet (checked by the caller) high-throughput frames written without response.
3142
+ */
3143
+ private resolveProtocolV2NativeFrameWriter(
3144
+ transport: BleTransport,
3145
+ context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
3146
+ nativeFrameWrite: boolean
3147
+ ): ProtocolV2NativeFrameWriter | undefined {
3148
+ if (!context.highThroughput || nativeFrameWrite === false) return undefined;
3149
+ if (
3150
+ shouldWriteProtocolV2WithResponse({
3151
+ platform: Platform.OS,
3152
+ highThroughput: context.highThroughput,
3153
+ requestedWithResponse: context.writeWithResponse,
3154
+ characteristic: transport.writeCharacteristic,
3155
+ })
3156
+ ) {
3157
+ return undefined;
3158
+ }
3159
+ if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
3160
+ return getProtocolV2NativeFrameWriter(this.blePlxManager);
3161
+ }
3162
+
3163
+ /**
3164
+ * Writes one frame with a single native call that sends its packets in order without response.
3165
+ * Nothing here retries it: a resend could duplicate bytes the device already received. The
3166
+ * native transaction is cancelled on abort, watchdog expiry, generation change and link
3167
+ * teardown so the native side stops writing a frame nobody waits for any more.
3168
+ */
3169
+ private async writeProtocolV2NativeFrame(
3170
+ uuid: string,
3171
+ transport: BleTransport,
3172
+ manager: ProtocolV2NativeFrameWriter,
3173
+ frame: Uint8Array,
3174
+ packetCapacity: number,
3175
+ context: ProtocolV2CallContext,
3176
+ assertCurrentGeneration: () => void
3177
+ ) {
3178
+ const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
3179
+ assertCurrentGeneration();
3180
+ if (context.signal.aborted) {
3181
+ throw new Error(abortMessage);
3182
+ }
3183
+
3184
+ this.protocolV2FrameWriteCounter += 1;
3185
+ const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
3186
+ let cancelError: Error | undefined;
3187
+ let rejectCancelled: (error: Error) => void = () => undefined;
3188
+ const cancelled = new Promise<never>((_, reject) => {
3189
+ rejectCancelled = reject;
2985
3190
  });
3191
+ const active: ActiveProtocolV2FrameWrite = {
3192
+ transactionId,
3193
+ generation: context.generation,
3194
+ cancel: error => {
3195
+ if (cancelError) return;
3196
+ cancelError = error;
3197
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3198
+ this.protocolV2FrameWrites.delete(uuid);
3199
+ }
3200
+ rejectCancelled(error);
3201
+ this.cancelNativeTransaction(manager, transactionId);
3202
+ },
3203
+ };
3204
+ // Same rule as writeBlePacket: a superseded generation must not tear down the current link.
3205
+ const isCurrentOwner = () => {
3206
+ try {
3207
+ assertCurrentGeneration();
3208
+ return !context.signal.aborted;
3209
+ } catch {
3210
+ return false;
3211
+ }
3212
+ };
3213
+ const onAbort = () => active.cancel(new Error(abortMessage));
3214
+ let timer: ReturnType<typeof setTimeout> | undefined;
3215
+ let completed = false;
3216
+ let nativeError: unknown;
3217
+ try {
3218
+ const nativeWrite = Promise.resolve(
3219
+ manager.writeCharacteristicWithoutResponseFrame(
3220
+ transport.writeCharacteristic.id,
3221
+ Buffer.from(frame).toString('base64'),
3222
+ packetCapacity,
3223
+ transactionId
3224
+ )
3225
+ );
3226
+ // A cancelled or timed-out frame still settles natively later; that outcome is ignored.
3227
+ nativeWrite.catch(() => undefined);
3228
+ this.protocolV2FrameWrites.set(uuid, active);
3229
+ context.signal.addEventListener('abort', onAbort);
3230
+ await Promise.race([
3231
+ nativeWrite,
3232
+ cancelled,
3233
+ new Promise<never>((_, reject) => {
3234
+ timer = setTimeout(() => {
3235
+ const owner = isCurrentOwner();
3236
+ const error = ERRORS.TypedError(
3237
+ HardwareErrorCode.BleWriteCharacteristicError,
3238
+ `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
3239
+ );
3240
+ active.cancel(error);
3241
+ reject(error);
3242
+ if (owner) {
3243
+ this.tearDownWedgedLink(uuid);
3244
+ } else {
3245
+ Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3246
+ }
3247
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
3248
+ }),
3249
+ ]);
3250
+ completed = true;
3251
+ } catch (error) {
3252
+ nativeError = error;
3253
+ } finally {
3254
+ if (timer) clearTimeout(timer);
3255
+ context.signal.removeEventListener('abort', onAbort);
3256
+ }
3257
+
3258
+ if (completed) {
3259
+ this.writeTimeoutCounts.delete(uuid);
3260
+ try {
3261
+ assertCurrentGeneration();
3262
+ } catch (error) {
3263
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
3264
+ }
3265
+ }
3266
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3267
+ this.protocolV2FrameWrites.delete(uuid);
3268
+ }
3269
+ if (cancelError) throw cancelError;
3270
+ if (completed) return;
3271
+ if (isNativeBleDisconnectError(nativeError)) {
3272
+ throw toBleDisconnectHardwareError(nativeError);
3273
+ }
3274
+ throw ERRORS.TypedError(
3275
+ HardwareErrorCode.BleWriteCharacteristicError,
3276
+ getNativeBleErrorReason(nativeError)
3277
+ );
3278
+ }
3279
+
3280
+ /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
3281
+ private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
3282
+ const active = this.protocolV2FrameWrites.get(uuid);
3283
+ if (!active || (generation !== undefined && active.generation !== generation)) return;
3284
+ active.cancel(error);
3285
+ }
3286
+
3287
+ private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
3288
+ const logFailure = (error: unknown) =>
3289
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
3290
+ error: error instanceof Error ? error.message : String(error),
3291
+ });
3292
+ try {
3293
+ Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
3294
+ } catch (error) {
3295
+ logFailure(error);
3296
+ }
2986
3297
  }
2987
3298
 
2988
3299
  private async callProtocolV2(
@@ -3031,20 +3342,50 @@ export default class ReactNativeBleTransport {
3031
3342
  packetCapacity,
3032
3343
  });
3033
3344
  }
3345
+ const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
3346
+ currentTransport,
3347
+ { highThroughput: true, writeWithResponse: options?.writeWithResponse },
3348
+ tuning.nativeFrameWrite
3349
+ )
3350
+ ? 'native-frame'
3351
+ : 'per-packet';
3352
+ const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
3353
+ if (!loggedSignatures.has(frameWriteModeSignature)) {
3354
+ loggedSignatures.add(frameWriteModeSignature);
3355
+ this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3356
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
3357
+ platform: Platform.OS,
3358
+ mode: frameWriteMode,
3359
+ nativeFrameWrite: tuning.nativeFrameWrite,
3360
+ nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
3361
+ packetCapacity,
3362
+ });
3363
+ }
3034
3364
  }
3035
3365
 
3036
3366
  if (highThroughputWrite) {
3037
3367
  await this.enableAndroidHighConnectionPriority(uuid);
3038
3368
  }
3039
3369
 
3370
+ const fileWritePerf =
3371
+ name === 'FilesystemFileWrite' && options?.fileWritePipeline
3372
+ ? createProtocolV2FileWritePerf()
3373
+ : undefined;
3374
+ if (fileWritePerf) {
3375
+ this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
3376
+ }
3377
+ let fileWriteOk = false;
3378
+
3040
3379
  try {
3041
- return await this.protocolV2Links.call(
3380
+ const response = await this.protocolV2Links.call(
3042
3381
  uuid,
3043
3382
  () => this.createProtocolV2Adapter(uuid),
3044
3383
  name,
3045
3384
  data,
3046
3385
  callOptions
3047
3386
  );
3387
+ fileWriteOk = response.type !== 'Failure';
3388
+ return response;
3048
3389
  } catch (e) {
3049
3390
  Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
3050
3391
  if (
@@ -3065,6 +3406,15 @@ export default class ReactNativeBleTransport {
3065
3406
  if (highThroughputWrite) {
3066
3407
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3067
3408
  }
3409
+ if (fileWritePerf) {
3410
+ if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
3411
+ this.protocolV2FileWritePerfs.delete(uuid);
3412
+ }
3413
+ Log?.debug(
3414
+ '[ReactNativeBleTransport] FileWrite perf',
3415
+ fileWritePerf.summarize(fileWriteOk)
3416
+ );
3417
+ }
3068
3418
  }
3069
3419
  }
3070
3420
 
@@ -3181,15 +3531,23 @@ export default class ReactNativeBleTransport {
3181
3531
  assertCurrentGeneration
3182
3532
  );
3183
3533
  },
3184
- readFrame: async () => {
3534
+ readFrame: async (context?: ProtocolV2CallContext) => {
3185
3535
  assertCurrentGeneration();
3536
+ const perf =
3537
+ context?.messageName === 'FilesystemFileWrite'
3538
+ ? this.protocolV2FileWritePerfs.get(uuid)
3539
+ : undefined;
3540
+ const startedAt = perf ? nowMs() : 0;
3186
3541
  const rxFrame = await this.readProtocolV2Frame(uuid);
3542
+ perf?.recordReadWait(nowMs() - startedAt);
3187
3543
  if (!(rxFrame instanceof Uint8Array)) {
3188
3544
  throw new Error('Protocol V2 response is not Uint8Array');
3189
3545
  }
3190
3546
  return rxFrame;
3191
3547
  },
3192
3548
  reset: (reason: string) => {
3549
+ // The frame belongs to this link even after a newer monitor generation took over.
3550
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
3193
3551
  if (this.monitorTokens.get(uuid) !== generation) return;
3194
3552
  this.protocolV2Assemblers.get(uuid)?.reset();
3195
3553
  this.rejectProtocolV2Frames(uuid, new Error(reason));