@onekeyfe/hd-transport-react-native 1.2.11-alpha.3 → 1.2.11-alpha.5
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.d.ts +5 -55
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +275 -464
- package/package.json +5 -5
- package/src/__tests__/nativeFrameWrite.test.ts +0 -1
- package/src/__tests__/protocolV2Link.test.ts +3 -486
- package/src/index.ts +341 -627
- package/dist/bleIosBond.d.ts +0 -3
- package/dist/bleIosBond.d.ts.map +0 -1
- package/src/__tests__/bleIosBond.test.ts +0 -35
- package/src/__tests__/iosPresentDeviceConnect.test.ts +0 -228
- package/src/__tests__/releaseBondConcurrency.test.ts +0 -284
- package/src/bleIosBond.ts +0 -39
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { PermissionsAndroid, Platform } from 'react-native';
|
|
2
2
|
import { Buffer } from 'buffer';
|
|
3
3
|
import {
|
|
4
|
+
BleError,
|
|
4
5
|
BleErrorCode,
|
|
5
6
|
BleManager as BlePlxManager,
|
|
6
7
|
ConnectionPriority,
|
|
@@ -31,12 +32,7 @@ import {
|
|
|
31
32
|
parseOnekeyBleColorCode,
|
|
32
33
|
} from '@onekeyfe/hd-shared';
|
|
33
34
|
|
|
34
|
-
import {
|
|
35
|
-
getBondedDevices,
|
|
36
|
-
getConnectedDeviceIds,
|
|
37
|
-
onDeviceBondState,
|
|
38
|
-
pairDevice,
|
|
39
|
-
} from './BleManager';
|
|
35
|
+
import { getConnectedDeviceIds, onDeviceBondState, pairDevice } from './BleManager';
|
|
40
36
|
import {
|
|
41
37
|
hasWritableCapability,
|
|
42
38
|
resolveProtocolV2PacketCapacity,
|
|
@@ -54,14 +50,13 @@ import {
|
|
|
54
50
|
isSameBleUuid,
|
|
55
51
|
} from './constants';
|
|
56
52
|
import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from './bleNativeDisconnect';
|
|
57
|
-
import { isIosPeerRemovedPairingInformation, toIosStaleBondError } from './bleIosBond';
|
|
58
53
|
import { isHeaderChunk } from './utils/validateNotify';
|
|
59
54
|
import BleTransport from './BleTransport';
|
|
60
55
|
import timer from './utils/timer';
|
|
61
56
|
import { bleLogger, setBleLogger } from './logger';
|
|
62
57
|
|
|
63
58
|
import type { Deferred } from '@onekeyfe/hd-shared';
|
|
64
|
-
import type {
|
|
59
|
+
import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
|
|
65
60
|
import type EventEmitter from 'events';
|
|
66
61
|
import type { BleAcquireInput, TransportOptions } from './types';
|
|
67
62
|
|
|
@@ -77,7 +72,7 @@ type FirmwareInstallBleAcquireInput = BleAcquireInput & {
|
|
|
77
72
|
const transport: typeof transportModule =
|
|
78
73
|
(transportModule as typeof transportModule & { default?: typeof transportModule }).default ??
|
|
79
74
|
transportModule;
|
|
80
|
-
const { check, ProtocolV1,
|
|
75
|
+
const { check, ProtocolV1, parseTransportConfigure } = transport;
|
|
81
76
|
|
|
82
77
|
const Log = bleLogger;
|
|
83
78
|
|
|
@@ -131,32 +126,6 @@ const delay = (ms: number) =>
|
|
|
131
126
|
setTimeout(resolve, ms);
|
|
132
127
|
});
|
|
133
128
|
|
|
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
|
-
|
|
160
129
|
export const getFirmwareUploadWriteRetryType = (
|
|
161
130
|
error: unknown
|
|
162
131
|
): FirmwareUploadWriteRetryType | null => {
|
|
@@ -216,11 +185,8 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
|
|
|
216
185
|
return (
|
|
217
186
|
isNativeBleDisconnectError(error) ||
|
|
218
187
|
code === HardwareErrorCode.BleDeviceNotBonded ||
|
|
219
|
-
code === HardwareErrorCode.BleDeviceBondError ||
|
|
220
188
|
code === HardwareErrorCode.BleDeviceBondedCanceled ||
|
|
221
|
-
code === HardwareErrorCode.BlePeerRemovedPairingInformation ||
|
|
222
189
|
code === HardwareErrorCode.BleDeviceDisconnected ||
|
|
223
|
-
code === HardwareErrorCode.BleBondInvalid ||
|
|
224
190
|
code === HardwareErrorCode.BleCharacteristicNotifyError ||
|
|
225
191
|
code === HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
|
|
226
192
|
code === HardwareErrorCode.BleWriteCharacteristicError
|
|
@@ -560,19 +526,6 @@ const isStaleGattTableNotifyReason = (reason: string | null | undefined): boolea
|
|
|
560
526
|
* inside the native budget, so this only fires when the native timeout did not.
|
|
561
527
|
*/
|
|
562
528
|
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);
|
|
576
529
|
/**
|
|
577
530
|
* Service discovery and characteristic resolution run after connect() succeeds, but
|
|
578
531
|
* CoreBluetooth schedules them on the same serial queue. If that queue is wedged by a
|
|
@@ -702,11 +655,6 @@ const resolveNegotiatedMtu = (
|
|
|
702
655
|
type IOBleErrorRemap = Error | BleError | null | undefined;
|
|
703
656
|
|
|
704
657
|
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
|
-
}
|
|
710
658
|
if (isNativeBleDisconnectError(error)) {
|
|
711
659
|
throw toBleDisconnectHardwareError(error);
|
|
712
660
|
}
|
|
@@ -722,9 +670,9 @@ function remapError(error: IOBleErrorRemap) {
|
|
|
722
670
|
export default class ReactNativeBleTransport {
|
|
723
671
|
blePlxManager: BlePlxManager | undefined;
|
|
724
672
|
|
|
725
|
-
_messages: ReturnType<typeof transport.
|
|
673
|
+
_messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
726
674
|
|
|
727
|
-
_messagesV2: ReturnType<typeof transport.
|
|
675
|
+
_messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
728
676
|
|
|
729
677
|
private protocolV2SchemaConfiguration: string | undefined;
|
|
730
678
|
|
|
@@ -734,10 +682,7 @@ export default class ReactNativeBleTransport {
|
|
|
734
682
|
|
|
735
683
|
stopped = false;
|
|
736
684
|
|
|
737
|
-
private readonly
|
|
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>();
|
|
685
|
+
private readonly bondAbortController = new AbortController();
|
|
741
686
|
|
|
742
687
|
scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
|
|
743
688
|
|
|
@@ -783,14 +728,6 @@ export default class ReactNativeBleTransport {
|
|
|
783
728
|
/** Android endpoints whose cached GATT table is suspect; the next connect refreshes it. */
|
|
784
729
|
private androidGattCacheRefreshes = new Set<string>();
|
|
785
730
|
|
|
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
|
-
|
|
794
731
|
private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
|
|
795
732
|
|
|
796
733
|
private protocolV2FrameQueues: Map<string, Uint8Array[]> = new Map();
|
|
@@ -862,7 +799,7 @@ export default class ReactNativeBleTransport {
|
|
|
862
799
|
}
|
|
863
800
|
|
|
864
801
|
configure(signedData: any) {
|
|
865
|
-
const messages =
|
|
802
|
+
const messages = parseTransportConfigure(signedData);
|
|
866
803
|
this.configured = true;
|
|
867
804
|
this._messages = messages;
|
|
868
805
|
}
|
|
@@ -874,7 +811,7 @@ export default class ReactNativeBleTransport {
|
|
|
874
811
|
}
|
|
875
812
|
|
|
876
813
|
const isReconfiguration = this.protocolV2SchemaConfiguration !== undefined;
|
|
877
|
-
this._messagesV2 =
|
|
814
|
+
this._messagesV2 = parseTransportConfigure(signedData);
|
|
878
815
|
this.protocolV2SchemaConfiguration = configuration;
|
|
879
816
|
if (isReconfiguration) {
|
|
880
817
|
this.protocolV2Links
|
|
@@ -1238,9 +1175,6 @@ export default class ReactNativeBleTransport {
|
|
|
1238
1175
|
);
|
|
1239
1176
|
|
|
1240
1177
|
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());
|
|
1244
1178
|
if (!finished && deviceList.every(d => d.id !== device.id)) {
|
|
1245
1179
|
firstDeviceMs ??= Date.now() - scanStartedAt;
|
|
1246
1180
|
const displayName = getDeviceDisplayName(device) ?? 'Unknown BLE Device';
|
|
@@ -1321,545 +1255,369 @@ export default class ReactNativeBleTransport {
|
|
|
1321
1255
|
return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
|
|
1322
1256
|
}
|
|
1323
1257
|
|
|
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);
|
|
1330
|
-
}
|
|
1331
|
-
controllers.add(controller);
|
|
1332
|
-
return controller;
|
|
1333
|
-
}
|
|
1334
|
-
|
|
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);
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
private abortActiveBonding(uuid?: string): void {
|
|
1345
|
-
if (uuid !== undefined) {
|
|
1346
|
-
this.activeBondControllers.get(uuid)?.forEach(controller => controller.abort());
|
|
1347
|
-
return;
|
|
1348
|
-
}
|
|
1349
|
-
this.activeBondControllers.forEach(controllers => {
|
|
1350
|
-
controllers.forEach(controller => controller.abort());
|
|
1351
|
-
});
|
|
1352
|
-
}
|
|
1353
|
-
|
|
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);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
|
|
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;
|
|
1402
|
-
try {
|
|
1403
|
-
this.throwIfBondingStopped(signal);
|
|
1404
|
-
const key = normalizeBleMac(uuid);
|
|
1405
|
-
|
|
1406
|
-
try {
|
|
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);
|
|
1440
|
-
if (bondState.bonding) {
|
|
1441
|
-
await onDeviceBondState(uuid, signal, {
|
|
1442
|
-
systemInitiated: bondState.initiated === false,
|
|
1443
|
-
});
|
|
1444
|
-
this.throwIfBondingStopped(signal);
|
|
1445
|
-
this.knownBondedDevices.add(key);
|
|
1446
|
-
return;
|
|
1447
|
-
}
|
|
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
1258
|
private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
|
|
1476
|
-
this.
|
|
1259
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1477
1260
|
const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
|
|
1478
|
-
const
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1261
|
+
const cachedTransport = transportCache[uuid];
|
|
1262
|
+
if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
|
|
1263
|
+
Log?.debug(
|
|
1264
|
+
'[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:',
|
|
1265
|
+
uuid
|
|
1266
|
+
);
|
|
1267
|
+
const manager = this.blePlxManager;
|
|
1268
|
+
await this.runNativeTeardown(uuid, manager, async () => {
|
|
1269
|
+
await this.runBestEffortNativeOperation(
|
|
1270
|
+
'firmware install reconnect: cancel uncached device connection',
|
|
1271
|
+
() => manager.cancelDeviceConnection(uuid)
|
|
1272
|
+
);
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
if (cachedTransport) {
|
|
1276
|
+
if (skipProtocolProbe) {
|
|
1483
1277
|
Log?.debug(
|
|
1484
|
-
'[ReactNativeBleTransport] refresh
|
|
1278
|
+
'[ReactNativeBleTransport] refresh cached BLE connection for firmware install:',
|
|
1485
1279
|
uuid
|
|
1486
1280
|
);
|
|
1487
1281
|
const manager = this.blePlxManager;
|
|
1282
|
+
await this.releaseUnlocked(uuid, true);
|
|
1488
1283
|
await this.runNativeTeardown(uuid, manager, async () => {
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
() => manager.cancelDeviceConnection(uuid)
|
|
1492
|
-
);
|
|
1493
|
-
});
|
|
1494
|
-
}
|
|
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
|
-
}
|
|
1284
|
+
const operations: Promise<unknown>[] = [];
|
|
1285
|
+
if (manager) {
|
|
1513
1286
|
operations.push(
|
|
1514
1287
|
this.runBestEffortNativeOperation(
|
|
1515
|
-
'firmware install reconnect: device
|
|
1516
|
-
() =>
|
|
1288
|
+
'firmware install reconnect: cancel device connection',
|
|
1289
|
+
() => manager.cancelDeviceConnection(uuid)
|
|
1517
1290
|
)
|
|
1518
1291
|
);
|
|
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
1292
|
}
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
await
|
|
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 };
|
|
1550
1318
|
}
|
|
1551
|
-
}
|
|
1552
1319
|
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
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
|
-
);
|
|
1320
|
+
/**
|
|
1321
|
+
* If the transport is not reusable due to a protocol mismatch or stale
|
|
1322
|
+
* connection, clean it up before creating a new transport instance.
|
|
1323
|
+
*/
|
|
1324
|
+
Log?.debug('transport not reusable, will release: ', uuid);
|
|
1325
|
+
await this.releaseUnlocked(uuid, true);
|
|
1583
1326
|
}
|
|
1327
|
+
}
|
|
1584
1328
|
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1329
|
+
let device: Device | null = null;
|
|
1330
|
+
const isAndroid = Platform.OS === 'android';
|
|
1331
|
+
// A firmware-install reconnect always refreshes: the new firmware may expose a different table.
|
|
1332
|
+
const refreshAndroidGattCache =
|
|
1333
|
+
isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
|
|
1334
|
+
let nativeConnectOptions = connectOptions;
|
|
1335
|
+
if (isAndroid) {
|
|
1336
|
+
nativeConnectOptions = refreshAndroidGattCache
|
|
1337
|
+
? androidRefreshGattConnectOptions
|
|
1338
|
+
: fallbackConnectOptions;
|
|
1339
|
+
}
|
|
1340
|
+
// Only a connect that carried refreshGatt clears the marker; the fallback connects drop it.
|
|
1341
|
+
let androidRefreshConnectRan = false;
|
|
1593
1342
|
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1343
|
+
if (forceCleanRunPromise && this.runPromise) {
|
|
1344
|
+
const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
|
|
1345
|
+
this.runPromise.reject(error);
|
|
1346
|
+
this.runPromise = null;
|
|
1347
|
+
this.runPromiseDeviceId = null;
|
|
1348
|
+
Log?.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
const blePlxManager = await this.getPlxManager();
|
|
1352
|
+
let skipPostConnectMtu = false;
|
|
1353
|
+
try {
|
|
1354
|
+
await subscribeBleOn(blePlxManager);
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
Log?.debug('subscribeBleOn error: ', error);
|
|
1357
|
+
throw error;
|
|
1358
|
+
}
|
|
1359
|
+
|
|
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
|
+
try {
|
|
1364
|
+
const bondState = await pairDevice(uuid);
|
|
1365
|
+
if (bondState.bonding) {
|
|
1366
|
+
await onDeviceBondState(uuid, this.bondAbortController.signal, {
|
|
1367
|
+
systemInitiated: bondState.initiated === false,
|
|
1604
1368
|
});
|
|
1605
|
-
|
|
1369
|
+
} else if (!bondState.bonded) {
|
|
1370
|
+
throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
|
|
1606
1371
|
}
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
await this.runNativeTeardown(uuid, blePlxManager, async () => {
|
|
1374
|
+
await this.runBestEffortNativeOperation('bond failure: cancel manager connection', () =>
|
|
1375
|
+
blePlxManager.cancelDeviceConnection(uuid)
|
|
1376
|
+
);
|
|
1377
|
+
});
|
|
1378
|
+
throw error;
|
|
1607
1379
|
}
|
|
1608
|
-
|
|
1380
|
+
}
|
|
1381
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1609
1382
|
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1383
|
+
if (!device) {
|
|
1384
|
+
const devices = await blePlxManager.devices([uuid]);
|
|
1385
|
+
[device] = devices;
|
|
1386
|
+
}
|
|
1614
1387
|
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1388
|
+
if (!device) {
|
|
1389
|
+
const connectedDevice = await blePlxManager.connectedDevices(getBluetoothServiceUuids());
|
|
1390
|
+
const deviceFilter = connectedDevice.filter(device => device.id === uuid);
|
|
1391
|
+
Log?.debug(`found connected device count: ${deviceFilter.length}`);
|
|
1392
|
+
[device] = deviceFilter;
|
|
1393
|
+
}
|
|
1621
1394
|
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1395
|
+
if (!device) {
|
|
1396
|
+
Log?.debug('try to connect to device: ', uuid);
|
|
1397
|
+
try {
|
|
1398
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1399
|
+
blePlxManager.connectToDevice(uuid, nativeConnectOptions)
|
|
1400
|
+
);
|
|
1401
|
+
androidRefreshConnectRan = refreshAndroidGattCache;
|
|
1402
|
+
} catch (e) {
|
|
1403
|
+
Log?.debug('try to connect to device has error: ', e);
|
|
1404
|
+
if (shouldRethrowBleSetupError(e)) {
|
|
1405
|
+
throw e;
|
|
1406
|
+
}
|
|
1407
|
+
if (isMtuOrCancelledConnectError(e)) {
|
|
1408
|
+
skipPostConnectMtu = true;
|
|
1409
|
+
Log?.debug('first try to reconnect without params');
|
|
1410
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1411
|
+
blePlxManager.connectToDevice(uuid, fallbackConnectOptions)
|
|
1629
1412
|
);
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
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
|
-
}
|
|
1413
|
+
} else if (e.errorCode === BleErrorCode.DeviceAlreadyConnected) {
|
|
1414
|
+
Log?.debug('device already connected');
|
|
1415
|
+
throw ERRORS.TypedError(HardwareErrorCode.BleAlreadyConnected);
|
|
1416
|
+
} else {
|
|
1417
|
+
remapError(e);
|
|
1650
1418
|
}
|
|
1651
1419
|
}
|
|
1420
|
+
}
|
|
1652
1421
|
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1422
|
+
if (!device) {
|
|
1423
|
+
throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'unable to connect to device');
|
|
1424
|
+
}
|
|
1656
1425
|
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1426
|
+
if (
|
|
1427
|
+
refreshAndroidGattCache &&
|
|
1428
|
+
!androidRefreshConnectRan &&
|
|
1429
|
+
(await device.isConnected().catch(() => false))
|
|
1430
|
+
) {
|
|
1431
|
+
// refreshGatt only reaches the stack through a connect. A link that is still up would
|
|
1432
|
+
// skip the connect below and keep serving the stale table, so it is dropped first.
|
|
1433
|
+
await this.dropAndroidLink(uuid, blePlxManager, device, 'gatt cache refresh');
|
|
1434
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1435
|
+
}
|
|
1667
1436
|
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1437
|
+
if (!(await device.isConnected())) {
|
|
1438
|
+
Log?.debug('not connected, try to connect to device: ', uuid);
|
|
1439
|
+
const disconnectedDevice = device;
|
|
1671
1440
|
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1441
|
+
try {
|
|
1442
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1443
|
+
disconnectedDevice.connect(nativeConnectOptions)
|
|
1444
|
+
);
|
|
1445
|
+
androidRefreshConnectRan = refreshAndroidGattCache;
|
|
1446
|
+
} catch (e) {
|
|
1447
|
+
Log?.debug('not connected, try to connect to device has error: ', e);
|
|
1448
|
+
if (shouldRethrowBleSetupError(e)) {
|
|
1449
|
+
throw e;
|
|
1450
|
+
}
|
|
1451
|
+
if (isMtuOrCancelledConnectError(e)) {
|
|
1452
|
+
skipPostConnectMtu = true;
|
|
1453
|
+
Log?.debug('second try to reconnect without params');
|
|
1454
|
+
try {
|
|
1455
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1456
|
+
disconnectedDevice.connect(fallbackConnectOptions)
|
|
1457
|
+
);
|
|
1458
|
+
} catch (fallbackError) {
|
|
1459
|
+
Log?.debug('last try to reconnect error: ', fallbackError);
|
|
1460
|
+
// last try to reconnect device if this issue exists
|
|
1461
|
+
// https://github.com/dotintent/react-native-ble-plx/issues/426
|
|
1462
|
+
if (fallbackError.errorCode === BleErrorCode.OperationCancelled) {
|
|
1463
|
+
Log?.debug('last try to reconnect');
|
|
1464
|
+
await disconnectedDevice.cancelConnection();
|
|
1465
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1466
|
+
disconnectedDevice.connect(fallbackConnectOptions)
|
|
1692
1467
|
);
|
|
1693
|
-
}
|
|
1694
|
-
|
|
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
|
-
}
|
|
1468
|
+
} else {
|
|
1469
|
+
remapError(fallbackError);
|
|
1708
1470
|
}
|
|
1709
|
-
} else {
|
|
1710
|
-
remapError(e);
|
|
1711
1471
|
}
|
|
1472
|
+
} else {
|
|
1473
|
+
remapError(e);
|
|
1712
1474
|
}
|
|
1713
1475
|
}
|
|
1476
|
+
}
|
|
1714
1477
|
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1478
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1479
|
+
if (Platform.OS === 'android' && !(await device.isConnected().catch(() => false))) {
|
|
1480
|
+
const disconnectedDevice = device;
|
|
1481
|
+
await this.runNativeTeardown(uuid, blePlxManager, async () => {
|
|
1482
|
+
await Promise.all([
|
|
1483
|
+
this.runBestEffortNativeOperation('connect failure: cancel manager connection', () =>
|
|
1484
|
+
blePlxManager.cancelDeviceConnection(uuid)
|
|
1485
|
+
),
|
|
1486
|
+
this.runBestEffortNativeOperation('connect failure: cancel device connection', () =>
|
|
1487
|
+
disconnectedDevice.cancelConnection()
|
|
1488
|
+
),
|
|
1489
|
+
]);
|
|
1490
|
+
});
|
|
1491
|
+
throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'device is not connected');
|
|
1492
|
+
}
|
|
1493
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1494
|
+
let characteristics: ResolvedBleCharacteristics | undefined;
|
|
1495
|
+
if (isAndroid) {
|
|
1496
|
+
if (refreshAndroidGattCache) {
|
|
1497
|
+
// refreshGatt has already started a full rediscovery; let it finish before the MTU
|
|
1498
|
+
// exchange so the request is not queued behind it.
|
|
1499
|
+
characteristics = await this.resolveCharacteristicsWithTimeout(uuid, device);
|
|
1500
|
+
if (androidRefreshConnectRan) this.androidGattCacheRefreshes.delete(uuid);
|
|
1501
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1502
|
+
}
|
|
1503
|
+
device = await this.negotiateAndroidMtu(uuid, blePlxManager, device);
|
|
1504
|
+
} else if (!skipPostConnectMtu) {
|
|
1505
|
+
// Match 1.1.31: MTU is a connect() best-effort. If connect already fell back
|
|
1506
|
+
// without requestMTU, do not put another requestMTU on the native serial
|
|
1507
|
+
// queue — that is what wedges GATT after Account#2 reconnect.
|
|
1508
|
+
const mtuResult = await resolveNegotiatedMtu(device, transactionId =>
|
|
1509
|
+
blePlxManager.cancelTransaction(transactionId)
|
|
1510
|
+
);
|
|
1511
|
+
device = mtuResult.device;
|
|
1512
|
+
if (mtuResult.timedOut) {
|
|
1513
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1514
|
+
Log?.debug(
|
|
1515
|
+
'[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU'
|
|
1516
|
+
);
|
|
1517
|
+
const timedOutDevice = device;
|
|
1518
|
+
let mtuTeardownSettled = false;
|
|
1718
1519
|
await this.runNativeTeardown(uuid, blePlxManager, async () => {
|
|
1719
|
-
await
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
this.runBestEffortNativeOperation('connect failure: cancel device connection', () =>
|
|
1724
|
-
disconnectedDevice.cancelConnection()
|
|
1725
|
-
),
|
|
1726
|
-
]);
|
|
1520
|
+
await this.runBestEffortNativeOperation('mtu timeout: cancel device connection', () =>
|
|
1521
|
+
timedOutDevice.cancelConnection()
|
|
1522
|
+
);
|
|
1523
|
+
mtuTeardownSettled = true;
|
|
1727
1524
|
});
|
|
1728
|
-
throw ERRORS.TypedError(HardwareErrorCode.
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
if (isAndroid) {
|
|
1733
|
-
if (refreshAndroidGattCache) {
|
|
1734
|
-
// refreshGatt has already started a full rediscovery; let it finish before the MTU
|
|
1735
|
-
// exchange so the request is not queued behind it.
|
|
1736
|
-
characteristics = await this.resolveCharacteristicsWithTimeout(uuid, device);
|
|
1737
|
-
if (androidRefreshConnectRan) this.androidGattCacheRefreshes.delete(uuid);
|
|
1738
|
-
this.throwIfBondingStopped(bondSignal);
|
|
1525
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1526
|
+
if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
|
|
1527
|
+
// The teardown budget expired and the manager that owned timedOutDevice was reset.
|
|
1528
|
+
throw ERRORS.TypedError(HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
|
|
1739
1529
|
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
// without requestMTU, do not put another requestMTU on the native serial
|
|
1744
|
-
// queue — that is what wedges GATT after Account#2 reconnect.
|
|
1745
|
-
const mtuResult = await resolveNegotiatedMtu(device, transactionId =>
|
|
1746
|
-
blePlxManager.cancelTransaction(transactionId)
|
|
1747
|
-
);
|
|
1748
|
-
device = mtuResult.device;
|
|
1749
|
-
if (mtuResult.timedOut) {
|
|
1750
|
-
this.throwIfBondingStopped(bondSignal);
|
|
1751
|
-
Log?.debug(
|
|
1752
|
-
'[ReactNativeBleTransport] post-connect MTU timed out, reconnecting without requesting MTU'
|
|
1530
|
+
try {
|
|
1531
|
+
device = await this.connectWithTimeout(uuid, () =>
|
|
1532
|
+
timedOutDevice.connect(fallbackConnectOptions)
|
|
1753
1533
|
);
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
}
|
|
1762
|
-
|
|
1763
|
-
if (!mtuTeardownSettled || this.blePlxManager !== blePlxManager) {
|
|
1764
|
-
// The teardown budget expired and the manager that owned timedOutDevice was reset.
|
|
1765
|
-
throw ERRORS.TypedError(HardwareErrorCode.BleTimeoutError, 'BLE MTU cleanup timed out');
|
|
1766
|
-
}
|
|
1767
|
-
try {
|
|
1768
|
-
device = await this.connectWithTimeout(
|
|
1769
|
-
uuid,
|
|
1770
|
-
() => timedOutDevice.connect(bareConnectOptions),
|
|
1771
|
-
connectBackstopMs
|
|
1772
|
-
);
|
|
1773
|
-
} catch (error) {
|
|
1774
|
-
if (shouldRethrowBleSetupError(error)) throw error;
|
|
1775
|
-
if (
|
|
1776
|
-
(error as { errorCode?: unknown })?.errorCode === BleErrorCode.DeviceAlreadyConnected
|
|
1777
|
-
) {
|
|
1778
|
-
// GATT resolution and the protocol probe below still validate the retained link.
|
|
1779
|
-
device = timedOutDevice;
|
|
1780
|
-
} else {
|
|
1781
|
-
remapError(error);
|
|
1782
|
-
}
|
|
1534
|
+
} catch (error) {
|
|
1535
|
+
if (shouldRethrowBleSetupError(error)) throw error;
|
|
1536
|
+
if (
|
|
1537
|
+
(error as { errorCode?: unknown })?.errorCode === BleErrorCode.DeviceAlreadyConnected
|
|
1538
|
+
) {
|
|
1539
|
+
// GATT resolution and the protocol probe below still validate the retained link.
|
|
1540
|
+
device = timedOutDevice;
|
|
1541
|
+
} else {
|
|
1542
|
+
remapError(error);
|
|
1783
1543
|
}
|
|
1784
1544
|
}
|
|
1785
1545
|
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
this.
|
|
1546
|
+
}
|
|
1547
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1548
|
+
const acquiredDevice = device;
|
|
1549
|
+
const { writeCharacteristic, notifyCharacteristic } =
|
|
1550
|
+
characteristics ?? (await this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice));
|
|
1551
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1791
1552
|
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1553
|
+
const protocolHint = expectedProtocol
|
|
1554
|
+
? undefined
|
|
1555
|
+
: input.protocolHint ?? this.deviceProtocolHints.get(uuid);
|
|
1795
1556
|
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1557
|
+
// release transport before new transport instance
|
|
1558
|
+
await this.releaseUnlocked(uuid, true);
|
|
1559
|
+
if (protocolHint) {
|
|
1560
|
+
this.deviceProtocolHints.set(uuid, protocolHint);
|
|
1561
|
+
}
|
|
1801
1562
|
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1563
|
+
try {
|
|
1564
|
+
await this.installTransportForAcquire(uuid, acquiredDevice, {
|
|
1565
|
+
writeCharacteristic,
|
|
1566
|
+
notifyCharacteristic,
|
|
1567
|
+
});
|
|
1807
1568
|
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
}
|
|
1815
|
-
const hasConfirmedProtocol =
|
|
1816
|
-
this.sessionProtocols.get(uuid) === expectedProtocol ||
|
|
1817
|
-
(expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
|
|
1818
|
-
if (!hasConfirmedProtocol) {
|
|
1819
|
-
throw ERRORS.TypedError(
|
|
1820
|
-
HardwareErrorCode.RuntimeError,
|
|
1821
|
-
'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint'
|
|
1822
|
-
);
|
|
1823
|
-
}
|
|
1824
|
-
this.deviceProtocol.set(uuid, expectedProtocol);
|
|
1825
|
-
this.sessionProtocols.set(uuid, expectedProtocol);
|
|
1826
|
-
this.protocolReprobeFailures.delete(uuid);
|
|
1827
|
-
Log?.debug('[ReactNativeBleTransport] protocol selected without probe', {
|
|
1828
|
-
deviceId: uuid,
|
|
1829
|
-
protocol: expectedProtocol,
|
|
1830
|
-
source: 'firmware-install-reconnect',
|
|
1831
|
-
});
|
|
1832
|
-
const currentTransport = transportCache[uuid];
|
|
1833
|
-
if (!currentTransport) {
|
|
1834
|
-
throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
|
|
1835
|
-
}
|
|
1836
|
-
this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
|
|
1837
|
-
return { uuid, protocolType: expectedProtocol };
|
|
1569
|
+
if (skipProtocolProbe) {
|
|
1570
|
+
if (!expectedProtocol) {
|
|
1571
|
+
throw ERRORS.TypedError(
|
|
1572
|
+
HardwareErrorCode.RuntimeError,
|
|
1573
|
+
'skipProtocolProbe requires an expected BLE protocol'
|
|
1574
|
+
);
|
|
1838
1575
|
}
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
uuid
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
this.
|
|
1576
|
+
const hasConfirmedProtocol =
|
|
1577
|
+
this.sessionProtocols.get(uuid) === expectedProtocol ||
|
|
1578
|
+
(expectedProtocol === 'V2' && this.confirmedProtocolV2.has(uuid));
|
|
1579
|
+
if (!hasConfirmedProtocol) {
|
|
1580
|
+
throw ERRORS.TypedError(
|
|
1581
|
+
HardwareErrorCode.RuntimeError,
|
|
1582
|
+
'skipProtocolProbe requires a previously confirmed protocol for this BLE endpoint'
|
|
1583
|
+
);
|
|
1584
|
+
}
|
|
1585
|
+
this.deviceProtocol.set(uuid, expectedProtocol);
|
|
1586
|
+
this.sessionProtocols.set(uuid, expectedProtocol);
|
|
1587
|
+
this.protocolReprobeFailures.delete(uuid);
|
|
1588
|
+
Log?.debug('[ReactNativeBleTransport] protocol selected without probe', {
|
|
1589
|
+
deviceId: uuid,
|
|
1590
|
+
protocol: expectedProtocol,
|
|
1591
|
+
source: 'firmware-install-reconnect',
|
|
1592
|
+
});
|
|
1849
1593
|
const currentTransport = transportCache[uuid];
|
|
1850
1594
|
if (!currentTransport) {
|
|
1851
1595
|
throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
|
|
1852
1596
|
}
|
|
1853
1597
|
this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
|
|
1854
|
-
return { uuid, protocolType };
|
|
1855
|
-
} catch (error) {
|
|
1856
|
-
// A failed acquire must retire the physical link before Core retries. Logical
|
|
1857
|
-
// release leaves GATT connected even when neither protocol receives a response.
|
|
1858
|
-
await this.disconnectUnlocked(uuid);
|
|
1859
|
-
throw error;
|
|
1598
|
+
return { uuid, protocolType: expectedProtocol };
|
|
1860
1599
|
}
|
|
1861
|
-
|
|
1862
|
-
this.
|
|
1600
|
+
|
|
1601
|
+
const protocolType = await this.detectProtocol(
|
|
1602
|
+
uuid,
|
|
1603
|
+
expectedProtocol,
|
|
1604
|
+
protocolHint,
|
|
1605
|
+
async () => {
|
|
1606
|
+
await this.installTransportForAcquire(uuid, acquiredDevice);
|
|
1607
|
+
}
|
|
1608
|
+
);
|
|
1609
|
+
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
1610
|
+
const currentTransport = transportCache[uuid];
|
|
1611
|
+
if (!currentTransport) {
|
|
1612
|
+
throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
|
|
1613
|
+
}
|
|
1614
|
+
this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
|
|
1615
|
+
return { uuid, protocolType };
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
// A failed acquire must retire the physical link before Core retries. Logical
|
|
1618
|
+
// release leaves GATT connected even when neither protocol receives a response.
|
|
1619
|
+
await this.disconnectUnlocked(uuid);
|
|
1620
|
+
throw error;
|
|
1863
1621
|
}
|
|
1864
1622
|
}
|
|
1865
1623
|
|
|
@@ -1887,17 +1645,6 @@ export default class ReactNativeBleTransport {
|
|
|
1887
1645
|
Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
|
|
1888
1646
|
return;
|
|
1889
1647
|
}
|
|
1890
|
-
if (Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
|
|
1891
|
-
const staleBondError = toIosStaleBondError(error);
|
|
1892
|
-
if (this.getActiveProtocol(uuid) === 'V2') {
|
|
1893
|
-
this.rejectProtocolV2Frames(uuid, staleBondError);
|
|
1894
|
-
return;
|
|
1895
|
-
}
|
|
1896
|
-
if (this.runPromise && this.runPromiseDeviceId === uuid) {
|
|
1897
|
-
this.runPromise.reject(staleBondError);
|
|
1898
|
-
}
|
|
1899
|
-
return;
|
|
1900
|
-
}
|
|
1901
1648
|
if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
|
|
1902
1649
|
this.androidGattCacheRefreshes.add(uuid);
|
|
1903
1650
|
}
|
|
@@ -2404,7 +2151,7 @@ export default class ReactNativeBleTransport {
|
|
|
2404
2151
|
if (this.stopPromise) return this.stopPromise;
|
|
2405
2152
|
this.stopped = true;
|
|
2406
2153
|
// Bonding precedes GATT, so cancelDeviceConnection cannot end this wait.
|
|
2407
|
-
this.
|
|
2154
|
+
this.bondAbortController.abort();
|
|
2408
2155
|
const deviceIds = new Set([
|
|
2409
2156
|
...this.monitorTokens.keys(),
|
|
2410
2157
|
...this.sessionProtocols.keys(),
|
|
@@ -2415,7 +2162,6 @@ export default class ReactNativeBleTransport {
|
|
|
2415
2162
|
this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
|
|
2416
2163
|
this.androidPriorityResetTimers.clear();
|
|
2417
2164
|
this.androidHighPriorityDevices.clear();
|
|
2418
|
-
this.iosLastAdvertisedAt.clear();
|
|
2419
2165
|
const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
2420
2166
|
this.runPromise?.reject(error);
|
|
2421
2167
|
this.runPromise = null;
|
|
@@ -2448,7 +2194,6 @@ export default class ReactNativeBleTransport {
|
|
|
2448
2194
|
}
|
|
2449
2195
|
|
|
2450
2196
|
async disconnect(session: string) {
|
|
2451
|
-
this.abortActiveBonding(session);
|
|
2452
2197
|
return this.runLifecycleOperation(session, () => this.disconnectUnlocked(session));
|
|
2453
2198
|
}
|
|
2454
2199
|
|
|
@@ -2602,12 +2347,11 @@ export default class ReactNativeBleTransport {
|
|
|
2602
2347
|
}
|
|
2603
2348
|
}
|
|
2604
2349
|
|
|
2605
|
-
async cancel(
|
|
2606
|
-
Log?.debug('transport-react-native transport cancel'
|
|
2607
|
-
this.abortActiveBonding(uuid);
|
|
2350
|
+
async cancel() {
|
|
2351
|
+
Log?.debug('transport-react-native transport cancel');
|
|
2608
2352
|
const pending = this.runPromise;
|
|
2609
2353
|
const deviceId = this.runPromiseDeviceId;
|
|
2610
|
-
if (pending
|
|
2354
|
+
if (pending) {
|
|
2611
2355
|
pending.reject(ERRORS.TypedError(HardwareErrorCode.CallQueueActionCancelled));
|
|
2612
2356
|
if (this.runPromise === pending) {
|
|
2613
2357
|
this.runPromise = null;
|
|
@@ -2711,25 +2455,8 @@ export default class ReactNativeBleTransport {
|
|
|
2711
2455
|
});
|
|
2712
2456
|
}
|
|
2713
2457
|
|
|
2714
|
-
/**
|
|
2715
|
-
* Whether this acquire may spend the longer iOS connect budget. The sighting is used up: the
|
|
2716
|
-
* retry that follows a timeout gets no new scan, and the device may have left by then. A
|
|
2717
|
-
* firmware-install reconnect keeps its short polling cadence.
|
|
2718
|
-
*/
|
|
2719
|
-
private takeIosPresentDeviceSighting(uuid: string, skipProtocolProbe?: boolean): boolean {
|
|
2720
|
-
if (Platform.OS !== 'ios') return false;
|
|
2721
|
-
const seenAt = this.iosLastAdvertisedAt.get(uuid);
|
|
2722
|
-
this.iosLastAdvertisedAt.delete(uuid);
|
|
2723
|
-
if (skipProtocolProbe || seenAt === undefined) return false;
|
|
2724
|
-
return Date.now() - seenAt <= IOS_PRESENT_DEVICE_WINDOW_MS;
|
|
2725
|
-
}
|
|
2726
|
-
|
|
2727
2458
|
/** Run a native connect under the JS backstop budget. */
|
|
2728
|
-
private async connectWithTimeout<T>(
|
|
2729
|
-
uuid: string,
|
|
2730
|
-
connect: () => Promise<T>,
|
|
2731
|
-
backstopMs = BLE_CONNECT_TIMEOUT_MS
|
|
2732
|
-
): Promise<T> {
|
|
2459
|
+
private async connectWithTimeout<T>(uuid: string, connect: () => Promise<T>): Promise<T> {
|
|
2733
2460
|
if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
|
|
2734
2461
|
const startedAt = Date.now();
|
|
2735
2462
|
let succeeded = false;
|
|
@@ -2748,10 +2475,10 @@ export default class ReactNativeBleTransport {
|
|
|
2748
2475
|
reject(
|
|
2749
2476
|
ERRORS.TypedError(
|
|
2750
2477
|
HardwareErrorCode.BleConnectedError,
|
|
2751
|
-
`BLE connect timeout after ${
|
|
2478
|
+
`BLE connect timeout after ${BLE_CONNECT_TIMEOUT_MS}ms for ${uuid}`
|
|
2752
2479
|
)
|
|
2753
2480
|
);
|
|
2754
|
-
},
|
|
2481
|
+
}, BLE_CONNECT_TIMEOUT_MS);
|
|
2755
2482
|
}),
|
|
2756
2483
|
]);
|
|
2757
2484
|
succeeded = true;
|
|
@@ -2774,7 +2501,6 @@ export default class ReactNativeBleTransport {
|
|
|
2774
2501
|
elapsedMs: Date.now() - startedAt,
|
|
2775
2502
|
succeeded,
|
|
2776
2503
|
backstopExpired: timedOut,
|
|
2777
|
-
backstopMs,
|
|
2778
2504
|
});
|
|
2779
2505
|
}
|
|
2780
2506
|
}
|
|
@@ -2818,12 +2544,6 @@ export default class ReactNativeBleTransport {
|
|
|
2818
2544
|
throw this.createWedgedBleSetupError();
|
|
2819
2545
|
}
|
|
2820
2546
|
}
|
|
2821
|
-
if (Platform.OS === 'ios' && isIosPeerRemovedPairingInformation(error)) {
|
|
2822
|
-
// iOS can report the lost bond on the first GATT operation instead of
|
|
2823
|
-
// on the connect. Check it before the generic disconnect mapping: the
|
|
2824
|
-
// same native failure may also carry the ble-plx disconnect code.
|
|
2825
|
-
throw toIosStaleBondError(error);
|
|
2826
|
-
}
|
|
2827
2547
|
if (isNativeBleDisconnectError(error)) {
|
|
2828
2548
|
throw toBleDisconnectHardwareError(error);
|
|
2829
2549
|
}
|
|
@@ -2981,7 +2701,6 @@ export default class ReactNativeBleTransport {
|
|
|
2981
2701
|
|
|
2982
2702
|
private resetPlxManager() {
|
|
2983
2703
|
if (bleManagerResetPromise) return;
|
|
2984
|
-
this.iosLastAdvertisedAt.clear();
|
|
2985
2704
|
const manager = this.blePlxManager;
|
|
2986
2705
|
this.blePlxManager = undefined;
|
|
2987
2706
|
const reason = 'React Native BLE manager reset';
|
|
@@ -3286,29 +3005,24 @@ export default class ReactNativeBleTransport {
|
|
|
3286
3005
|
|
|
3287
3006
|
this.probingProtocols.set(uuid, 'V2');
|
|
3288
3007
|
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
if (!detected) {
|
|
3303
|
-
this.clearProbeProtocol(uuid, 'V2');
|
|
3304
|
-
} else {
|
|
3305
|
-
this.probingProtocols.delete(uuid);
|
|
3306
|
-
}
|
|
3307
|
-
return detected;
|
|
3308
|
-
} catch (error) {
|
|
3008
|
+
const detected = await probeProtocolV2Helper({
|
|
3009
|
+
call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
|
|
3010
|
+
this.callProtocolV2(uuid, name, data, options),
|
|
3011
|
+
timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
|
|
3012
|
+
logger: Log,
|
|
3013
|
+
logPrefix: 'ProtocolV2 RN-BLE',
|
|
3014
|
+
onProbeFailed: () => {
|
|
3015
|
+
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3016
|
+
this.resetProtocolV2Frames(uuid);
|
|
3017
|
+
},
|
|
3018
|
+
shouldRethrow: shouldRethrowProtocolProbeError,
|
|
3019
|
+
});
|
|
3020
|
+
if (!detected) {
|
|
3309
3021
|
this.clearProbeProtocol(uuid, 'V2');
|
|
3310
|
-
|
|
3022
|
+
} else {
|
|
3023
|
+
this.probingProtocols.delete(uuid);
|
|
3311
3024
|
}
|
|
3025
|
+
return detected;
|
|
3312
3026
|
}
|
|
3313
3027
|
|
|
3314
3028
|
private handleProtocolV2Notification(uuid: string, monitorToken: number, data: Uint8Array) {
|