@onekeyfe/hd-transport-react-native 1.2.11-alpha.1 → 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/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,409 @@ 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
+ this.throwIfBondingStopped(bondSignal);
1493
+ if (reactNative.Platform.OS === 'android' && !(yield device.isConnected().catch(() => false))) {
1494
+ const disconnectedDevice = device;
1370
1495
  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;
1496
+ yield Promise.all([
1497
+ this.runBestEffortNativeOperation('connect failure: cancel manager connection', () => blePlxManager.cancelDeviceConnection(uuid)),
1498
+ this.runBestEffortNativeOperation('connect failure: cancel device connection', () => disconnectedDevice.cancelConnection()),
1499
+ ]);
1373
1500
  }));
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));
1501
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'device is not connected');
1502
+ }
1503
+ this.throwIfBondingStopped(bondSignal);
1504
+ let characteristics;
1505
+ if (isAndroid) {
1506
+ if (refreshAndroidGattCache) {
1507
+ characteristics = yield this.resolveCharacteristicsWithTimeout(uuid, device);
1508
+ if (androidRefreshConnectRan)
1509
+ this.androidGattCacheRefreshes.delete(uuid);
1510
+ this.throwIfBondingStopped(bondSignal);
1381
1511
  }
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;
1512
+ device = yield this.negotiateAndroidMtu(uuid, blePlxManager, device);
1513
+ }
1514
+ else if (!skipPostConnectMtu) {
1515
+ const mtuResult = yield resolveNegotiatedMtu(device, transactionId => blePlxManager.cancelTransaction(transactionId));
1516
+ device = mtuResult.device;
1517
+ if (mtuResult.timedOut) {
1518
+ this.throwIfBondingStopped(bondSignal);
1519
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU');
1520
+ const timedOutDevice = device;
1521
+ let mtuTeardownSettled = false;
1522
+ yield this.runNativeTeardown(uuid, blePlxManager, () => __awaiter(this, void 0, void 0, function* () {
1523
+ yield this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () => timedOutDevice.cancelConnection());
1524
+ mtuTeardownSettled = true;
1525
+ }));
1526
+ this.throwIfBondingStopped(bondSignal);
1527
+ if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
1528
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
1387
1529
  }
1388
- else {
1389
- remapError(error);
1530
+ try {
1531
+ device = yield this.connectWithTimeout(uuid, () => timedOutDevice.connect(bareConnectOptions), connectBackstopMs);
1532
+ }
1533
+ catch (error) {
1534
+ if (shouldRethrowBleSetupError(error))
1535
+ throw error;
1536
+ if ((error === null || error === void 0 ? void 0 : error.errorCode) === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
1537
+ device = timedOutDevice;
1538
+ }
1539
+ else {
1540
+ remapError(error);
1541
+ }
1390
1542
  }
1391
1543
  }
1392
1544
  }
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',
1545
+ this.throwIfBondingStopped(bondSignal);
1546
+ const acquiredDevice = device;
1547
+ const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
1548
+ this.throwIfBondingStopped(bondSignal);
1549
+ const protocolHint = expectedProtocol
1550
+ ? undefined
1551
+ : (_a = input.protocolHint) !== null && _a !== void 0 ? _a : this.deviceProtocolHints.get(uuid);
1552
+ yield this.releaseUnlocked(uuid, true);
1553
+ if (protocolHint) {
1554
+ this.deviceProtocolHints.set(uuid, protocolHint);
1555
+ }
1556
+ try {
1557
+ yield this.installTransportForAcquire(uuid, acquiredDevice, {
1558
+ writeCharacteristic,
1559
+ notifyCharacteristic,
1428
1560
  });
1561
+ if (skipProtocolProbe) {
1562
+ if (!expectedProtocol) {
1563
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires an expected BLE protocol');
1564
+ }
1565
+ const hasConfirmedProtocol = this.sessionProtocols.get(uuid) === expectedProtocol ||
1566
+ (expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
1567
+ if (!hasConfirmedProtocol) {
1568
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint');
1569
+ }
1570
+ this.deviceProtocol.set(uuid, expectedProtocol);
1571
+ this.sessionProtocols.set(uuid, expectedProtocol);
1572
+ this.protocolReprobeFailures.delete(uuid);
1573
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol selected without probe', {
1574
+ deviceId: uuid,
1575
+ protocol: expectedProtocol,
1576
+ source: 'firmware-install-reconnect',
1577
+ });
1578
+ const currentTransport = transportCache[uuid];
1579
+ if (!currentTransport) {
1580
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1581
+ }
1582
+ this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1583
+ return { uuid, protocolType: expectedProtocol };
1584
+ }
1585
+ const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint, () => __awaiter(this, void 0, void 0, function* () {
1586
+ yield this.installTransportForAcquire(uuid, acquiredDevice);
1587
+ }));
1588
+ this.throwIfBondingStopped(bondSignal);
1429
1589
  const currentTransport = transportCache[uuid];
1430
1590
  if (!currentTransport) {
1431
1591
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1432
1592
  }
1433
1593
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1434
- return { uuid, protocolType: expectedProtocol };
1594
+ return { uuid, protocolType };
1435
1595
  }
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);
1596
+ catch (error) {
1597
+ yield this.disconnectUnlocked(uuid);
1598
+ throw error;
1444
1599
  }
1445
- this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1446
- return { uuid, protocolType };
1447
1600
  }
1448
- catch (error) {
1449
- yield this.disconnectUnlocked(uuid);
1450
- throw error;
1601
+ finally {
1602
+ this.releaseBondAbortController(uuid, bondController);
1451
1603
  }
1452
1604
  });
1453
1605
  }
@@ -1467,6 +1619,17 @@ class ReactNativeBleTransport {
1467
1619
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1468
1620
  return;
1469
1621
  }
1622
+ if (reactNative.Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
1623
+ const staleBondError = toIosStaleBondError(error);
1624
+ if (this.getActiveProtocol(uuid) === 'V2') {
1625
+ this.rejectProtocolV2Frames(uuid, staleBondError);
1626
+ return;
1627
+ }
1628
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
1629
+ this.runPromise.reject(staleBondError);
1630
+ }
1631
+ return;
1632
+ }
1470
1633
  if (reactNative.Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1471
1634
  this.androidGattCacheRefreshes.add(uuid);
1472
1635
  }
@@ -1858,7 +2021,7 @@ class ReactNativeBleTransport {
1858
2021
  if (this.stopPromise)
1859
2022
  return this.stopPromise;
1860
2023
  this.stopped = true;
1861
- this.bondAbortController.abort();
2024
+ this.abortActiveBonding();
1862
2025
  const deviceIds = new Set([
1863
2026
  ...this.monitorTokens.keys(),
1864
2027
  ...this.sessionProtocols.keys(),
@@ -1869,6 +2032,7 @@ class ReactNativeBleTransport {
1869
2032
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
1870
2033
  this.androidPriorityResetTimers.clear();
1871
2034
  this.androidHighPriorityDevices.clear();
2035
+ this.iosLastAdvertisedAt.clear();
1872
2036
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1873
2037
  (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.reject(error);
1874
2038
  this.runPromise = null;
@@ -1894,6 +2058,7 @@ class ReactNativeBleTransport {
1894
2058
  }
1895
2059
  disconnect(session) {
1896
2060
  return __awaiter(this, void 0, void 0, function* () {
2061
+ this.abortActiveBonding(session);
1897
2062
  return this.runLifecycleOperation(session, () => this.disconnectUnlocked(session));
1898
2063
  });
1899
2064
  }
@@ -2022,12 +2187,13 @@ class ReactNativeBleTransport {
2022
2187
  }
2023
2188
  });
2024
2189
  }
2025
- cancel() {
2190
+ cancel(uuid) {
2026
2191
  return __awaiter(this, void 0, void 0, function* () {
2027
- Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport cancel');
2192
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport cancel', uuid);
2193
+ this.abortActiveBonding(uuid);
2028
2194
  const pending = this.runPromise;
2029
2195
  const deviceId = this.runPromiseDeviceId;
2030
- if (pending) {
2196
+ if (pending && (uuid === undefined || deviceId === uuid)) {
2031
2197
  pending.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
2032
2198
  if (this.runPromise === pending) {
2033
2199
  this.runPromise = null;
@@ -2104,7 +2270,16 @@ class ReactNativeBleTransport {
2104
2270
  });
2105
2271
  });
2106
2272
  }
2107
- connectWithTimeout(uuid, connect) {
2273
+ takeIosPresentDeviceSighting(uuid, skipProtocolProbe) {
2274
+ if (reactNative.Platform.OS !== 'ios')
2275
+ return false;
2276
+ const seenAt = this.iosLastAdvertisedAt.get(uuid);
2277
+ this.iosLastAdvertisedAt.delete(uuid);
2278
+ if (skipProtocolProbe || seenAt === undefined)
2279
+ return false;
2280
+ return Date.now() - seenAt <= IOS_PRESENT_DEVICE_WINDOW_MS;
2281
+ }
2282
+ connectWithTimeout(uuid, connect, backstopMs = BLE_CONNECT_TIMEOUT_MS) {
2108
2283
  return __awaiter(this, void 0, void 0, function* () {
2109
2284
  if (this.stopped)
2110
2285
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
@@ -2120,8 +2295,8 @@ class ReactNativeBleTransport {
2120
2295
  new Promise((_, reject) => {
2121
2296
  timer = setTimeout(() => {
2122
2297
  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);
2298
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `BLE connect timeout after ${backstopMs}ms for ${uuid}`));
2299
+ }, backstopMs);
2125
2300
  }),
2126
2301
  ]);
2127
2302
  succeeded = true;
@@ -2144,6 +2319,7 @@ class ReactNativeBleTransport {
2144
2319
  elapsedMs: Date.now() - startedAt,
2145
2320
  succeeded,
2146
2321
  backstopExpired: timedOut,
2322
+ backstopMs,
2147
2323
  });
2148
2324
  }
2149
2325
  });
@@ -2177,6 +2353,9 @@ class ReactNativeBleTransport {
2177
2353
  throw this.createWedgedBleSetupError();
2178
2354
  }
2179
2355
  }
2356
+ if (reactNative.Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
2357
+ throw toIosStaleBondError(error);
2358
+ }
2180
2359
  if (isNativeBleDisconnectError(error)) {
2181
2360
  throw toBleDisconnectHardwareError(error);
2182
2361
  }
@@ -2294,6 +2473,7 @@ class ReactNativeBleTransport {
2294
2473
  resetPlxManager() {
2295
2474
  if (bleManagerResetPromise)
2296
2475
  return;
2476
+ this.iosLastAdvertisedAt.clear();
2297
2477
  const manager = this.blePlxManager;
2298
2478
  this.blePlxManager = undefined;
2299
2479
  const reason = 'React Native BLE manager reset';
@@ -2540,25 +2720,31 @@ class ReactNativeBleTransport {
2540
2720
  }
2541
2721
  this.probingProtocols.set(uuid, 'V2');
2542
2722
  (_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');
2723
+ try {
2724
+ const detected = yield transportModule.probeProtocolV2({
2725
+ call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2726
+ timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
2727
+ logger: Log,
2728
+ logPrefix: 'ProtocolV2 RN-BLE',
2729
+ onProbeFailed: () => {
2730
+ var _a;
2731
+ (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2732
+ this.resetProtocolV2Frames(uuid);
2733
+ },
2734
+ shouldRethrow: shouldRethrowProtocolProbeError,
2735
+ });
2736
+ if (!detected) {
2737
+ this.clearProbeProtocol(uuid, 'V2');
2738
+ }
2739
+ else {
2740
+ this.probingProtocols.delete(uuid);
2741
+ }
2742
+ return detected;
2557
2743
  }
2558
- else {
2559
- this.probingProtocols.delete(uuid);
2744
+ catch (error) {
2745
+ this.clearProbeProtocol(uuid, 'V2');
2746
+ throw error;
2560
2747
  }
2561
- return detected;
2562
2748
  });
2563
2749
  }
2564
2750
  handleProtocolV2Notification(uuid, monitorToken, data) {
@@ -3073,6 +3259,9 @@ exports.BLE_NATIVE_TEARDOWN_TIMEOUT_MS = BLE_NATIVE_TEARDOWN_TIMEOUT_MS;
3073
3259
  exports.BLE_SETUP_WEDGED_MESSAGE = BLE_SETUP_WEDGED_MESSAGE;
3074
3260
  exports.BLE_WRITE_PACKET_TIMEOUT_MS = BLE_WRITE_PACKET_TIMEOUT_MS;
3075
3261
  exports.BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD;
3262
+ exports.IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS = IOS_PRESENT_DEVICE_CONNECT_BACKSTOP_MS;
3263
+ exports.IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS = IOS_PRESENT_DEVICE_CONNECT_TIMEOUT_MS;
3264
+ exports.IOS_PRESENT_DEVICE_WINDOW_MS = IOS_PRESENT_DEVICE_WINDOW_MS;
3076
3265
  exports.PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = PROTOCOL_REPROBE_FALLBACK_ATTEMPTS;
3077
3266
  exports.configureProtocolV2BleTuning = configureProtocolV2BleTuning;
3078
3267
  exports["default"] = ReactNativeBleTransport;