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