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

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/dist/index.js CHANGED
@@ -71,6 +71,7 @@ const bondFailureReasons = {
71
71
  9: 'removed',
72
72
  };
73
73
  const getConnectedDeviceIds = (serviceUuids) => BleUtils.getConnectedPeripherals(serviceUuids);
74
+ const getBondedDevices = () => BleUtils.getBondedPeripherals();
74
75
  const pairDevice = (macAddress) => BleUtils.pairDevice(macAddress);
75
76
  const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
76
77
  const createBondFailureError = (bondState) => {
@@ -296,6 +297,22 @@ const toBleDisconnectHardwareError = (error) => {
296
297
  return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected, nativeErrorText(nativeError) || undefined);
297
298
  };
298
299
 
300
+ const IOS_PEER_REMOVED_PAIRING_INFORMATION = 14;
301
+ const isIosPeerRemovedPairingInformation = (error) => {
302
+ if (!error || typeof error !== 'object') {
303
+ return false;
304
+ }
305
+ return error.iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION;
306
+ };
307
+ const toIosStaleBondError = (error) => {
308
+ const nativeError = (error !== null && error !== void 0 ? error : {});
309
+ const nativeErrorMessage = [nativeError.reason, nativeError.message]
310
+ .filter((value) => typeof value === 'string')
311
+ .join(' ')
312
+ .slice(0, 240);
313
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation, hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation], Object.assign({ phase: 'connect', reason: 'peer_removed_pairing_information' }, (nativeErrorMessage ? { nativeErrorMessage } : {})));
314
+ };
315
+
299
316
  const isHeaderChunk = (chunk) => {
300
317
  if (chunk.length < 9)
301
318
  return false;
@@ -365,6 +382,16 @@ const hasGattCongestedStatus = (text) => {
365
382
  const delay = (ms) => new Promise(resolve => {
366
383
  setTimeout(resolve, ms);
367
384
  });
385
+ const ANDROID_BOND_ATTEMPTS = 3;
386
+ const ANDROID_BOND_RETRY_DELAY_MS = 300;
387
+ const normalizeBleMac = (id) => (id !== null && id !== void 0 ? id : '').replace(/[\s:-]/g, '').toUpperCase();
388
+ const findBondedDevice = (macAddress) => __awaiter(void 0, void 0, void 0, function* () {
389
+ const target = normalizeBleMac(macAddress);
390
+ if (!target)
391
+ return false;
392
+ const bonded = yield getBondedDevices();
393
+ return bonded.some(device => normalizeBleMac(device.id) === target);
394
+ });
368
395
  const getFirmwareUploadWriteRetryType = (error) => {
369
396
  if (!error || typeof error !== 'object')
370
397
  return null;
@@ -392,8 +419,11 @@ const shouldRethrowProtocolProbeError = (error) => {
392
419
  const code = error === null || error === void 0 ? void 0 : error.errorCode;
393
420
  return (isNativeBleDisconnectError(error) ||
394
421
  code === hdShared.HardwareErrorCode.BleDeviceNotBonded ||
422
+ code === hdShared.HardwareErrorCode.BleDeviceBondError ||
395
423
  code === hdShared.HardwareErrorCode.BleDeviceBondedCanceled ||
424
+ code === hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation ||
396
425
  code === hdShared.HardwareErrorCode.BleDeviceDisconnected ||
426
+ code === hdShared.HardwareErrorCode.BleBondInvalid ||
397
427
  code === hdShared.HardwareErrorCode.BleCharacteristicNotifyError ||
398
428
  code === hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
399
429
  code === hdShared.HardwareErrorCode.BleWriteCharacteristicError);
@@ -593,6 +623,9 @@ const isStaleGattTableNotifyReason = (reason) => !!reason &&
593
623
  reason.includes('The handle is invalid') ||
594
624
  reason.includes('Writing is not permitted'));
595
625
  const BLE_CONNECT_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS * 2 + 2000;
626
+ const IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS = 8000;
627
+ const IOS_PRESENT_DEVICE_WINDOW_MS = 15000;
628
+ const IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS = IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS + (BLE_CONNECT_TIMEOUT_MS - BLE_NATIVE_CONNECT_TIMEOUT_MS);
596
629
  const BLE_GATT_SETUP_TIMEOUT_MS = 10000;
597
630
  const PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = 3;
598
631
  const BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
@@ -683,6 +716,9 @@ const resolveNegotiatedMtu = (device, cancelTransaction) => shouldRefreshNegotia
683
716
  : Promise.resolve({ device, timedOut: false });
684
717
  function remapError(error) {
685
718
  var _a, _b;
719
+ if (reactNative.Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
720
+ throw toIosStaleBondError(error);
721
+ }
686
722
  if (isNativeBleDisconnectError(error)) {
687
723
  throw toBleDisconnectHardwareError(error);
688
724
  }
@@ -697,7 +733,8 @@ class ReactNativeBleTransport {
697
733
  this.name = 'ReactNativeBleTransport';
698
734
  this.configured = false;
699
735
  this.stopped = false;
700
- this.bondAbortController = new AbortController();
736
+ this.activeBondControllers = new Map();
737
+ this.iosLastAdvertisedAt = new Map();
701
738
  this.scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
702
739
  this.runPromise = null;
703
740
  this.runPromiseDeviceId = null;
@@ -712,6 +749,7 @@ class ReactNativeBleTransport {
712
749
  this.protocolReprobeFailures = new Map();
713
750
  this.silentDetections = new Map();
714
751
  this.androidGattCacheRefreshes = new Set();
752
+ this.knownBondedDevices = new Set();
715
753
  this.protocolV2Assemblers = new Map();
716
754
  this.protocolV2FrameQueues = new Map();
717
755
  this.protocolV2FramePromises = new Map();
@@ -1096,6 +1134,8 @@ class ReactNativeBleTransport {
1096
1134
  }, error => Log === null || Log === void 0 ? void 0 : Log.debug('search connected peripheral failed:', error));
1097
1135
  const addDevice = (device) => {
1098
1136
  var _a;
1137
+ if (reactNative.Platform.OS === 'ios')
1138
+ this.iosLastAdvertisedAt.set(device.id, Date.now());
1099
1139
  if (!finished && deviceList.every(d => d.id !== device.id)) {
1100
1140
  firstDeviceMs !== null && firstDeviceMs !== void 0 ? firstDeviceMs : (firstDeviceMs = Date.now() - scanStartedAt);
1101
1141
  const displayName = (_a = getDeviceDisplayName(device)) !== null && _a !== void 0 ? _a : 'Unknown BLE Device';
@@ -1157,297 +1197,412 @@ class ReactNativeBleTransport {
1157
1197
  return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1158
1198
  });
1159
1199
  }
1200
+ createBondAbortController(uuid) {
1201
+ const controller = new AbortController();
1202
+ let controllers = this.activeBondControllers.get(uuid);
1203
+ if (!controllers) {
1204
+ controllers = new Set();
1205
+ this.activeBondControllers.set(uuid, controllers);
1206
+ }
1207
+ controllers.add(controller);
1208
+ return controller;
1209
+ }
1210
+ releaseBondAbortController(uuid, controller) {
1211
+ const controllers = this.activeBondControllers.get(uuid);
1212
+ if (!controllers)
1213
+ return;
1214
+ controllers.delete(controller);
1215
+ if (controllers.size === 0) {
1216
+ this.activeBondControllers.delete(uuid);
1217
+ }
1218
+ }
1219
+ abortActiveBonding(uuid) {
1220
+ var _a;
1221
+ if (uuid !== undefined) {
1222
+ (_a = this.activeBondControllers.get(uuid)) === null || _a === void 0 ? void 0 : _a.forEach(controller => controller.abort());
1223
+ return;
1224
+ }
1225
+ this.activeBondControllers.forEach(controllers => {
1226
+ controllers.forEach(controller => controller.abort());
1227
+ });
1228
+ }
1229
+ throwIfBondingStopped(signal) {
1230
+ if (this.stopped || (signal === null || signal === void 0 ? void 0 : signal.aborted)) {
1231
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1232
+ }
1233
+ }
1234
+ delayUnlessBondingStopped(ms, signal) {
1235
+ return new Promise((resolve, reject) => {
1236
+ if (this.stopped || (signal === null || signal === void 0 ? void 0 : signal.aborted)) {
1237
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
1238
+ return;
1239
+ }
1240
+ const onAbort = () => {
1241
+ clearTimeout(timeout);
1242
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
1243
+ };
1244
+ const timeout = setTimeout(() => {
1245
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
1246
+ if (this.stopped || (signal === null || signal === void 0 ? void 0 : signal.aborted)) {
1247
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
1248
+ return;
1249
+ }
1250
+ resolve();
1251
+ }, ms);
1252
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onAbort, { once: true });
1253
+ });
1254
+ }
1255
+ ensureAndroidBond(uuid, acquireSignal) {
1256
+ return __awaiter(this, void 0, void 0, function* () {
1257
+ const localController = acquireSignal ? undefined : this.createBondAbortController(uuid);
1258
+ const signal = acquireSignal !== null && acquireSignal !== void 0 ? acquireSignal : localController === null || localController === void 0 ? void 0 : localController.signal;
1259
+ try {
1260
+ this.throwIfBondingStopped(signal);
1261
+ const key = normalizeBleMac(uuid);
1262
+ try {
1263
+ const bonded = yield findBondedDevice(uuid);
1264
+ this.throwIfBondingStopped(signal);
1265
+ if (bonded) {
1266
+ this.knownBondedDevices.add(key);
1267
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android device already bonded, skipping createBond:', uuid);
1268
+ return;
1269
+ }
1270
+ }
1271
+ catch (error) {
1272
+ this.throwIfBondingStopped(signal);
1273
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android bonded list query failed, using pairDevice:', {
1274
+ uuid,
1275
+ error: error instanceof Error ? error.message : String(error),
1276
+ });
1277
+ }
1278
+ for (let attempt = 0; attempt < ANDROID_BOND_ATTEMPTS; attempt += 1) {
1279
+ this.throwIfBondingStopped(signal);
1280
+ let bondState;
1281
+ try {
1282
+ bondState = yield pairDevice(uuid);
1283
+ }
1284
+ catch (error) {
1285
+ this.throwIfBondingStopped(signal);
1286
+ throw error;
1287
+ }
1288
+ this.throwIfBondingStopped(signal);
1289
+ if (bondState.bonding) {
1290
+ yield onDeviceBondState(uuid, signal, {
1291
+ systemInitiated: bondState.initiated === false,
1292
+ });
1293
+ this.throwIfBondingStopped(signal);
1294
+ this.knownBondedDevices.add(key);
1295
+ return;
1296
+ }
1297
+ if (bondState.bonded) {
1298
+ this.knownBondedDevices.add(key);
1299
+ return;
1300
+ }
1301
+ if (attempt + 1 < ANDROID_BOND_ATTEMPTS) {
1302
+ yield this.delayUnlessBondingStopped(ANDROID_BOND_RETRY_DELAY_MS, signal);
1303
+ }
1304
+ }
1305
+ this.throwIfBondingStopped(signal);
1306
+ if (this.knownBondedDevices.has(key)) {
1307
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceBondError, 'Bluetooth pairing could not be restarted for a previously paired device', { phase: 'bond', reason: 'peer_removed_pairing', attempts: ANDROID_BOND_ATTEMPTS });
1308
+ }
1309
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1310
+ }
1311
+ finally {
1312
+ if (localController) {
1313
+ this.releaseBondAbortController(uuid, localController);
1314
+ }
1315
+ }
1316
+ });
1317
+ }
1160
1318
  acquireUnlocked(input) {
1161
1319
  var _a;
1162
1320
  return __awaiter(this, void 0, void 0, function* () {
1163
- if (this.stopped)
1164
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1321
+ this.throwIfBondingStopped();
1165
1322
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1166
- const cachedTransport = transportCache[uuid];
1167
- if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1168
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:', uuid);
1169
- const manager = this.blePlxManager;
1170
- yield this.runNativeTeardown(uuid, manager, () => __awaiter(this, void 0, void 0, function* () {
1171
- yield this.runBestEffortNativeOperation('firmware install reconnect: cancel uncached device connection', () => manager.cancelDeviceConnection(uuid));
1172
- }));
1173
- }
1174
- if (cachedTransport) {
1175
- if (skipProtocolProbe) {
1176
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh cached BLE connection for firmware install:', uuid);
1323
+ const bondController = this.createBondAbortController(uuid);
1324
+ const bondSignal = bondController.signal;
1325
+ try {
1326
+ const cachedTransport = transportCache[uuid];
1327
+ if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1328
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:', uuid);
1177
1329
  const manager = this.blePlxManager;
1178
- yield this.releaseUnlocked(uuid, true);
1179
1330
  yield this.runNativeTeardown(uuid, manager, () => __awaiter(this, void 0, void 0, function* () {
1180
- const operations = [];
1181
- if (manager) {
1182
- operations.push(this.runBestEffortNativeOperation('firmware install reconnect: cancel device connection', () => manager.cancelDeviceConnection(uuid)));
1183
- }
1184
- operations.push(this.runBestEffortNativeOperation('firmware install reconnect: device cancel connection', () => cachedTransport.device.cancelConnection()));
1185
- yield Promise.all(operations);
1331
+ yield this.runBestEffortNativeOperation('firmware install reconnect: cancel uncached device connection', () => manager.cancelDeviceConnection(uuid));
1186
1332
  }));
1187
1333
  }
1188
- else {
1189
- const cachedProtocol = this.deviceProtocol.get(uuid);
1190
- const isCachedDeviceConnected = yield cachedTransport.device
1191
- .isConnected()
1192
- .catch(() => false);
1193
- const isCachedAndroidLinkUsable = reactNative.Platform.OS !== 'android' || !this.androidGattCacheRefreshes.has(uuid);
1194
- if (isCachedDeviceConnected &&
1195
- isCachedAndroidLinkUsable &&
1196
- cachedProtocol &&
1197
- (!expectedProtocol || cachedProtocol === expectedProtocol)) {
1198
- if (this.stopped)
1199
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1200
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] reuse cached BLE transport:', uuid, cachedProtocol);
1201
- return { uuid, protocolType: cachedProtocol };
1334
+ if (cachedTransport) {
1335
+ if (skipProtocolProbe) {
1336
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh cached BLE connection for firmware install:', uuid);
1337
+ const manager = this.blePlxManager;
1338
+ yield this.releaseUnlocked(uuid, true);
1339
+ yield this.runNativeTeardown(uuid, manager, () => __awaiter(this, void 0, void 0, function* () {
1340
+ const operations = [];
1341
+ if (manager) {
1342
+ operations.push(this.runBestEffortNativeOperation('firmware install reconnect: cancel device connection', () => manager.cancelDeviceConnection(uuid)));
1343
+ }
1344
+ operations.push(this.runBestEffortNativeOperation('firmware install reconnect: device cancel connection', () => cachedTransport.device.cancelConnection()));
1345
+ yield Promise.all(operations);
1346
+ }));
1347
+ }
1348
+ else {
1349
+ const cachedProtocol = this.deviceProtocol.get(uuid);
1350
+ const isCachedDeviceConnected = yield cachedTransport.device
1351
+ .isConnected()
1352
+ .catch(() => false);
1353
+ const isCachedAndroidLinkUsable = reactNative.Platform.OS !== 'android' || !this.androidGattCacheRefreshes.has(uuid);
1354
+ if (isCachedDeviceConnected &&
1355
+ isCachedAndroidLinkUsable &&
1356
+ cachedProtocol &&
1357
+ (!expectedProtocol || cachedProtocol === expectedProtocol)) {
1358
+ this.throwIfBondingStopped(bondSignal);
1359
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] reuse cached BLE transport:', uuid, cachedProtocol);
1360
+ return { uuid, protocolType: cachedProtocol };
1361
+ }
1362
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport not reusable, will release: ', uuid);
1363
+ yield this.releaseUnlocked(uuid, true);
1202
1364
  }
1203
- Log === null || Log === void 0 ? void 0 : Log.debug('transport not reusable, will release: ', uuid);
1204
- yield this.releaseUnlocked(uuid, true);
1205
1365
  }
1206
- }
1207
- let device = null;
1208
- const isAndroid = reactNative.Platform.OS === 'android';
1209
- const refreshAndroidGattCache = isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1210
- let nativeConnectOptions = connectOptions;
1211
- if (isAndroid) {
1212
- nativeConnectOptions = refreshAndroidGattCache
1213
- ? androidRefreshGattConnectOptions
1214
- : fallbackConnectOptions;
1215
- }
1216
- let androidRefreshConnectRan = false;
1217
- if (forceCleanRunPromise && this.runPromise) {
1218
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1219
- this.runPromise.reject(error);
1220
- this.runPromise = null;
1221
- this.runPromiseDeviceId = null;
1222
- Log === null || Log === void 0 ? void 0 : Log.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
1223
- }
1224
- const blePlxManager = yield this.getPlxManager();
1225
- let skipPostConnectMtu = false;
1226
- try {
1227
- yield subscribeBleOn(blePlxManager);
1228
- }
1229
- catch (error) {
1230
- Log === null || Log === void 0 ? void 0 : Log.debug('subscribeBleOn error: ', error);
1231
- throw error;
1232
- }
1233
- if (this.stopped)
1234
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1235
- if (reactNative.Platform.OS === 'android') {
1366
+ let device = null;
1367
+ const isAndroid = reactNative.Platform.OS === 'android';
1368
+ const refreshAndroidGattCache = isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1369
+ let nativeConnectOptions = connectOptions;
1370
+ let bareConnectOptions = fallbackConnectOptions;
1371
+ let connectBackstopMs = BLE_CONNECT_TIMEOUT_MS;
1372
+ if (isAndroid) {
1373
+ nativeConnectOptions = refreshAndroidGattCache
1374
+ ? androidRefreshGattConnectOptions
1375
+ : fallbackConnectOptions;
1376
+ }
1377
+ else if (this.takeIosPresentDeviceSighting(uuid, skipProtocolProbe)) {
1378
+ const timeout = IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS;
1379
+ nativeConnectOptions = Object.assign(Object.assign({}, connectOptions), { timeout });
1380
+ bareConnectOptions = Object.assign(Object.assign({}, fallbackConnectOptions), { timeout });
1381
+ connectBackstopMs = IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS;
1382
+ }
1383
+ let androidRefreshConnectRan = false;
1384
+ if (forceCleanRunPromise && this.runPromise) {
1385
+ const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1386
+ this.runPromise.reject(error);
1387
+ this.runPromise = null;
1388
+ this.runPromiseDeviceId = null;
1389
+ Log === null || Log === void 0 ? void 0 : Log.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
1390
+ }
1391
+ const blePlxManager = yield this.getPlxManager();
1392
+ let skipPostConnectMtu = false;
1236
1393
  try {
1237
- const bondState = yield pairDevice(uuid);
1238
- if (bondState.bonding) {
1239
- yield onDeviceBondState(uuid, this.bondAbortController.signal, {
1240
- systemInitiated: bondState.initiated === false,
1241
- });
1242
- }
1243
- else if (!bondState.bonded) {
1244
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1245
- }
1394
+ yield subscribeBleOn(blePlxManager);
1246
1395
  }
1247
1396
  catch (error) {
1248
- yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1249
- yield this.runBestEffortNativeOperation('bond failure: cancel manager connection', () => blePlxManager.cancelDeviceConnection(uuid));
1250
- }));
1397
+ Log === null || Log === void 0 ? void 0 : Log.debug('subscribeBleOn error: ', error);
1251
1398
  throw error;
1252
1399
  }
1253
- }
1254
- if (this.stopped)
1255
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1256
- if (!device) {
1257
- const devices = yield blePlxManager.devices([uuid]);
1258
- [device] = devices;
1259
- }
1260
- if (!device) {
1261
- const connectedDevice = yield blePlxManager.connectedDevices(getBluetoothServiceUuids());
1262
- const deviceFilter = connectedDevice.filter(device => device.id === uuid);
1263
- Log === null || Log === void 0 ? void 0 : Log.debug(`found connected device count: ${deviceFilter.length}`);
1264
- [device] = deviceFilter;
1265
- }
1266
- if (!device) {
1267
- Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device: ', uuid);
1268
- try {
1269
- device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, nativeConnectOptions));
1270
- androidRefreshConnectRan = refreshAndroidGattCache;
1271
- }
1272
- catch (e) {
1273
- Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device has error: ', e);
1274
- if (shouldRethrowBleSetupError(e)) {
1275
- throw e;
1400
+ this.throwIfBondingStopped(bondSignal);
1401
+ if (reactNative.Platform.OS === 'android') {
1402
+ try {
1403
+ yield this.ensureAndroidBond(uuid, bondSignal);
1276
1404
  }
1277
- if (isMtuOrCancelledConnectError(e)) {
1278
- skipPostConnectMtu = true;
1279
- Log === null || Log === void 0 ? void 0 : Log.debug('first try to reconnect without params');
1280
- device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, fallbackConnectOptions));
1405
+ catch (error) {
1406
+ yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1407
+ yield this.runBestEffortNativeOperation('bond failure: cancel manager connection', () => blePlxManager.cancelDeviceConnection(uuid));
1408
+ }));
1409
+ throw error;
1281
1410
  }
1282
- else if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
1283
- Log === null || Log === void 0 ? void 0 : Log.debug('device already connected');
1284
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleAlreadyConnected);
1411
+ }
1412
+ this.throwIfBondingStopped(bondSignal);
1413
+ if (!device) {
1414
+ const devices = yield blePlxManager.devices([uuid]);
1415
+ [device] = devices;
1416
+ }
1417
+ if (!device) {
1418
+ const connectedDevice = yield blePlxManager.connectedDevices(getBluetoothServiceUuids());
1419
+ const deviceFilter = connectedDevice.filter(device => device.id === uuid);
1420
+ Log === null || Log === void 0 ? void 0 : Log.debug(`found connected device count: ${deviceFilter.length}`);
1421
+ [device] = deviceFilter;
1422
+ }
1423
+ if (!device) {
1424
+ Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device: ', uuid);
1425
+ try {
1426
+ device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, nativeConnectOptions), connectBackstopMs);
1427
+ androidRefreshConnectRan = refreshAndroidGattCache;
1285
1428
  }
1286
- else {
1287
- remapError(e);
1429
+ catch (e) {
1430
+ Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device has error: ', e);
1431
+ if (shouldRethrowBleSetupError(e)) {
1432
+ throw e;
1433
+ }
1434
+ if (isMtuOrCancelledConnectError(e)) {
1435
+ skipPostConnectMtu = true;
1436
+ Log === null || Log === void 0 ? void 0 : Log.debug('first try to reconnect without params');
1437
+ device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, bareConnectOptions), connectBackstopMs);
1438
+ }
1439
+ else if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
1440
+ Log === null || Log === void 0 ? void 0 : Log.debug('device already connected');
1441
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleAlreadyConnected);
1442
+ }
1443
+ else {
1444
+ remapError(e);
1445
+ }
1288
1446
  }
1289
1447
  }
1290
- }
1291
- if (!device) {
1292
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'unable to connect to device');
1293
- }
1294
- if (refreshAndroidGattCache &&
1295
- !androidRefreshConnectRan &&
1296
- (yield device.isConnected().catch(() => false))) {
1297
- yield this.dropAndroidLink(uuid, blePlxManager, device, 'gatt cache refresh');
1298
- if (this.stopped)
1299
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1300
- }
1301
- if (!(yield device.isConnected())) {
1302
- Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device: ', uuid);
1303
- const disconnectedDevice = device;
1304
- try {
1305
- device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(nativeConnectOptions));
1306
- androidRefreshConnectRan = refreshAndroidGattCache;
1448
+ if (!device) {
1449
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'unable to connect to device');
1307
1450
  }
1308
- catch (e) {
1309
- Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device has error: ', e);
1310
- if (shouldRethrowBleSetupError(e)) {
1311
- throw e;
1451
+ if (refreshAndroidGattCache &&
1452
+ !androidRefreshConnectRan &&
1453
+ (yield device.isConnected().catch(() => false))) {
1454
+ yield this.dropAndroidLink(uuid, blePlxManager, device, 'gatt cache refresh');
1455
+ this.throwIfBondingStopped(bondSignal);
1456
+ }
1457
+ if (!(yield device.isConnected())) {
1458
+ Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device: ', uuid);
1459
+ const disconnectedDevice = device;
1460
+ try {
1461
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(nativeConnectOptions), connectBackstopMs);
1462
+ androidRefreshConnectRan = refreshAndroidGattCache;
1312
1463
  }
1313
- if (isMtuOrCancelledConnectError(e)) {
1314
- skipPostConnectMtu = true;
1315
- Log === null || Log === void 0 ? void 0 : Log.debug('second try to reconnect without params');
1316
- try {
1317
- device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(fallbackConnectOptions));
1464
+ catch (e) {
1465
+ Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device has error: ', e);
1466
+ if (shouldRethrowBleSetupError(e)) {
1467
+ throw e;
1318
1468
  }
1319
- catch (fallbackError) {
1320
- Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect error: ', fallbackError);
1321
- if (fallbackError.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
1322
- Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect');
1323
- yield disconnectedDevice.cancelConnection();
1324
- device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(fallbackConnectOptions));
1469
+ if (isMtuOrCancelledConnectError(e)) {
1470
+ skipPostConnectMtu = true;
1471
+ Log === null || Log === void 0 ? void 0 : Log.debug('second try to reconnect without params');
1472
+ try {
1473
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(bareConnectOptions), connectBackstopMs);
1325
1474
  }
1326
- else {
1327
- remapError(fallbackError);
1475
+ catch (fallbackError) {
1476
+ Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect error: ', fallbackError);
1477
+ if (fallbackError.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
1478
+ Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect');
1479
+ yield disconnectedDevice.cancelConnection();
1480
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(bareConnectOptions), connectBackstopMs);
1481
+ }
1482
+ else {
1483
+ remapError(fallbackError);
1484
+ }
1328
1485
  }
1329
1486
  }
1330
- }
1331
- else {
1332
- remapError(e);
1487
+ else {
1488
+ remapError(e);
1489
+ }
1333
1490
  }
1334
1491
  }
1335
- }
1336
- if (this.stopped)
1337
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1338
- if (reactNative.Platform.OS === 'android' && !(yield device.isConnected().catch(() => false))) {
1339
- const disconnectedDevice = device;
1340
- yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1341
- yield Promise.all([
1342
- this.runBestEffortNativeOperation('connect failure: cancel manager connection', () => blePlxManager.cancelDeviceConnection(uuid)),
1343
- this.runBestEffortNativeOperation('connect failure: cancel device connection', () => disconnectedDevice.cancelConnection()),
1344
- ]);
1345
- }));
1346
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'device is not connected');
1347
- }
1348
- if (this.stopped)
1349
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1350
- let characteristics;
1351
- if (isAndroid) {
1352
- if (refreshAndroidGattCache) {
1353
- characteristics = yield this.resolveCharacteristicsWithTimeout(uuid, device);
1354
- if (androidRefreshConnectRan)
1355
- this.androidGattCacheRefreshes.delete(uuid);
1356
- if (this.stopped)
1357
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1358
- }
1359
- device = yield this.negotiateAndroidMtu(uuid, blePlxManager, device);
1360
- }
1361
- else if (!skipPostConnectMtu) {
1362
- const mtuResult = yield resolveNegotiatedMtu(device, transactionId => blePlxManager.cancelTransaction(transactionId));
1363
- device = mtuResult.device;
1364
- if (mtuResult.timedOut) {
1365
- if (this.stopped)
1366
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1367
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU');
1368
- const timedOutDevice = device;
1369
- let mtuTeardownSettled = false;
1492
+ if (this.stopped || bondSignal.aborted) {
1493
+ yield this.disconnectUnlocked(uuid);
1494
+ this.throwIfBondingStopped(bondSignal);
1495
+ }
1496
+ if (reactNative.Platform.OS === 'android' && !(yield device.isConnected().catch(() => false))) {
1497
+ const disconnectedDevice = device;
1370
1498
  yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1371
- yield this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () => timedOutDevice.cancelConnection());
1372
- mtuTeardownSettled = true;
1499
+ yield Promise.all([
1500
+ this.runBestEffortNativeOperation('connect failure: cancel manager connection', () => blePlxManager.cancelDeviceConnection(uuid)),
1501
+ this.runBestEffortNativeOperation('connect failure: cancel device connection', () => disconnectedDevice.cancelConnection()),
1502
+ ]);
1373
1503
  }));
1374
- if (this.stopped)
1375
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1376
- if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
1377
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
1378
- }
1379
- try {
1380
- device = yield this.connectWithTimeout(uuid, () => timedOutDevice.connect(fallbackConnectOptions));
1504
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'device is not connected');
1505
+ }
1506
+ this.throwIfBondingStopped(bondSignal);
1507
+ let characteristics;
1508
+ if (isAndroid) {
1509
+ if (refreshAndroidGattCache) {
1510
+ characteristics = yield this.resolveCharacteristicsWithTimeout(uuid, device);
1511
+ if (androidRefreshConnectRan)
1512
+ this.androidGattCacheRefreshes.delete(uuid);
1513
+ this.throwIfBondingStopped(bondSignal);
1381
1514
  }
1382
- catch (error) {
1383
- if (shouldRethrowBleSetupError(error))
1384
- throw error;
1385
- if ((error === null || error === void 0 ? void 0 : error.errorCode) === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
1386
- device = timedOutDevice;
1515
+ device = yield this.negotiateAndroidMtu(uuid, blePlxManager, device);
1516
+ }
1517
+ else if (!skipPostConnectMtu) {
1518
+ const mtuResult = yield resolveNegotiatedMtu(device, transactionId => blePlxManager.cancelTransaction(transactionId));
1519
+ device = mtuResult.device;
1520
+ if (mtuResult.timedOut) {
1521
+ this.throwIfBondingStopped(bondSignal);
1522
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU');
1523
+ const timedOutDevice = device;
1524
+ let mtuTeardownSettled = false;
1525
+ yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1526
+ yield this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () => timedOutDevice.cancelConnection());
1527
+ mtuTeardownSettled = true;
1528
+ }));
1529
+ this.throwIfBondingStopped(bondSignal);
1530
+ if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
1531
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
1387
1532
  }
1388
- else {
1389
- remapError(error);
1533
+ try {
1534
+ device = yield this.connectWithTimeout(uuid, () => timedOutDevice.connect(bareConnectOptions), connectBackstopMs);
1535
+ }
1536
+ catch (error) {
1537
+ if (shouldRethrowBleSetupError(error))
1538
+ throw error;
1539
+ if ((error === null || error === void 0 ? void 0 : error.errorCode) === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
1540
+ device = timedOutDevice;
1541
+ }
1542
+ else {
1543
+ remapError(error);
1544
+ }
1390
1545
  }
1391
1546
  }
1392
1547
  }
1393
- }
1394
- if (this.stopped)
1395
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1396
- const acquiredDevice = device;
1397
- const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
1398
- if (this.stopped)
1399
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1400
- const protocolHint = expectedProtocol
1401
- ? undefined
1402
- : (_a = input.protocolHint) !== null && _a !== void 0 ? _a : this.deviceProtocolHints.get(uuid);
1403
- yield this.releaseUnlocked(uuid, true);
1404
- if (protocolHint) {
1405
- this.deviceProtocolHints.set(uuid, protocolHint);
1406
- }
1407
- try {
1408
- yield this.installTransportForAcquire(uuid, acquiredDevice, {
1409
- writeCharacteristic,
1410
- notifyCharacteristic,
1411
- });
1412
- if (skipProtocolProbe) {
1413
- if (!expectedProtocol) {
1414
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires an expected BLE protocol');
1415
- }
1416
- const hasConfirmedProtocol = this.sessionProtocols.get(uuid) === expectedProtocol ||
1417
- (expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
1418
- if (!hasConfirmedProtocol) {
1419
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint');
1420
- }
1421
- this.deviceProtocol.set(uuid, expectedProtocol);
1422
- this.sessionProtocols.set(uuid, expectedProtocol);
1423
- this.protocolReprobeFailures.delete(uuid);
1424
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol selected without probe', {
1425
- deviceId: uuid,
1426
- protocol: expectedProtocol,
1427
- source: 'firmware-install-reconnect',
1548
+ this.throwIfBondingStopped(bondSignal);
1549
+ const acquiredDevice = device;
1550
+ const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
1551
+ this.throwIfBondingStopped(bondSignal);
1552
+ const protocolHint = expectedProtocol
1553
+ ? undefined
1554
+ : (_a = input.protocolHint) !== null && _a !== void 0 ? _a : this.deviceProtocolHints.get(uuid);
1555
+ yield this.releaseUnlocked(uuid, true);
1556
+ if (protocolHint) {
1557
+ this.deviceProtocolHints.set(uuid, protocolHint);
1558
+ }
1559
+ try {
1560
+ yield this.installTransportForAcquire(uuid, acquiredDevice, {
1561
+ writeCharacteristic,
1562
+ notifyCharacteristic,
1428
1563
  });
1564
+ if (skipProtocolProbe) {
1565
+ if (!expectedProtocol) {
1566
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires an expected BLE protocol');
1567
+ }
1568
+ const hasConfirmedProtocol = this.sessionProtocols.get(uuid) === expectedProtocol ||
1569
+ (expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
1570
+ if (!hasConfirmedProtocol) {
1571
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint');
1572
+ }
1573
+ this.deviceProtocol.set(uuid, expectedProtocol);
1574
+ this.sessionProtocols.set(uuid, expectedProtocol);
1575
+ this.protocolReprobeFailures.delete(uuid);
1576
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol selected without probe', {
1577
+ deviceId: uuid,
1578
+ protocol: expectedProtocol,
1579
+ source: 'firmware-install-reconnect',
1580
+ });
1581
+ const currentTransport = transportCache[uuid];
1582
+ if (!currentTransport) {
1583
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1584
+ }
1585
+ this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1586
+ return { uuid, protocolType: expectedProtocol };
1587
+ }
1588
+ const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint, () => __awaiter(this, void 0, void 0, function* () {
1589
+ yield this.installTransportForAcquire(uuid, acquiredDevice);
1590
+ }));
1591
+ this.throwIfBondingStopped(bondSignal);
1429
1592
  const currentTransport = transportCache[uuid];
1430
1593
  if (!currentTransport) {
1431
1594
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1432
1595
  }
1433
1596
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1434
- return { uuid, protocolType: expectedProtocol };
1597
+ return { uuid, protocolType };
1435
1598
  }
1436
- const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint, () => __awaiter(this, void 0, void 0, function* () {
1437
- yield this.installTransportForAcquire(uuid, acquiredDevice);
1438
- }));
1439
- if (this.stopped)
1440
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1441
- const currentTransport = transportCache[uuid];
1442
- if (!currentTransport) {
1443
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1599
+ catch (error) {
1600
+ yield this.disconnectUnlocked(uuid);
1601
+ throw error;
1444
1602
  }
1445
- this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1446
- return { uuid, protocolType };
1447
1603
  }
1448
- catch (error) {
1449
- yield this.disconnectUnlocked(uuid);
1450
- throw error;
1604
+ finally {
1605
+ this.releaseBondAbortController(uuid, bondController);
1451
1606
  }
1452
1607
  });
1453
1608
  }
@@ -1467,6 +1622,17 @@ class ReactNativeBleTransport {
1467
1622
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1468
1623
  return;
1469
1624
  }
1625
+ if (reactNative.Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
1626
+ const staleBondError = toIosStaleBondError(error);
1627
+ if (this.getActiveProtocol(uuid) === 'V2') {
1628
+ this.rejectProtocolV2Frames(uuid, staleBondError);
1629
+ return;
1630
+ }
1631
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
1632
+ this.runPromise.reject(staleBondError);
1633
+ }
1634
+ return;
1635
+ }
1470
1636
  if (reactNative.Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1471
1637
  this.androidGattCacheRefreshes.add(uuid);
1472
1638
  }
@@ -1858,7 +2024,7 @@ class ReactNativeBleTransport {
1858
2024
  if (this.stopPromise)
1859
2025
  return this.stopPromise;
1860
2026
  this.stopped = true;
1861
- this.bondAbortController.abort();
2027
+ this.abortActiveBonding();
1862
2028
  const deviceIds = new Set([
1863
2029
  ...this.monitorTokens.keys(),
1864
2030
  ...this.sessionProtocols.keys(),
@@ -1869,6 +2035,7 @@ class ReactNativeBleTransport {
1869
2035
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
1870
2036
  this.androidPriorityResetTimers.clear();
1871
2037
  this.androidHighPriorityDevices.clear();
2038
+ this.iosLastAdvertisedAt.clear();
1872
2039
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1873
2040
  (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.reject(error);
1874
2041
  this.runPromise = null;
@@ -1894,6 +2061,7 @@ class ReactNativeBleTransport {
1894
2061
  }
1895
2062
  disconnect(session) {
1896
2063
  return __awaiter(this, void 0, void 0, function* () {
2064
+ this.abortActiveBonding(session);
1897
2065
  return this.runLifecycleOperation(session, () => this.disconnectUnlocked(session));
1898
2066
  });
1899
2067
  }
@@ -2022,12 +2190,13 @@ class ReactNativeBleTransport {
2022
2190
  }
2023
2191
  });
2024
2192
  }
2025
- cancel() {
2193
+ cancel(uuid) {
2026
2194
  return __awaiter(this, void 0, void 0, function* () {
2027
- Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport cancel');
2195
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport cancel', uuid);
2196
+ this.abortActiveBonding(uuid);
2028
2197
  const pending = this.runPromise;
2029
2198
  const deviceId = this.runPromiseDeviceId;
2030
- if (pending) {
2199
+ if (pending && (uuid === undefined || deviceId === uuid)) {
2031
2200
  pending.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
2032
2201
  if (this.runPromise === pending) {
2033
2202
  this.runPromise = null;
@@ -2104,7 +2273,16 @@ class ReactNativeBleTransport {
2104
2273
  });
2105
2274
  });
2106
2275
  }
2107
- connectWithTimeout(uuid, connect) {
2276
+ takeIosPresentDeviceSighting(uuid, skipProtocolProbe) {
2277
+ if (reactNative.Platform.OS !== 'ios')
2278
+ return false;
2279
+ const seenAt = this.iosLastAdvertisedAt.get(uuid);
2280
+ this.iosLastAdvertisedAt.delete(uuid);
2281
+ if (skipProtocolProbe || seenAt === undefined)
2282
+ return false;
2283
+ return Date.now() - seenAt <= IOS_PRESENT_DEVICE_WINDOW_MS;
2284
+ }
2285
+ connectWithTimeout(uuid, connect, backstopMs = BLE_CONNECT_TIMEOUT_MS) {
2108
2286
  return __awaiter(this, void 0, void 0, function* () {
2109
2287
  if (this.stopped)
2110
2288
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
@@ -2120,8 +2298,8 @@ class ReactNativeBleTransport {
2120
2298
  new Promise((_, reject) => {
2121
2299
  timer = setTimeout(() => {
2122
2300
  timedOut = true;
2123
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `BLE connect timeout after ${BLE_CONNECT_TIMEOUT_MS}ms for ${uuid}`));
2124
- }, BLE_CONNECT_TIMEOUT_MS);
2301
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `BLE connect timeout after ${backstopMs}ms for ${uuid}`));
2302
+ }, backstopMs);
2125
2303
  }),
2126
2304
  ]);
2127
2305
  succeeded = true;
@@ -2144,6 +2322,7 @@ class ReactNativeBleTransport {
2144
2322
  elapsedMs: Date.now() - startedAt,
2145
2323
  succeeded,
2146
2324
  backstopExpired: timedOut,
2325
+ backstopMs,
2147
2326
  });
2148
2327
  }
2149
2328
  });
@@ -2177,6 +2356,9 @@ class ReactNativeBleTransport {
2177
2356
  throw this.createWedgedBleSetupError();
2178
2357
  }
2179
2358
  }
2359
+ if (reactNative.Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
2360
+ throw toIosStaleBondError(error);
2361
+ }
2180
2362
  if (isNativeBleDisconnectError(error)) {
2181
2363
  throw toBleDisconnectHardwareError(error);
2182
2364
  }
@@ -2294,6 +2476,7 @@ class ReactNativeBleTransport {
2294
2476
  resetPlxManager() {
2295
2477
  if (bleManagerResetPromise)
2296
2478
  return;
2479
+ this.iosLastAdvertisedAt.clear();
2297
2480
  const manager = this.blePlxManager;
2298
2481
  this.blePlxManager = undefined;
2299
2482
  const reason = 'React Native BLE manager reset';
@@ -2540,25 +2723,31 @@ class ReactNativeBleTransport {
2540
2723
  }
2541
2724
  this.probingProtocols.set(uuid, 'V2');
2542
2725
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2543
- const detected = yield transportModule.probeProtocolV2({
2544
- call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2545
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
2546
- logger: Log,
2547
- logPrefix: 'ProtocolV2 RN-BLE',
2548
- onProbeFailed: () => {
2549
- var _a;
2550
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2551
- this.resetProtocolV2Frames(uuid);
2552
- },
2553
- shouldRethrow: shouldRethrowProtocolProbeError,
2554
- });
2555
- if (!detected) {
2556
- this.clearProbeProtocol(uuid, 'V2');
2726
+ try {
2727
+ const detected = yield transportModule.probeProtocolV2({
2728
+ call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2729
+ timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
2730
+ logger: Log,
2731
+ logPrefix: 'ProtocolV2 RN-BLE',
2732
+ onProbeFailed: () => {
2733
+ var _a;
2734
+ (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2735
+ this.resetProtocolV2Frames(uuid);
2736
+ },
2737
+ shouldRethrow: shouldRethrowProtocolProbeError,
2738
+ });
2739
+ if (!detected) {
2740
+ this.clearProbeProtocol(uuid, 'V2');
2741
+ }
2742
+ else {
2743
+ this.probingProtocols.delete(uuid);
2744
+ }
2745
+ return detected;
2557
2746
  }
2558
- else {
2559
- this.probingProtocols.delete(uuid);
2747
+ catch (error) {
2748
+ this.clearProbeProtocol(uuid, 'V2');
2749
+ throw error;
2560
2750
  }
2561
- return detected;
2562
2751
  });
2563
2752
  }
2564
2753
  handleProtocolV2Notification(uuid, monitorToken, data) {
@@ -3073,6 +3262,9 @@ exports.BLE_NATIVE_TEARDOWN_TIMEOUT_MS = BLE_NATIVE_TEARDOWN_TIMEOUT_MS;
3073
3262
  exports.BLE_SETUP_WEDGED_MESSAGE = BLE_SETUP_WEDGED_MESSAGE;
3074
3263
  exports.BLE_WRITE_PACKET_TIMEOUT_MS = BLE_WRITE_PACKET_TIMEOUT_MS;
3075
3264
  exports.BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD;
3265
+ exports.IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS = IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS;
3266
+ exports.IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS = IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS;
3267
+ exports.IOS_PRESENT_DEVICE_WINDOW_MS = IOS_PRESENT_DEVICE_WINDOW_MS;
3076
3268
  exports.PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = PROTOCOL_REPROBE_FALLBACK_ATTEMPTS;
3077
3269
  exports.configureProtocolV2BleTuning = configureProtocolV2BleTuning;
3078
3270
  exports["default"] = ReactNativeBleTransport;