@onekeyfe/hd-transport-react-native 1.2.8 → 1.2.9

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.
Files changed (35) hide show
  1. package/dist/BleManager.d.ts +2 -4
  2. package/dist/BleManager.d.ts.map +1 -1
  3. package/dist/bleNativeDisconnect.d.ts.map +1 -1
  4. package/dist/index.d.ts +44 -64
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +449 -615
  7. package/dist/subscribeBleOn.d.ts.map +1 -1
  8. package/package.json +5 -5
  9. package/src/BleManager.ts +8 -32
  10. package/src/__tests__/bleNativeDisconnect.test.ts +22 -1
  11. package/src/__tests__/connectTimeout.test.ts +110 -0
  12. package/src/__tests__/enumerate.test.ts +207 -17
  13. package/src/__tests__/moduleInterop.test.ts +48 -0
  14. package/src/__tests__/nativeFrameWrite.test.ts +910 -0
  15. package/src/__tests__/protocolV2Link.test.ts +284 -81
  16. package/src/__tests__/subscribeBleOn.test.ts +114 -0
  17. package/src/bleNativeDisconnect.ts +2 -1
  18. package/src/index.ts +535 -350
  19. package/src/subscribeBleOn.ts +30 -11
  20. package/dist/bleEncryption.d.ts +0 -17
  21. package/dist/bleEncryption.d.ts.map +0 -1
  22. package/dist/bleIosStaleBond.d.ts +0 -16
  23. package/dist/bleIosStaleBond.d.ts.map +0 -1
  24. package/dist/bleKeyMissing.d.ts +0 -7
  25. package/dist/bleKeyMissing.d.ts.map +0 -1
  26. package/dist/bleStaleBond.d.ts +0 -5
  27. package/dist/bleStaleBond.d.ts.map +0 -1
  28. package/src/__tests__/androidEncryption.test.ts +0 -482
  29. package/src/__tests__/androidKeyMissing.test.ts +0 -307
  30. package/src/__tests__/bleStaleBond.test.ts +0 -47
  31. package/src/__tests__/iosPeerTermination.test.ts +0 -318
  32. package/src/bleEncryption.ts +0 -267
  33. package/src/bleIosStaleBond.ts +0 -92
  34. package/src/bleKeyMissing.ts +0 -106
  35. package/src/bleStaleBond.ts +0 -64
package/dist/index.js CHANGED
@@ -6,15 +6,15 @@ var reactNative = require('react-native');
6
6
  var buffer = require('buffer');
7
7
  var reactNativeBlePlx = require('react-native-ble-plx');
8
8
  var ByteBuffer = require('bytebuffer');
9
- var transport = require('@onekeyfe/hd-transport');
9
+ var transportModule = require('@onekeyfe/hd-transport');
10
10
  var hdShared = require('@onekeyfe/hd-shared');
11
- var BleUtils = require('@onekeyfe/react-native-ble-utils');
11
+ var BleUtilsModule = require('@onekeyfe/react-native-ble-utils');
12
12
 
13
13
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
14
 
15
15
  var ByteBuffer__default = /*#__PURE__*/_interopDefaultLegacy(ByteBuffer);
16
- var transport__default = /*#__PURE__*/_interopDefaultLegacy(transport);
17
- var BleUtils__default = /*#__PURE__*/_interopDefaultLegacy(BleUtils);
16
+ var transportModule__default = /*#__PURE__*/_interopDefaultLegacy(transportModule);
17
+ var BleUtilsModule__default = /*#__PURE__*/_interopDefaultLegacy(BleUtilsModule);
18
18
 
19
19
  /******************************************************************************
20
20
  Copyright (c) Microsoft Corporation.
@@ -46,76 +46,6 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
46
46
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
47
  };
48
48
 
49
- const lastKeyMissingAt = new Map();
50
- const listeners$1 = new Set();
51
- let unsubscribeNative$1;
52
- const normalizeDeviceId$1 = (deviceId) => deviceId.toLowerCase();
53
- const getCapableBleUtils$1 = () => {
54
- if (reactNative.Platform.OS !== 'android')
55
- return undefined;
56
- const bleUtils = BleUtils__default["default"];
57
- if (typeof bleUtils.supportsDeviceKeyMissing !== 'function' ||
58
- typeof bleUtils.onDeviceKeyMissing !== 'function') {
59
- return undefined;
60
- }
61
- return bleUtils.supportsDeviceKeyMissing() ? bleUtils : undefined;
62
- };
63
- const isBleKeyMissingSupported = () => getCapableBleUtils$1() !== undefined;
64
- const startBleKeyMissingTracking = () => {
65
- if (unsubscribeNative$1)
66
- return true;
67
- const bleUtils = getCapableBleUtils$1();
68
- if (!(bleUtils === null || bleUtils === void 0 ? void 0 : bleUtils.onDeviceKeyMissing))
69
- return false;
70
- unsubscribeNative$1 = bleUtils.onDeviceKeyMissing(event => {
71
- if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
72
- return;
73
- const deviceId = normalizeDeviceId$1(event.id);
74
- lastKeyMissingAt.set(deviceId, Date.now());
75
- listeners$1.forEach(listener => listener(deviceId));
76
- });
77
- return true;
78
- };
79
- const stopBleKeyMissingTracking = () => {
80
- unsubscribeNative$1 === null || unsubscribeNative$1 === void 0 ? void 0 : unsubscribeNative$1();
81
- unsubscribeNative$1 = undefined;
82
- lastKeyMissingAt.clear();
83
- listeners$1.clear();
84
- };
85
- const hasBleKeyMissingSince = (deviceId, sinceMs) => {
86
- const at = lastKeyMissingAt.get(normalizeDeviceId$1(deviceId));
87
- return at !== undefined && at >= sinceMs;
88
- };
89
- const onBleKeyMissing = (deviceId, callback) => {
90
- const target = normalizeDeviceId$1(deviceId);
91
- const listener = id => {
92
- if (id === target)
93
- callback();
94
- };
95
- listeners$1.add(listener);
96
- return () => {
97
- listeners$1.delete(listener);
98
- };
99
- };
100
- const waitForBleKeyMissing = (deviceId, sinceMs, timeoutMs) => {
101
- if (!startBleKeyMissingTracking())
102
- return Promise.resolve(false);
103
- if (hasBleKeyMissingSince(deviceId, sinceMs))
104
- return Promise.resolve(true);
105
- return new Promise(resolve => {
106
- const settle = (found) => {
107
- clearTimeout(timer);
108
- cleanup();
109
- resolve(found);
110
- };
111
- const cleanup = onBleKeyMissing(deviceId, () => {
112
- if (hasBleKeyMissingSince(deviceId, sinceMs))
113
- settle(true);
114
- });
115
- const timer = setTimeout(() => settle(false), timeoutMs);
116
- });
117
- };
118
-
119
49
  let activeLogger;
120
50
  const setBleLogger = (logger) => {
121
51
  activeLogger = logger;
@@ -126,7 +56,9 @@ const bleLogger = {
126
56
  warn: (...args) => { var _a; return (_a = activeLogger === null || activeLogger === void 0 ? void 0 : activeLogger.warn) === null || _a === void 0 ? void 0 : _a.call(activeLogger, ...args); },
127
57
  };
128
58
 
59
+ var _a$1;
129
60
  const Logger = bleLogger;
61
+ const BleUtils = (_a$1 = BleUtilsModule__default["default"].default) !== null && _a$1 !== void 0 ? _a$1 : BleUtilsModule__default["default"];
130
62
  const bondFailureReasons = {
131
63
  1: 'authentication_failed',
132
64
  2: 'rejected',
@@ -138,8 +70,8 @@ const bondFailureReasons = {
138
70
  8: 'remote_canceled',
139
71
  9: 'removed',
140
72
  };
141
- const getConnectedDeviceIds = (serviceUuids) => BleUtils__default["default"].getConnectedPeripherals(serviceUuids);
142
- const pairDevice = (macAddress) => BleUtils__default["default"].pairDevice(macAddress);
73
+ const getConnectedDeviceIds = (serviceUuids) => BleUtils.getConnectedPeripherals(serviceUuids);
74
+ const pairDevice = (macAddress) => BleUtils.pairDevice(macAddress);
143
75
  const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
144
76
  const createBondFailureError = (bondState) => {
145
77
  var _a;
@@ -168,7 +100,6 @@ const onDeviceBondState = (bleMacAddress, signal, options) => new Promise((resol
168
100
  clearTimeout(pendingFailure);
169
101
  if (cleanupListener)
170
102
  cleanupListener();
171
- cleanupKeyMissing === null || cleanupKeyMissing === void 0 ? void 0 : cleanupKeyMissing();
172
103
  signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
173
104
  };
174
105
  const onAbort = () => {
@@ -183,16 +114,7 @@ const onDeviceBondState = (bleMacAddress, signal, options) => new Promise((resol
183
114
  reason: 'timeout',
184
115
  }));
185
116
  }, 60 * 1000);
186
- const cleanupKeyMissing = startBleKeyMissingTracking()
187
- ? onBleKeyMissing(bleMacAddress, () => {
188
- cleanup();
189
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
190
- phase: 'bond',
191
- reason: 'key_missing',
192
- }));
193
- })
194
- : undefined;
195
- const cleanupListener = BleUtils__default["default"].onDeviceBondState(peripheral => {
117
+ const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
196
118
  var _a;
197
119
  if (((_a = peripheral.id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== bleMacAddress.toLowerCase()) {
198
120
  return;
@@ -308,252 +230,53 @@ const timer = process.env.NODE_ENV === 'development'
308
230
  },
309
231
  };
310
232
 
311
- const subscribeBleOn = (bleManager, ms = 1000) => new Promise((resolve, reject) => {
233
+ const subscribeBleOn = (bleManager, ms = 2000) => new Promise((resolve, reject) => {
312
234
  let done = false;
235
+ let pendingError;
236
+ let cancelTimeout = () => undefined;
237
+ let removeSubscription = () => undefined;
238
+ const finish = (error) => {
239
+ if (done)
240
+ return;
241
+ done = true;
242
+ cancelTimeout();
243
+ removeSubscription();
244
+ if (error)
245
+ reject(error);
246
+ else
247
+ resolve();
248
+ };
313
249
  const subscription = bleManager.onStateChange(state => {
314
250
  if (state === 'PoweredOn') {
315
- if (done)
316
- return;
317
- clearTimeout();
318
- done = true;
319
- subscription.remove();
320
- resolve();
251
+ finish();
321
252
  }
322
- }, true);
323
- const clearTimeout = timer.timeout(() => {
324
- if (done)
325
- return;
326
- subscription.remove();
327
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
328
- }, ms);
329
- });
330
-
331
- const HCI_PIN_OR_KEY_MISSING = 0x06;
332
- const lastEncryption = new Map();
333
- const lastAclDisconnectAt = new Map();
334
- const listeners = new Set();
335
- let unsubscribeNative;
336
- const normalizeDeviceId = (deviceId) => deviceId.toLowerCase();
337
- const isEncrypted = (record) => record.status === 0 && record.enabled;
338
- const getCapableBleUtils = () => {
339
- if (reactNative.Platform.OS !== 'android')
340
- return undefined;
341
- const bleUtils = BleUtils__default["default"];
342
- if (typeof bleUtils.supportsDeviceEncryptionChange !== 'function' ||
343
- typeof bleUtils.onDeviceEncryptionChange !== 'function' ||
344
- typeof bleUtils.onDeviceAclDisconnected !== 'function') {
345
- return undefined;
346
- }
347
- return bleUtils.supportsDeviceEncryptionChange() ? bleUtils : undefined;
348
- };
349
- const notify = (deviceId) => {
350
- listeners.forEach(listener => listener(deviceId));
351
- };
352
- const startBleEncryptionTracking = () => {
353
- if (unsubscribeNative)
354
- return true;
355
- const bleUtils = getCapableBleUtils();
356
- if (!(bleUtils === null || bleUtils === void 0 ? void 0 : bleUtils.onDeviceEncryptionChange) || !bleUtils.onDeviceAclDisconnected)
357
- return false;
358
- unsubscribeNative = [
359
- bleUtils.onDeviceEncryptionChange(event => {
360
- if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
361
- return;
362
- const deviceId = normalizeDeviceId(event.id);
363
- lastEncryption.set(deviceId, {
364
- at: Date.now(),
365
- status: Number(event.status),
366
- enabled: event.enabled === true,
367
- });
368
- notify(deviceId);
369
- }),
370
- bleUtils.onDeviceAclDisconnected(event => {
371
- if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
372
- return;
373
- const deviceId = normalizeDeviceId(event.id);
374
- lastAclDisconnectAt.set(deviceId, Date.now());
375
- notify(deviceId);
376
- }),
377
- ];
378
- return true;
379
- };
380
- const stopBleEncryptionTracking = () => {
381
- unsubscribeNative === null || unsubscribeNative === void 0 ? void 0 : unsubscribeNative.forEach(unsubscribe => unsubscribe());
382
- unsubscribeNative = undefined;
383
- lastEncryption.clear();
384
- lastAclDisconnectAt.clear();
385
- listeners.clear();
386
- };
387
- const markBleLinkEncrypted = (deviceId) => {
388
- if (!unsubscribeNative)
389
- return;
390
- lastEncryption.set(normalizeDeviceId(deviceId), { at: Date.now(), status: 0, enabled: true });
391
- };
392
- const waitForAndroidLinkEncryption = ({ deviceId, linkStartedAt, resultTimeoutMs, repairTimeoutMs, keyMissingGraceMs, signal, onRepairStarted, }) => {
393
- if (!startBleEncryptionTracking())
394
- return Promise.resolve('unresolved');
395
- startBleKeyMissingTracking();
396
- const target = normalizeDeviceId(deviceId);
397
- const previous = lastEncryption.get(target);
398
- const previousDropAt = lastAclDisconnectAt.get(target);
399
- if (previous &&
400
- previous.at < linkStartedAt &&
401
- isEncrypted(previous) &&
402
- (previousDropAt === undefined || previousDropAt < previous.at)) {
403
- return Promise.resolve('already-encrypted');
404
- }
405
- return new Promise((resolve, reject) => {
406
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
407
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
408
- return;
253
+ else if (state === 'PoweredOff') {
254
+ pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePoweredOff);
409
255
  }
410
- let repairStartedAt;
411
- let droppedDuringRepair = false;
412
- let timer;
413
- let settled = false;
414
- const cleanup = () => {
415
- settled = true;
416
- if (timer)
417
- clearTimeout(timer);
418
- listeners.delete(onLinkEvent);
419
- cleanupKeyMissing();
420
- signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
421
- };
422
- const finish = (result) => {
423
- cleanup();
424
- resolve(result);
425
- };
426
- const fail = (error) => {
427
- cleanup();
428
- reject(error);
429
- };
430
- const arm = (ms, onExpire) => {
431
- if (timer)
432
- clearTimeout(timer);
433
- timer = setTimeout(onExpire, ms);
434
- };
435
- const bondInvalid = () => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
436
- phase: 'connect',
437
- reason: 'key_missing',
438
- });
439
- const evaluate = () => {
440
- if (settled)
441
- return;
442
- const record = lastEncryption.get(target);
443
- const dropAt = lastAclDisconnectAt.get(target);
444
- if (repairStartedAt === undefined) {
445
- if (hasBleKeyMissingSince(target, linkStartedAt)) {
446
- fail(bondInvalid());
447
- return;
448
- }
449
- if (dropAt !== undefined && dropAt >= linkStartedAt) {
450
- finish('unresolved');
451
- return;
452
- }
453
- if (!record || record.at < linkStartedAt)
454
- return;
455
- if (isEncrypted(record)) {
456
- finish('encrypted');
457
- return;
458
- }
459
- if (record.status !== HCI_PIN_OR_KEY_MISSING) {
460
- finish('unresolved');
461
- return;
462
- }
463
- repairStartedAt = record.at;
464
- onRepairStarted === null || onRepairStarted === void 0 ? void 0 : onRepairStarted();
465
- arm(repairTimeoutMs, () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing timed out', {
466
- phase: 'bond',
467
- reason: 'timeout',
468
- })));
469
- return;
470
- }
471
- if (hasBleKeyMissingSince(target, repairStartedAt)) {
472
- fail(bondInvalid());
473
- return;
474
- }
475
- if (record && record.at > repairStartedAt && isEncrypted(record)) {
476
- finish('re-paired');
477
- return;
478
- }
479
- if (!droppedDuringRepair && dropAt !== undefined && dropAt >= repairStartedAt) {
480
- droppedDuringRepair = true;
481
- arm(keyMissingGraceMs, () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected)));
482
- }
483
- };
484
- const onLinkEvent = id => {
485
- if (id === target)
486
- evaluate();
487
- };
488
- const onAbort = () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
489
- listeners.add(onLinkEvent);
490
- const cleanupKeyMissing = onBleKeyMissing(target, evaluate);
491
- signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onAbort, { once: true });
492
- arm(resultTimeoutMs, () => finish('unresolved'));
493
- evaluate();
494
- });
495
- };
496
-
497
- const IOS_PERIPHERAL_DISCONNECTED$1 = 7;
498
- const IOS_PEER_TERMINATION_LINK_WINDOW_MS = 10000;
499
- const IOS_PEER_TERMINATION_REPEAT_WINDOW_MS = 60000;
500
- const isIosPeerTerminationError = (error) => (error === null || error === void 0 ? void 0 : error.iosErrorCode) ===
501
- IOS_PERIPHERAL_DISCONNECTED$1;
502
- class IosPeerTerminationTracker {
503
- constructor() {
504
- this.linkStartedAt = new Map();
505
- this.terminatedAt = new Map();
506
- this.evidenceAt = new Map();
507
- }
508
- attemptStarted(deviceId) {
509
- this.linkStartedAt.delete(deviceId);
510
- this.terminatedAt.delete(deviceId);
511
- }
512
- linkStarted(deviceId) {
513
- this.linkStartedAt.set(deviceId, Date.now());
514
- this.terminatedAt.delete(deviceId);
515
- }
516
- note(deviceId, error) {
517
- if (!isIosPeerTerminationError(error))
518
- return;
519
- if (!this.terminatedAt.has(deviceId))
520
- this.terminatedAt.set(deviceId, Date.now());
521
- }
522
- linkProven(deviceId) {
523
- this.forget(deviceId);
524
- }
525
- forget(deviceId) {
526
- this.linkStartedAt.delete(deviceId);
527
- this.terminatedAt.delete(deviceId);
528
- this.evidenceAt.delete(deviceId);
529
- }
530
- attemptFailed(deviceId) {
531
- const startedAt = this.linkStartedAt.get(deviceId);
532
- const terminatedAt = this.terminatedAt.get(deviceId);
533
- const previous = this.evidenceAt.get(deviceId);
534
- this.forget(deviceId);
535
- if (startedAt === undefined ||
536
- terminatedAt === undefined ||
537
- terminatedAt - startedAt > IOS_PEER_TERMINATION_LINK_WINDOW_MS) {
538
- return false;
256
+ else if (state === 'Unsupported') {
257
+ pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleUnsupported);
539
258
  }
540
- if (previous !== undefined &&
541
- terminatedAt - previous <= IOS_PEER_TERMINATION_REPEAT_WINDOW_MS) {
542
- return true;
259
+ else if (state === 'Unauthorized') {
260
+ pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationError);
543
261
  }
544
- this.evidenceAt.set(deviceId, terminatedAt);
545
- return false;
262
+ else {
263
+ pendingError = undefined;
264
+ }
265
+ }, true);
266
+ removeSubscription = () => subscription.remove();
267
+ if (done) {
268
+ removeSubscription();
546
269
  }
547
- reset() {
548
- this.linkStartedAt.clear();
549
- this.terminatedAt.clear();
550
- this.evidenceAt.clear();
270
+ else {
271
+ cancelTimeout = timer.timeout(() => {
272
+ finish(pendingError !== null && pendingError !== void 0 ? pendingError : hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError));
273
+ }, ms);
551
274
  }
552
- }
275
+ });
553
276
 
554
277
  const BLE_PLX_DEVICE_DISCONNECTED = 201;
555
278
  const IOS_PERIPHERAL_DISCONNECTED = 7;
556
- const nativeErrorText$1 = (error) => [error.reason, error.message]
279
+ const nativeErrorText = (error) => [error.reason, error.message]
557
280
  .filter((value) => typeof value === 'string')
558
281
  .join(' ');
559
282
  const isNativeBleDisconnectError = (error) => {
@@ -562,57 +285,24 @@ const isNativeBleDisconnectError = (error) => {
562
285
  }
563
286
  const nativeError = error;
564
287
  return (nativeError.errorCode === BLE_PLX_DEVICE_DISCONNECTED ||
565
- nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED);
288
+ nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED ||
289
+ nativeErrorText(nativeError).toLowerCase().includes('was disconnected'));
566
290
  };
567
291
  const toBleDisconnectHardwareError = (error) => {
568
292
  if ((error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleDeviceDisconnected) {
569
293
  return error;
570
294
  }
571
295
  const nativeError = (error !== null && error !== void 0 ? error : {});
572
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected, nativeErrorText$1(nativeError) || undefined);
573
- };
574
-
575
- const ATT_INSUFFICIENT_AUTHENTICATION = 5;
576
- const ATT_INSUFFICIENT_ENCRYPTION = 15;
577
- const IOS_PEER_REMOVED_PAIRING_INFORMATION = 14;
578
- const nativeErrorText = (error) => [error.reason, error.message]
579
- .filter((value) => typeof value === 'string')
580
- .join(' ');
581
- const isNativeBleStaleBondError = (error) => {
582
- if (!error || typeof error !== 'object') {
583
- return typeof error === 'string' ? hdShared.isBleStaleBondErrorText(error) : false;
584
- }
585
- const nativeError = error;
586
- if (nativeError.attErrorCode === ATT_INSUFFICIENT_AUTHENTICATION ||
587
- nativeError.attErrorCode === ATT_INSUFFICIENT_ENCRYPTION ||
588
- nativeError.androidErrorCode === ATT_INSUFFICIENT_AUTHENTICATION ||
589
- nativeError.androidErrorCode === ATT_INSUFFICIENT_ENCRYPTION ||
590
- nativeError.iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION) {
591
- return true;
592
- }
593
- return hdShared.isBleStaleBondErrorText(nativeErrorText(nativeError));
594
- };
595
- const toBleStaleBondHardwareError = (error) => {
596
- if (hdShared.isBleStaleBondHardwareError(error)) {
597
- return error;
598
- }
599
- const nativeError = (error !== null && error !== void 0 ? error : {});
600
- const text = nativeErrorText(nativeError);
601
- const normalizedText = text.toLowerCase();
602
- const peerRemoved = nativeError.iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION ||
603
- normalizedText.includes('peer removed pairing information');
604
- return hdShared.ERRORS.TypedError(peerRemoved
605
- ? hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation
606
- : hdShared.HardwareErrorCode.BleDeviceBondError, text || undefined);
296
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected, nativeErrorText(nativeError) || undefined);
607
297
  };
608
298
 
609
299
  const isHeaderChunk = (chunk) => {
610
300
  if (chunk.length < 9)
611
301
  return false;
612
302
  const [MagicQuestionMark, sharp1, sharp2] = chunk;
613
- if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transport.PROTOCOL_V1_REPORT_ID) &&
614
- String.fromCharCode(sharp1) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE) &&
615
- String.fromCharCode(sharp2) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE)) {
303
+ if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transportModule.PROTOCOL_V1_REPORT_ID) &&
304
+ String.fromCharCode(sharp1) === String.fromCharCode(transportModule.PROTOCOL_V1_HEADER_BYTE) &&
305
+ String.fromCharCode(sharp2) === String.fromCharCode(transportModule.PROTOCOL_V1_HEADER_BYTE)) {
616
306
  return true;
617
307
  }
618
308
  return false;
@@ -633,7 +323,9 @@ class BleTransport {
633
323
  }
634
324
  }
635
325
 
636
- const { check, ProtocolV1, parseConfigure } = transport__default["default"];
326
+ var _a;
327
+ const transport = (_a = transportModule__default["default"].default) !== null && _a !== void 0 ? _a : transportModule__default["default"];
328
+ const { check, ProtocolV1, parseConfigure } = transport;
637
329
  const Log = bleLogger;
638
330
  const transportCache = {};
639
331
  let bleManagerResetPromise;
@@ -695,10 +387,10 @@ const WEDGED_WRITE_MESSAGE = 'BLE write timeout after';
695
387
  const isWedgedWriteError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleWriteCharacteristicError &&
696
388
  typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
697
389
  error.message.startsWith(WEDGED_WRITE_MESSAGE);
390
+ const createWedgedWriteError = () => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `${WEDGED_WRITE_MESSAGE} ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`);
698
391
  const shouldRethrowProtocolProbeError = (error) => {
699
392
  const code = error === null || error === void 0 ? void 0 : error.errorCode;
700
- return (hdShared.isBleStaleBondHardwareError(error) ||
701
- isNativeBleDisconnectError(error) ||
393
+ return (isNativeBleDisconnectError(error) ||
702
394
  code === hdShared.HardwareErrorCode.BleDeviceNotBonded ||
703
395
  code === hdShared.HardwareErrorCode.BleDeviceBondedCanceled ||
704
396
  code === hdShared.HardwareErrorCode.BleDeviceDisconnected ||
@@ -706,18 +398,6 @@ const shouldRethrowProtocolProbeError = (error) => {
706
398
  code === hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
707
399
  code === hdShared.HardwareErrorCode.BleWriteCharacteristicError);
708
400
  };
709
- const ANDROID_KEY_MISSING_LINK_WINDOW_MS = 10000;
710
- const ANDROID_KEY_MISSING_GRACE_MS = 500;
711
- const ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = 1500;
712
- const ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = 35000;
713
- const isAndroidLinkLossError = (error) => {
714
- const code = error === null || error === void 0 ? void 0 : error.errorCode;
715
- return (isNativeBleDisconnectError(error) ||
716
- code === hdShared.HardwareErrorCode.BleDeviceNotBonded ||
717
- code === hdShared.HardwareErrorCode.BleDeviceDisconnected ||
718
- code === hdShared.HardwareErrorCode.BleCharacteristicNotifyError ||
719
- code === hdShared.HardwareErrorCode.BleConnectedError);
720
- };
721
401
  const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
722
402
  const DEVICE_SCAN_TIMEOUT_MS = 3000;
723
403
  const IOS_NOTIFY_READY_DELAY_MS = 150;
@@ -725,6 +405,8 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
725
405
  const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
726
406
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
727
407
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
408
+ nativeFrameWrite: true,
409
+ androidHighConnectionPriority: 'auto',
728
410
  };
729
411
  let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
730
412
  const normalizePositiveInteger = (value, fallback) => {
@@ -737,6 +419,13 @@ function configureProtocolV2BleTuning(tuning = {}) {
737
419
  protocolV2BleTuning = {
738
420
  iosPacketLength: normalizePositiveInteger(tuning.iosPacketLength, protocolV2BleTuning.iosPacketLength),
739
421
  androidPacketLength: normalizePositiveInteger(tuning.androidPacketLength, protocolV2BleTuning.androidPacketLength),
422
+ nativeFrameWrite: typeof tuning.nativeFrameWrite === 'boolean'
423
+ ? tuning.nativeFrameWrite
424
+ : protocolV2BleTuning.nativeFrameWrite,
425
+ androidHighConnectionPriority: typeof tuning.androidHighConnectionPriority === 'boolean' ||
426
+ tuning.androidHighConnectionPriority === 'auto'
427
+ ? tuning.androidHighConnectionPriority
428
+ : protocolV2BleTuning.androidHighConnectionPriority,
740
429
  };
741
430
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
742
431
  }
@@ -747,12 +436,128 @@ function resetProtocolV2BleTuning() {
747
436
  function getProtocolV2BleTuning() {
748
437
  return Object.assign({}, protocolV2BleTuning);
749
438
  }
439
+ const getProtocolV2NativeFrameWriter = (manager) => {
440
+ var _a;
441
+ const candidate = manager;
442
+ if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
443
+ return undefined;
444
+ }
445
+ try {
446
+ return ((_a = candidate.isWriteCharacteristicWithoutResponseFrameSupported) === null || _a === void 0 ? void 0 : _a.call(candidate)) === true
447
+ ? candidate
448
+ : undefined;
449
+ }
450
+ catch (_b) {
451
+ return undefined;
452
+ }
453
+ };
454
+ const getNativeBleErrorReason = (error) => {
455
+ const { reason, message } = (error !== null && error !== void 0 ? error : {});
456
+ if (typeof reason === 'string' && reason)
457
+ return reason;
458
+ return typeof message === 'string' && message ? message : undefined;
459
+ };
460
+ const nowMs = () => typeof performance !== 'undefined' && typeof performance.now === 'function'
461
+ ? performance.now()
462
+ : Date.now();
463
+ const roundMs = (ms) => Math.round(ms * 10) / 10;
464
+ const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
465
+ const createDurationStats = () => {
466
+ let total = 0;
467
+ let count = 0;
468
+ let max = 0;
469
+ return {
470
+ add(ms) {
471
+ total += ms;
472
+ count += 1;
473
+ max = Math.max(max, ms);
474
+ },
475
+ summarize: () => ({
476
+ total: roundMs(total),
477
+ avg: count ? roundMs(total / count) : 0,
478
+ max: roundMs(max),
479
+ }),
480
+ };
481
+ };
482
+ const createProtocolV2FileWritePerf = () => {
483
+ const startedAt = nowMs();
484
+ let nativeFrames = 0;
485
+ let frames = 0;
486
+ let packets = 0;
487
+ let frameBytes = 0;
488
+ const write = createDurationStats();
489
+ const readWait = createDurationStats();
490
+ const packet = createDurationStats();
491
+ const packetHistogram = Array.from({ length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 }, () => 0);
492
+ return {
493
+ startFrame(mode) {
494
+ if (mode === 'native-frame')
495
+ nativeFrames += 1;
496
+ },
497
+ recordFrame(bytes, framePackets, elapsedMs) {
498
+ frames += 1;
499
+ packets += framePackets;
500
+ frameBytes += bytes;
501
+ write.add(elapsedMs);
502
+ },
503
+ recordPacket(elapsedMs) {
504
+ packet.add(elapsedMs);
505
+ const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
506
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
507
+ },
508
+ recordReadWait(elapsedMs) {
509
+ readWait.add(elapsedMs);
510
+ },
511
+ summarize(ok) {
512
+ const mode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
513
+ const packetStats = packet.summarize();
514
+ return Object.assign({ platform: reactNative.Platform.OS, mode,
515
+ ok,
516
+ frames,
517
+ packets,
518
+ frameBytes, elapsedMs: roundMs(nowMs() - startedAt), writeMs: write.summarize(), readWaitMs: readWait.summarize() }, (mode === 'per-packet'
519
+ ? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
520
+ : {}));
521
+ },
522
+ };
523
+ };
750
524
  function getDeviceDisplayName(device) {
751
525
  return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
752
526
  }
527
+ const bleColorCodesById = new Map();
528
+ function getManufacturerDataLength(device) {
529
+ return (device === null || device === void 0 ? void 0 : device.manufacturerData) ? buffer.Buffer.from(device.manufacturerData, 'base64').length : 0;
530
+ }
531
+ function rememberBleColorCode(device) {
532
+ if (!(device === null || device === void 0 ? void 0 : device.id) || !device.manufacturerData)
533
+ return;
534
+ const colorCode = hdShared.parseOnekeyBleColorCode(buffer.Buffer.from(device.manufacturerData, 'base64'));
535
+ const key = device.id.toLowerCase();
536
+ if (colorCode && bleColorCodesById.get(key) !== colorCode) {
537
+ bleColorCodesById.set(key, colorCode);
538
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE color code', {
539
+ deviceId: device.id,
540
+ bleColorCode: colorCode,
541
+ });
542
+ }
543
+ }
544
+ function withBleColorCode(device) {
545
+ const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
546
+ return bleColorCode ? Object.assign(Object.assign({}, device), { bleColorCode }) : device;
547
+ }
753
548
  const IOS_REQUEST_MTU = 247;
754
549
  const ANDROID_REQUEST_MTU = 517;
755
550
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
551
+ const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
552
+ const shouldRequestAndroidHighConnectionPriority = () => {
553
+ if (reactNative.Platform.OS !== 'android')
554
+ return false;
555
+ const { androidHighConnectionPriority } = protocolV2BleTuning;
556
+ if (typeof androidHighConnectionPriority === 'boolean')
557
+ return androidHighConnectionPriority;
558
+ const apiLevel = Number(reactNative.Platform.Version);
559
+ return (!Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL);
560
+ };
756
561
  const getRequestedBleMtu = () => reactNative.Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
757
562
  const BLE_NATIVE_CONNECT_TIMEOUT_MS = 3000;
758
563
  const BLE_MTU_REQUEST_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS;
@@ -877,21 +682,14 @@ const resolveNegotiatedMtu = (device, cancelTransaction) => shouldRefreshNegotia
877
682
  ? requestNegotiatedMtu(device, 'connected', 0, cancelTransaction)
878
683
  : Promise.resolve({ device, timedOut: false });
879
684
  function remapError(error) {
880
- var _a;
881
- if (error instanceof reactNativeBlePlx.BleError) {
882
- if (isNativeBleStaleBondError(error)) {
883
- throw toBleStaleBondHardwareError(error);
884
- }
885
- if ((error === null || error === void 0 ? void 0 : error.attErrorCode) === 22) {
886
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceBondError);
887
- }
685
+ var _a, _b;
686
+ if (isNativeBleDisconnectError(error)) {
687
+ throw toBleDisconnectHardwareError(error);
888
688
  }
889
- if (error instanceof Error &&
890
- error.message &&
891
- (error.message.includes('was disconnected') || error.message.includes('not found'))) {
689
+ if (error instanceof Error && ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('not found'))) {
892
690
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
893
691
  }
894
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_a = error.reason) !== null && _a !== void 0 ? _a : error);
692
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_b = error.reason) !== null && _b !== void 0 ? _b : error);
895
693
  }
896
694
  class ReactNativeBleTransport {
897
695
  constructor(options) {
@@ -914,14 +712,10 @@ class ReactNativeBleTransport {
914
712
  this.protocolReprobeFailures = new Map();
915
713
  this.silentDetections = new Map();
916
714
  this.androidGattCacheRefreshes = new Set();
917
- this.staleBondErrors = new Map();
918
- this.androidLinkStartedAt = new Map();
919
- this.iosPeerTermination = new IosPeerTerminationTracker();
920
- this.acquiringProtocolV2 = new Set();
921
715
  this.protocolV2Assemblers = new Map();
922
716
  this.protocolV2FrameQueues = new Map();
923
717
  this.protocolV2FramePromises = new Map();
924
- this.protocolV2Links = new transport.ProtocolV2LinkManager({
718
+ this.protocolV2Links = new transportModule.ProtocolV2LinkManager({
925
719
  getSchemas: () => {
926
720
  if (!this._messages || !this._messagesV2) {
927
721
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
@@ -956,6 +750,9 @@ class ReactNativeBleTransport {
956
750
  this.protocolV2HighVolumeLogSignatures = new Map();
957
751
  this.androidHighPriorityDevices = new Set();
958
752
  this.androidPriorityResetTimers = new Map();
753
+ this.protocolV2FrameWrites = new Map();
754
+ this.protocolV2FrameWriteCounter = 0;
755
+ this.protocolV2FileWritePerfs = new Map();
959
756
  this.nextMonitorToken = 1;
960
757
  this.lifecycleOperations = new Map();
961
758
  this.scanCleanups = new Set();
@@ -964,10 +761,6 @@ class ReactNativeBleTransport {
964
761
  init(logger, emitter) {
965
762
  setBleLogger(logger);
966
763
  this.emitter = emitter;
967
- if (reactNative.Platform.OS === 'android') {
968
- startBleKeyMissingTracking();
969
- startBleEncryptionTracking();
970
- }
971
764
  }
972
765
  configure(signedData) {
973
766
  const messages = parseConfigure(signedData);
@@ -1136,7 +929,7 @@ class ReactNativeBleTransport {
1136
929
  return;
1137
930
  }
1138
931
  this.disconnectEventTokens.set(uuid, token);
1139
- (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(transport.TRANSPORT_EVENT.DEVICE_DISCONNECT, {
932
+ (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(transportModule.TRANSPORT_EVENT.DEVICE_DISCONNECT, {
1140
933
  name,
1141
934
  id: uuid,
1142
935
  connectId: uuid,
@@ -1190,7 +983,6 @@ class ReactNativeBleTransport {
1190
983
  const scanStartedAt = Date.now();
1191
984
  let firstDeviceMs;
1192
985
  const blePlxManager = yield this.getPlxManager();
1193
- yield subscribeBleOn(blePlxManager);
1194
986
  if (reactNative.Platform.OS === 'android' && reactNative.Platform.Version >= 31) {
1195
987
  Log === null || Log === void 0 ? void 0 : Log.debug('requesting permissions, please wait...');
1196
988
  const resultConnect = yield reactNative.PermissionsAndroid.requestMultiple([
@@ -1200,9 +992,10 @@ class ReactNativeBleTransport {
1200
992
  Log === null || Log === void 0 ? void 0 : Log.debug('requesting permissions, result: ', resultConnect);
1201
993
  if (resultConnect[reactNative.PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT] !== 'granted' ||
1202
994
  resultConnect[reactNative.PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN] !== 'granted') {
1203
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError);
995
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationError);
1204
996
  }
1205
997
  }
998
+ yield subscribeBleOn(blePlxManager);
1206
999
  if (this.stopped)
1207
1000
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1208
1001
  return new Promise((resolve, reject) => {
@@ -1221,7 +1014,7 @@ class ReactNativeBleTransport {
1221
1014
  if (error)
1222
1015
  reject(error);
1223
1016
  else
1224
- resolve(deviceList);
1017
+ resolve(deviceList.map(withBleColorCode));
1225
1018
  });
1226
1019
  return scanCleanup;
1227
1020
  };
@@ -1243,8 +1036,11 @@ class ReactNativeBleTransport {
1243
1036
  var _a, _b;
1244
1037
  if (error) {
1245
1038
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan error: ', error);
1246
- if ([reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff, reactNativeBlePlx.BleErrorCode.BluetoothInUnknownState].includes(error.errorCode)) {
1247
- finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
1039
+ if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff) {
1040
+ finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePoweredOff));
1041
+ }
1042
+ else if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothUnsupported) {
1043
+ finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleUnsupported));
1248
1044
  }
1249
1045
  else if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothUnauthorized) {
1250
1046
  finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationError));
@@ -1258,6 +1054,7 @@ class ReactNativeBleTransport {
1258
1054
  }
1259
1055
  return;
1260
1056
  }
1057
+ rememberBleColorCode(device);
1261
1058
  const displayName = getDeviceDisplayName(device);
1262
1059
  const isUnnamedIOSPeripheral = reactNative.Platform.OS === 'ios' && !(displayName === null || displayName === void 0 ? void 0 : displayName.trim());
1263
1060
  const isOneKey = !isUnnamedIOSPeripheral &&
@@ -1307,6 +1104,8 @@ class ReactNativeBleTransport {
1307
1104
  deviceId: device.id,
1308
1105
  name: displayName,
1309
1106
  serviceUUIDs: device.serviceUUIDs,
1107
+ manufacturerDataLength: getManufacturerDataLength(device),
1108
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
1310
1109
  });
1311
1110
  }
1312
1111
  };
@@ -1318,18 +1117,18 @@ class ReactNativeBleTransport {
1318
1117
  const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, device));
1319
1118
  if (this.stopped)
1320
1119
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1321
- const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
1322
- transport$1.mtuSize = typeof device.mtu === 'number' ? device.mtu : undefined;
1120
+ const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
1121
+ transport.mtuSize = typeof device.mtu === 'number' ? device.mtu : undefined;
1323
1122
  const monitorToken = this.nextMonitorToken;
1324
1123
  this.nextMonitorToken += 1;
1325
1124
  const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
1326
- transport$1.monitorToken = monitorToken;
1327
- transport$1.notifyTransactionId = notifyTransactionId;
1125
+ transport.monitorToken = monitorToken;
1126
+ transport.notifyTransactionId = notifyTransactionId;
1328
1127
  this.monitorTokens.set(uuid, monitorToken);
1329
- transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
1330
- transportCache[uuid] = transport$1;
1128
+ transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
1129
+ transportCache[uuid] = transport;
1331
1130
  this.protocolV2HighVolumeLogSignatures.set(uuid, new Set());
1332
- this.protocolV2Assemblers.set(uuid, new transport.ProtocolV2FrameAssembler(transport.PROTOCOL_V2_BLE_FRAME_MAX_BYTES));
1131
+ this.protocolV2Assemblers.set(uuid, new transportModule.ProtocolV2FrameAssembler(transportModule.PROTOCOL_V2_BLE_FRAME_MAX_BYTES));
1333
1132
  if (reactNative.Platform.OS === 'ios') {
1334
1133
  yield new Promise(resolve => {
1335
1134
  setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
@@ -1341,11 +1140,12 @@ class ReactNativeBleTransport {
1341
1140
  if (this.stopped)
1342
1141
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1343
1142
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE MTU ready', {
1143
+ connectionId: monitorToken,
1344
1144
  platform: reactNative.Platform.OS,
1345
1145
  requested: getRequestedBleMtu(),
1346
- actual: transport$1.mtuSize,
1146
+ actual: transport.mtuSize,
1347
1147
  });
1348
- return transport$1;
1148
+ return transport;
1349
1149
  });
1350
1150
  }
1351
1151
  acquire(input) {
@@ -1354,14 +1154,7 @@ class ReactNativeBleTransport {
1354
1154
  if (!uuid) {
1355
1155
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
1356
1156
  }
1357
- return this.runLifecycleOperation(uuid, () => __awaiter(this, void 0, void 0, function* () {
1358
- try {
1359
- return yield this.acquireUnlocked(input);
1360
- }
1361
- catch (error) {
1362
- throw this.resolveIosBondInvalid(input, yield this.resolveAndroidBondInvalid(uuid, error));
1363
- }
1364
- }));
1157
+ return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1365
1158
  });
1366
1159
  }
1367
1160
  acquireUnlocked(input) {
@@ -1370,10 +1163,6 @@ class ReactNativeBleTransport {
1370
1163
  if (this.stopped)
1371
1164
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1372
1165
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1373
- this.iosPeerTermination.attemptStarted(uuid);
1374
- const shouldMapProtocolV2StaleBond = expectedProtocol
1375
- ? expectedProtocol === 'V2'
1376
- : this.confirmedProtocolV2.has(uuid);
1377
1166
  const cachedTransport = transportCache[uuid];
1378
1167
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1379
1168
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:', uuid);
@@ -1417,7 +1206,6 @@ class ReactNativeBleTransport {
1417
1206
  }
1418
1207
  let device = null;
1419
1208
  const isAndroid = reactNative.Platform.OS === 'android';
1420
- let androidBondedBeforeConnect = false;
1421
1209
  const refreshAndroidGattCache = isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1422
1210
  let nativeConnectOptions = connectOptions;
1423
1211
  if (isAndroid) {
@@ -1445,12 +1233,8 @@ class ReactNativeBleTransport {
1445
1233
  if (this.stopped)
1446
1234
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1447
1235
  if (reactNative.Platform.OS === 'android') {
1448
- startBleKeyMissingTracking();
1449
- startBleEncryptionTracking();
1450
- this.androidLinkStartedAt.delete(uuid);
1451
1236
  try {
1452
1237
  const bondState = yield pairDevice(uuid);
1453
- androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1454
1238
  if (bondState.bonding) {
1455
1239
  yield onDeviceBondState(uuid, this.bondAbortController.signal, {
1456
1240
  systemInitiated: bondState.initiated === false,
@@ -1466,7 +1250,6 @@ class ReactNativeBleTransport {
1466
1250
  }));
1467
1251
  throw error;
1468
1252
  }
1469
- this.androidLinkStartedAt.set(uuid, Date.now());
1470
1253
  }
1471
1254
  if (this.stopped)
1472
1255
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
@@ -1621,16 +1404,7 @@ class ReactNativeBleTransport {
1621
1404
  if (protocolHint) {
1622
1405
  this.deviceProtocolHints.set(uuid, protocolHint);
1623
1406
  }
1624
- if (shouldMapProtocolV2StaleBond) {
1625
- this.acquiringProtocolV2.add(uuid);
1626
- }
1627
- let linkEncryption;
1628
1407
  try {
1629
- if (androidBondedBeforeConnect && !skipProtocolProbe) {
1630
- linkEncryption = yield this.waitForAndroidLinkSecurity(uuid);
1631
- if (this.stopped)
1632
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1633
- }
1634
1408
  yield this.installTransportForAcquire(uuid, acquiredDevice, {
1635
1409
  writeCharacteristic,
1636
1410
  notifyCharacteristic,
@@ -1664,24 +1438,17 @@ class ReactNativeBleTransport {
1664
1438
  }));
1665
1439
  if (this.stopped)
1666
1440
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1667
- this.iosPeerTermination.linkProven(uuid);
1668
1441
  const currentTransport = transportCache[uuid];
1669
1442
  if (!currentTransport) {
1670
1443
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1671
1444
  }
1672
1445
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1673
- if (linkEncryption === 'unresolved') {
1674
- markBleLinkEncrypted(uuid);
1675
- }
1676
1446
  return { uuid, protocolType };
1677
1447
  }
1678
1448
  catch (error) {
1679
1449
  yield this.disconnectUnlocked(uuid);
1680
1450
  throw error;
1681
1451
  }
1682
- finally {
1683
- this.acquiringProtocolV2.delete(uuid);
1684
- }
1685
1452
  });
1686
1453
  }
1687
1454
  _monitorCharacteristic(characteristic, uuid, monitorToken, notifyTransactionId) {
@@ -1691,8 +1458,6 @@ class ReactNativeBleTransport {
1691
1458
  var _a, _b, _c, _d, _e, _f;
1692
1459
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1693
1460
  if (error) {
1694
- if (isCurrentMonitor)
1695
- this.noteIosLinkError(uuid, 'notify', error);
1696
1461
  Log === null || Log === void 0 ? void 0 : Log.debug(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
1697
1462
  if (this.firmwareUploadWriteRecoveryIds.has(uuid)) {
1698
1463
  Log === null || Log === void 0 ? void 0 : Log.debug('notify error ignored during FirmwareUpload write recovery: ', uuid);
@@ -1702,11 +1467,6 @@ class ReactNativeBleTransport {
1702
1467
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1703
1468
  return;
1704
1469
  }
1705
- if ((this.getActiveProtocol(uuid) === 'V2' || this.acquiringProtocolV2.has(uuid)) &&
1706
- isNativeBleStaleBondError(error)) {
1707
- this.rememberStaleBondError(uuid, toBleStaleBondHardwareError(error));
1708
- return;
1709
- }
1710
1470
  if (reactNative.Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1711
1471
  this.androidGattCacheRefreshes.add(uuid);
1712
1472
  }
@@ -1765,7 +1525,7 @@ class ReactNativeBleTransport {
1765
1525
  else {
1766
1526
  buffer$1 = buffer$1.concat([...data]);
1767
1527
  }
1768
- if (buffer$1.length - transport.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
1528
+ if (buffer$1.length - transportModule.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
1769
1529
  const value = buffer.Buffer.from(buffer$1);
1770
1530
  bufferLength = 0;
1771
1531
  buffer$1 = [];
@@ -1787,20 +1547,33 @@ class ReactNativeBleTransport {
1787
1547
  }, notifyTransactionId);
1788
1548
  return subscription;
1789
1549
  }
1790
- release(uuid, onclose = false) {
1550
+ release(uuid, onclose = false, keepSession = false) {
1791
1551
  return __awaiter(this, void 0, void 0, function* () {
1792
- return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose));
1552
+ return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose, keepSession));
1793
1553
  });
1794
1554
  }
1795
- releaseUnlocked(uuid, onclose = false) {
1555
+ releaseUnlocked(uuid, onclose = false, keepSession = false) {
1796
1556
  return __awaiter(this, void 0, void 0, function* () {
1797
- yield this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1557
+ const transport = transportCache[uuid];
1558
+ if (keepSession &&
1559
+ !onclose &&
1560
+ transport &&
1561
+ this.deviceProtocol.get(uuid) === 'V2' &&
1562
+ !this.protocolV2FrameWrites.has(uuid) &&
1563
+ !this.protocolV2FramePromises.has(uuid)) {
1564
+ yield this.runNativeTeardown(uuid, this.blePlxManager, () => this.restoreAndroidConnectionPriority(uuid, transport));
1565
+ return true;
1566
+ }
1567
+ const reason = 'React Native BLE transport released';
1568
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
1569
+ yield this.protocolV2Links.invalidateLink(uuid, reason);
1798
1570
  return this.releaseNative(uuid, onclose);
1799
1571
  });
1800
1572
  }
1801
1573
  releaseNative(uuid, onclose = false) {
1802
1574
  var _a, _b, _c, _d, _e;
1803
1575
  return __awaiter(this, void 0, void 0, function* () {
1576
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1804
1577
  const transport = transportCache[uuid];
1805
1578
  const manager = this.blePlxManager;
1806
1579
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1835,8 +1608,6 @@ class ReactNativeBleTransport {
1835
1608
  this.protocolV2HighVolumeLogSignatures.delete(uuid);
1836
1609
  this.deviceProtocol.delete(uuid);
1837
1610
  this.probingProtocols.delete(uuid);
1838
- this.staleBondErrors.delete(uuid);
1839
- this.acquiringProtocolV2.delete(uuid);
1840
1611
  (_e = this.protocolV2Assemblers.get(uuid)) === null || _e === void 0 ? void 0 : _e.reset();
1841
1612
  this.protocolV2Assemblers.delete(uuid);
1842
1613
  this.resetProtocolV2Frames(uuid);
@@ -1880,94 +1651,9 @@ class ReactNativeBleTransport {
1880
1651
  if (protocol !== 'V2' && this.runPromise && !forceRun) {
1881
1652
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
1882
1653
  }
1883
- try {
1884
- return protocol === 'V2'
1885
- ? yield this.callProtocolV2(uuid, name, data, options)
1886
- : yield this.callProtocolV1(uuid, name, data, options);
1887
- }
1888
- catch (error) {
1889
- throw yield this.resolveAndroidBondInvalid(uuid, error);
1890
- }
1891
- });
1892
- }
1893
- resolveAndroidBondInvalid(uuid, error) {
1894
- return __awaiter(this, void 0, void 0, function* () {
1895
- if (reactNative.Platform.OS !== 'android' || !isBleKeyMissingSupported())
1896
- return error;
1897
- if (hdShared.isBleStaleBondHardwareError(error) || !isAndroidLinkLossError(error))
1898
- return error;
1899
- const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1900
- if (linkStartedAt === undefined ||
1901
- Date.now() - linkStartedAt > ANDROID_KEY_MISSING_LINK_WINDOW_MS) {
1902
- return error;
1903
- }
1904
- if (!(yield waitForBleKeyMissing(uuid, linkStartedAt, ANDROID_KEY_MISSING_GRACE_MS))) {
1905
- return error;
1906
- }
1907
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android key missing, bond is invalid:', uuid);
1908
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
1909
- phase: 'connect',
1910
- reason: 'key_missing',
1911
- });
1912
- });
1913
- }
1914
- noteIosLinkError(uuid, stage, error) {
1915
- if (reactNative.Platform.OS !== 'ios')
1916
- return;
1917
- this.iosPeerTermination.note(uuid, error);
1918
- if (stage !== 'gatt-setup' && !isNativeBleDisconnectError(error))
1919
- return;
1920
- const native = (error !== null && error !== void 0 ? error : {});
1921
- const code = (value) => typeof value === 'number' || typeof value === 'string' ? value : undefined;
1922
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] iOS operation failed', {
1923
- connectIdSuffix: uuid.slice(-8),
1924
- stage,
1925
- errorCode: code(native.errorCode),
1926
- iosErrorCode: code(native.iosErrorCode),
1927
- attErrorCode: code(native.attErrorCode),
1928
- });
1929
- }
1930
- resolveIosBondInvalid(input, error) {
1931
- if (reactNative.Platform.OS !== 'ios')
1932
- return error;
1933
- const { uuid, skipProtocolProbe } = input;
1934
- if (skipProtocolProbe || hdShared.isBleStaleBondHardwareError(error)) {
1935
- this.iosPeerTermination.forget(uuid);
1936
- return error;
1937
- }
1938
- if (!this.iosPeerTermination.attemptFailed(uuid))
1939
- return error;
1940
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] iOS peer ended two new links in a row, bond is invalid:', {
1941
- connectIdSuffix: uuid.slice(-8),
1942
- });
1943
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
1944
- phase: 'connect',
1945
- reason: 'peer_disconnected',
1946
- });
1947
- }
1948
- waitForAndroidLinkSecurity(uuid) {
1949
- return __awaiter(this, void 0, void 0, function* () {
1950
- const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1951
- if (linkStartedAt === undefined)
1952
- return 'unresolved';
1953
- const waitStartedAt = Date.now();
1954
- const result = yield waitForAndroidLinkEncryption({
1955
- deviceId: uuid,
1956
- linkStartedAt,
1957
- resultTimeoutMs: ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS,
1958
- repairTimeoutMs: ANDROID_SYSTEM_REPAIR_TIMEOUT_MS,
1959
- keyMissingGraceMs: ANDROID_KEY_MISSING_GRACE_MS,
1960
- signal: this.bondAbortController.signal,
1961
- onRepairStarted: () => {
1962
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android bond lost, waiting for system re-pairing:', uuid);
1963
- },
1964
- });
1965
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android link encryption', {
1966
- connectIdSuffix: uuid.slice(-8),
1967
- result,
1968
- waitedMs: Date.now() - waitStartedAt,
1969
- });
1970
- return result;
1654
+ return protocol === 'V2'
1655
+ ? this.callProtocolV2(uuid, name, data, options)
1656
+ : this.callProtocolV1(uuid, name, data, options);
1971
1657
  });
1972
1658
  }
1973
1659
  callProtocolV1(uuid, name, data, options) {
@@ -2183,10 +1869,6 @@ class ReactNativeBleTransport {
2183
1869
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
2184
1870
  this.androidPriorityResetTimers.clear();
2185
1871
  this.androidHighPriorityDevices.clear();
2186
- this.androidLinkStartedAt.clear();
2187
- this.iosPeerTermination.reset();
2188
- stopBleKeyMissingTracking();
2189
- stopBleEncryptionTracking();
2190
1872
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
2191
1873
  (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.reject(error);
2192
1874
  this.runPromise = null;
@@ -2218,7 +1900,11 @@ class ReactNativeBleTransport {
2218
1900
  disconnectUnlocked(session) {
2219
1901
  var _a, _b, _c;
2220
1902
  return __awaiter(this, void 0, void 0, function* () {
2221
- yield this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1903
+ this.clearAndroidPriorityResetTimer(session);
1904
+ this.androidHighPriorityDevices.delete(session);
1905
+ const reason = 'React Native BLE transport disconnected';
1906
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
1907
+ yield this.protocolV2Links.invalidateLink(session, reason);
2222
1908
  const transport = transportCache[session];
2223
1909
  const manager = this.blePlxManager;
2224
1910
  const monitorToken = (_a = transport === null || transport === void 0 ? void 0 : transport.monitorToken) !== null && _a !== void 0 ? _a : this.monitorTokens.get(session);
@@ -2247,7 +1933,6 @@ class ReactNativeBleTransport {
2247
1933
  }
2248
1934
  this.deviceProtocol.delete(session);
2249
1935
  this.probingProtocols.delete(session);
2250
- this.staleBondErrors.delete(session);
2251
1936
  this.deviceProtocolHints.delete(session);
2252
1937
  this.sessionProtocols.delete(session);
2253
1938
  this.protocolReprobeFailures.delete(session);
@@ -2440,7 +2125,6 @@ class ReactNativeBleTransport {
2440
2125
  }),
2441
2126
  ]);
2442
2127
  succeeded = true;
2443
- this.iosPeerTermination.linkStarted(uuid);
2444
2128
  return result;
2445
2129
  }
2446
2130
  catch (error) {
@@ -2487,16 +2171,15 @@ class ReactNativeBleTransport {
2487
2171
  return result;
2488
2172
  }
2489
2173
  catch (error) {
2490
- this.noteIosLinkError(uuid, 'gatt-setup', error);
2491
- if (reactNative.Platform.OS === 'ios' && isNativeBleStaleBondError(error)) {
2492
- throw toBleStaleBondHardwareError(error);
2493
- }
2494
2174
  if (timedOut || isNativeOperationTimeoutError(error)) {
2495
2175
  const resetManager = this.abandonStalledConnection(uuid, timedOut ? 'gatt-backstop' : 'gatt-native');
2496
2176
  if (resetManager) {
2497
2177
  throw this.createWedgedBleSetupError();
2498
2178
  }
2499
2179
  }
2180
+ if (isNativeBleDisconnectError(error)) {
2181
+ throw toBleDisconnectHardwareError(error);
2182
+ }
2500
2183
  if (reactNative.Platform.OS === 'android' && isMissingGattShapeError(error)) {
2501
2184
  this.androidGattCacheRefreshes.add(uuid);
2502
2185
  }
@@ -2530,8 +2213,6 @@ class ReactNativeBleTransport {
2530
2213
  }
2531
2214
  this.deviceProtocol.delete(uuid);
2532
2215
  this.probingProtocols.delete(uuid);
2533
- this.staleBondErrors.delete(uuid);
2534
- this.acquiringProtocolV2.delete(uuid);
2535
2216
  this.protocolV2Assemblers.delete(uuid);
2536
2217
  this.resetProtocolV2Frames(uuid);
2537
2218
  if (timeouts >= BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD) {
@@ -2562,14 +2243,13 @@ class ReactNativeBleTransport {
2562
2243
  new Promise((_, reject) => {
2563
2244
  timer = setTimeout(() => {
2564
2245
  timedOut = true;
2565
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2246
+ reject(createWedgedWriteError());
2566
2247
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2567
2248
  }),
2568
2249
  ]);
2569
2250
  this.writeTimeoutCounts.delete(uuid);
2570
2251
  }
2571
2252
  catch (error) {
2572
- this.noteIosLinkError(uuid, 'write', error);
2573
2253
  if (timedOut) {
2574
2254
  if (isCurrentOwner && !isCurrentOwner()) {
2575
2255
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE write timed out, link kept:', uuid);
@@ -2593,6 +2273,7 @@ class ReactNativeBleTransport {
2593
2273
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE write timed out, tearing down link:', uuid, {
2594
2274
  consecutiveWriteTimeouts: timeouts,
2595
2275
  });
2276
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2596
2277
  const wedged = transportCache[uuid];
2597
2278
  this.disconnect(uuid).catch(error => {
2598
2279
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2602,8 +2283,6 @@ class ReactNativeBleTransport {
2602
2283
  }
2603
2284
  this.deviceProtocol.delete(uuid);
2604
2285
  this.probingProtocols.delete(uuid);
2605
- this.staleBondErrors.delete(uuid);
2606
- this.acquiringProtocolV2.delete(uuid);
2607
2286
  this.protocolV2Assemblers.delete(uuid);
2608
2287
  this.resetProtocolV2Frames(uuid);
2609
2288
  if (timeouts >= BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD) {
@@ -2618,6 +2297,7 @@ class ReactNativeBleTransport {
2618
2297
  const manager = this.blePlxManager;
2619
2298
  this.blePlxManager = undefined;
2620
2299
  const reason = 'React Native BLE manager reset';
2300
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2621
2301
  Object.entries(transportCache).forEach(([uuid, cachedTransport]) => {
2622
2302
  var _a, _b, _c, _d;
2623
2303
  try {
@@ -2648,8 +2328,6 @@ class ReactNativeBleTransport {
2648
2328
  });
2649
2329
  this.deviceProtocol.clear();
2650
2330
  this.probingProtocols.clear();
2651
- this.staleBondErrors.clear();
2652
- this.acquiringProtocolV2.clear();
2653
2331
  this.sessionProtocols.clear();
2654
2332
  this.protocolReprobeFailures.clear();
2655
2333
  this.silentDetections.clear();
@@ -2673,10 +2351,12 @@ class ReactNativeBleTransport {
2673
2351
  });
2674
2352
  }
2675
2353
  createProtocolMismatchError(expected) {
2676
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
2354
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportProtocolProbeFailed, undefined, {
2355
+ expectedProtocol: expected,
2356
+ });
2677
2357
  }
2678
2358
  createProtocolDetectionError() {
2679
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'Unable to detect BLE protocol: device did not respond to Protocol V1 GetFeatures or Protocol V2 Ping');
2359
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportProtocolProbeFailed);
2680
2360
  }
2681
2361
  clearProbeProtocol(uuid, protocol) {
2682
2362
  if (this.probingProtocols.get(uuid) === protocol) {
@@ -2702,9 +2382,6 @@ class ReactNativeBleTransport {
2702
2382
  });
2703
2383
  return 'V1';
2704
2384
  }
2705
- if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2706
- this.throwIfStaleBondError(uuid);
2707
- }
2708
2385
  if (expectedProtocol === 'V2') {
2709
2386
  if (yield this.probeProtocolV2(uuid)) {
2710
2387
  this.deviceProtocol.set(uuid, 'V2');
@@ -2863,8 +2540,7 @@ class ReactNativeBleTransport {
2863
2540
  }
2864
2541
  this.probingProtocols.set(uuid, 'V2');
2865
2542
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2866
- this.throwIfStaleBondError(uuid);
2867
- const detected = yield transport.probeProtocolV2({
2543
+ const detected = yield transportModule.probeProtocolV2({
2868
2544
  call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2869
2545
  timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
2870
2546
  logger: Log,
@@ -2935,19 +2611,6 @@ class ReactNativeBleTransport {
2935
2611
  framePromise.reject(error);
2936
2612
  }
2937
2613
  }
2938
- rememberStaleBondError(uuid, error) {
2939
- this.staleBondErrors.set(uuid, error);
2940
- this.rejectProtocolV2Frames(uuid, error);
2941
- if (this.runPromise && this.runPromiseDeviceId === uuid) {
2942
- this.runPromise.reject(error);
2943
- }
2944
- }
2945
- throwIfStaleBondError(uuid) {
2946
- const error = this.staleBondErrors.get(uuid);
2947
- if (error) {
2948
- throw error;
2949
- }
2950
- }
2951
2614
  readProtocolV2Frame(uuid) {
2952
2615
  return __awaiter(this, void 0, void 0, function* () {
2953
2616
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
@@ -2996,11 +2659,6 @@ class ReactNativeBleTransport {
2996
2659
  return;
2997
2660
  }
2998
2661
  catch (error) {
2999
- if (isNativeBleStaleBondError(error) || hdShared.isBleStaleBondHardwareError(error)) {
3000
- const bondError = toBleStaleBondHardwareError(error);
3001
- this.rememberStaleBondError(uuid, bondError);
3002
- throw bondError;
3003
- }
3004
2662
  if (isNativeBleDisconnectError(error)) {
3005
2663
  throw toBleDisconnectHardwareError(error);
3006
2664
  }
@@ -3020,35 +2678,178 @@ class ReactNativeBleTransport {
3020
2678
  }
3021
2679
  });
3022
2680
  }
3023
- writeProtocolV2Frame(uuid, transport$1, frame, context, assertCurrentGeneration) {
2681
+ writeProtocolV2Frame(uuid, transport, frame, context, assertCurrentGeneration) {
3024
2682
  return __awaiter(this, void 0, void 0, function* () {
3025
2683
  const tuning = getProtocolV2BleTuning();
3026
2684
  const packetCapacity = resolveProtocolV2PacketCapacity({
3027
2685
  platform: reactNative.Platform.OS,
3028
2686
  iosPacketLength: tuning.iosPacketLength,
3029
2687
  androidPacketLength: tuning.androidPacketLength,
3030
- mtu: transport$1.mtuSize,
2688
+ mtu: transport.mtuSize,
3031
2689
  });
3032
- yield transport.writeProtocolV2BleFrame({
3033
- frame,
3034
- packetCapacity,
3035
- assertActive: assertCurrentGeneration,
3036
- signal: context.signal,
3037
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
3038
- wait: delay,
3039
- writePacket: packet => this.writeProtocolV2Packet(uuid, transport$1, buffer.Buffer.from(packet).toString('base64'), context, assertCurrentGeneration),
2690
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
2691
+ const startedAt = perf ? nowMs() : 0;
2692
+ const nativeFrameWriter = frame.length > packetCapacity
2693
+ ? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
2694
+ : undefined;
2695
+ perf === null || perf === void 0 ? void 0 : perf.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
2696
+ if (nativeFrameWriter) {
2697
+ yield this.writeProtocolV2NativeFrame(uuid, transport, nativeFrameWriter, frame, packetCapacity, context, assertCurrentGeneration);
2698
+ }
2699
+ else {
2700
+ yield transportModule.writeProtocolV2BleFrame({
2701
+ frame,
2702
+ packetCapacity,
2703
+ assertActive: assertCurrentGeneration,
2704
+ signal: context.signal,
2705
+ abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2706
+ wait: delay,
2707
+ writePacket: (packet) => __awaiter(this, void 0, void 0, function* () {
2708
+ const packetStartedAt = perf ? nowMs() : 0;
2709
+ yield this.writeProtocolV2Packet(uuid, transport, buffer.Buffer.from(packet).toString('base64'), context, assertCurrentGeneration);
2710
+ perf === null || perf === void 0 ? void 0 : perf.recordPacket(nowMs() - packetStartedAt);
2711
+ }),
2712
+ });
2713
+ }
2714
+ perf === null || perf === void 0 ? void 0 : perf.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
2715
+ });
2716
+ }
2717
+ resolveProtocolV2NativeFrameWriter(transport, context, nativeFrameWrite) {
2718
+ if (!context.highThroughput || !nativeFrameWrite)
2719
+ return undefined;
2720
+ if (shouldWriteProtocolV2WithResponse({
2721
+ platform: reactNative.Platform.OS,
2722
+ highThroughput: context.highThroughput,
2723
+ requestedWithResponse: context.writeWithResponse,
2724
+ characteristic: transport.writeCharacteristic,
2725
+ })) {
2726
+ return undefined;
2727
+ }
2728
+ if (typeof transport.writeCharacteristic.id !== 'number')
2729
+ return undefined;
2730
+ return getProtocolV2NativeFrameWriter(this.blePlxManager);
2731
+ }
2732
+ writeProtocolV2NativeFrame(uuid, transport, manager, frame, packetCapacity, context, assertCurrentGeneration) {
2733
+ return __awaiter(this, void 0, void 0, function* () {
2734
+ const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
2735
+ assertCurrentGeneration();
2736
+ if (context.signal.aborted) {
2737
+ throw new Error(abortMessage);
2738
+ }
2739
+ this.protocolV2FrameWriteCounter += 1;
2740
+ const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
2741
+ let cancelError;
2742
+ let rejectCancelled = () => undefined;
2743
+ const cancelled = new Promise((_, reject) => {
2744
+ rejectCancelled = reject;
3040
2745
  });
2746
+ const active = {
2747
+ generation: context.generation,
2748
+ cancel: error => {
2749
+ if (cancelError)
2750
+ return;
2751
+ cancelError = error;
2752
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
2753
+ this.protocolV2FrameWrites.delete(uuid);
2754
+ }
2755
+ rejectCancelled(error);
2756
+ this.cancelNativeTransaction(manager, transactionId);
2757
+ },
2758
+ };
2759
+ const isCurrentOwner = () => {
2760
+ try {
2761
+ assertCurrentGeneration();
2762
+ return !context.signal.aborted;
2763
+ }
2764
+ catch (_a) {
2765
+ return false;
2766
+ }
2767
+ };
2768
+ const onAbort = () => active.cancel(new Error(abortMessage));
2769
+ let timer;
2770
+ try {
2771
+ const nativeWrite = Promise.resolve(manager.writeCharacteristicWithoutResponseFrame(transport.writeCharacteristic.id, buffer.Buffer.from(frame).toString('base64'), packetCapacity, transactionId));
2772
+ nativeWrite.catch(() => undefined);
2773
+ this.protocolV2FrameWrites.set(uuid, active);
2774
+ context.signal.addEventListener('abort', onAbort);
2775
+ timer = setTimeout(() => {
2776
+ const owner = isCurrentOwner();
2777
+ active.cancel(createWedgedWriteError());
2778
+ if (owner) {
2779
+ this.tearDownWedgedLink(uuid);
2780
+ }
2781
+ else {
2782
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
2783
+ }
2784
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
2785
+ yield Promise.race([nativeWrite, cancelled]);
2786
+ }
2787
+ catch (error) {
2788
+ if (cancelError)
2789
+ throw cancelError;
2790
+ if (isNativeBleDisconnectError(error)) {
2791
+ throw toBleDisconnectHardwareError(error);
2792
+ }
2793
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, getNativeBleErrorReason(error));
2794
+ }
2795
+ finally {
2796
+ if (timer)
2797
+ clearTimeout(timer);
2798
+ context.signal.removeEventListener('abort', onAbort);
2799
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
2800
+ this.protocolV2FrameWrites.delete(uuid);
2801
+ }
2802
+ }
2803
+ this.writeTimeoutCounts.delete(uuid);
2804
+ try {
2805
+ assertCurrentGeneration();
2806
+ }
2807
+ catch (error) {
2808
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
2809
+ }
2810
+ if (cancelError)
2811
+ throw cancelError;
3041
2812
  });
3042
2813
  }
3043
- callProtocolV2(uuid, name, data, options) {
2814
+ cancelProtocolV2FrameWrite(uuid, error, generation) {
2815
+ const active = this.protocolV2FrameWrites.get(uuid);
2816
+ if (!active || (generation !== undefined && active.generation !== generation))
2817
+ return;
2818
+ active.cancel(error);
2819
+ }
2820
+ cancelNativeTransaction(manager, transactionId) {
2821
+ const logFailure = (error) => Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
2822
+ error: error instanceof Error ? error.message : String(error),
2823
+ });
2824
+ try {
2825
+ Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
2826
+ }
2827
+ catch (error) {
2828
+ logFailure(error);
2829
+ }
2830
+ }
2831
+ getProtocolV2FileWritePerf(uuid, context) {
2832
+ return context.messageName === 'FilesystemFileWrite'
2833
+ ? this.protocolV2FileWritePerfs.get(uuid)
2834
+ : undefined;
2835
+ }
2836
+ markProtocolV2LogSignature(uuid, signature) {
3044
2837
  var _a;
2838
+ const signatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2839
+ if (signatures.has(signature))
2840
+ return false;
2841
+ signatures.add(signature);
2842
+ this.protocolV2HighVolumeLogSignatures.set(uuid, signatures);
2843
+ return true;
2844
+ }
2845
+ callProtocolV2(uuid, name, data, options) {
3045
2846
  return __awaiter(this, void 0, void 0, function* () {
3046
2847
  if (!this._messages || !this._messagesV2) {
3047
2848
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
3048
2849
  }
3049
2850
  const isProtocolProbe = this.probingProtocols.get(uuid) === 'V2';
3050
2851
  const callOptions = options;
3051
- const highThroughputWrite = transport.isProtocolV2HighThroughputCall(name);
2852
+ const highThroughputWrite = transportModule.isProtocolV2HighThroughputCall(name);
3052
2853
  if (highThroughputWrite) {
3053
2854
  yield this.ensureProtocolV2HighThroughputMtu(uuid);
3054
2855
  const tuning = getProtocolV2BleTuning();
@@ -3067,10 +2868,7 @@ class ReactNativeBleTransport {
3067
2868
  });
3068
2869
  const writeMode = writeWithResponse ? 'withResponse' : 'withoutResponse';
3069
2870
  const logSignature = `${name}:${writeMode}:${String(currentTransport.mtuSize)}:${packetCapacity}`;
3070
- const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
3071
- if (!loggedSignatures.has(logSignature)) {
3072
- loggedSignatures.add(logSignature);
3073
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2871
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
3074
2872
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
3075
2873
  name,
3076
2874
  writeMode,
@@ -3078,12 +2876,33 @@ class ReactNativeBleTransport {
3078
2876
  packetCapacity,
3079
2877
  });
3080
2878
  }
2879
+ const frameWriteMode = this.resolveProtocolV2NativeFrameWriter(currentTransport, { highThroughput: true, writeWithResponse: options === null || options === void 0 ? void 0 : options.writeWithResponse }, tuning.nativeFrameWrite)
2880
+ ? 'native-frame'
2881
+ : 'per-packet';
2882
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
2883
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
2884
+ platform: reactNative.Platform.OS,
2885
+ mode: frameWriteMode,
2886
+ nativeFrameWrite: tuning.nativeFrameWrite,
2887
+ nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
2888
+ packetCapacity,
2889
+ });
2890
+ }
3081
2891
  }
3082
2892
  if (highThroughputWrite) {
3083
2893
  yield this.enableAndroidHighConnectionPriority(uuid);
3084
2894
  }
2895
+ const fileWritePerf = name === 'FilesystemFileWrite' && (options === null || options === void 0 ? void 0 : options.fileWritePipeline)
2896
+ ? createProtocolV2FileWritePerf()
2897
+ : undefined;
2898
+ if (fileWritePerf) {
2899
+ this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
2900
+ }
2901
+ let fileWriteOk = false;
3085
2902
  try {
3086
- return yield this.protocolV2Links.call(uuid, () => this.createProtocolV2Adapter(uuid), name, data, callOptions);
2903
+ const response = yield this.protocolV2Links.call(uuid, () => this.createProtocolV2Adapter(uuid), name, data, callOptions);
2904
+ fileWriteOk = response.type !== 'Failure';
2905
+ return response;
3087
2906
  }
3088
2907
  catch (e) {
3089
2908
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
@@ -3101,6 +2920,12 @@ class ReactNativeBleTransport {
3101
2920
  if (highThroughputWrite) {
3102
2921
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3103
2922
  }
2923
+ if (fileWritePerf) {
2924
+ if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
2925
+ this.protocolV2FileWritePerfs.delete(uuid);
2926
+ }
2927
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] FileWrite perf', fileWritePerf.summarize(fileWriteOk));
2928
+ }
3104
2929
  }
3105
2930
  });
3106
2931
  }
@@ -3132,6 +2957,15 @@ class ReactNativeBleTransport {
3132
2957
  this.clearAndroidPriorityResetTimer(uuid);
3133
2958
  if (this.androidHighPriorityDevices.has(uuid))
3134
2959
  return;
2960
+ if (!shouldRequestAndroidHighConnectionPriority()) {
2961
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
2962
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
2963
+ apiLevel: reactNative.Platform.Version,
2964
+ setting: protocolV2BleTuning.androidHighConnectionPriority,
2965
+ });
2966
+ }
2967
+ return;
2968
+ }
3135
2969
  const transport = transportCache[uuid];
3136
2970
  if (!transport)
3137
2971
  return;
@@ -3187,8 +3021,8 @@ class ReactNativeBleTransport {
3187
3021
  }
3188
3022
  };
3189
3023
  return {
3190
- router: transport.PROTOCOL_V2_CHANNEL_BLE_UART,
3191
- maxFrameBytes: transport.PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
3024
+ router: transportModule.PROTOCOL_V2_CHANNEL_BLE_UART,
3025
+ maxFrameBytes: transportModule.PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
3192
3026
  generation,
3193
3027
  prepareCall: () => {
3194
3028
  var _a;
@@ -3201,9 +3035,12 @@ class ReactNativeBleTransport {
3201
3035
  const currentTransport = this.getCachedTransport(uuid);
3202
3036
  yield this.writeProtocolV2Frame(uuid, currentTransport, frame, context, assertCurrentGeneration);
3203
3037
  }),
3204
- readFrame: () => __awaiter(this, void 0, void 0, function* () {
3038
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
3205
3039
  assertCurrentGeneration();
3040
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3041
+ const startedAt = perf ? nowMs() : 0;
3206
3042
  const rxFrame = yield this.readProtocolV2Frame(uuid);
3043
+ perf === null || perf === void 0 ? void 0 : perf.recordReadWait(nowMs() - startedAt);
3207
3044
  if (!(rxFrame instanceof Uint8Array)) {
3208
3045
  throw new Error('Protocol V2 response is not Uint8Array');
3209
3046
  }
@@ -3211,6 +3048,7 @@ class ReactNativeBleTransport {
3211
3048
  }),
3212
3049
  reset: (reason) => {
3213
3050
  var _a;
3051
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
3214
3052
  if (this.monitorTokens.get(uuid) !== generation)
3215
3053
  return;
3216
3054
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
@@ -3226,12 +3064,8 @@ class ReactNativeBleTransport {
3226
3064
  }
3227
3065
  }
3228
3066
 
3229
- exports.ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS;
3230
- exports.ANDROID_KEY_MISSING_GRACE_MS = ANDROID_KEY_MISSING_GRACE_MS;
3231
- exports.ANDROID_KEY_MISSING_LINK_WINDOW_MS = ANDROID_KEY_MISSING_LINK_WINDOW_MS;
3232
3067
  exports.ANDROID_LINK_DROP_QUIET_MS = ANDROID_LINK_DROP_QUIET_MS;
3233
3068
  exports.ANDROID_MTU_EXCHANGE_TIMEOUT_MS = ANDROID_MTU_EXCHANGE_TIMEOUT_MS;
3234
- exports.ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = ANDROID_SYSTEM_REPAIR_TIMEOUT_MS;
3235
3069
  exports.BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD;
3236
3070
  exports.BLE_CONNECT_TIMEOUT_MS = BLE_CONNECT_TIMEOUT_MS;
3237
3071
  exports.BLE_GATT_SETUP_TIMEOUT_MS = BLE_GATT_SETUP_TIMEOUT_MS;