@onekeyfe/hd-transport-react-native 1.2.8 → 1.2.9

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.
Files changed (35) hide show
  1. package/dist/BleManager.d.ts +2 -4
  2. package/dist/BleManager.d.ts.map +1 -1
  3. package/dist/bleNativeDisconnect.d.ts.map +1 -1
  4. package/dist/index.d.ts +44 -64
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +449 -615
  7. package/dist/subscribeBleOn.d.ts.map +1 -1
  8. package/package.json +5 -5
  9. package/src/BleManager.ts +8 -32
  10. package/src/__tests__/bleNativeDisconnect.test.ts +22 -1
  11. package/src/__tests__/connectTimeout.test.ts +110 -0
  12. package/src/__tests__/enumerate.test.ts +207 -17
  13. package/src/__tests__/moduleInterop.test.ts +48 -0
  14. package/src/__tests__/nativeFrameWrite.test.ts +910 -0
  15. package/src/__tests__/protocolV2Link.test.ts +284 -81
  16. package/src/__tests__/subscribeBleOn.test.ts +114 -0
  17. package/src/bleNativeDisconnect.ts +2 -1
  18. package/src/index.ts +535 -350
  19. package/src/subscribeBleOn.ts +30 -11
  20. package/dist/bleEncryption.d.ts +0 -17
  21. package/dist/bleEncryption.d.ts.map +0 -1
  22. package/dist/bleIosStaleBond.d.ts +0 -16
  23. package/dist/bleIosStaleBond.d.ts.map +0 -1
  24. package/dist/bleKeyMissing.d.ts +0 -7
  25. package/dist/bleKeyMissing.d.ts.map +0 -1
  26. package/dist/bleStaleBond.d.ts +0 -5
  27. package/dist/bleStaleBond.d.ts.map +0 -1
  28. package/src/__tests__/androidEncryption.test.ts +0 -482
  29. package/src/__tests__/androidKeyMissing.test.ts +0 -307
  30. package/src/__tests__/bleStaleBond.test.ts +0 -47
  31. package/src/__tests__/iosPeerTermination.test.ts +0 -318
  32. package/src/bleEncryption.ts +0 -267
  33. package/src/bleIosStaleBond.ts +0 -92
  34. package/src/bleKeyMissing.ts +0 -106
  35. package/src/bleStaleBond.ts +0 -64
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';
@@ -47,25 +49,7 @@ import {
47
49
  getInfosForServiceUuid,
48
50
  isSameBleUuid,
49
51
  } from './constants';
50
- import {
51
- isBleKeyMissingSupported,
52
- startBleKeyMissingTracking,
53
- stopBleKeyMissingTracking,
54
- waitForBleKeyMissing,
55
- } from './bleKeyMissing';
56
- import {
57
- markBleLinkEncrypted,
58
- startBleEncryptionTracking,
59
- stopBleEncryptionTracking,
60
- waitForAndroidLinkEncryption,
61
- } from './bleEncryption';
62
- import { IosPeerTerminationTracker } from './bleIosStaleBond';
63
52
  import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from './bleNativeDisconnect';
64
- import {
65
- isBleStaleBondHardwareError,
66
- isNativeBleStaleBondError,
67
- toBleStaleBondHardwareError,
68
- } from './bleStaleBond';
69
53
  import { isHeaderChunk } from './utils/validateNotify';
70
54
  import BleTransport from './BleTransport';
71
55
  import timer from './utils/timer';
@@ -75,7 +59,6 @@ import type { Deferred } from '@onekeyfe/hd-shared';
75
59
  import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
76
60
  import type EventEmitter from 'events';
77
61
  import type { BleAcquireInput, TransportOptions } from './types';
78
- import type { AndroidLinkEncryption } from './bleEncryption';
79
62
 
80
63
  type FirmwareInstallBleAcquireInput = BleAcquireInput & {
81
64
  /**
@@ -86,6 +69,9 @@ type FirmwareInstallBleAcquireInput = BleAcquireInput & {
86
69
  skipProtocolProbe?: boolean;
87
70
  };
88
71
 
72
+ const transport: typeof transportModule =
73
+ (transportModule as typeof transportModule & { default?: typeof transportModule }).default ??
74
+ transportModule;
89
75
  const { check, ProtocolV1, parseConfigure } = transport;
90
76
 
91
77
  const Log = bleLogger;
@@ -185,14 +171,18 @@ const isWedgedWriteError = (error: unknown): boolean =>
185
171
  (error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
186
172
  typeof (error as { message?: unknown })?.message === 'string' &&
187
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
+ );
188
179
  const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
189
180
  const code = (error as { errorCode?: unknown })?.errorCode;
190
181
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
191
182
  // them instead of probing another protocol on an unusable connection.
192
- // Native PLX disconnects (errorCode 201 / iOS 7) must match before they are
193
- // mapped: Protocol V2 writes rethrow them unchanged unless normalized first.
183
+ // Native PLX disconnects (errorCode 201 / iOS 7, or the unstructured
184
+ // "was disconnected" fallback) must match before Protocol V2 probing.
194
185
  return (
195
- isBleStaleBondHardwareError(error) ||
196
186
  isNativeBleDisconnectError(error) ||
197
187
  code === HardwareErrorCode.BleDeviceNotBonded ||
198
188
  code === HardwareErrorCode.BleDeviceBondedCanceled ||
@@ -202,38 +192,6 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
202
192
  code === HardwareErrorCode.BleWriteCharacteristicError
203
193
  );
204
194
  };
205
- /**
206
- * Android reports a lost bond (ACTION_KEY_MISSING) while it encrypts a new link, so only
207
- * a failure this soon after the link started can be explained by it. Later disconnects,
208
- * such as a firmware-update reboot, must keep their own meaning.
209
- */
210
- export const ANDROID_KEY_MISSING_LINK_WINDOW_MS = 10_000;
211
- /** The broadcast and the GATT disconnect it explains travel separately; either can land first. */
212
- export const ANDROID_KEY_MISSING_GRACE_MS = 500;
213
- /**
214
- * Android reports a bonded link's first encryption result within about half a second of
215
- * connecting. Past this, the result is treated as unknown and the link is used as before.
216
- */
217
- export const ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = 1500;
218
- /**
219
- * A system re-pairing needs the user to accept a pairing request and confirm the code on the
220
- * device. The Bluetooth stack gives up after 30s and then reports key missing.
221
- */
222
- export const ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = 35_000;
223
- /**
224
- * How a link dropped by a device that refuses a stale bond reaches JS. A wedged write is
225
- * excluded: the system is still re-pairing then and has not reported key missing yet.
226
- */
227
- const isAndroidLinkLossError = (error: unknown): boolean => {
228
- const code = (error as { errorCode?: unknown })?.errorCode;
229
- return (
230
- isNativeBleDisconnectError(error) ||
231
- code === HardwareErrorCode.BleDeviceNotBonded ||
232
- code === HardwareErrorCode.BleDeviceDisconnected ||
233
- code === HardwareErrorCode.BleCharacteristicNotifyError ||
234
- code === HardwareErrorCode.BleConnectedError
235
- );
236
- };
237
195
  /** Consecutive wedged writes on one device before the BLE manager itself is recreated. */
238
196
  export const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
239
197
  const DEVICE_SCAN_TIMEOUT_MS = 3000;
@@ -242,6 +200,16 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
242
200
  export type ProtocolV2BleTuning = {
243
201
  iosPacketLength?: number;
244
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';
245
213
  };
246
214
 
247
215
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -249,6 +217,8 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
249
217
  const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
250
218
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
251
219
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
220
+ nativeFrameWrite: true,
221
+ androidHighConnectionPriority: 'auto',
252
222
  };
253
223
 
254
224
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -269,6 +239,15 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
269
239
  tuning.androidPacketLength,
270
240
  protocolV2BleTuning.androidPacketLength
271
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,
272
251
  };
273
252
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
274
253
  }
@@ -282,13 +261,193 @@ export function getProtocolV2BleTuning() {
282
261
  return { ...protocolV2BleTuning };
283
262
  }
284
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
+
285
398
  function getDeviceDisplayName(device?: Device | null) {
286
399
  return device?.name || device?.localName || null;
287
400
  }
288
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
+
289
430
  const IOS_REQUEST_MTU = 247;
290
431
  const ANDROID_REQUEST_MTU = 517;
291
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
+ };
292
451
 
293
452
  const getRequestedBleMtu = () =>
294
453
  Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
@@ -408,7 +567,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
408
567
 
409
568
  type NegotiatedMtuResult = { device: Device; timedOut: boolean };
410
569
 
411
- export type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
570
+ export type IOneKeyDevice = OneKeyDeviceInfoBase &
571
+ Device &
572
+ Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
412
573
 
413
574
  const tryToGetConfiguration = (device: Device) => {
414
575
  if (!device || !device.serviceUUIDs) return null;
@@ -494,23 +655,11 @@ const resolveNegotiatedMtu = (
494
655
  type IOBleErrorRemap = Error | BleError | null | undefined;
495
656
 
496
657
  function remapError(error: IOBleErrorRemap) {
497
- if (error instanceof BleError) {
498
- if (isNativeBleStaleBondError(error)) {
499
- throw toBleStaleBondHardwareError(error);
500
- }
501
-
502
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
503
- // @ts-ignore It's not documented but seems to match a refusal on Android pairing
504
- if (error?.attErrorCode === 22) {
505
- throw ERRORS.TypedError(HardwareErrorCode.BleDeviceBondError);
506
- }
658
+ if (isNativeBleDisconnectError(error)) {
659
+ throw toBleDisconnectHardwareError(error);
507
660
  }
508
661
 
509
- if (
510
- error instanceof Error &&
511
- error.message &&
512
- (error.message.includes('was disconnected') || error.message.includes('not found'))
513
- ) {
662
+ if (error instanceof Error && error.message?.includes('not found')) {
514
663
  throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
515
664
  }
516
665
 
@@ -579,22 +728,6 @@ export default class ReactNativeBleTransport {
579
728
  /** Android endpoints whose cached GATT table is suspect; the next connect refreshes it. */
580
729
  private androidGattCacheRefreshes = new Set<string>();
581
730
 
582
- /**
583
- * Native encryption/pairing failures seen before Protocol V2 probe starts.
584
- * Pro2/Neo GATT connect can succeed on a stale iOS bond; the CCCD write then
585
- * fails with ATT 5/15. Remember it so detectProtocol fails immediately.
586
- */
587
- private staleBondErrors: Map<string, Error> = new Map();
588
-
589
- /** When the current Android link attempt began; bounds which key-missing signals apply. */
590
- private androidLinkStartedAt: Map<string, number> = new Map();
591
-
592
- /** iOS acquire attempts whose new link the peer ended; two in a row mean a stale bond. */
593
- private iosPeerTermination = new IosPeerTerminationTracker();
594
-
595
- /** Strict or previously confirmed V2 target while acquire installs notifications. */
596
- private acquiringProtocolV2 = new Set<string>();
597
-
598
731
  private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
599
732
 
600
733
  private protocolV2FrameQueues: Map<string, Uint8Array[]> = new Map();
@@ -640,6 +773,13 @@ export default class ReactNativeBleTransport {
640
773
 
641
774
  private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
642
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
+
643
783
  private nextMonitorToken = 1;
644
784
 
645
785
  /** Serializes transport lifecycle changes for the same physical device. */
@@ -656,11 +796,6 @@ export default class ReactNativeBleTransport {
656
796
  init(logger: any, emitter: EventEmitter) {
657
797
  setBleLogger(logger);
658
798
  this.emitter = emitter;
659
- if (Platform.OS === 'android') {
660
- // Link security events are only meaningful if they were observed since the link came up.
661
- startBleKeyMissingTracking();
662
- startBleEncryptionTracking();
663
- }
664
799
  }
665
800
 
666
801
  configure(signedData: any) {
@@ -908,7 +1043,6 @@ export default class ReactNativeBleTransport {
908
1043
  const scanStartedAt = Date.now();
909
1044
  let firstDeviceMs: number | undefined;
910
1045
  const blePlxManager = await this.getPlxManager();
911
- await subscribeBleOn(blePlxManager);
912
1046
  if (Platform.OS === 'android' && Platform.Version >= 31) {
913
1047
  Log?.debug('requesting permissions, please wait...');
914
1048
 
@@ -922,9 +1056,10 @@ export default class ReactNativeBleTransport {
922
1056
  resultConnect[PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT] !== 'granted' ||
923
1057
  resultConnect[PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN] !== 'granted'
924
1058
  ) {
925
- throw ERRORS.TypedError(HardwareErrorCode.BlePermissionError);
1059
+ throw ERRORS.TypedError(HardwareErrorCode.BleLocationError);
926
1060
  }
927
1061
  }
1062
+ await subscribeBleOn(blePlxManager);
928
1063
 
929
1064
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
930
1065
  return new Promise<IOneKeyDevice[]>((resolve, reject) => {
@@ -940,7 +1075,7 @@ export default class ReactNativeBleTransport {
940
1075
  }).then(() => {
941
1076
  this.scanCleanups.delete(cancelScan);
942
1077
  if (error) reject(error);
943
- else resolve(deviceList);
1078
+ else resolve(deviceList.map(withBleColorCode));
944
1079
  });
945
1080
  return scanCleanup;
946
1081
  };
@@ -967,12 +1102,10 @@ export default class ReactNativeBleTransport {
967
1102
  (error, device) => {
968
1103
  if (error) {
969
1104
  Log?.debug('ble scan error: ', error);
970
- if (
971
- [BleErrorCode.BluetoothPoweredOff, BleErrorCode.BluetoothInUnknownState].includes(
972
- error.errorCode
973
- )
974
- ) {
975
- finishScan(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
1105
+ if (error.errorCode === BleErrorCode.BluetoothPoweredOff) {
1106
+ finishScan(ERRORS.TypedError(HardwareErrorCode.BlePoweredOff));
1107
+ } else if (error.errorCode === BleErrorCode.BluetoothUnsupported) {
1108
+ finishScan(ERRORS.TypedError(HardwareErrorCode.BleUnsupported));
976
1109
  } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
977
1110
  finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationError));
978
1111
  } else if (error.errorCode === BleErrorCode.LocationServicesDisabled) {
@@ -987,6 +1120,9 @@ export default class ReactNativeBleTransport {
987
1120
  return;
988
1121
  }
989
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);
990
1126
  const displayName = getDeviceDisplayName(device);
991
1127
  // iOS may report a service-only advertisement before the named scan response.
992
1128
  // Do not cache that incomplete advertisement as an unknown device.
@@ -1052,6 +1188,9 @@ export default class ReactNativeBleTransport {
1052
1188
  deviceId: device.id,
1053
1189
  name: displayName,
1054
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()),
1055
1194
  });
1056
1195
  }
1057
1196
  };
@@ -1097,6 +1236,7 @@ export default class ReactNativeBleTransport {
1097
1236
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1098
1237
 
1099
1238
  Log?.debug('[ReactNativeBleTransport] BLE MTU ready', {
1239
+ connectionId: monitorToken,
1100
1240
  platform: Platform.OS,
1101
1241
  requested: getRequestedBleMtu(),
1102
1242
  actual: transport.mtuSize,
@@ -1112,23 +1252,12 @@ export default class ReactNativeBleTransport {
1112
1252
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
1113
1253
  }
1114
1254
 
1115
- return this.runLifecycleOperation(uuid, async () => {
1116
- try {
1117
- return await this.acquireUnlocked(input);
1118
- } catch (error) {
1119
- throw this.resolveIosBondInvalid(input, await this.resolveAndroidBondInvalid(uuid, error));
1120
- }
1121
- });
1255
+ return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1122
1256
  }
1123
1257
 
1124
1258
  private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1125
1259
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1126
1260
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1127
- this.iosPeerTermination.attemptStarted(uuid);
1128
- const shouldMapProtocolV2StaleBond = expectedProtocol
1129
- ? expectedProtocol === 'V2'
1130
- : this.confirmedProtocolV2.has(uuid);
1131
-
1132
1261
  const cachedTransport = transportCache[uuid];
1133
1262
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1134
1263
  Log?.debug(
@@ -1199,8 +1328,6 @@ export default class ReactNativeBleTransport {
1199
1328
 
1200
1329
  let device: Device | null = null;
1201
1330
  const isAndroid = Platform.OS === 'android';
1202
- // Only a bond that existed before this acquire can have been lost by the device.
1203
- let androidBondedBeforeConnect = false;
1204
1331
  // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1205
1332
  const refreshAndroidGattCache =
1206
1333
  isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
@@ -1232,15 +1359,9 @@ export default class ReactNativeBleTransport {
1232
1359
 
1233
1360
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1234
1361
  if (Platform.OS === 'android') {
1235
- // Subscribe before the link exists: key missing is broadcast while Android encrypts it.
1236
- startBleKeyMissingTracking();
1237
- startBleEncryptionTracking();
1238
- // Failures before the new link starts must not be read against the previous link.
1239
- this.androidLinkStartedAt.delete(uuid);
1240
1362
  // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1241
1363
  try {
1242
1364
  const bondState = await pairDevice(uuid);
1243
- androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1244
1365
  if (bondState.bonding) {
1245
1366
  await onDeviceBondState(uuid, this.bondAbortController.signal, {
1246
1367
  systemInitiated: bondState.initiated === false,
@@ -1256,7 +1377,6 @@ export default class ReactNativeBleTransport {
1256
1377
  });
1257
1378
  throw error;
1258
1379
  }
1259
- this.androidLinkStartedAt.set(uuid, Date.now());
1260
1380
  }
1261
1381
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1262
1382
 
@@ -1440,17 +1560,7 @@ export default class ReactNativeBleTransport {
1440
1560
  this.deviceProtocolHints.set(uuid, protocolHint);
1441
1561
  }
1442
1562
 
1443
- if (shouldMapProtocolV2StaleBond) {
1444
- this.acquiringProtocolV2.add(uuid);
1445
- }
1446
-
1447
- let linkEncryption: AndroidLinkEncryption | undefined;
1448
1563
  try {
1449
- // A firmware-install reconnect keeps its existing sequence.
1450
- if (androidBondedBeforeConnect && !skipProtocolProbe) {
1451
- linkEncryption = await this.waitForAndroidLinkSecurity(uuid);
1452
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1453
- }
1454
1564
  await this.installTransportForAcquire(uuid, acquiredDevice, {
1455
1565
  writeCharacteristic,
1456
1566
  notifyCharacteristic,
@@ -1497,25 +1607,17 @@ export default class ReactNativeBleTransport {
1497
1607
  }
1498
1608
  );
1499
1609
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1500
- this.iosPeerTermination.linkProven(uuid);
1501
1610
  const currentTransport = transportCache[uuid];
1502
1611
  if (!currentTransport) {
1503
1612
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1504
1613
  }
1505
1614
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1506
- if (linkEncryption === 'unresolved') {
1507
- // Notifications and the probe only work on an encrypted link, so the next reuse of this
1508
- // link needs no result that was reported before tracking started.
1509
- markBleLinkEncrypted(uuid);
1510
- }
1511
1615
  return { uuid, protocolType };
1512
1616
  } catch (error) {
1513
1617
  // A failed acquire must retire the physical link before Core retries. Logical
1514
1618
  // release leaves GATT connected even when neither protocol receives a response.
1515
1619
  await this.disconnectUnlocked(uuid);
1516
1620
  throw error;
1517
- } finally {
1518
- this.acquiringProtocolV2.delete(uuid);
1519
1621
  }
1520
1622
  }
1521
1623
 
@@ -1530,7 +1632,6 @@ export default class ReactNativeBleTransport {
1530
1632
  const subscription = characteristic.monitor((error, c) => {
1531
1633
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1532
1634
  if (error) {
1533
- if (isCurrentMonitor) this.noteIosLinkError(uuid, 'notify', error);
1534
1635
  Log?.debug(
1535
1636
  `error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${
1536
1637
  error as unknown as string
@@ -1544,13 +1645,6 @@ export default class ReactNativeBleTransport {
1544
1645
  Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1545
1646
  return;
1546
1647
  }
1547
- if (
1548
- (this.getActiveProtocol(uuid) === 'V2' || this.acquiringProtocolV2.has(uuid)) &&
1549
- isNativeBleStaleBondError(error)
1550
- ) {
1551
- this.rememberStaleBondError(uuid, toBleStaleBondHardwareError(error));
1552
- return;
1553
- }
1554
1648
  if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1555
1649
  this.androidGattCacheRefreshes.add(uuid);
1556
1650
  }
@@ -1656,16 +1750,34 @@ export default class ReactNativeBleTransport {
1656
1750
  return subscription;
1657
1751
  }
1658
1752
 
1659
- async release(uuid: string, onclose = false) {
1660
- 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));
1661
1755
  }
1662
1756
 
1663
- private async releaseUnlocked(uuid: string, onclose = false) {
1664
- 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);
1665
1776
  return this.releaseNative(uuid, onclose);
1666
1777
  }
1667
1778
 
1668
1779
  private async releaseNative(uuid: string, onclose = false) {
1780
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1669
1781
  const transport = transportCache[uuid];
1670
1782
  const manager = this.blePlxManager;
1671
1783
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1710,8 +1822,6 @@ export default class ReactNativeBleTransport {
1710
1822
 
1711
1823
  this.deviceProtocol.delete(uuid);
1712
1824
  this.probingProtocols.delete(uuid);
1713
- this.staleBondErrors.delete(uuid);
1714
- this.acquiringProtocolV2.delete(uuid);
1715
1825
  // Confirmed protocol and caller hints stay in deviceProtocol / protocolHint.
1716
1826
  this.protocolV2Assemblers.get(uuid)?.reset();
1717
1827
  this.protocolV2Assemblers.delete(uuid);
@@ -1782,122 +1892,9 @@ export default class ReactNativeBleTransport {
1782
1892
  throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
1783
1893
  }
1784
1894
 
1785
- try {
1786
- return protocol === 'V2'
1787
- ? await this.callProtocolV2(uuid, name, data, options)
1788
- : await this.callProtocolV1(uuid, name, data, options);
1789
- } catch (error) {
1790
- // An expected-V1 acquire skips the probe, so the first call is what meets the dropped link.
1791
- throw await this.resolveAndroidBondInvalid(uuid, error);
1792
- }
1793
- }
1794
-
1795
- /**
1796
- * Android 16+ keeps a bond the device no longer holds keys for. The device drops the link
1797
- * and the only structured evidence is ACTION_KEY_MISSING, so a link loss right after
1798
- * connect is re-read as an invalid bond when that signal belongs to the same attempt.
1799
- */
1800
- private async resolveAndroidBondInvalid(uuid: string, error: unknown): Promise<unknown> {
1801
- if (Platform.OS !== 'android' || !isBleKeyMissingSupported()) return error;
1802
- if (isBleStaleBondHardwareError(error) || !isAndroidLinkLossError(error)) return error;
1803
- const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1804
- if (
1805
- linkStartedAt === undefined ||
1806
- Date.now() - linkStartedAt > ANDROID_KEY_MISSING_LINK_WINDOW_MS
1807
- ) {
1808
- return error;
1809
- }
1810
- if (!(await waitForBleKeyMissing(uuid, linkStartedAt, ANDROID_KEY_MISSING_GRACE_MS))) {
1811
- return error;
1812
- }
1813
- Log?.debug('[ReactNativeBleTransport] Android key missing, bond is invalid:', uuid);
1814
- return ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
1815
- phase: 'connect',
1816
- reason: 'key_missing',
1817
- });
1818
- }
1819
-
1820
- /**
1821
- * iOS says why a link ended only on the operation it interrupted, so the native codes are read
1822
- * and logged here. Codes only: the reason text is localized and cannot be matched or searched.
1823
- */
1824
- private noteIosLinkError(uuid: string, stage: 'gatt-setup' | 'notify' | 'write', error: unknown) {
1825
- if (Platform.OS !== 'ios') return;
1826
- this.iosPeerTermination.note(uuid, error);
1827
- // Writes and notifications also fail for reasons that say nothing about the link.
1828
- if (stage !== 'gatt-setup' && !isNativeBleDisconnectError(error)) return;
1829
- const native = (error ?? {}) as {
1830
- errorCode?: unknown;
1831
- iosErrorCode?: unknown;
1832
- attErrorCode?: unknown;
1833
- };
1834
- const code = (value: unknown) =>
1835
- typeof value === 'number' || typeof value === 'string' ? value : undefined;
1836
- Log?.debug('[ReactNativeBleTransport] iOS operation failed', {
1837
- connectIdSuffix: uuid.slice(-8),
1838
- stage,
1839
- errorCode: code(native.errorCode),
1840
- iosErrorCode: code(native.iosErrorCode),
1841
- attErrorCode: code(native.attErrorCode),
1842
- });
1843
- }
1844
-
1845
- /**
1846
- * iPhones that do not report a lost bond only show the device ending each new link. One such
1847
- * attempt keeps its error so Core retries; the second in a row is the stale bond.
1848
- */
1849
- private resolveIosBondInvalid(input: FirmwareInstallBleAcquireInput, error: unknown): unknown {
1850
- if (Platform.OS !== 'ios') return error;
1851
- const { uuid, skipProtocolProbe } = input;
1852
- // A firmware-install reconnect expects the device to come and go.
1853
- if (skipProtocolProbe || isBleStaleBondHardwareError(error)) {
1854
- this.iosPeerTermination.forget(uuid);
1855
- return error;
1856
- }
1857
- if (!this.iosPeerTermination.attemptFailed(uuid)) return error;
1858
- Log?.debug(
1859
- '[ReactNativeBleTransport] iOS peer ended two new links in a row, bond is invalid:',
1860
- {
1861
- connectIdSuffix: uuid.slice(-8),
1862
- }
1863
- );
1864
- return ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
1865
- phase: 'connect',
1866
- reason: 'peer_disconnected',
1867
- });
1868
- }
1869
-
1870
- /**
1871
- * Android 16+ encrypts a bonded link on its own right after connecting. Subscribing to
1872
- * notifications before that finishes gets the CCCD write rejected, and the framework's retry
1873
- * encrypts again with the same stale key; firmware that allows one failure per link then drops
1874
- * it before the system can re-pair. Holding GATT until the result lets a lost bond be re-paired
1875
- * in place. Without the platform signal this resolves immediately.
1876
- */
1877
- private async waitForAndroidLinkSecurity(uuid: string): Promise<AndroidLinkEncryption> {
1878
- const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1879
- if (linkStartedAt === undefined) return 'unresolved';
1880
- const waitStartedAt = Date.now();
1881
- const result = await waitForAndroidLinkEncryption({
1882
- deviceId: uuid,
1883
- linkStartedAt,
1884
- resultTimeoutMs: ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS,
1885
- repairTimeoutMs: ANDROID_SYSTEM_REPAIR_TIMEOUT_MS,
1886
- keyMissingGraceMs: ANDROID_KEY_MISSING_GRACE_MS,
1887
- signal: this.bondAbortController.signal,
1888
- onRepairStarted: () => {
1889
- Log?.debug(
1890
- '[ReactNativeBleTransport] Android bond lost, waiting for system re-pairing:',
1891
- uuid
1892
- );
1893
- },
1894
- });
1895
- Log?.debug('[ReactNativeBleTransport] Android link encryption', {
1896
- connectIdSuffix: uuid.slice(-8),
1897
- result,
1898
- waitedMs: Date.now() - waitStartedAt,
1899
- });
1900
- return result;
1895
+ return protocol === 'V2'
1896
+ ? this.callProtocolV2(uuid, name, data, options)
1897
+ : this.callProtocolV1(uuid, name, data, options);
1901
1898
  }
1902
1899
 
1903
1900
  private async callProtocolV1(
@@ -2165,10 +2162,6 @@ export default class ReactNativeBleTransport {
2165
2162
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
2166
2163
  this.androidPriorityResetTimers.clear();
2167
2164
  this.androidHighPriorityDevices.clear();
2168
- this.androidLinkStartedAt.clear();
2169
- this.iosPeerTermination.reset();
2170
- stopBleKeyMissingTracking();
2171
- stopBleEncryptionTracking();
2172
2165
  const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
2173
2166
  this.runPromise?.reject(error);
2174
2167
  this.runPromise = null;
@@ -2205,7 +2198,13 @@ export default class ReactNativeBleTransport {
2205
2198
  }
2206
2199
 
2207
2200
  private async disconnectUnlocked(session: string) {
2208
- 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);
2209
2208
  const transport = transportCache[session];
2210
2209
  const manager = this.blePlxManager;
2211
2210
  const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
@@ -2242,7 +2241,6 @@ export default class ReactNativeBleTransport {
2242
2241
  }
2243
2242
  this.deviceProtocol.delete(session);
2244
2243
  this.probingProtocols.delete(session);
2245
- this.staleBondErrors.delete(session);
2246
2244
  this.deviceProtocolHints.delete(session);
2247
2245
  this.sessionProtocols.delete(session);
2248
2246
  this.protocolReprobeFailures.delete(session);
@@ -2484,7 +2482,6 @@ export default class ReactNativeBleTransport {
2484
2482
  }),
2485
2483
  ]);
2486
2484
  succeeded = true;
2487
- this.iosPeerTermination.linkStarted(uuid);
2488
2485
  return result;
2489
2486
  } catch (error) {
2490
2487
  if (timedOut || isNativeOperationTimeoutError(error)) {
@@ -2538,11 +2535,6 @@ export default class ReactNativeBleTransport {
2538
2535
  succeeded = true;
2539
2536
  return result;
2540
2537
  } catch (error) {
2541
- this.noteIosLinkError(uuid, 'gatt-setup', error);
2542
- if (Platform.OS === 'ios' && isNativeBleStaleBondError(error)) {
2543
- // iOS can report the lost bond on the first request instead of on the connect.
2544
- throw toBleStaleBondHardwareError(error);
2545
- }
2546
2538
  if (timedOut || isNativeOperationTimeoutError(error)) {
2547
2539
  const resetManager = this.abandonStalledConnection(
2548
2540
  uuid,
@@ -2552,6 +2544,9 @@ export default class ReactNativeBleTransport {
2552
2544
  throw this.createWedgedBleSetupError();
2553
2545
  }
2554
2546
  }
2547
+ if (isNativeBleDisconnectError(error)) {
2548
+ throw toBleDisconnectHardwareError(error);
2549
+ }
2555
2550
  if (Platform.OS === 'android' && isMissingGattShapeError(error)) {
2556
2551
  this.androidGattCacheRefreshes.add(uuid);
2557
2552
  }
@@ -2599,8 +2594,6 @@ export default class ReactNativeBleTransport {
2599
2594
  }
2600
2595
  this.deviceProtocol.delete(uuid);
2601
2596
  this.probingProtocols.delete(uuid);
2602
- this.staleBondErrors.delete(uuid);
2603
- this.acquiringProtocolV2.delete(uuid);
2604
2597
  this.protocolV2Assemblers.delete(uuid);
2605
2598
  this.resetProtocolV2Frames(uuid);
2606
2599
 
@@ -2649,18 +2642,12 @@ export default class ReactNativeBleTransport {
2649
2642
  new Promise<never>((_, reject) => {
2650
2643
  timer = setTimeout(() => {
2651
2644
  timedOut = true;
2652
- reject(
2653
- ERRORS.TypedError(
2654
- HardwareErrorCode.BleWriteCharacteristicError,
2655
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2656
- )
2657
- );
2645
+ reject(createWedgedWriteError());
2658
2646
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2659
2647
  }),
2660
2648
  ]);
2661
2649
  this.writeTimeoutCounts.delete(uuid);
2662
2650
  } catch (error) {
2663
- this.noteIosLinkError(uuid, 'write', error);
2664
2651
  if (timedOut) {
2665
2652
  // A superseded call's late write must not tear down the link the current
2666
2653
  // call is using; only the owner of the transport may declare it dead.
@@ -2689,6 +2676,7 @@ export default class ReactNativeBleTransport {
2689
2676
  consecutiveWriteTimeouts: timeouts,
2690
2677
  });
2691
2678
 
2679
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2692
2680
  const wedged = transportCache[uuid];
2693
2681
  this.disconnect(uuid).catch(error => {
2694
2682
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2698,8 +2686,6 @@ export default class ReactNativeBleTransport {
2698
2686
  }
2699
2687
  this.deviceProtocol.delete(uuid);
2700
2688
  this.probingProtocols.delete(uuid);
2701
- this.staleBondErrors.delete(uuid);
2702
- this.acquiringProtocolV2.delete(uuid);
2703
2689
  this.protocolV2Assemblers.delete(uuid);
2704
2690
  this.resetProtocolV2Frames(uuid);
2705
2691
 
@@ -2718,6 +2704,8 @@ export default class ReactNativeBleTransport {
2718
2704
  const manager = this.blePlxManager;
2719
2705
  this.blePlxManager = undefined;
2720
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)));
2721
2709
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2722
2710
  // each cached session before clearing generations so Core cannot retain a
2723
2711
  // silently stale connection for an unrelated device.
@@ -2751,8 +2739,6 @@ export default class ReactNativeBleTransport {
2751
2739
  });
2752
2740
  this.deviceProtocol.clear();
2753
2741
  this.probingProtocols.clear();
2754
- this.staleBondErrors.clear();
2755
- this.acquiringProtocolV2.clear();
2756
2742
  this.sessionProtocols.clear();
2757
2743
  // Keep transport-lifetime V2 proof so the same endpoint can finish a no-probe
2758
2744
  // firmware reconnect after the native BLE manager is recreated.
@@ -2782,17 +2768,13 @@ export default class ReactNativeBleTransport {
2782
2768
  private createProtocolMismatchError(expected: ProtocolType) {
2783
2769
  // A protocol probe miss alone does not prove that the OS bond is stale.
2784
2770
  // Native authentication/encryption failures are mapped separately.
2785
- return ERRORS.TypedError(
2786
- HardwareErrorCode.RuntimeError,
2787
- `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`
2788
- );
2771
+ return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed, undefined, {
2772
+ expectedProtocol: expected,
2773
+ });
2789
2774
  }
2790
2775
 
2791
2776
  private createProtocolDetectionError() {
2792
- return ERRORS.TypedError(
2793
- HardwareErrorCode.BleTimeoutError,
2794
- 'Unable to detect BLE protocol: device did not respond to Protocol V1 GetFeatures or Protocol V2 Ping'
2795
- );
2777
+ return ERRORS.TypedError(HardwareErrorCode.TransportProtocolProbeFailed);
2796
2778
  }
2797
2779
 
2798
2780
  private clearProbeProtocol(uuid: string, protocol: ProtocolType) {
@@ -2835,10 +2817,6 @@ export default class ReactNativeBleTransport {
2835
2817
  return 'V1';
2836
2818
  }
2837
2819
 
2838
- if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2839
- this.throwIfStaleBondError(uuid);
2840
- }
2841
-
2842
2820
  if (expectedProtocol === 'V2') {
2843
2821
  if (await this.probeProtocolV2(uuid)) {
2844
2822
  this.deviceProtocol.set(uuid, 'V2');
@@ -3027,7 +3005,6 @@ export default class ReactNativeBleTransport {
3027
3005
 
3028
3006
  this.probingProtocols.set(uuid, 'V2');
3029
3007
  this.protocolV2Assemblers.get(uuid)?.reset();
3030
- this.throwIfStaleBondError(uuid);
3031
3008
  const detected = await probeProtocolV2Helper({
3032
3009
  call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
3033
3010
  this.callProtocolV2(uuid, name, data, options),
@@ -3107,21 +3084,6 @@ export default class ReactNativeBleTransport {
3107
3084
  }
3108
3085
  }
3109
3086
 
3110
- private rememberStaleBondError(uuid: string, error: Error) {
3111
- this.staleBondErrors.set(uuid, error);
3112
- this.rejectProtocolV2Frames(uuid, error);
3113
- if (this.runPromise && this.runPromiseDeviceId === uuid) {
3114
- this.runPromise.reject(error);
3115
- }
3116
- }
3117
-
3118
- private throwIfStaleBondError(uuid: string) {
3119
- const error = this.staleBondErrors.get(uuid);
3120
- if (error) {
3121
- throw error;
3122
- }
3123
- }
3124
-
3125
3087
  private async readProtocolV2Frame(uuid: string) {
3126
3088
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
3127
3089
  if (queuedFrame) {
@@ -3180,11 +3142,6 @@ export default class ReactNativeBleTransport {
3180
3142
  assertCurrentGeneration();
3181
3143
  return;
3182
3144
  } catch (error) {
3183
- if (isNativeBleStaleBondError(error) || isBleStaleBondHardwareError(error)) {
3184
- const bondError = toBleStaleBondHardwareError(error);
3185
- this.rememberStaleBondError(uuid, bondError);
3186
- throw bondError;
3187
- }
3188
3145
  if (isNativeBleDisconnectError(error)) {
3189
3146
  throw toBleDisconnectHardwareError(error);
3190
3147
  }
@@ -3220,22 +3177,204 @@ export default class ReactNativeBleTransport {
3220
3177
  androidPacketLength: tuning.androidPacketLength,
3221
3178
  mtu: transport.mtuSize,
3222
3179
  });
3223
- await writeProtocolV2BleFrame({
3224
- frame,
3225
- packetCapacity,
3226
- assertActive: assertCurrentGeneration,
3227
- signal: context.signal,
3228
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
3229
- wait: delay,
3230
- writePacket: packet =>
3231
- this.writeProtocolV2Packet(
3232
- uuid,
3233
- transport,
3234
- Buffer.from(packet).toString('base64'),
3235
- context,
3236
- assertCurrentGeneration
3237
- ),
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;
3238
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;
3239
3378
  }
3240
3379
 
3241
3380
  private async callProtocolV2(
@@ -3272,11 +3411,7 @@ export default class ReactNativeBleTransport {
3272
3411
  const logSignature = `${name}:${writeMode}:${String(
3273
3412
  currentTransport.mtuSize
3274
3413
  )}:${packetCapacity}`;
3275
- const loggedSignatures =
3276
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3277
- if (!loggedSignatures.has(logSignature)) {
3278
- loggedSignatures.add(logSignature);
3279
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3414
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
3280
3415
  Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
3281
3416
  name,
3282
3417
  writeMode,
@@ -3284,20 +3419,47 @@ export default class ReactNativeBleTransport {
3284
3419
  packetCapacity,
3285
3420
  });
3286
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
+ }
3287
3438
  }
3288
3439
 
3289
3440
  if (highThroughputWrite) {
3290
3441
  await this.enableAndroidHighConnectionPriority(uuid);
3291
3442
  }
3292
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
+
3293
3453
  try {
3294
- return await this.protocolV2Links.call(
3454
+ const response = await this.protocolV2Links.call(
3295
3455
  uuid,
3296
3456
  () => this.createProtocolV2Adapter(uuid),
3297
3457
  name,
3298
3458
  data,
3299
3459
  callOptions
3300
3460
  );
3461
+ fileWriteOk = response.type !== 'Failure';
3462
+ return response;
3301
3463
  } catch (e) {
3302
3464
  Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
3303
3465
  if (
@@ -3318,6 +3480,15 @@ export default class ReactNativeBleTransport {
3318
3480
  if (highThroughputWrite) {
3319
3481
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3320
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
+ }
3321
3492
  }
3322
3493
  }
3323
3494
 
@@ -3356,6 +3527,15 @@ export default class ReactNativeBleTransport {
3356
3527
 
3357
3528
  this.clearAndroidPriorityResetTimer(uuid);
3358
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
+ }
3359
3539
 
3360
3540
  const transport = transportCache[uuid];
3361
3541
  if (!transport) return;
@@ -3434,15 +3614,20 @@ export default class ReactNativeBleTransport {
3434
3614
  assertCurrentGeneration
3435
3615
  );
3436
3616
  },
3437
- readFrame: async () => {
3617
+ readFrame: async (context: ProtocolV2CallContext) => {
3438
3618
  assertCurrentGeneration();
3619
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3620
+ const startedAt = perf ? nowMs() : 0;
3439
3621
  const rxFrame = await this.readProtocolV2Frame(uuid);
3622
+ perf?.recordReadWait(nowMs() - startedAt);
3440
3623
  if (!(rxFrame instanceof Uint8Array)) {
3441
3624
  throw new Error('Protocol V2 response is not Uint8Array');
3442
3625
  }
3443
3626
  return rxFrame;
3444
3627
  },
3445
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);
3446
3631
  if (this.monitorTokens.get(uuid) !== generation) return;
3447
3632
  this.protocolV2Assemblers.get(uuid)?.reset();
3448
3633
  this.rejectProtocolV2Frames(uuid, new Error(reason));