@onekeyfe/hd-transport-react-native 1.2.11-alpha.2 → 1.2.11-alpha.3

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
@@ -1,7 +1,6 @@
1
1
  import { PermissionsAndroid, Platform } from 'react-native';
2
2
  import { Buffer } from 'buffer';
3
3
  import {
4
- BleError,
5
4
  BleErrorCode,
6
5
  BleManager as BlePlxManager,
7
6
  ConnectionPriority,
@@ -32,7 +31,12 @@ import {
32
31
  parseOnekeyBleColorCode,
33
32
  } from '@onekeyfe/hd-shared';
34
33
 
35
- import { getConnectedDeviceIds, onDeviceBondState, pairDevice } from './BleManager';
34
+ import {
35
+ getBondedDevices,
36
+ getConnectedDeviceIds,
37
+ onDeviceBondState,
38
+ pairDevice,
39
+ } from './BleManager';
36
40
  import {
37
41
  hasWritableCapability,
38
42
  resolveProtocolV2PacketCapacity,
@@ -50,13 +54,14 @@ import {
50
54
  isSameBleUuid,
51
55
  } from './constants';
52
56
  import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from './bleNativeDisconnect';
57
+ import { isIosPeerRemovedPairingInformation, toIosStaleBondError } from './bleIosBond';
53
58
  import { isHeaderChunk } from './utils/validateNotify';
54
59
  import BleTransport from './BleTransport';
55
60
  import timer from './utils/timer';
56
61
  import { bleLogger, setBleLogger } from './logger';
57
62
 
58
63
  import type { Deferred } from '@onekeyfe/hd-shared';
59
- import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
64
+ import type { BleError, Characteristic, Device, Subscription } from 'react-native-ble-plx';
60
65
  import type EventEmitter from 'events';
61
66
  import type { BleAcquireInput, TransportOptions } from './types';
62
67
 
@@ -126,6 +131,32 @@ const delay = (ms: number) =>
126
131
  setTimeout(resolve, ms);
127
132
  });
128
133
 
134
+ /**
135
+ * Android createBond() can transiently refuse to start (returns
136
+ * { bonded: false, bonding: false }) right after the host removed a pairing while
137
+ * the peripheral is between advertisements. Bounded retries give the stack a
138
+ * chance to see the device again before we surface an error. This happens before
139
+ * GATT, so no side-effecting command is ever replayed.
140
+ */
141
+ const ANDROID_BOND_ATTEMPTS = 3;
142
+ const ANDROID_BOND_RETRY_DELAY_MS = 300;
143
+
144
+ /**
145
+ * BluetoothDevice#getAddress() and ble-plx ids are the same MAC but the exact
146
+ * separators/case vary across Android builds. Compare against the authoritative
147
+ * bonded list with separators stripped and case normalized.
148
+ */
149
+ const normalizeBleMac = (id?: string | null): string =>
150
+ (id ?? '').replace(/[\s:-]/g, '').toUpperCase();
151
+
152
+ /** Whether the Android system bonded-device list already contains this address. */
153
+ const findBondedDevice = async (macAddress: string): Promise<boolean> => {
154
+ const target = normalizeBleMac(macAddress);
155
+ if (!target) return false;
156
+ const bonded = await getBondedDevices();
157
+ return bonded.some(device => normalizeBleMac(device.id) === target);
158
+ };
159
+
129
160
  export const getFirmwareUploadWriteRetryType = (
130
161
  error: unknown
131
162
  ): FirmwareUploadWriteRetryType | null => {
@@ -185,8 +216,11 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
185
216
  return (
186
217
  isNativeBleDisconnectError(error) ||
187
218
  code === HardwareErrorCode.BleDeviceNotBonded ||
219
+ code === HardwareErrorCode.BleDeviceBondError ||
188
220
  code === HardwareErrorCode.BleDeviceBondedCanceled ||
221
+ code === HardwareErrorCode.BlePeerRemovedPairingInformation ||
189
222
  code === HardwareErrorCode.BleDeviceDisconnected ||
223
+ code === HardwareErrorCode.BleBondInvalid ||
190
224
  code === HardwareErrorCode.BleCharacteristicNotifyError ||
191
225
  code === HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
192
226
  code === HardwareErrorCode.BleWriteCharacteristicError
@@ -526,6 +560,19 @@ const isStaleGattTableNotifyReason = (reason: string | null | undefined): boolea
526
560
  * inside the native budget, so this only fires when the native timeout did not.
527
561
  */
528
562
  export const BLE_CONNECT_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS * 2 + 2000;
563
+ /**
564
+ * iOS names a bond the device no longer holds only by failing the connect, and
565
+ * on some phones that takes a little longer than the native budget: the
566
+ * attempt is cancelled first, the answer is lost, and two such timeouts reset
567
+ * the BLE manager and end as a connect timeout. A device that was just seen
568
+ * advertising is present, so its connect gets the time iOS needs. Without that
569
+ * sighting the budget stays short, because an absent device never answers.
570
+ */
571
+ export const IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS = 8000;
572
+ /** How recent a sighting must be to show that the device is present. */
573
+ export const IOS_PRESENT_DEVICE_WINDOW_MS = 15_000;
574
+ export const IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS =
575
+ IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS + (BLE_CONNECT_TIMEOUT_MS - BLE_NATIVE_CONNECT_TIMEOUT_MS);
529
576
  /**
530
577
  * Service discovery and characteristic resolution run after connect() succeeds, but
531
578
  * CoreBluetooth schedules them on the same serial queue. If that queue is wedged by a
@@ -655,6 +702,11 @@ const resolveNegotiatedMtu = (
655
702
  type IOBleErrorRemap = Error | BleError | null | undefined;
656
703
 
657
704
  function remapError(error: IOBleErrorRemap) {
705
+ // iOS can name the lost bond on the connect itself; that is the signal the
706
+ // App's re-pair dialog is keyed on, not a generic connect failure.
707
+ if (Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
708
+ throw toIosStaleBondError(error);
709
+ }
658
710
  if (isNativeBleDisconnectError(error)) {
659
711
  throw toBleDisconnectHardwareError(error);
660
712
  }
@@ -682,7 +734,10 @@ export default class ReactNativeBleTransport {
682
734
 
683
735
  stopped = false;
684
736
 
685
- private readonly bondAbortController = new AbortController();
737
+ private readonly activeBondControllers = new Map<string, Set<AbortController>>();
738
+
739
+ /** When a scan last saw each device on iOS; a fresh sighting earns one longer connect. */
740
+ private iosLastAdvertisedAt = new Map<string, number>();
686
741
 
687
742
  scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
688
743
 
@@ -728,6 +783,14 @@ export default class ReactNativeBleTransport {
728
783
  /** Android endpoints whose cached GATT table is suspect; the next connect refreshes it. */
729
784
  private androidGattCacheRefreshes = new Set<string>();
730
785
 
786
+ /**
787
+ * Android MACs this transport has observed bonded (from the bonded list, a
788
+ * successful pairDevice, or a completed onDeviceBondState). Used to distinguish
789
+ * "previously paired but the host no longer holds a bond" (re-pair) from
790
+ * "never paired" (plain not-bonded) when createBond() cannot be restarted.
791
+ */
792
+ private knownBondedDevices = new Set<string>();
793
+
731
794
  private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
732
795
 
733
796
  private protocolV2FrameQueues: Map<string, Uint8Array[]> = new Map();
@@ -1175,6 +1238,9 @@ export default class ReactNativeBleTransport {
1175
1238
  );
1176
1239
 
1177
1240
  const addDevice = (device: Device) => {
1241
+ // A sighting is presence evidence even when the same device was already
1242
+ // listed by an earlier round; the connect that follows may spend it.
1243
+ if (Platform.OS === 'ios') this.iosLastAdvertisedAt.set(device.id, Date.now());
1178
1244
  if (!finished && deviceList.every(d => d.id !== device.id)) {
1179
1245
  firstDeviceMs ??= Date.now() - scanStartedAt;
1180
1246
  const displayName = getDeviceDisplayName(device) ?? 'Unknown BLE Device';
@@ -1255,369 +1321,545 @@ export default class ReactNativeBleTransport {
1255
1321
  return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1256
1322
  }
1257
1323
 
1258
- private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1259
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1260
- const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1261
- const cachedTransport = transportCache[uuid];
1262
- if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1263
- Log?.debug(
1264
- '[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:',
1265
- uuid
1266
- );
1267
- const manager = this.blePlxManager;
1268
- await this.runNativeTeardown(uuid, manager, async () => {
1269
- await this.runBestEffortNativeOperation(
1270
- 'firmware install reconnect: cancel uncached device connection',
1271
- () => manager.cancelDeviceConnection(uuid)
1272
- );
1273
- });
1324
+ private createBondAbortController(uuid: string): AbortController {
1325
+ const controller = new AbortController();
1326
+ let controllers = this.activeBondControllers.get(uuid);
1327
+ if (!controllers) {
1328
+ controllers = new Set();
1329
+ this.activeBondControllers.set(uuid, controllers);
1274
1330
  }
1275
- if (cachedTransport) {
1276
- if (skipProtocolProbe) {
1277
- Log?.debug(
1278
- '[ReactNativeBleTransport] refresh cached BLE connection for firmware install:',
1279
- uuid
1280
- );
1281
- const manager = this.blePlxManager;
1282
- await this.releaseUnlocked(uuid, true);
1283
- await this.runNativeTeardown(uuid, manager, async () => {
1284
- const operations: Promise<unknown>[] = [];
1285
- if (manager) {
1286
- operations.push(
1287
- this.runBestEffortNativeOperation(
1288
- 'firmware install reconnect: cancel device connection',
1289
- () => manager.cancelDeviceConnection(uuid)
1290
- )
1291
- );
1292
- }
1293
- operations.push(
1294
- this.runBestEffortNativeOperation(
1295
- 'firmware install reconnect: device cancel connection',
1296
- () => cachedTransport.device.cancelConnection()
1297
- )
1298
- );
1299
- await Promise.all(operations);
1300
- });
1301
- } else {
1302
- const cachedProtocol = this.deviceProtocol.get(uuid);
1303
- const isCachedDeviceConnected = await cachedTransport.device
1304
- .isConnected()
1305
- .catch(() => false);
1306
- // A suspect GATT table is only refreshed through a new connect.
1307
- const isCachedAndroidLinkUsable =
1308
- Platform.OS !== 'android' || !this.androidGattCacheRefreshes.has(uuid);
1309
- if (
1310
- isCachedDeviceConnected &&
1311
- isCachedAndroidLinkUsable &&
1312
- cachedProtocol &&
1313
- (!expectedProtocol || cachedProtocol === expectedProtocol)
1314
- ) {
1315
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1316
- Log?.debug('[ReactNativeBleTransport] reuse cached BLE transport:', uuid, cachedProtocol);
1317
- return { uuid, protocolType: cachedProtocol };
1318
- }
1331
+ controllers.add(controller);
1332
+ return controller;
1333
+ }
1319
1334
 
1320
- /**
1321
- * If the transport is not reusable due to a protocol mismatch or stale
1322
- * connection, clean it up before creating a new transport instance.
1323
- */
1324
- Log?.debug('transport not reusable, will release: ', uuid);
1325
- await this.releaseUnlocked(uuid, true);
1326
- }
1335
+ private releaseBondAbortController(uuid: string, controller: AbortController): void {
1336
+ const controllers = this.activeBondControllers.get(uuid);
1337
+ if (!controllers) return;
1338
+ controllers.delete(controller);
1339
+ if (controllers.size === 0) {
1340
+ this.activeBondControllers.delete(uuid);
1327
1341
  }
1342
+ }
1328
1343
 
1329
- let device: Device | null = null;
1330
- const isAndroid = Platform.OS === 'android';
1331
- // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1332
- const refreshAndroidGattCache =
1333
- isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1334
- let nativeConnectOptions = connectOptions;
1335
- if (isAndroid) {
1336
- nativeConnectOptions = refreshAndroidGattCache
1337
- ? androidRefreshGattConnectOptions
1338
- : fallbackConnectOptions;
1344
+ private abortActiveBonding(uuid?: string): void {
1345
+ if (uuid !== undefined) {
1346
+ this.activeBondControllers.get(uuid)?.forEach(controller => controller.abort());
1347
+ return;
1339
1348
  }
1340
- // Only a connect that carried refreshGatt clears the marker; the fallback connects drop it.
1341
- let androidRefreshConnectRan = false;
1349
+ this.activeBondControllers.forEach(controllers => {
1350
+ controllers.forEach(controller => controller.abort());
1351
+ });
1352
+ }
1342
1353
 
1343
- if (forceCleanRunPromise && this.runPromise) {
1344
- const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
1345
- this.runPromise.reject(error);
1346
- this.runPromise = null;
1347
- this.runPromiseDeviceId = null;
1348
- Log?.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
1354
+ /**
1355
+ * stop(), cancel(), or disconnect() aborts bonding. Match other acquire
1356
+ * paths: report BleDeviceDisconnected so callers do not treat this as a
1357
+ * pairing failure that should pop another system dialog.
1358
+ */
1359
+ private throwIfBondingStopped(signal?: AbortSignal): void {
1360
+ if (this.stopped || signal?.aborted) {
1361
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1349
1362
  }
1363
+ }
1350
1364
 
1351
- const blePlxManager = await this.getPlxManager();
1352
- let skipPostConnectMtu = false;
1365
+ /** Retry delay that rejects as soon as stop() or cancel() aborts bonding. */
1366
+ private delayUnlessBondingStopped(ms: number, signal?: AbortSignal): Promise<void> {
1367
+ return new Promise((resolve, reject) => {
1368
+ if (this.stopped || signal?.aborted) {
1369
+ reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
1370
+ return;
1371
+ }
1372
+ const onAbort = () => {
1373
+ clearTimeout(timeout);
1374
+ reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
1375
+ };
1376
+ const timeout = setTimeout(() => {
1377
+ signal?.removeEventListener('abort', onAbort);
1378
+ if (this.stopped || signal?.aborted) {
1379
+ reject(ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected));
1380
+ return;
1381
+ }
1382
+ resolve();
1383
+ }, ms);
1384
+ signal?.addEventListener('abort', onAbort, { once: true });
1385
+ });
1386
+ }
1387
+
1388
+ /**
1389
+ * Android must bond before GATT so the peripheral cannot trigger its own
1390
+ * pairing mid-session. Three cases:
1391
+ * - The authoritative bonded list already has the device (OK-66336): skip
1392
+ * createBond entirely. BluetoothDevice#bondState can be stale (BOND_NONE)
1393
+ * and a blind createBond() then pops a redundant system dialog.
1394
+ * - createBond() returns { bonded: false, bonding: false } (OK-64703): retry a
1395
+ * bounded number of times with a short settle delay.
1396
+ * - Retries exhausted: report a re-pairing error for a device this transport
1397
+ * previously observed bonded, otherwise keep the "never paired" error.
1398
+ */
1399
+ private async ensureAndroidBond(uuid: string, acquireSignal?: AbortSignal): Promise<void> {
1400
+ const localController = acquireSignal ? undefined : this.createBondAbortController(uuid);
1401
+ const signal = acquireSignal ?? localController?.signal;
1353
1402
  try {
1354
- await subscribeBleOn(blePlxManager);
1355
- } catch (error) {
1356
- Log?.debug('subscribeBleOn error: ', error);
1357
- throw error;
1358
- }
1403
+ this.throwIfBondingStopped(signal);
1404
+ const key = normalizeBleMac(uuid);
1359
1405
 
1360
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1361
- if (Platform.OS === 'android') {
1362
- // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1363
1406
  try {
1364
- const bondState = await pairDevice(uuid);
1407
+ const bonded = await findBondedDevice(uuid);
1408
+ this.throwIfBondingStopped(signal);
1409
+ if (bonded) {
1410
+ this.knownBondedDevices.add(key);
1411
+ Log?.debug(
1412
+ '[ReactNativeBleTransport] Android device already bonded, skipping createBond:',
1413
+ uuid
1414
+ );
1415
+ return;
1416
+ }
1417
+ } catch (error) {
1418
+ this.throwIfBondingStopped(signal);
1419
+ // getBondedDevices can fail on older native builds or a transient adapter
1420
+ // error; fall back to the legacy pairDevice path below.
1421
+ Log?.debug(
1422
+ '[ReactNativeBleTransport] Android bonded list query failed, using pairDevice:',
1423
+ {
1424
+ uuid,
1425
+ error: error instanceof Error ? error.message : String(error),
1426
+ }
1427
+ );
1428
+ }
1429
+
1430
+ for (let attempt = 0; attempt < ANDROID_BOND_ATTEMPTS; attempt += 1) {
1431
+ this.throwIfBondingStopped(signal);
1432
+ let bondState;
1433
+ try {
1434
+ bondState = await pairDevice(uuid);
1435
+ } catch (error) {
1436
+ this.throwIfBondingStopped(signal);
1437
+ throw error;
1438
+ }
1439
+ this.throwIfBondingStopped(signal);
1365
1440
  if (bondState.bonding) {
1366
- await onDeviceBondState(uuid, this.bondAbortController.signal, {
1441
+ await onDeviceBondState(uuid, signal, {
1367
1442
  systemInitiated: bondState.initiated === false,
1368
1443
  });
1369
- } else if (!bondState.bonded) {
1370
- throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1444
+ this.throwIfBondingStopped(signal);
1445
+ this.knownBondedDevices.add(key);
1446
+ return;
1371
1447
  }
1372
- } catch (error) {
1373
- await this.runNativeTeardown(uuid, blePlxManager, async () => {
1374
- await this.runBestEffortNativeOperation('bond failure: cancel manager connection', () =>
1375
- blePlxManager.cancelDeviceConnection(uuid)
1448
+ if (bondState.bonded) {
1449
+ this.knownBondedDevices.add(key);
1450
+ return;
1451
+ }
1452
+ // { bonded: false, bonding: false }: createBond() could not start. Give the
1453
+ // device a moment to become visible/connectable before the next attempt.
1454
+ if (attempt + 1 < ANDROID_BOND_ATTEMPTS) {
1455
+ await this.delayUnlessBondingStopped(ANDROID_BOND_RETRY_DELAY_MS, signal);
1456
+ }
1457
+ }
1458
+
1459
+ this.throwIfBondingStopped(signal);
1460
+ if (this.knownBondedDevices.has(key)) {
1461
+ throw ERRORS.TypedError(
1462
+ HardwareErrorCode.BleDeviceBondError,
1463
+ 'Bluetooth pairing could not be restarted for a previously paired device',
1464
+ { phase: 'bond', reason: 'peer_removed_pairing', attempts: ANDROID_BOND_ATTEMPTS }
1465
+ );
1466
+ }
1467
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1468
+ } finally {
1469
+ if (localController) {
1470
+ this.releaseBondAbortController(uuid, localController);
1471
+ }
1472
+ }
1473
+ }
1474
+
1475
+ private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1476
+ this.throwIfBondingStopped();
1477
+ const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1478
+ const bondController = this.createBondAbortController(uuid);
1479
+ const bondSignal = bondController.signal;
1480
+ try {
1481
+ const cachedTransport = transportCache[uuid];
1482
+ if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1483
+ Log?.debug(
1484
+ '[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:',
1485
+ uuid
1486
+ );
1487
+ const manager = this.blePlxManager;
1488
+ await this.runNativeTeardown(uuid, manager, async () => {
1489
+ await this.runBestEffortNativeOperation(
1490
+ 'firmware install reconnect: cancel uncached device connection',
1491
+ () => manager.cancelDeviceConnection(uuid)
1376
1492
  );
1377
1493
  });
1378
- throw error;
1379
1494
  }
1380
- }
1381
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1495
+ if (cachedTransport) {
1496
+ if (skipProtocolProbe) {
1497
+ Log?.debug(
1498
+ '[ReactNativeBleTransport] refresh cached BLE connection for firmware install:',
1499
+ uuid
1500
+ );
1501
+ const manager = this.blePlxManager;
1502
+ await this.releaseUnlocked(uuid, true);
1503
+ await this.runNativeTeardown(uuid, manager, async () => {
1504
+ const operations: Promise<unknown>[] = [];
1505
+ if (manager) {
1506
+ operations.push(
1507
+ this.runBestEffortNativeOperation(
1508
+ 'firmware install reconnect: cancel device connection',
1509
+ () => manager.cancelDeviceConnection(uuid)
1510
+ )
1511
+ );
1512
+ }
1513
+ operations.push(
1514
+ this.runBestEffortNativeOperation(
1515
+ 'firmware install reconnect: device cancel connection',
1516
+ () => cachedTransport.device.cancelConnection()
1517
+ )
1518
+ );
1519
+ await Promise.all(operations);
1520
+ });
1521
+ } else {
1522
+ const cachedProtocol = this.deviceProtocol.get(uuid);
1523
+ const isCachedDeviceConnected = await cachedTransport.device
1524
+ .isConnected()
1525
+ .catch(() => false);
1526
+ // A suspect GATT table is only refreshed through a new connect.
1527
+ const isCachedAndroidLinkUsable =
1528
+ Platform.OS !== 'android' || !this.androidGattCacheRefreshes.has(uuid);
1529
+ if (
1530
+ isCachedDeviceConnected &&
1531
+ isCachedAndroidLinkUsable &&
1532
+ cachedProtocol &&
1533
+ (!expectedProtocol || cachedProtocol === expectedProtocol)
1534
+ ) {
1535
+ this.throwIfBondingStopped(bondSignal);
1536
+ Log?.debug(
1537
+ '[ReactNativeBleTransport] reuse cached BLE transport:',
1538
+ uuid,
1539
+ cachedProtocol
1540
+ );
1541
+ return { uuid, protocolType: cachedProtocol };
1542
+ }
1382
1543
 
1383
- if (!device) {
1384
- const devices = await blePlxManager.devices([uuid]);
1385
- [device] = devices;
1386
- }
1544
+ /**
1545
+ * If the transport is not reusable due to a protocol mismatch or stale
1546
+ * connection, clean it up before creating a new transport instance.
1547
+ */
1548
+ Log?.debug('transport not reusable, will release: ', uuid);
1549
+ await this.releaseUnlocked(uuid, true);
1550
+ }
1551
+ }
1387
1552
 
1388
- if (!device) {
1389
- const connectedDevice = await blePlxManager.connectedDevices(getBluetoothServiceUuids());
1390
- const deviceFilter = connectedDevice.filter(device => device.id === uuid);
1391
- Log?.debug(`found connected device count: ${deviceFilter.length}`);
1392
- [device] = deviceFilter;
1393
- }
1553
+ let device: Device | null = null;
1554
+ const isAndroid = Platform.OS === 'android';
1555
+ // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1556
+ const refreshAndroidGattCache =
1557
+ isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1558
+ let nativeConnectOptions = connectOptions;
1559
+ let bareConnectOptions = fallbackConnectOptions;
1560
+ let connectBackstopMs = BLE_CONNECT_TIMEOUT_MS;
1561
+ if (isAndroid) {
1562
+ nativeConnectOptions = refreshAndroidGattCache
1563
+ ? androidRefreshGattConnectOptions
1564
+ : fallbackConnectOptions;
1565
+ } else if (this.takeIosPresentDeviceSighting(uuid, skipProtocolProbe)) {
1566
+ const timeout = IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS;
1567
+ nativeConnectOptions = { ...connectOptions, timeout };
1568
+ bareConnectOptions = { ...fallbackConnectOptions, timeout };
1569
+ connectBackstopMs = IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS;
1570
+ }
1571
+ // Only a connect that carried refreshGatt clears the marker; the fallback connects drop it.
1572
+ let androidRefreshConnectRan = false;
1573
+
1574
+ if (forceCleanRunPromise && this.runPromise) {
1575
+ const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
1576
+ this.runPromise.reject(error);
1577
+ this.runPromise = null;
1578
+ this.runPromiseDeviceId = null;
1579
+ Log?.debug(
1580
+ 'Force clean Bluetooth run promise, forceCleanRunPromise: ',
1581
+ forceCleanRunPromise
1582
+ );
1583
+ }
1394
1584
 
1395
- if (!device) {
1396
- Log?.debug('try to connect to device: ', uuid);
1585
+ const blePlxManager = await this.getPlxManager();
1586
+ let skipPostConnectMtu = false;
1397
1587
  try {
1398
- device = await this.connectWithTimeout(uuid, () =>
1399
- blePlxManager.connectToDevice(uuid, nativeConnectOptions)
1400
- );
1401
- androidRefreshConnectRan = refreshAndroidGattCache;
1402
- } catch (e) {
1403
- Log?.debug('try to connect to device has error: ', e);
1404
- if (shouldRethrowBleSetupError(e)) {
1405
- throw e;
1588
+ await subscribeBleOn(blePlxManager);
1589
+ } catch (error) {
1590
+ Log?.debug('subscribeBleOn error: ', error);
1591
+ throw error;
1592
+ }
1593
+
1594
+ this.throwIfBondingStopped(bondSignal);
1595
+ if (Platform.OS === 'android') {
1596
+ // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1597
+ try {
1598
+ await this.ensureAndroidBond(uuid, bondSignal);
1599
+ } catch (error) {
1600
+ await this.runNativeTeardown(uuid, blePlxManager, async () => {
1601
+ await this.runBestEffortNativeOperation('bond failure: cancel manager connection', () =>
1602
+ blePlxManager.cancelDeviceConnection(uuid)
1603
+ );
1604
+ });
1605
+ throw error;
1406
1606
  }
1407
- if (isMtuOrCancelledConnectError(e)) {
1408
- skipPostConnectMtu = true;
1409
- Log?.debug('first try to reconnect without params');
1410
- device = await this.connectWithTimeout(uuid, () =>
1411
- blePlxManager.connectToDevice(uuid, fallbackConnectOptions)
1607
+ }
1608
+ this.throwIfBondingStopped(bondSignal);
1609
+
1610
+ if (!device) {
1611
+ const devices = await blePlxManager.devices([uuid]);
1612
+ [device] = devices;
1613
+ }
1614
+
1615
+ if (!device) {
1616
+ const connectedDevice = await blePlxManager.connectedDevices(getBluetoothServiceUuids());
1617
+ const deviceFilter = connectedDevice.filter(device => device.id === uuid);
1618
+ Log?.debug(`found connected device count: ${deviceFilter.length}`);
1619
+ [device] = deviceFilter;
1620
+ }
1621
+
1622
+ if (!device) {
1623
+ Log?.debug('try to connect to device: ', uuid);
1624
+ try {
1625
+ device = await this.connectWithTimeout(
1626
+ uuid,
1627
+ () => blePlxManager.connectToDevice(uuid, nativeConnectOptions),
1628
+ connectBackstopMs
1412
1629
  );
1413
- } else if (e.errorCode === BleErrorCode.DeviceAlreadyConnected) {
1414
- Log?.debug('device already connected');
1415
- throw ERRORS.TypedError(HardwareErrorCode.BleAlreadyConnected);
1416
- } else {
1417
- remapError(e);
1630
+ androidRefreshConnectRan = refreshAndroidGattCache;
1631
+ } catch (e) {
1632
+ Log?.debug('try to connect to device has error: ', e);
1633
+ if (shouldRethrowBleSetupError(e)) {
1634
+ throw e;
1635
+ }
1636
+ if (isMtuOrCancelledConnectError(e)) {
1637
+ skipPostConnectMtu = true;
1638
+ Log?.debug('first try to reconnect without params');
1639
+ device = await this.connectWithTimeout(
1640
+ uuid,
1641
+ () => blePlxManager.connectToDevice(uuid, bareConnectOptions),
1642
+ connectBackstopMs
1643
+ );
1644
+ } else if (e.errorCode === BleErrorCode.DeviceAlreadyConnected) {
1645
+ Log?.debug('device already connected');
1646
+ throw ERRORS.TypedError(HardwareErrorCode.BleAlreadyConnected);
1647
+ } else {
1648
+ remapError(e);
1649
+ }
1418
1650
  }
1419
1651
  }
1420
- }
1421
1652
 
1422
- if (!device) {
1423
- throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'unable to connect to device');
1424
- }
1653
+ if (!device) {
1654
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'unable to connect to device');
1655
+ }
1425
1656
 
1426
- if (
1427
- refreshAndroidGattCache &&
1428
- !androidRefreshConnectRan &&
1429
- (await device.isConnected().catch(() => false))
1430
- ) {
1431
- // refreshGatt only reaches the stack through a connect. A link that is still up would
1432
- // skip the connect below and keep serving the stale table, so it is dropped first.
1433
- await this.dropAndroidLink(uuid, blePlxManager, device, 'gatt cache refresh');
1434
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1435
- }
1657
+ if (
1658
+ refreshAndroidGattCache &&
1659
+ !androidRefreshConnectRan &&
1660
+ (await device.isConnected().catch(() => false))
1661
+ ) {
1662
+ // refreshGatt only reaches the stack through a connect. A link that is still up would
1663
+ // skip the connect below and keep serving the stale table, so it is dropped first.
1664
+ await this.dropAndroidLink(uuid, blePlxManager, device, 'gatt cache refresh');
1665
+ this.throwIfBondingStopped(bondSignal);
1666
+ }
1436
1667
 
1437
- if (!(await device.isConnected())) {
1438
- Log?.debug('not connected, try to connect to device: ', uuid);
1439
- const disconnectedDevice = device;
1668
+ if (!(await device.isConnected())) {
1669
+ Log?.debug('not connected, try to connect to device: ', uuid);
1670
+ const disconnectedDevice = device;
1440
1671
 
1441
- try {
1442
- device = await this.connectWithTimeout(uuid, () =>
1443
- disconnectedDevice.connect(nativeConnectOptions)
1444
- );
1445
- androidRefreshConnectRan = refreshAndroidGattCache;
1446
- } catch (e) {
1447
- Log?.debug('not connected, try to connect to device has error: ', e);
1448
- if (shouldRethrowBleSetupError(e)) {
1449
- throw e;
1450
- }
1451
- if (isMtuOrCancelledConnectError(e)) {
1452
- skipPostConnectMtu = true;
1453
- Log?.debug('second try to reconnect without params');
1454
- try {
1455
- device = await this.connectWithTimeout(uuid, () =>
1456
- disconnectedDevice.connect(fallbackConnectOptions)
1457
- );
1458
- } catch (fallbackError) {
1459
- Log?.debug('last try to reconnect error: ', fallbackError);
1460
- // last try to reconnect device if this issue exists
1461
- // https://github.com/dotintent/react-native-ble-plx/issues/426
1462
- if (fallbackError.errorCode === BleErrorCode.OperationCancelled) {
1463
- Log?.debug('last try to reconnect');
1464
- await disconnectedDevice.cancelConnection();
1465
- device = await this.connectWithTimeout(uuid, () =>
1466
- disconnectedDevice.connect(fallbackConnectOptions)
1672
+ try {
1673
+ device = await this.connectWithTimeout(
1674
+ uuid,
1675
+ () => disconnectedDevice.connect(nativeConnectOptions),
1676
+ connectBackstopMs
1677
+ );
1678
+ androidRefreshConnectRan = refreshAndroidGattCache;
1679
+ } catch (e) {
1680
+ Log?.debug('not connected, try to connect to device has error: ', e);
1681
+ if (shouldRethrowBleSetupError(e)) {
1682
+ throw e;
1683
+ }
1684
+ if (isMtuOrCancelledConnectError(e)) {
1685
+ skipPostConnectMtu = true;
1686
+ Log?.debug('second try to reconnect without params');
1687
+ try {
1688
+ device = await this.connectWithTimeout(
1689
+ uuid,
1690
+ () => disconnectedDevice.connect(bareConnectOptions),
1691
+ connectBackstopMs
1467
1692
  );
1468
- } else {
1469
- remapError(fallbackError);
1693
+ } catch (fallbackError) {
1694
+ Log?.debug('last try to reconnect error: ', fallbackError);
1695
+ // last try to reconnect device if this issue exists
1696
+ // https://github.com/dotintent/react-native-ble-plx/issues/426
1697
+ if (fallbackError.errorCode === BleErrorCode.OperationCancelled) {
1698
+ Log?.debug('last try to reconnect');
1699
+ await disconnectedDevice.cancelConnection();
1700
+ device = await this.connectWithTimeout(
1701
+ uuid,
1702
+ () => disconnectedDevice.connect(bareConnectOptions),
1703
+ connectBackstopMs
1704
+ );
1705
+ } else {
1706
+ remapError(fallbackError);
1707
+ }
1470
1708
  }
1709
+ } else {
1710
+ remapError(e);
1471
1711
  }
1472
- } else {
1473
- remapError(e);
1474
1712
  }
1475
1713
  }
1476
- }
1477
1714
 
1478
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1479
- if (Platform.OS === 'android' && !(await device.isConnected().catch(() => false))) {
1480
- const disconnectedDevice = device;
1481
- await this.runNativeTeardown(uuid, blePlxManager, async () => {
1482
- await Promise.all([
1483
- this.runBestEffortNativeOperation('connect failure: cancel manager connection', () =>
1484
- blePlxManager.cancelDeviceConnection(uuid)
1485
- ),
1486
- this.runBestEffortNativeOperation('connect failure: cancel device connection', () =>
1487
- disconnectedDevice.cancelConnection()
1488
- ),
1489
- ]);
1490
- });
1491
- throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'device is not connected');
1492
- }
1493
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1494
- let characteristics: ResolvedBleCharacteristics | undefined;
1495
- if (isAndroid) {
1496
- if (refreshAndroidGattCache) {
1497
- // refreshGatt has already started a full rediscovery; let it finish before the MTU
1498
- // exchange so the request is not queued behind it.
1499
- characteristics = await this.resolveCharacteristicsWithTimeout(uuid, device);
1500
- if (androidRefreshConnectRan) this.androidGattCacheRefreshes.delete(uuid);
1501
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1502
- }
1503
- device = await this.negotiateAndroidMtu(uuid, blePlxManager, device);
1504
- } else if (!skipPostConnectMtu) {
1505
- // Match 1.1.31: MTU is a connect() best-effort. If connect already fell back
1506
- // without requestMTU, do not put another requestMTU on the native serial
1507
- // queue — that is what wedges GATT after Account#2 reconnect.
1508
- const mtuResult = await resolveNegotiatedMtu(device, transactionId =>
1509
- blePlxManager.cancelTransaction(transactionId)
1510
- );
1511
- device = mtuResult.device;
1512
- if (mtuResult.timedOut) {
1513
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1514
- Log?.debug(
1515
- '[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU'
1516
- );
1517
- const timedOutDevice = device;
1518
- let mtuTeardownSettled = false;
1715
+ this.throwIfBondingStopped(bondSignal);
1716
+ if (Platform.OS === 'android' && !(await device.isConnected().catch(() => false))) {
1717
+ const disconnectedDevice = device;
1519
1718
  await this.runNativeTeardown(uuid, blePlxManager, async () => {
1520
- await this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () =>
1521
- timedOutDevice.cancelConnection()
1522
- );
1523
- mtuTeardownSettled = true;
1719
+ await Promise.all([
1720
+ this.runBestEffortNativeOperation('connect failure: cancel manager connection', () =>
1721
+ blePlxManager.cancelDeviceConnection(uuid)
1722
+ ),
1723
+ this.runBestEffortNativeOperation('connect failure: cancel device connection', () =>
1724
+ disconnectedDevice.cancelConnection()
1725
+ ),
1726
+ ]);
1524
1727
  });
1525
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1526
- if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
1527
- // The teardown budget expired and the manager that owned timedOutDevice was reset.
1528
- throw ERRORS.TypedError(HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
1728
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'device is not connected');
1729
+ }
1730
+ this.throwIfBondingStopped(bondSignal);
1731
+ let characteristics: ResolvedBleCharacteristics | undefined;
1732
+ if (isAndroid) {
1733
+ if (refreshAndroidGattCache) {
1734
+ // refreshGatt has already started a full rediscovery; let it finish before the MTU
1735
+ // exchange so the request is not queued behind it.
1736
+ characteristics = await this.resolveCharacteristicsWithTimeout(uuid, device);
1737
+ if (androidRefreshConnectRan) this.androidGattCacheRefreshes.delete(uuid);
1738
+ this.throwIfBondingStopped(bondSignal);
1529
1739
  }
1530
- try {
1531
- device = await this.connectWithTimeout(uuid, () =>
1532
- timedOutDevice.connect(fallbackConnectOptions)
1740
+ device = await this.negotiateAndroidMtu(uuid, blePlxManager, device);
1741
+ } else if (!skipPostConnectMtu) {
1742
+ // Match 1.1.31: MTU is a connect() best-effort. If connect already fell back
1743
+ // without requestMTU, do not put another requestMTU on the native serial
1744
+ // queue — that is what wedges GATT after Account#2 reconnect.
1745
+ const mtuResult = await resolveNegotiatedMtu(device, transactionId =>
1746
+ blePlxManager.cancelTransaction(transactionId)
1747
+ );
1748
+ device = mtuResult.device;
1749
+ if (mtuResult.timedOut) {
1750
+ this.throwIfBondingStopped(bondSignal);
1751
+ Log?.debug(
1752
+ '[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU'
1533
1753
  );
1534
- } catch (error) {
1535
- if (shouldRethrowBleSetupError(error)) throw error;
1536
- if (
1537
- (error as { errorCode?: unknown })?.errorCode === BleErrorCode.DeviceAlreadyConnected
1538
- ) {
1539
- // GATT resolution and the protocol probe below still validate the retained link.
1540
- device = timedOutDevice;
1541
- } else {
1542
- remapError(error);
1754
+ const timedOutDevice = device;
1755
+ let mtuTeardownSettled = false;
1756
+ await this.runNativeTeardown(uuid, blePlxManager, async () => {
1757
+ await this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () =>
1758
+ timedOutDevice.cancelConnection()
1759
+ );
1760
+ mtuTeardownSettled = true;
1761
+ });
1762
+ this.throwIfBondingStopped(bondSignal);
1763
+ if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
1764
+ // The teardown budget expired and the manager that owned timedOutDevice was reset.
1765
+ throw ERRORS.TypedError(HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
1766
+ }
1767
+ try {
1768
+ device = await this.connectWithTimeout(
1769
+ uuid,
1770
+ () => timedOutDevice.connect(bareConnectOptions),
1771
+ connectBackstopMs
1772
+ );
1773
+ } catch (error) {
1774
+ if (shouldRethrowBleSetupError(error)) throw error;
1775
+ if (
1776
+ (error as { errorCode?: unknown })?.errorCode === BleErrorCode.DeviceAlreadyConnected
1777
+ ) {
1778
+ // GATT resolution and the protocol probe below still validate the retained link.
1779
+ device = timedOutDevice;
1780
+ } else {
1781
+ remapError(error);
1782
+ }
1543
1783
  }
1544
1784
  }
1545
1785
  }
1546
- }
1547
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1548
- const acquiredDevice = device;
1549
- const { writeCharacteristic, notifyCharacteristic } =
1550
- characteristics ?? (await this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
1551
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1786
+ this.throwIfBondingStopped(bondSignal);
1787
+ const acquiredDevice = device;
1788
+ const { writeCharacteristic, notifyCharacteristic } =
1789
+ characteristics ?? (await this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
1790
+ this.throwIfBondingStopped(bondSignal);
1552
1791
 
1553
- const protocolHint = expectedProtocol
1554
- ? undefined
1555
- : input.protocolHint ?? this.deviceProtocolHints.get(uuid);
1792
+ const protocolHint = expectedProtocol
1793
+ ? undefined
1794
+ : input.protocolHint ?? this.deviceProtocolHints.get(uuid);
1556
1795
 
1557
- // release transport before new transport instance
1558
- await this.releaseUnlocked(uuid, true);
1559
- if (protocolHint) {
1560
- this.deviceProtocolHints.set(uuid, protocolHint);
1561
- }
1796
+ // release transport before new transport instance
1797
+ await this.releaseUnlocked(uuid, true);
1798
+ if (protocolHint) {
1799
+ this.deviceProtocolHints.set(uuid, protocolHint);
1800
+ }
1562
1801
 
1563
- try {
1564
- await this.installTransportForAcquire(uuid, acquiredDevice, {
1565
- writeCharacteristic,
1566
- notifyCharacteristic,
1567
- });
1802
+ try {
1803
+ await this.installTransportForAcquire(uuid, acquiredDevice, {
1804
+ writeCharacteristic,
1805
+ notifyCharacteristic,
1806
+ });
1568
1807
 
1569
- if (skipProtocolProbe) {
1570
- if (!expectedProtocol) {
1571
- throw ERRORS.TypedError(
1572
- HardwareErrorCode.RuntimeError,
1573
- 'skipProtocolProbe requires an expected BLE protocol'
1574
- );
1575
- }
1576
- const hasConfirmedProtocol =
1577
- this.sessionProtocols.get(uuid) === expectedProtocol ||
1578
- (expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
1579
- if (!hasConfirmedProtocol) {
1580
- throw ERRORS.TypedError(
1581
- HardwareErrorCode.RuntimeError,
1582
- 'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint'
1583
- );
1808
+ if (skipProtocolProbe) {
1809
+ if (!expectedProtocol) {
1810
+ throw ERRORS.TypedError(
1811
+ HardwareErrorCode.RuntimeError,
1812
+ 'skipProtocolProbe requires an expected BLE protocol'
1813
+ );
1814
+ }
1815
+ const hasConfirmedProtocol =
1816
+ this.sessionProtocols.get(uuid) === expectedProtocol ||
1817
+ (expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
1818
+ if (!hasConfirmedProtocol) {
1819
+ throw ERRORS.TypedError(
1820
+ HardwareErrorCode.RuntimeError,
1821
+ 'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint'
1822
+ );
1823
+ }
1824
+ this.deviceProtocol.set(uuid, expectedProtocol);
1825
+ this.sessionProtocols.set(uuid, expectedProtocol);
1826
+ this.protocolReprobeFailures.delete(uuid);
1827
+ Log?.debug('[ReactNativeBleTransport] protocol selected without probe', {
1828
+ deviceId: uuid,
1829
+ protocol: expectedProtocol,
1830
+ source: 'firmware-install-reconnect',
1831
+ });
1832
+ const currentTransport = transportCache[uuid];
1833
+ if (!currentTransport) {
1834
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1835
+ }
1836
+ this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1837
+ return { uuid, protocolType: expectedProtocol };
1584
1838
  }
1585
- this.deviceProtocol.set(uuid, expectedProtocol);
1586
- this.sessionProtocols.set(uuid, expectedProtocol);
1587
- this.protocolReprobeFailures.delete(uuid);
1588
- Log?.debug('[ReactNativeBleTransport] protocol selected without probe', {
1589
- deviceId: uuid,
1590
- protocol: expectedProtocol,
1591
- source: 'firmware-install-reconnect',
1592
- });
1839
+
1840
+ const protocolType = await this.detectProtocol(
1841
+ uuid,
1842
+ expectedProtocol,
1843
+ protocolHint,
1844
+ async () => {
1845
+ await this.installTransportForAcquire(uuid, acquiredDevice);
1846
+ }
1847
+ );
1848
+ this.throwIfBondingStopped(bondSignal);
1593
1849
  const currentTransport = transportCache[uuid];
1594
1850
  if (!currentTransport) {
1595
1851
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1596
1852
  }
1597
1853
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1598
- return { uuid, protocolType: expectedProtocol };
1599
- }
1600
-
1601
- const protocolType = await this.detectProtocol(
1602
- uuid,
1603
- expectedProtocol,
1604
- protocolHint,
1605
- async () => {
1606
- await this.installTransportForAcquire(uuid, acquiredDevice);
1607
- }
1608
- );
1609
- if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1610
- const currentTransport = transportCache[uuid];
1611
- if (!currentTransport) {
1612
- throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1854
+ return { uuid, protocolType };
1855
+ } catch (error) {
1856
+ // A failed acquire must retire the physical link before Core retries. Logical
1857
+ // release leaves GATT connected even when neither protocol receives a response.
1858
+ await this.disconnectUnlocked(uuid);
1859
+ throw error;
1613
1860
  }
1614
- this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1615
- return { uuid, protocolType };
1616
- } catch (error) {
1617
- // A failed acquire must retire the physical link before Core retries. Logical
1618
- // release leaves GATT connected even when neither protocol receives a response.
1619
- await this.disconnectUnlocked(uuid);
1620
- throw error;
1861
+ } finally {
1862
+ this.releaseBondAbortController(uuid, bondController);
1621
1863
  }
1622
1864
  }
1623
1865
 
@@ -1645,6 +1887,17 @@ export default class ReactNativeBleTransport {
1645
1887
  Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1646
1888
  return;
1647
1889
  }
1890
+ if (Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
1891
+ const staleBondError = toIosStaleBondError(error);
1892
+ if (this.getActiveProtocol(uuid) === 'V2') {
1893
+ this.rejectProtocolV2Frames(uuid, staleBondError);
1894
+ return;
1895
+ }
1896
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
1897
+ this.runPromise.reject(staleBondError);
1898
+ }
1899
+ return;
1900
+ }
1648
1901
  if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1649
1902
  this.androidGattCacheRefreshes.add(uuid);
1650
1903
  }
@@ -2151,7 +2404,7 @@ export default class ReactNativeBleTransport {
2151
2404
  if (this.stopPromise) return this.stopPromise;
2152
2405
  this.stopped = true;
2153
2406
  // Bonding precedes GATT, so cancelDeviceConnection cannot end this wait.
2154
- this.bondAbortController.abort();
2407
+ this.abortActiveBonding();
2155
2408
  const deviceIds = new Set([
2156
2409
  ...this.monitorTokens.keys(),
2157
2410
  ...this.sessionProtocols.keys(),
@@ -2162,6 +2415,7 @@ export default class ReactNativeBleTransport {
2162
2415
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
2163
2416
  this.androidPriorityResetTimers.clear();
2164
2417
  this.androidHighPriorityDevices.clear();
2418
+ this.iosLastAdvertisedAt.clear();
2165
2419
  const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
2166
2420
  this.runPromise?.reject(error);
2167
2421
  this.runPromise = null;
@@ -2194,6 +2448,7 @@ export default class ReactNativeBleTransport {
2194
2448
  }
2195
2449
 
2196
2450
  async disconnect(session: string) {
2451
+ this.abortActiveBonding(session);
2197
2452
  return this.runLifecycleOperation(session, () => this.disconnectUnlocked(session));
2198
2453
  }
2199
2454
 
@@ -2347,11 +2602,12 @@ export default class ReactNativeBleTransport {
2347
2602
  }
2348
2603
  }
2349
2604
 
2350
- async cancel() {
2351
- Log?.debug('transport-react-native transport cancel');
2605
+ async cancel(uuid?: string) {
2606
+ Log?.debug('transport-react-native transport cancel', uuid);
2607
+ this.abortActiveBonding(uuid);
2352
2608
  const pending = this.runPromise;
2353
2609
  const deviceId = this.runPromiseDeviceId;
2354
- if (pending) {
2610
+ if (pending && (uuid === undefined || deviceId === uuid)) {
2355
2611
  pending.reject(ERRORS.TypedError(HardwareErrorCode.CallQueueActionCancelled));
2356
2612
  if (this.runPromise === pending) {
2357
2613
  this.runPromise = null;
@@ -2455,8 +2711,25 @@ export default class ReactNativeBleTransport {
2455
2711
  });
2456
2712
  }
2457
2713
 
2714
+ /**
2715
+ * Whether this acquire may spend the longer iOS connect budget. The sighting is used up: the
2716
+ * retry that follows a timeout gets no new scan, and the device may have left by then. A
2717
+ * firmware-install reconnect keeps its short polling cadence.
2718
+ */
2719
+ private takeIosPresentDeviceSighting(uuid: string, skipProtocolProbe?: boolean): boolean {
2720
+ if (Platform.OS !== 'ios') return false;
2721
+ const seenAt = this.iosLastAdvertisedAt.get(uuid);
2722
+ this.iosLastAdvertisedAt.delete(uuid);
2723
+ if (skipProtocolProbe || seenAt === undefined) return false;
2724
+ return Date.now() - seenAt <= IOS_PRESENT_DEVICE_WINDOW_MS;
2725
+ }
2726
+
2458
2727
  /** Run a native connect under the JS backstop budget. */
2459
- private async connectWithTimeout<T>(uuid: string, connect: () => Promise<T>): Promise<T> {
2728
+ private async connectWithTimeout<T>(
2729
+ uuid: string,
2730
+ connect: () => Promise<T>,
2731
+ backstopMs = BLE_CONNECT_TIMEOUT_MS
2732
+ ): Promise<T> {
2460
2733
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
2461
2734
  const startedAt = Date.now();
2462
2735
  let succeeded = false;
@@ -2475,10 +2748,10 @@ export default class ReactNativeBleTransport {
2475
2748
  reject(
2476
2749
  ERRORS.TypedError(
2477
2750
  HardwareErrorCode.BleConnectedError,
2478
- `BLE connect timeout after ${BLE_CONNECT_TIMEOUT_MS}ms for ${uuid}`
2751
+ `BLE connect timeout after ${backstopMs}ms for ${uuid}`
2479
2752
  )
2480
2753
  );
2481
- }, BLE_CONNECT_TIMEOUT_MS);
2754
+ }, backstopMs);
2482
2755
  }),
2483
2756
  ]);
2484
2757
  succeeded = true;
@@ -2501,6 +2774,7 @@ export default class ReactNativeBleTransport {
2501
2774
  elapsedMs: Date.now() - startedAt,
2502
2775
  succeeded,
2503
2776
  backstopExpired: timedOut,
2777
+ backstopMs,
2504
2778
  });
2505
2779
  }
2506
2780
  }
@@ -2544,6 +2818,12 @@ export default class ReactNativeBleTransport {
2544
2818
  throw this.createWedgedBleSetupError();
2545
2819
  }
2546
2820
  }
2821
+ if (Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
2822
+ // iOS can report the lost bond on the first GATT operation instead of
2823
+ // on the connect. Check it before the generic disconnect mapping: the
2824
+ // same native failure may also carry the ble-plx disconnect code.
2825
+ throw toIosStaleBondError(error);
2826
+ }
2547
2827
  if (isNativeBleDisconnectError(error)) {
2548
2828
  throw toBleDisconnectHardwareError(error);
2549
2829
  }
@@ -2701,6 +2981,7 @@ export default class ReactNativeBleTransport {
2701
2981
 
2702
2982
  private resetPlxManager() {
2703
2983
  if (bleManagerResetPromise) return;
2984
+ this.iosLastAdvertisedAt.clear();
2704
2985
  const manager = this.blePlxManager;
2705
2986
  this.blePlxManager = undefined;
2706
2987
  const reason = 'React Native BLE manager reset';
@@ -3005,24 +3286,29 @@ export default class ReactNativeBleTransport {
3005
3286
 
3006
3287
  this.probingProtocols.set(uuid, 'V2');
3007
3288
  this.protocolV2Assemblers.get(uuid)?.reset();
3008
- const detected = await probeProtocolV2Helper({
3009
- call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
3010
- this.callProtocolV2(uuid, name, data, options),
3011
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
3012
- logger: Log,
3013
- logPrefix: 'ProtocolV2 RN-BLE',
3014
- onProbeFailed: () => {
3015
- this.protocolV2Assemblers.get(uuid)?.reset();
3016
- this.resetProtocolV2Frames(uuid);
3017
- },
3018
- shouldRethrow: shouldRethrowProtocolProbeError,
3019
- });
3020
- if (!detected) {
3289
+ try {
3290
+ const detected = await probeProtocolV2Helper({
3291
+ call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
3292
+ this.callProtocolV2(uuid, name, data, options),
3293
+ timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
3294
+ logger: Log,
3295
+ logPrefix: 'ProtocolV2 RN-BLE',
3296
+ onProbeFailed: () => {
3297
+ this.protocolV2Assemblers.get(uuid)?.reset();
3298
+ this.resetProtocolV2Frames(uuid);
3299
+ },
3300
+ shouldRethrow: shouldRethrowProtocolProbeError,
3301
+ });
3302
+ if (!detected) {
3303
+ this.clearProbeProtocol(uuid, 'V2');
3304
+ } else {
3305
+ this.probingProtocols.delete(uuid);
3306
+ }
3307
+ return detected;
3308
+ } catch (error) {
3021
3309
  this.clearProbeProtocol(uuid, 'V2');
3022
- } else {
3023
- this.probingProtocols.delete(uuid);
3310
+ throw error;
3024
3311
  }
3025
- return detected;
3026
3312
  }
3027
3313
 
3028
3314
  private handleProtocolV2Notification(uuid: string, monitorToken: number, data: Uint8Array) {