@onekeyfe/hd-transport-react-native 1.2.8-alpha.13 → 1.2.8-alpha.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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.
@@ -56,7 +56,9 @@ const bleLogger = {
56
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); },
57
57
  };
58
58
 
59
+ var _a$1;
59
60
  const Logger = bleLogger;
61
+ const BleUtils = (_a$1 = BleUtilsModule__default["default"].default) !== null && _a$1 !== void 0 ? _a$1 : BleUtilsModule__default["default"];
60
62
  const bondFailureReasons = {
61
63
  1: 'authentication_failed',
62
64
  2: 'rejected',
@@ -68,8 +70,8 @@ const bondFailureReasons = {
68
70
  8: 'remote_canceled',
69
71
  9: 'removed',
70
72
  };
71
- const getConnectedDeviceIds = (serviceUuids) => BleUtils__default["default"].getConnectedPeripherals(serviceUuids);
72
- const pairDevice = (macAddress) => BleUtils__default["default"].pairDevice(macAddress);
73
+ const getConnectedDeviceIds = (serviceUuids) => BleUtils.getConnectedPeripherals(serviceUuids);
74
+ const pairDevice = (macAddress) => BleUtils.pairDevice(macAddress);
73
75
  const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
74
76
  const createBondFailureError = (bondState) => {
75
77
  var _a;
@@ -112,7 +114,7 @@ const onDeviceBondState = (bleMacAddress, signal, options) => new Promise((resol
112
114
  reason: 'timeout',
113
115
  }));
114
116
  }, 60 * 1000);
115
- const cleanupListener = BleUtils__default["default"].onDeviceBondState(peripheral => {
117
+ const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
116
118
  var _a;
117
119
  if (((_a = peripheral.id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== bleMacAddress.toLowerCase()) {
118
120
  return;
@@ -298,9 +300,9 @@ const isHeaderChunk = (chunk) => {
298
300
  if (chunk.length < 9)
299
301
  return false;
300
302
  const [MagicQuestionMark, sharp1, sharp2] = chunk;
301
- if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transport.PROTOCOL_V1_REPORT_ID) &&
302
- String.fromCharCode(sharp1) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE) &&
303
- 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)) {
304
306
  return true;
305
307
  }
306
308
  return false;
@@ -321,7 +323,9 @@ class BleTransport {
321
323
  }
322
324
  }
323
325
 
324
- 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;
325
329
  const Log = bleLogger;
326
330
  const transportCache = {};
327
331
  let bleManagerResetPromise;
@@ -383,6 +387,7 @@ const WEDGED_WRITE_MESSAGE = 'BLE write timeout after';
383
387
  const isWedgedWriteError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleWriteCharacteristicError &&
384
388
  typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
385
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`);
386
391
  const shouldRethrowProtocolProbeError = (error) => {
387
392
  const code = error === null || error === void 0 ? void 0 : error.errorCode;
388
393
  return (isNativeBleDisconnectError(error) ||
@@ -400,6 +405,8 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
400
405
  const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
401
406
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
402
407
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
408
+ nativeFrameWrite: true,
409
+ androidHighConnectionPriority: 'auto',
403
410
  };
404
411
  let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
405
412
  const normalizePositiveInteger = (value, fallback) => {
@@ -412,6 +419,13 @@ function configureProtocolV2BleTuning(tuning = {}) {
412
419
  protocolV2BleTuning = {
413
420
  iosPacketLength: normalizePositiveInteger(tuning.iosPacketLength, protocolV2BleTuning.iosPacketLength),
414
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,
415
429
  };
416
430
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
417
431
  }
@@ -422,12 +436,128 @@ function resetProtocolV2BleTuning() {
422
436
  function getProtocolV2BleTuning() {
423
437
  return Object.assign({}, protocolV2BleTuning);
424
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
+ };
425
524
  function getDeviceDisplayName(device) {
426
525
  return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
427
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
+ }
428
548
  const IOS_REQUEST_MTU = 247;
429
549
  const ANDROID_REQUEST_MTU = 517;
430
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
+ };
431
561
  const getRequestedBleMtu = () => reactNative.Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
432
562
  const BLE_NATIVE_CONNECT_TIMEOUT_MS = 3000;
433
563
  const BLE_MTU_REQUEST_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS;
@@ -585,7 +715,7 @@ class ReactNativeBleTransport {
585
715
  this.protocolV2Assemblers = new Map();
586
716
  this.protocolV2FrameQueues = new Map();
587
717
  this.protocolV2FramePromises = new Map();
588
- this.protocolV2Links = new transport.ProtocolV2LinkManager({
718
+ this.protocolV2Links = new transportModule.ProtocolV2LinkManager({
589
719
  getSchemas: () => {
590
720
  if (!this._messages || !this._messagesV2) {
591
721
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
@@ -620,6 +750,9 @@ class ReactNativeBleTransport {
620
750
  this.protocolV2HighVolumeLogSignatures = new Map();
621
751
  this.androidHighPriorityDevices = new Set();
622
752
  this.androidPriorityResetTimers = new Map();
753
+ this.protocolV2FrameWrites = new Map();
754
+ this.protocolV2FrameWriteCounter = 0;
755
+ this.protocolV2FileWritePerfs = new Map();
623
756
  this.nextMonitorToken = 1;
624
757
  this.lifecycleOperations = new Map();
625
758
  this.scanCleanups = new Set();
@@ -796,7 +929,7 @@ class ReactNativeBleTransport {
796
929
  return;
797
930
  }
798
931
  this.disconnectEventTokens.set(uuid, token);
799
- (_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, {
800
933
  name,
801
934
  id: uuid,
802
935
  connectId: uuid,
@@ -881,7 +1014,7 @@ class ReactNativeBleTransport {
881
1014
  if (error)
882
1015
  reject(error);
883
1016
  else
884
- resolve(deviceList);
1017
+ resolve(deviceList.map(withBleColorCode));
885
1018
  });
886
1019
  return scanCleanup;
887
1020
  };
@@ -921,6 +1054,7 @@ class ReactNativeBleTransport {
921
1054
  }
922
1055
  return;
923
1056
  }
1057
+ rememberBleColorCode(device);
924
1058
  const displayName = getDeviceDisplayName(device);
925
1059
  const isUnnamedIOSPeripheral = reactNative.Platform.OS === 'ios' && !(displayName === null || displayName === void 0 ? void 0 : displayName.trim());
926
1060
  const isOneKey = !isUnnamedIOSPeripheral &&
@@ -970,6 +1104,8 @@ class ReactNativeBleTransport {
970
1104
  deviceId: device.id,
971
1105
  name: displayName,
972
1106
  serviceUUIDs: device.serviceUUIDs,
1107
+ manufacturerDataLength: getManufacturerDataLength(device),
1108
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
973
1109
  });
974
1110
  }
975
1111
  };
@@ -981,18 +1117,18 @@ class ReactNativeBleTransport {
981
1117
  const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, device));
982
1118
  if (this.stopped)
983
1119
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
984
- const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
985
- 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;
986
1122
  const monitorToken = this.nextMonitorToken;
987
1123
  this.nextMonitorToken += 1;
988
1124
  const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
989
- transport$1.monitorToken = monitorToken;
990
- transport$1.notifyTransactionId = notifyTransactionId;
1125
+ transport.monitorToken = monitorToken;
1126
+ transport.notifyTransactionId = notifyTransactionId;
991
1127
  this.monitorTokens.set(uuid, monitorToken);
992
- transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
993
- transportCache[uuid] = transport$1;
1128
+ transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
1129
+ transportCache[uuid] = transport;
994
1130
  this.protocolV2HighVolumeLogSignatures.set(uuid, new Set());
995
- 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));
996
1132
  if (reactNative.Platform.OS === 'ios') {
997
1133
  yield new Promise(resolve => {
998
1134
  setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
@@ -1007,9 +1143,9 @@ class ReactNativeBleTransport {
1007
1143
  connectionId: monitorToken,
1008
1144
  platform: reactNative.Platform.OS,
1009
1145
  requested: getRequestedBleMtu(),
1010
- actual: transport$1.mtuSize,
1146
+ actual: transport.mtuSize,
1011
1147
  });
1012
- return transport$1;
1148
+ return transport;
1013
1149
  });
1014
1150
  }
1015
1151
  acquire(input) {
@@ -1389,7 +1525,7 @@ class ReactNativeBleTransport {
1389
1525
  else {
1390
1526
  buffer$1 = buffer$1.concat([...data]);
1391
1527
  }
1392
- if (buffer$1.length - transport.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
1528
+ if (buffer$1.length - transportModule.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
1393
1529
  const value = buffer.Buffer.from(buffer$1);
1394
1530
  bufferLength = 0;
1395
1531
  buffer$1 = [];
@@ -1411,20 +1547,33 @@ class ReactNativeBleTransport {
1411
1547
  }, notifyTransactionId);
1412
1548
  return subscription;
1413
1549
  }
1414
- release(uuid, onclose = false) {
1550
+ release(uuid, onclose = false, keepSession = false) {
1415
1551
  return __awaiter(this, void 0, void 0, function* () {
1416
- return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose));
1552
+ return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose, keepSession));
1417
1553
  });
1418
1554
  }
1419
- releaseUnlocked(uuid, onclose = false) {
1555
+ releaseUnlocked(uuid, onclose = false, keepSession = false) {
1420
1556
  return __awaiter(this, void 0, void 0, function* () {
1421
- 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);
1422
1570
  return this.releaseNative(uuid, onclose);
1423
1571
  });
1424
1572
  }
1425
1573
  releaseNative(uuid, onclose = false) {
1426
1574
  var _a, _b, _c, _d, _e;
1427
1575
  return __awaiter(this, void 0, void 0, function* () {
1576
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1428
1577
  const transport = transportCache[uuid];
1429
1578
  const manager = this.blePlxManager;
1430
1579
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1751,7 +1900,11 @@ class ReactNativeBleTransport {
1751
1900
  disconnectUnlocked(session) {
1752
1901
  var _a, _b, _c;
1753
1902
  return __awaiter(this, void 0, void 0, function* () {
1754
- 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);
1755
1908
  const transport = transportCache[session];
1756
1909
  const manager = this.blePlxManager;
1757
1910
  const monitorToken = (_a = transport === null || transport === void 0 ? void 0 : transport.monitorToken) !== null && _a !== void 0 ? _a : this.monitorTokens.get(session);
@@ -2090,7 +2243,7 @@ class ReactNativeBleTransport {
2090
2243
  new Promise((_, reject) => {
2091
2244
  timer = setTimeout(() => {
2092
2245
  timedOut = true;
2093
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2246
+ reject(createWedgedWriteError());
2094
2247
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2095
2248
  }),
2096
2249
  ]);
@@ -2120,6 +2273,7 @@ class ReactNativeBleTransport {
2120
2273
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE write timed out, tearing down link:', uuid, {
2121
2274
  consecutiveWriteTimeouts: timeouts,
2122
2275
  });
2276
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2123
2277
  const wedged = transportCache[uuid];
2124
2278
  this.disconnect(uuid).catch(error => {
2125
2279
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2143,6 +2297,7 @@ class ReactNativeBleTransport {
2143
2297
  const manager = this.blePlxManager;
2144
2298
  this.blePlxManager = undefined;
2145
2299
  const reason = 'React Native BLE manager reset';
2300
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2146
2301
  Object.entries(transportCache).forEach(([uuid, cachedTransport]) => {
2147
2302
  var _a, _b, _c, _d;
2148
2303
  try {
@@ -2196,10 +2351,12 @@ class ReactNativeBleTransport {
2196
2351
  });
2197
2352
  }
2198
2353
  createProtocolMismatchError(expected) {
2199
- 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
+ });
2200
2357
  }
2201
2358
  createProtocolDetectionError() {
2202
- 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);
2203
2360
  }
2204
2361
  clearProbeProtocol(uuid, protocol) {
2205
2362
  if (this.probingProtocols.get(uuid) === protocol) {
@@ -2383,7 +2540,7 @@ class ReactNativeBleTransport {
2383
2540
  }
2384
2541
  this.probingProtocols.set(uuid, 'V2');
2385
2542
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2386
- const detected = yield transport.probeProtocolV2({
2543
+ const detected = yield transportModule.probeProtocolV2({
2387
2544
  call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2388
2545
  timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
2389
2546
  logger: Log,
@@ -2521,35 +2678,178 @@ class ReactNativeBleTransport {
2521
2678
  }
2522
2679
  });
2523
2680
  }
2524
- writeProtocolV2Frame(uuid, transport$1, frame, context, assertCurrentGeneration) {
2681
+ writeProtocolV2Frame(uuid, transport, frame, context, assertCurrentGeneration) {
2525
2682
  return __awaiter(this, void 0, void 0, function* () {
2526
2683
  const tuning = getProtocolV2BleTuning();
2527
2684
  const packetCapacity = resolveProtocolV2PacketCapacity({
2528
2685
  platform: reactNative.Platform.OS,
2529
2686
  iosPacketLength: tuning.iosPacketLength,
2530
2687
  androidPacketLength: tuning.androidPacketLength,
2531
- mtu: transport$1.mtuSize,
2688
+ mtu: transport.mtuSize,
2532
2689
  });
2533
- yield transport.writeProtocolV2BleFrame({
2534
- frame,
2535
- packetCapacity,
2536
- assertActive: assertCurrentGeneration,
2537
- signal: context.signal,
2538
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2539
- wait: delay,
2540
- 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;
2541
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;
2542
2812
  });
2543
2813
  }
2544
- 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) {
2545
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) {
2546
2846
  return __awaiter(this, void 0, void 0, function* () {
2547
2847
  if (!this._messages || !this._messagesV2) {
2548
2848
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
2549
2849
  }
2550
2850
  const isProtocolProbe = this.probingProtocols.get(uuid) === 'V2';
2551
2851
  const callOptions = options;
2552
- const highThroughputWrite = transport.isProtocolV2HighThroughputCall(name);
2852
+ const highThroughputWrite = transportModule.isProtocolV2HighThroughputCall(name);
2553
2853
  if (highThroughputWrite) {
2554
2854
  yield this.ensureProtocolV2HighThroughputMtu(uuid);
2555
2855
  const tuning = getProtocolV2BleTuning();
@@ -2568,10 +2868,7 @@ class ReactNativeBleTransport {
2568
2868
  });
2569
2869
  const writeMode = writeWithResponse ? 'withResponse' : 'withoutResponse';
2570
2870
  const logSignature = `${name}:${writeMode}:${String(currentTransport.mtuSize)}:${packetCapacity}`;
2571
- const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2572
- if (!loggedSignatures.has(logSignature)) {
2573
- loggedSignatures.add(logSignature);
2574
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2871
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
2575
2872
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
2576
2873
  name,
2577
2874
  writeMode,
@@ -2579,12 +2876,33 @@ class ReactNativeBleTransport {
2579
2876
  packetCapacity,
2580
2877
  });
2581
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
+ }
2582
2891
  }
2583
2892
  if (highThroughputWrite) {
2584
2893
  yield this.enableAndroidHighConnectionPriority(uuid);
2585
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;
2586
2902
  try {
2587
- 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;
2588
2906
  }
2589
2907
  catch (e) {
2590
2908
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
@@ -2602,6 +2920,12 @@ class ReactNativeBleTransport {
2602
2920
  if (highThroughputWrite) {
2603
2921
  this.scheduleAndroidBalancedConnectionPriority(uuid);
2604
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
+ }
2605
2929
  }
2606
2930
  });
2607
2931
  }
@@ -2633,6 +2957,15 @@ class ReactNativeBleTransport {
2633
2957
  this.clearAndroidPriorityResetTimer(uuid);
2634
2958
  if (this.androidHighPriorityDevices.has(uuid))
2635
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
+ }
2636
2969
  const transport = transportCache[uuid];
2637
2970
  if (!transport)
2638
2971
  return;
@@ -2688,8 +3021,8 @@ class ReactNativeBleTransport {
2688
3021
  }
2689
3022
  };
2690
3023
  return {
2691
- router: transport.PROTOCOL_V2_CHANNEL_BLE_UART,
2692
- 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,
2693
3026
  generation,
2694
3027
  prepareCall: () => {
2695
3028
  var _a;
@@ -2702,9 +3035,12 @@ class ReactNativeBleTransport {
2702
3035
  const currentTransport = this.getCachedTransport(uuid);
2703
3036
  yield this.writeProtocolV2Frame(uuid, currentTransport, frame, context, assertCurrentGeneration);
2704
3037
  }),
2705
- readFrame: () => __awaiter(this, void 0, void 0, function* () {
3038
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
2706
3039
  assertCurrentGeneration();
3040
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3041
+ const startedAt = perf ? nowMs() : 0;
2707
3042
  const rxFrame = yield this.readProtocolV2Frame(uuid);
3043
+ perf === null || perf === void 0 ? void 0 : perf.recordReadWait(nowMs() - startedAt);
2708
3044
  if (!(rxFrame instanceof Uint8Array)) {
2709
3045
  throw new Error('Protocol V2 response is not Uint8Array');
2710
3046
  }
@@ -2712,6 +3048,7 @@ class ReactNativeBleTransport {
2712
3048
  }),
2713
3049
  reset: (reason) => {
2714
3050
  var _a;
3051
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
2715
3052
  if (this.monitorTokens.get(uuid) !== generation)
2716
3053
  return;
2717
3054
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();