@onekeyfe/hd-transport-react-native 1.2.8-alpha.116 → 1.2.8-alpha.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as transport from '@onekeyfe/hd-transport';
2
- import transport__default, { ProtocolType, OneKeyDeviceInfoBase, TransportCallOptions } from '@onekeyfe/hd-transport';
2
+ import transport__default, { ProtocolType, OneKeyDeviceInfoBase, OneKeyMobileDeviceInfo, TransportCallOptions } from '@onekeyfe/hd-transport';
3
3
  import { Device, Characteristic, Subscription, BleManager } from 'react-native-ble-plx';
4
4
  import { Deferred } from '@onekeyfe/hd-shared';
5
5
  import EventEmitter from 'events';
@@ -72,6 +72,11 @@ type ProtocolV2BleTuning = {
72
72
  * BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
73
73
  */
74
74
  nativeFrameWrite?: boolean;
75
+ /**
76
+ * Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
77
+ * default) requests it below Android 17 only; true or false forces it on every version.
78
+ */
79
+ androidHighConnectionPriority?: boolean | 'auto';
75
80
  };
76
81
  declare function configureProtocolV2BleTuning(tuning?: ProtocolV2BleTuning): void;
77
82
  declare function resetProtocolV2BleTuning(): void;
@@ -79,6 +84,7 @@ declare function getProtocolV2BleTuning(): {
79
84
  iosPacketLength: number;
80
85
  androidPacketLength: number;
81
86
  nativeFrameWrite: boolean;
87
+ androidHighConnectionPriority: boolean | "auto";
82
88
  };
83
89
  /**
84
90
  * With no cached GATT table the stack runs its own discovery (up to ~8s) before the MTU
@@ -116,7 +122,7 @@ declare const PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = 3;
116
122
  /** BLE setup timeouts since the last successful setup before the manager is recreated. */
117
123
  declare const BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
118
124
  declare const BLE_SETUP_WEDGED_MESSAGE = "BLE setup wedged repeatedly";
119
- type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
125
+ type IOneKeyDevice = OneKeyDeviceInfoBase & Device & Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
120
126
  declare class ReactNativeBleTransport {
121
127
  blePlxManager: BleManager | undefined;
122
128
  _messages: ReturnType<typeof transport__default.parseConfigure> | undefined;
@@ -277,13 +283,17 @@ declare class ReactNativeBleTransport {
277
283
  /**
278
284
  * Writes one frame with a single native call that sends its packets in order without response.
279
285
  * Nothing here retries it: a resend could duplicate bytes the device already received. The
280
- * native transaction is cancelled on abort, watchdog expiry, generation change and link
281
- * teardown so the native side stops writing a frame nobody waits for any more.
286
+ * native transaction is cancelled on abort, watchdog expiry and link teardown so the native
287
+ * side stops writing a frame nobody waits for any more; a generation change detected after
288
+ * the frame completes still fails the write.
282
289
  */
283
290
  private writeProtocolV2NativeFrame;
284
291
  /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
285
292
  private cancelProtocolV2FrameWrite;
286
293
  private cancelNativeTransaction;
294
+ private getProtocolV2FileWritePerf;
295
+ /** Returns true the first time `signature` is seen for `uuid` on this link. */
296
+ private markProtocolV2LogSignature;
287
297
  private callProtocolV2;
288
298
  private ensureProtocolV2HighThroughputMtu;
289
299
  private clearAndroidPriorityResetTimer;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,EAGL,UAAU,IAAI,aAAa,EAG5B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,SAAS,EAAE,EAChB,KAAK,oBAAoB,EAIzB,KAAK,YAAY,EAKjB,KAAK,oBAAoB,EAI1B,MAAM,wBAAwB,CAAC;AA2BhC,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAI1C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,sBAA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OlC,OAAO,CAAC,0BAA0B;YAQpB,cAAc;YAmHd,iCAAiC;IAsB/C,OAAO,CAAC,8BAA8B;YAQxB,mCAAmC;IA+BjD,OAAO,CAAC,yCAAyC;YAanC,gCAAgC;IAoB9C,OAAO,CAAC,uBAAuB;IAwD/B,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;CAGxD"}
package/dist/index.js CHANGED
@@ -383,6 +383,7 @@ const WEDGED_WRITE_MESSAGE = 'BLE write timeout after';
383
383
  const isWedgedWriteError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleWriteCharacteristicError &&
384
384
  typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
385
385
  error.message.startsWith(WEDGED_WRITE_MESSAGE);
386
+ const createWedgedWriteError = () => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `${WEDGED_WRITE_MESSAGE} ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`);
386
387
  const shouldRethrowProtocolProbeError = (error) => {
387
388
  const code = error === null || error === void 0 ? void 0 : error.errorCode;
388
389
  return (isNativeBleDisconnectError(error) ||
@@ -401,6 +402,7 @@ const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
401
402
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
402
403
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
403
404
  nativeFrameWrite: true,
405
+ androidHighConnectionPriority: 'auto',
404
406
  };
405
407
  let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
406
408
  const normalizePositiveInteger = (value, fallback) => {
@@ -416,6 +418,10 @@ function configureProtocolV2BleTuning(tuning = {}) {
416
418
  nativeFrameWrite: typeof tuning.nativeFrameWrite === 'boolean'
417
419
  ? tuning.nativeFrameWrite
418
420
  : protocolV2BleTuning.nativeFrameWrite,
421
+ androidHighConnectionPriority: typeof tuning.androidHighConnectionPriority === 'boolean' ||
422
+ tuning.androidHighConnectionPriority === 'auto'
423
+ ? tuning.androidHighConnectionPriority
424
+ : protocolV2BleTuning.androidHighConnectionPriority,
419
425
  };
420
426
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
421
427
  }
@@ -478,7 +484,7 @@ const createProtocolV2FileWritePerf = () => {
478
484
  const write = createDurationStats();
479
485
  const readWait = createDurationStats();
480
486
  const packet = createDurationStats();
481
- const packetHistogram = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.map(() => 0).concat(0);
487
+ const packetHistogram = Array.from({ length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 }, () => 0);
482
488
  return {
483
489
  startFrame(mode) {
484
490
  if (mode === 'native-frame')
@@ -493,7 +499,7 @@ const createProtocolV2FileWritePerf = () => {
493
499
  recordPacket(elapsedMs) {
494
500
  packet.add(elapsedMs);
495
501
  const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
496
- packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
502
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
497
503
  },
498
504
  recordReadWait(elapsedMs) {
499
505
  readWait.add(elapsedMs);
@@ -514,9 +520,40 @@ const createProtocolV2FileWritePerf = () => {
514
520
  function getDeviceDisplayName(device) {
515
521
  return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
516
522
  }
523
+ const bleColorCodesById = new Map();
524
+ function getManufacturerDataLength(device) {
525
+ return (device === null || device === void 0 ? void 0 : device.manufacturerData) ? buffer.Buffer.from(device.manufacturerData, 'base64').length : 0;
526
+ }
527
+ function rememberBleColorCode(device) {
528
+ if (!(device === null || device === void 0 ? void 0 : device.id) || !device.manufacturerData)
529
+ return;
530
+ const colorCode = hdShared.parseOnekeyBleColorCode(buffer.Buffer.from(device.manufacturerData, 'base64'));
531
+ const key = device.id.toLowerCase();
532
+ if (colorCode && bleColorCodesById.get(key) !== colorCode) {
533
+ bleColorCodesById.set(key, colorCode);
534
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE color code', {
535
+ deviceId: device.id,
536
+ bleColorCode: colorCode,
537
+ });
538
+ }
539
+ }
540
+ function withBleColorCode(device) {
541
+ const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
542
+ return bleColorCode ? Object.assign(Object.assign({}, device), { bleColorCode }) : device;
543
+ }
517
544
  const IOS_REQUEST_MTU = 247;
518
545
  const ANDROID_REQUEST_MTU = 517;
519
546
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
547
+ const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
548
+ const shouldRequestAndroidHighConnectionPriority = () => {
549
+ if (reactNative.Platform.OS !== 'android')
550
+ return false;
551
+ const { androidHighConnectionPriority } = protocolV2BleTuning;
552
+ if (typeof androidHighConnectionPriority === 'boolean')
553
+ return androidHighConnectionPriority;
554
+ const apiLevel = Number(reactNative.Platform.Version);
555
+ return (!Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL);
556
+ };
520
557
  const getRequestedBleMtu = () => reactNative.Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
521
558
  const BLE_NATIVE_CONNECT_TIMEOUT_MS = 3000;
522
559
  const BLE_MTU_REQUEST_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS;
@@ -973,7 +1010,7 @@ class ReactNativeBleTransport {
973
1010
  if (error)
974
1011
  reject(error);
975
1012
  else
976
- resolve(deviceList);
1013
+ resolve(deviceList.map(withBleColorCode));
977
1014
  });
978
1015
  return scanCleanup;
979
1016
  };
@@ -1013,6 +1050,7 @@ class ReactNativeBleTransport {
1013
1050
  }
1014
1051
  return;
1015
1052
  }
1053
+ rememberBleColorCode(device);
1016
1054
  const displayName = getDeviceDisplayName(device);
1017
1055
  const isUnnamedIOSPeripheral = reactNative.Platform.OS === 'ios' && !(displayName === null || displayName === void 0 ? void 0 : displayName.trim());
1018
1056
  const isOneKey = !isUnnamedIOSPeripheral &&
@@ -1062,6 +1100,8 @@ class ReactNativeBleTransport {
1062
1100
  deviceId: device.id,
1063
1101
  name: displayName,
1064
1102
  serviceUUIDs: device.serviceUUIDs,
1103
+ manufacturerDataLength: getManufacturerDataLength(device),
1104
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
1065
1105
  });
1066
1106
  }
1067
1107
  };
@@ -1510,8 +1550,9 @@ class ReactNativeBleTransport {
1510
1550
  }
1511
1551
  releaseUnlocked(uuid, onclose = false) {
1512
1552
  return __awaiter(this, void 0, void 0, function* () {
1513
- this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1514
- yield this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1553
+ const reason = 'React Native BLE transport released';
1554
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
1555
+ yield this.protocolV2Links.invalidateLink(uuid, reason);
1515
1556
  return this.releaseNative(uuid, onclose);
1516
1557
  });
1517
1558
  }
@@ -1845,8 +1886,11 @@ class ReactNativeBleTransport {
1845
1886
  disconnectUnlocked(session) {
1846
1887
  var _a, _b, _c;
1847
1888
  return __awaiter(this, void 0, void 0, function* () {
1848
- this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
1849
- yield this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1889
+ this.clearAndroidPriorityResetTimer(session);
1890
+ this.androidHighPriorityDevices.delete(session);
1891
+ const reason = 'React Native BLE transport disconnected';
1892
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
1893
+ yield this.protocolV2Links.invalidateLink(session, reason);
1850
1894
  const transport = transportCache[session];
1851
1895
  const manager = this.blePlxManager;
1852
1896
  const monitorToken = (_a = transport === null || transport === void 0 ? void 0 : transport.monitorToken) !== null && _a !== void 0 ? _a : this.monitorTokens.get(session);
@@ -2185,7 +2229,7 @@ class ReactNativeBleTransport {
2185
2229
  new Promise((_, reject) => {
2186
2230
  timer = setTimeout(() => {
2187
2231
  timedOut = true;
2188
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2232
+ reject(createWedgedWriteError());
2189
2233
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2190
2234
  }),
2191
2235
  ]);
@@ -2215,7 +2259,7 @@ class ReactNativeBleTransport {
2215
2259
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE write timed out, tearing down link:', uuid, {
2216
2260
  consecutiveWriteTimeouts: timeouts,
2217
2261
  });
2218
- this.cancelProtocolV2FrameWrite(uuid, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2262
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2219
2263
  const wedged = transportCache[uuid];
2220
2264
  this.disconnect(uuid).catch(error => {
2221
2265
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2239,7 +2283,7 @@ class ReactNativeBleTransport {
2239
2283
  const manager = this.blePlxManager;
2240
2284
  this.blePlxManager = undefined;
2241
2285
  const reason = 'React Native BLE manager reset';
2242
- Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid => this.cancelProtocolV2FrameWrite(uuid, new Error(reason)));
2286
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2243
2287
  Object.entries(transportCache).forEach(([uuid, cachedTransport]) => {
2244
2288
  var _a, _b, _c, _d;
2245
2289
  try {
@@ -2629,9 +2673,7 @@ class ReactNativeBleTransport {
2629
2673
  androidPacketLength: tuning.androidPacketLength,
2630
2674
  mtu: transport$1.mtuSize,
2631
2675
  });
2632
- const perf = context.messageName === 'FilesystemFileWrite'
2633
- ? this.protocolV2FileWritePerfs.get(uuid)
2634
- : undefined;
2676
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
2635
2677
  const startedAt = perf ? nowMs() : 0;
2636
2678
  const nativeFrameWriter = frame.length > packetCapacity
2637
2679
  ? this.resolveProtocolV2NativeFrameWriter(transport$1, context, tuning.nativeFrameWrite)
@@ -2659,7 +2701,7 @@ class ReactNativeBleTransport {
2659
2701
  });
2660
2702
  }
2661
2703
  resolveProtocolV2NativeFrameWriter(transport, context, nativeFrameWrite) {
2662
- if (!context.highThroughput || nativeFrameWrite === false)
2704
+ if (!context.highThroughput || !nativeFrameWrite)
2663
2705
  return undefined;
2664
2706
  if (shouldWriteProtocolV2WithResponse({
2665
2707
  platform: reactNative.Platform.OS,
@@ -2688,7 +2730,6 @@ class ReactNativeBleTransport {
2688
2730
  rejectCancelled = reject;
2689
2731
  });
2690
2732
  const active = {
2691
- transactionId,
2692
2733
  generation: context.generation,
2693
2734
  cancel: error => {
2694
2735
  if (cancelError)
@@ -2712,61 +2753,48 @@ class ReactNativeBleTransport {
2712
2753
  };
2713
2754
  const onAbort = () => active.cancel(new Error(abortMessage));
2714
2755
  let timer;
2715
- let completed = false;
2716
- let nativeError;
2717
2756
  try {
2718
2757
  const nativeWrite = Promise.resolve(manager.writeCharacteristicWithoutResponseFrame(transport.writeCharacteristic.id, buffer.Buffer.from(frame).toString('base64'), packetCapacity, transactionId));
2719
2758
  nativeWrite.catch(() => undefined);
2720
2759
  this.protocolV2FrameWrites.set(uuid, active);
2721
2760
  context.signal.addEventListener('abort', onAbort);
2722
- yield Promise.race([
2723
- nativeWrite,
2724
- cancelled,
2725
- new Promise((_, reject) => {
2726
- timer = setTimeout(() => {
2727
- const owner = isCurrentOwner();
2728
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`);
2729
- active.cancel(error);
2730
- reject(error);
2731
- if (owner) {
2732
- this.tearDownWedgedLink(uuid);
2733
- }
2734
- else {
2735
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
2736
- }
2737
- }, BLE_WRITE_PACKET_TIMEOUT_MS);
2738
- }),
2739
- ]);
2740
- completed = true;
2761
+ timer = setTimeout(() => {
2762
+ const owner = isCurrentOwner();
2763
+ active.cancel(createWedgedWriteError());
2764
+ if (owner) {
2765
+ this.tearDownWedgedLink(uuid);
2766
+ }
2767
+ else {
2768
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
2769
+ }
2770
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
2771
+ yield Promise.race([nativeWrite, cancelled]);
2741
2772
  }
2742
2773
  catch (error) {
2743
- nativeError = error;
2774
+ if (cancelError)
2775
+ throw cancelError;
2776
+ if (isNativeBleDisconnectError(error)) {
2777
+ throw toBleDisconnectHardwareError(error);
2778
+ }
2779
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, getNativeBleErrorReason(error));
2744
2780
  }
2745
2781
  finally {
2746
2782
  if (timer)
2747
2783
  clearTimeout(timer);
2748
2784
  context.signal.removeEventListener('abort', onAbort);
2749
- }
2750
- if (completed) {
2751
- this.writeTimeoutCounts.delete(uuid);
2752
- try {
2753
- assertCurrentGeneration();
2754
- }
2755
- catch (error) {
2756
- active.cancel(error instanceof Error ? error : new Error(String(error)));
2785
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
2786
+ this.protocolV2FrameWrites.delete(uuid);
2757
2787
  }
2758
2788
  }
2759
- if (this.protocolV2FrameWrites.get(uuid) === active) {
2760
- this.protocolV2FrameWrites.delete(uuid);
2789
+ this.writeTimeoutCounts.delete(uuid);
2790
+ try {
2791
+ assertCurrentGeneration();
2792
+ }
2793
+ catch (error) {
2794
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
2761
2795
  }
2762
2796
  if (cancelError)
2763
2797
  throw cancelError;
2764
- if (completed)
2765
- return;
2766
- if (isNativeBleDisconnectError(nativeError)) {
2767
- throw toBleDisconnectHardwareError(nativeError);
2768
- }
2769
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, getNativeBleErrorReason(nativeError));
2770
2798
  });
2771
2799
  }
2772
2800
  cancelProtocolV2FrameWrite(uuid, error, generation) {
@@ -2786,8 +2814,21 @@ class ReactNativeBleTransport {
2786
2814
  logFailure(error);
2787
2815
  }
2788
2816
  }
2789
- callProtocolV2(uuid, name, data, options) {
2817
+ getProtocolV2FileWritePerf(uuid, context) {
2818
+ return context.messageName === 'FilesystemFileWrite'
2819
+ ? this.protocolV2FileWritePerfs.get(uuid)
2820
+ : undefined;
2821
+ }
2822
+ markProtocolV2LogSignature(uuid, signature) {
2790
2823
  var _a;
2824
+ const signatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2825
+ if (signatures.has(signature))
2826
+ return false;
2827
+ signatures.add(signature);
2828
+ this.protocolV2HighVolumeLogSignatures.set(uuid, signatures);
2829
+ return true;
2830
+ }
2831
+ callProtocolV2(uuid, name, data, options) {
2791
2832
  return __awaiter(this, void 0, void 0, function* () {
2792
2833
  if (!this._messages || !this._messagesV2) {
2793
2834
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
@@ -2813,10 +2854,7 @@ class ReactNativeBleTransport {
2813
2854
  });
2814
2855
  const writeMode = writeWithResponse ? 'withResponse' : 'withoutResponse';
2815
2856
  const logSignature = `${name}:${writeMode}:${String(currentTransport.mtuSize)}:${packetCapacity}`;
2816
- const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2817
- if (!loggedSignatures.has(logSignature)) {
2818
- loggedSignatures.add(logSignature);
2819
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2857
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
2820
2858
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
2821
2859
  name,
2822
2860
  writeMode,
@@ -2827,10 +2865,7 @@ class ReactNativeBleTransport {
2827
2865
  const frameWriteMode = this.resolveProtocolV2NativeFrameWriter(currentTransport, { highThroughput: true, writeWithResponse: options === null || options === void 0 ? void 0 : options.writeWithResponse }, tuning.nativeFrameWrite)
2828
2866
  ? 'native-frame'
2829
2867
  : 'per-packet';
2830
- const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
2831
- if (!loggedSignatures.has(frameWriteModeSignature)) {
2832
- loggedSignatures.add(frameWriteModeSignature);
2833
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2868
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
2834
2869
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
2835
2870
  platform: reactNative.Platform.OS,
2836
2871
  mode: frameWriteMode,
@@ -2908,6 +2943,15 @@ class ReactNativeBleTransport {
2908
2943
  this.clearAndroidPriorityResetTimer(uuid);
2909
2944
  if (this.androidHighPriorityDevices.has(uuid))
2910
2945
  return;
2946
+ if (!shouldRequestAndroidHighConnectionPriority()) {
2947
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
2948
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
2949
+ apiLevel: reactNative.Platform.Version,
2950
+ setting: protocolV2BleTuning.androidHighConnectionPriority,
2951
+ });
2952
+ }
2953
+ return;
2954
+ }
2911
2955
  const transport = transportCache[uuid];
2912
2956
  if (!transport)
2913
2957
  return;
@@ -2979,9 +3023,7 @@ class ReactNativeBleTransport {
2979
3023
  }),
2980
3024
  readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
2981
3025
  assertCurrentGeneration();
2982
- const perf = (context === null || context === void 0 ? void 0 : context.messageName) === 'FilesystemFileWrite'
2983
- ? this.protocolV2FileWritePerfs.get(uuid)
2984
- : undefined;
3026
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
2985
3027
  const startedAt = perf ? nowMs() : 0;
2986
3028
  const rxFrame = yield this.readProtocolV2Frame(uuid);
2987
3029
  perf === null || perf === void 0 ? void 0 : perf.recordReadWait(nowMs() - startedAt);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-react-native",
3
- "version": "1.2.8-alpha.116",
3
+ "version": "1.2.8-alpha.118",
4
4
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -20,11 +20,11 @@
20
20
  "lint:fix": "eslint . --fix"
21
21
  },
22
22
  "dependencies": {
23
- "@onekeyfe/hd-core": "1.2.8-alpha.116",
24
- "@onekeyfe/hd-shared": "1.2.8-alpha.116",
25
- "@onekeyfe/hd-transport": "1.2.8-alpha.116",
23
+ "@onekeyfe/hd-core": "1.2.8-alpha.118",
24
+ "@onekeyfe/hd-shared": "1.2.8-alpha.118",
25
+ "@onekeyfe/hd-transport": "1.2.8-alpha.118",
26
26
  "@onekeyfe/react-native-ble-utils": "0.1.9",
27
27
  "react-native-ble-plx": "3.5.1"
28
28
  },
29
- "gitHead": "3278c53853e85c2b3dff67caf65fcc59481f28eb"
29
+ "gitHead": "7b5fe42a7c29ff0aa4c8340c1d5da93026a1b590"
30
30
  }
@@ -214,3 +214,142 @@ describe('ReactNativeBleTransport iOS discovery', () => {
214
214
  expect(devices.map(device => device.id)).toEqual(['wallet-peripheral']);
215
215
  });
216
216
  });
217
+
218
+ describe('ReactNativeBleTransport advertisement color', () => {
219
+ const PRO2_SERVICE_UUIDS = [
220
+ '0000180a-0000-1000-8000-00805f9b34fb',
221
+ '0000180f-0000-1000-8000-00805f9b34fb',
222
+ '0000fffd-0000-1000-8000-00805f9b34fb',
223
+ ONEKEY_SERVICE_UUID,
224
+ ];
225
+ const manufacturerData = (bytes: number[]) => Buffer.from(bytes).toString('base64');
226
+
227
+ const scanOnce = async (advertisements: Record<string, unknown>[]) => {
228
+ const blePlxManager = {
229
+ startDeviceScan: jest.fn((_serviceUUIDs, _options, listener) => {
230
+ queueMicrotask(() => {
231
+ advertisements.forEach(advertisement => listener(null, advertisement));
232
+ });
233
+ }),
234
+ stopDeviceScan: jest.fn(),
235
+ };
236
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
237
+ transport.blePlxManager = blePlxManager as never;
238
+ transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
239
+ return transport.enumerate();
240
+ };
241
+
242
+ beforeEach(() => {
243
+ jest.clearAllMocks();
244
+ jest.mocked(getConnectedDeviceIds).mockResolvedValue([]);
245
+ });
246
+
247
+ afterEach(() => {
248
+ Object.assign(Platform, { OS: 'ios', Version: undefined });
249
+ });
250
+
251
+ test('keeps the color from an unnamed iOS advertisement for the named device', async () => {
252
+ const devices = await scanOnce([
253
+ {
254
+ id: 'COLOR-UNNAMED',
255
+ name: null,
256
+ localName: null,
257
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
258
+ manufacturerData: manufacturerData([0x42, 0, 0, 0, 0]),
259
+ },
260
+ {
261
+ id: 'COLOR-UNNAMED',
262
+ name: 'Pro 2 769D',
263
+ localName: 'Pro 2 769D',
264
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
265
+ manufacturerData: null,
266
+ },
267
+ ]);
268
+
269
+ expect(devices).toHaveLength(1);
270
+ expect(devices[0]).toMatchObject({ id: 'COLOR-UNNAMED', bleColorCode: 'B' });
271
+ });
272
+
273
+ test('fills a later color without letting a legacy payload clear it', async () => {
274
+ Object.assign(Platform, { OS: 'android', Version: 30 });
275
+
276
+ const devices = await scanOnce([
277
+ {
278
+ id: 'AA:BB:CC:00:00:01',
279
+ name: 'Neo 1A2B',
280
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
281
+ manufacturerData: null,
282
+ },
283
+ {
284
+ id: 'AA:BB:CC:00:00:01',
285
+ name: 'Neo 1A2B',
286
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
287
+ manufacturerData: manufacturerData([0x45, 0, 0, 0, 0]),
288
+ },
289
+ {
290
+ id: 'AA:BB:CC:00:00:01',
291
+ name: 'Neo 1A2B',
292
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
293
+ manufacturerData: manufacturerData([0, 0, 0, 0]),
294
+ },
295
+ ]);
296
+
297
+ expect(devices).toHaveLength(1);
298
+ expect(devices[0]).toMatchObject({ id: 'AA:BB:CC:00:00:01', bleColorCode: 'E' });
299
+ });
300
+
301
+ test('reports no color for legacy, unset or undecodable payloads', async () => {
302
+ const devices = await scanOnce([
303
+ {
304
+ id: 'LEGACY-NONCE',
305
+ name: 'Pro 2 0001',
306
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
307
+ manufacturerData: manufacturerData([0, 0, 0, 0]),
308
+ },
309
+ {
310
+ id: 'SN-NOT-SYNCED',
311
+ name: 'Pro 2 0002',
312
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
313
+ manufacturerData: manufacturerData([0, 0, 0, 0, 0]),
314
+ },
315
+ {
316
+ id: 'INVALID-BASE64',
317
+ name: 'Pro 2 0003',
318
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
319
+ manufacturerData: '%%%',
320
+ },
321
+ ]);
322
+
323
+ expect(devices.map(device => device.id)).toEqual([
324
+ 'LEGACY-NONCE',
325
+ 'SN-NOT-SYNCED',
326
+ 'INVALID-BASE64',
327
+ ]);
328
+ devices.forEach(device => expect(device).not.toHaveProperty('bleColorCode'));
329
+ });
330
+
331
+ test('reuses an earlier color for a connected peripheral that no longer advertises', async () => {
332
+ await scanOnce([
333
+ {
334
+ id: 'CONNECTED-NEO',
335
+ name: 'Neo 3C4D',
336
+ serviceUUIDs: PRO2_SERVICE_UUIDS,
337
+ manufacturerData: manufacturerData([0x46, 0, 0, 0, 0]),
338
+ },
339
+ ]);
340
+ // iOS reports already-connected peripherals with lowercased ids.
341
+ jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([
342
+ {
343
+ id: 'connected-neo',
344
+ name: 'Neo 3C4D',
345
+ localName: null,
346
+ serviceUUIDs: [ONEKEY_SERVICE_UUID],
347
+ },
348
+ ] as never);
349
+
350
+ const devices = await scanOnce([]);
351
+
352
+ expect(devices).toHaveLength(1);
353
+ expect(devices[0]).toMatchObject({ id: 'connected-neo', bleColorCode: 'F' });
354
+ });
355
+ });
@@ -1,5 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import transportPackage, {
3
+ PROTOCOL_V2_BLE_FILE_CHUNK_SIZE,
3
4
  PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
4
5
  PROTOCOL_V2_CHANNEL_BLE_UART,
5
6
  ProtocolV2,
@@ -242,10 +243,16 @@ describe('Protocol V2 native frame write selection', () => {
242
243
  expect(manager.writeCharacteristicWithoutResponseFrame ?? jest.fn()).not.toHaveBeenCalled();
243
244
  });
244
245
 
245
- test('keeps the per-packet path when the native frame write tuning is off', async () => {
246
- configureProtocolV2BleTuning({ nativeFrameWrite: false });
246
+ test.each([
247
+ ['the native frame write tuning is off', { nativeFrameWrite: false }, 42],
248
+ ['the characteristic has no native identifier', {}, null],
249
+ ] as const)('keeps the per-packet path when %s', async (_label, tuning, characteristicId) => {
250
+ configureProtocolV2BleTuning(tuning);
247
251
  const manager = createFrameManager();
248
- const { transport, bleTransport, writeWithoutResponse } = createUnit({ manager });
252
+ const { transport, bleTransport, writeWithoutResponse } = createUnit({
253
+ manager,
254
+ characteristicId,
255
+ });
249
256
  const { context } = createContext();
250
257
 
251
258
  await transport.writeProtocolV2Frame('dev', bleTransport, createFrame(600), context, jest.fn());
@@ -277,20 +284,6 @@ describe('Protocol V2 native frame write selection', () => {
277
284
  expect(manager.writeCharacteristicWithoutResponseFrame).not.toHaveBeenCalled();
278
285
  }
279
286
  );
280
-
281
- test('keeps the per-packet path when the characteristic has no native identifier', async () => {
282
- const manager = createFrameManager();
283
- const { transport, bleTransport, writeWithoutResponse } = createUnit({
284
- manager,
285
- characteristicId: null,
286
- });
287
- const { context } = createContext();
288
-
289
- await transport.writeProtocolV2Frame('dev', bleTransport, createFrame(600), context, jest.fn());
290
-
291
- expect(writeWithoutResponse).toHaveBeenCalledTimes(3);
292
- expect(manager.writeCharacteristicWithoutResponseFrame).not.toHaveBeenCalled();
293
- });
294
287
  });
295
288
 
296
289
  describe('Protocol V2 native frame write failures', () => {
@@ -627,7 +620,7 @@ const schemas = {
627
620
  };
628
621
 
629
622
  const FILE_PATH = 'vol0:/test-app.bin';
630
- const CHUNK_BYTES = 1800;
623
+ const CHUNK_BYTES = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
631
624
 
632
625
  const fileChunks = (totalSize: number) => {
633
626
  const chunks: Record<string, unknown>[] = [];
@@ -12,6 +12,7 @@ import ReactNativeBleTransport, {
12
12
  BLE_WRITE_PACKET_TIMEOUT_MS,
13
13
  configureProtocolV2BleTuning,
14
14
  getFirmwareUploadWriteRetryType,
15
+ getProtocolV2BleTuning,
15
16
  resetProtocolV2BleTuning,
16
17
  } from '../index';
17
18
 
@@ -2090,6 +2091,101 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
2090
2091
  expect(device.requestConnectionPriority).toHaveBeenLastCalledWith(0);
2091
2092
  });
2092
2093
 
2094
+ describe('Android connection priority by API level', () => {
2095
+ const setPlatformVersion = (version: number | undefined) => {
2096
+ const reactNative: { Platform: { Version?: number } } = jest.requireMock('react-native');
2097
+ reactNative.Platform.Version = version;
2098
+ };
2099
+
2100
+ afterEach(() => {
2101
+ setPlatformVersion(undefined);
2102
+ });
2103
+
2104
+ const runHighVolumeCalls = async (harness: ReturnType<typeof createHarness>) => {
2105
+ await harness.transport.acquire({ uuid: harness.uuid, expectedProtocol: 'V2' });
2106
+ await harness.transport.call(harness.uuid, 'FileWrite', {});
2107
+ await harness.transport.call(harness.uuid, 'FileWrite', {});
2108
+ };
2109
+
2110
+ const createAndroidHarness = (apiLevel: number) => {
2111
+ setPlatformOS('android');
2112
+ setPlatformVersion(apiLevel);
2113
+ const harness = createHarness();
2114
+ harness.device.mtu = 517;
2115
+ return harness;
2116
+ };
2117
+
2118
+ test('leaves the priority to the peripheral on Android 17 by default', async () => {
2119
+ const harness = createAndroidHarness(37);
2120
+
2121
+ await runHighVolumeCalls(harness);
2122
+ await harness.transport.release(harness.uuid, true);
2123
+
2124
+ expect(harness.device.requestConnectionPriority).not.toHaveBeenCalled();
2125
+ expect(
2126
+ harness.logger.debug.mock.calls.filter(
2127
+ ([message]) =>
2128
+ message ===
2129
+ '[ReactNativeBleTransport] Android BLE connection priority left to peripheral'
2130
+ )
2131
+ ).toHaveLength(1);
2132
+ });
2133
+
2134
+ test('keeps requesting HIGH below Android 17 by default', async () => {
2135
+ const harness = createAndroidHarness(36);
2136
+
2137
+ await runHighVolumeCalls(harness);
2138
+ expect(harness.device.requestConnectionPriority).toHaveBeenCalledTimes(1);
2139
+ expect(harness.device.requestConnectionPriority).toHaveBeenCalledWith(1);
2140
+
2141
+ await harness.transport.release(harness.uuid, true);
2142
+ expect(harness.device.requestConnectionPriority).toHaveBeenLastCalledWith(0);
2143
+ });
2144
+
2145
+ test.each([
2146
+ [37, true],
2147
+ [36, false],
2148
+ ] as const)('applies the tuning switch on API %s when set to %s', async (apiLevel, setting) => {
2149
+ configureProtocolV2BleTuning({ androidHighConnectionPriority: setting });
2150
+ const harness = createAndroidHarness(apiLevel);
2151
+
2152
+ await runHighVolumeCalls(harness);
2153
+
2154
+ if (setting) {
2155
+ expect(harness.device.requestConnectionPriority).toHaveBeenCalledWith(1);
2156
+ } else {
2157
+ expect(harness.device.requestConnectionPriority).not.toHaveBeenCalled();
2158
+ }
2159
+ await harness.transport.release(harness.uuid, true);
2160
+ });
2161
+
2162
+ test('keeps the switch across unrelated tuning and ignores invalid values', () => {
2163
+ expect(getProtocolV2BleTuning().androidHighConnectionPriority).toBe('auto');
2164
+ configureProtocolV2BleTuning({ androidHighConnectionPriority: false });
2165
+ configureProtocolV2BleTuning({ androidPacketLength: 200 });
2166
+ expect(getProtocolV2BleTuning().androidHighConnectionPriority).toBe(false);
2167
+ configureProtocolV2BleTuning({ androidHighConnectionPriority: 'on' as never });
2168
+ expect(getProtocolV2BleTuning().androidHighConnectionPriority).toBe(false);
2169
+ configureProtocolV2BleTuning({ androidHighConnectionPriority: 'auto' });
2170
+ expect(getProtocolV2BleTuning().androidHighConnectionPriority).toBe('auto');
2171
+ });
2172
+
2173
+ test('requests HIGH again on the next link after a manual disconnect', async () => {
2174
+ const harness = createAndroidHarness(36);
2175
+
2176
+ await runHighVolumeCalls(harness);
2177
+ expect(harness.device.requestConnectionPriority).toHaveBeenCalledTimes(1);
2178
+
2179
+ await harness.transport.disconnect(harness.uuid);
2180
+ await runHighVolumeCalls(harness);
2181
+
2182
+ expect(
2183
+ harness.device.requestConnectionPriority.mock.calls.filter(([priority]) => priority === 1)
2184
+ ).toHaveLength(2);
2185
+ await harness.transport.release(harness.uuid, true);
2186
+ });
2187
+ });
2188
+
2093
2189
  test('uses withResponse for an iOS Protocol V2 firmware file write when requested', async () => {
2094
2190
  const { transport, uuid, writeCharacteristic } = createHarness();
2095
2191
 
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  import ByteBuffer from 'bytebuffer';
11
11
  import transport, {
12
12
  type OneKeyDeviceInfoBase,
13
+ type OneKeyMobileDeviceInfo,
13
14
  PROTOCOL_V1_MESSAGE_HEADER_SIZE,
14
15
  PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
15
16
  PROTOCOL_V2_CHANNEL_BLE_UART,
@@ -28,6 +29,7 @@ import {
28
29
  HardwareErrorCode,
29
30
  createDeferred,
30
31
  isOnekeyBluetoothDevice,
32
+ parseOnekeyBleColorCode,
31
33
  } from '@onekeyfe/hd-shared';
32
34
 
33
35
  import { getConnectedDeviceIds, onDeviceBondState, pairDevice } from './BleManager';
@@ -166,6 +168,11 @@ const isWedgedWriteError = (error: unknown): boolean =>
166
168
  (error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
167
169
  typeof (error as { message?: unknown })?.message === 'string' &&
168
170
  (error as { message: string }).message.startsWith(WEDGED_WRITE_MESSAGE);
171
+ const createWedgedWriteError = () =>
172
+ ERRORS.TypedError(
173
+ HardwareErrorCode.BleWriteCharacteristicError,
174
+ `${WEDGED_WRITE_MESSAGE} ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
175
+ );
169
176
  const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
170
177
  const code = (error as { errorCode?: unknown })?.errorCode;
171
178
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
@@ -195,6 +202,11 @@ export type ProtocolV2BleTuning = {
195
202
  * BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
196
203
  */
197
204
  nativeFrameWrite?: boolean;
205
+ /**
206
+ * Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
207
+ * default) requests it below Android 17 only; true or false forces it on every version.
208
+ */
209
+ androidHighConnectionPriority?: boolean | 'auto';
198
210
  };
199
211
 
200
212
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -203,6 +215,7 @@ const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
203
215
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
204
216
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
205
217
  nativeFrameWrite: true,
218
+ androidHighConnectionPriority: 'auto',
206
219
  };
207
220
 
208
221
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -227,6 +240,11 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
227
240
  typeof tuning.nativeFrameWrite === 'boolean'
228
241
  ? tuning.nativeFrameWrite
229
242
  : protocolV2BleTuning.nativeFrameWrite,
243
+ androidHighConnectionPriority:
244
+ typeof tuning.androidHighConnectionPriority === 'boolean' ||
245
+ tuning.androidHighConnectionPriority === 'auto'
246
+ ? tuning.androidHighConnectionPriority
247
+ : protocolV2BleTuning.androidHighConnectionPriority,
230
248
  };
231
249
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
232
250
  }
@@ -257,7 +275,6 @@ type ProtocolV2NativeFrameWriteExtension = {
257
275
  type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
258
276
 
259
277
  type ActiveProtocolV2FrameWrite = {
260
- transactionId: string;
261
278
  generation: number;
262
279
  cancel: (error: Error) => void;
263
280
  };
@@ -328,7 +345,10 @@ const createProtocolV2FileWritePerf = () => {
328
345
  const write = createDurationStats();
329
346
  const readWait = createDurationStats();
330
347
  const packet = createDurationStats();
331
- const packetHistogram = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.map(() => 0).concat(0);
348
+ const packetHistogram = Array.from(
349
+ { length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 },
350
+ () => 0
351
+ );
332
352
 
333
353
  return {
334
354
  /** Called before each frame write so a frame that fails still reports its mode. */
@@ -344,7 +364,7 @@ const createProtocolV2FileWritePerf = () => {
344
364
  recordPacket(elapsedMs: number) {
345
365
  packet.add(elapsedMs);
346
366
  const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
347
- packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
367
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
348
368
  },
349
369
  recordReadWait(elapsedMs: number) {
350
370
  readWait.add(elapsedMs);
@@ -376,9 +396,55 @@ function getDeviceDisplayName(device?: Device | null) {
376
396
  return device?.name || device?.localName || null;
377
397
  }
378
398
 
399
+ // The color is only in the primary advertisement, and the name only in the scan
400
+ // response, so the callback a scan keeps may not carry it. A connected device stops
401
+ // advertising. Keep the last valid color per device for the life of the process.
402
+ // iOS reports connected peripherals with lowercased ids, so key case-insensitively.
403
+ const bleColorCodesById = new Map<string, string>();
404
+
405
+ function getManufacturerDataLength(device?: Device | null) {
406
+ return device?.manufacturerData ? Buffer.from(device.manufacturerData, 'base64').length : 0;
407
+ }
408
+
409
+ function rememberBleColorCode(device?: Device | null) {
410
+ if (!device?.id || !device.manufacturerData) return;
411
+ const colorCode = parseOnekeyBleColorCode(Buffer.from(device.manufacturerData, 'base64'));
412
+ const key = device.id.toLowerCase();
413
+ if (colorCode && bleColorCodesById.get(key) !== colorCode) {
414
+ bleColorCodesById.set(key, colorCode);
415
+ Log?.debug('[ReactNativeBleTransport] BLE color code', {
416
+ deviceId: device.id,
417
+ bleColorCode: colorCode,
418
+ });
419
+ }
420
+ }
421
+
422
+ function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
423
+ const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
424
+ return bleColorCode ? ({ ...device, bleColorCode } as IOneKeyDevice) : device;
425
+ }
426
+
379
427
  const IOS_REQUEST_MTU = 247;
380
428
  const ANDROID_REQUEST_MTU = 517;
381
429
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
430
+ /**
431
+ * Android 17 maps CONNECTION_PRIORITY_HIGH to 11.25-15 ms with peripheral latency 1. OneKey BLE
432
+ * firmware accepts any latency at its 15 ms interval, and latency 1 roughly halves Protocol V2
433
+ * FileWrite throughput. BLE 1.0.23 requests 15 ms with latency 0 by itself; older BLE firmware
434
+ * asks for 15-30 ms or nothing and has not been measured on Android 17 without HIGH.
435
+ */
436
+ const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
437
+
438
+ const shouldRequestAndroidHighConnectionPriority = () => {
439
+ if (Platform.OS !== 'android') return false;
440
+ const { androidHighConnectionPriority } = protocolV2BleTuning;
441
+ if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
442
+ const apiLevel = Number(Platform.Version);
443
+ // Unknown versions keep the long-standing HIGH request.
444
+ return (
445
+ !Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
446
+ );
447
+ };
382
448
 
383
449
  const getRequestedBleMtu = () =>
384
450
  Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
@@ -498,7 +564,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
498
564
 
499
565
  type NegotiatedMtuResult = { device: Device; timedOut: boolean };
500
566
 
501
- export type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
567
+ export type IOneKeyDevice = OneKeyDeviceInfoBase &
568
+ Device &
569
+ Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
502
570
 
503
571
  const tryToGetConfiguration = (device: Device) => {
504
572
  if (!device || !device.serviceUUIDs) return null;
@@ -1004,7 +1072,7 @@ export default class ReactNativeBleTransport {
1004
1072
  }).then(() => {
1005
1073
  this.scanCleanups.delete(cancelScan);
1006
1074
  if (error) reject(error);
1007
- else resolve(deviceList);
1075
+ else resolve(deviceList.map(withBleColorCode));
1008
1076
  });
1009
1077
  return scanCleanup;
1010
1078
  };
@@ -1049,6 +1117,9 @@ export default class ReactNativeBleTransport {
1049
1117
  return;
1050
1118
  }
1051
1119
 
1120
+ // The native scan is filtered to the OneKey communication service, so an
1121
+ // unnamed iOS advertisement rejected below can still carry the color.
1122
+ rememberBleColorCode(device);
1052
1123
  const displayName = getDeviceDisplayName(device);
1053
1124
  // iOS may report a service-only advertisement before the named scan response.
1054
1125
  // Do not cache that incomplete advertisement as an unknown device.
@@ -1114,6 +1185,9 @@ export default class ReactNativeBleTransport {
1114
1185
  deviceId: device.id,
1115
1186
  name: displayName,
1116
1187
  serviceUUIDs: device.serviceUUIDs,
1188
+ // 5 = advertises a color slot; 4 = BLE firmware before 1.0.23.
1189
+ manufacturerDataLength: getManufacturerDataLength(device),
1190
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
1117
1191
  });
1118
1192
  }
1119
1193
  };
@@ -1678,8 +1752,9 @@ export default class ReactNativeBleTransport {
1678
1752
  }
1679
1753
 
1680
1754
  private async releaseUnlocked(uuid: string, onclose = false) {
1681
- this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1682
- await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1755
+ const reason = 'React Native BLE transport released';
1756
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
1757
+ await this.protocolV2Links.invalidateLink(uuid, reason);
1683
1758
  return this.releaseNative(uuid, onclose);
1684
1759
  }
1685
1760
 
@@ -2105,8 +2180,13 @@ export default class ReactNativeBleTransport {
2105
2180
  }
2106
2181
 
2107
2182
  private async disconnectUnlocked(session: string) {
2108
- this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
2109
- await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
2183
+ // The next link starts at the stack's default priority; a cached HIGH or a pending
2184
+ // Balanced restore from this link must not carry over to it.
2185
+ this.clearAndroidPriorityResetTimer(session);
2186
+ this.androidHighPriorityDevices.delete(session);
2187
+ const reason = 'React Native BLE transport disconnected';
2188
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
2189
+ await this.protocolV2Links.invalidateLink(session, reason);
2110
2190
  const transport = transportCache[session];
2111
2191
  const manager = this.blePlxManager;
2112
2192
  const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
@@ -2544,12 +2624,7 @@ export default class ReactNativeBleTransport {
2544
2624
  new Promise<never>((_, reject) => {
2545
2625
  timer = setTimeout(() => {
2546
2626
  timedOut = true;
2547
- reject(
2548
- ERRORS.TypedError(
2549
- HardwareErrorCode.BleWriteCharacteristicError,
2550
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2551
- )
2552
- );
2627
+ reject(createWedgedWriteError());
2553
2628
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2554
2629
  }),
2555
2630
  ]);
@@ -2583,13 +2658,7 @@ export default class ReactNativeBleTransport {
2583
2658
  consecutiveWriteTimeouts: timeouts,
2584
2659
  });
2585
2660
 
2586
- this.cancelProtocolV2FrameWrite(
2587
- uuid,
2588
- ERRORS.TypedError(
2589
- HardwareErrorCode.BleWriteCharacteristicError,
2590
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2591
- )
2592
- );
2661
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2593
2662
  const wedged = transportCache[uuid];
2594
2663
  this.disconnect(uuid).catch(error => {
2595
2664
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2618,9 +2687,7 @@ export default class ReactNativeBleTransport {
2618
2687
  this.blePlxManager = undefined;
2619
2688
  const reason = 'React Native BLE manager reset';
2620
2689
  // Cancel through the manager that started each frame before destroy() drops its queue.
2621
- Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid =>
2622
- this.cancelProtocolV2FrameWrite(uuid, new Error(reason))
2623
- );
2690
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2624
2691
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2625
2692
  // each cached session before clearing generations so Core cannot retain a
2626
2693
  // silently stale connection for an unrelated device.
@@ -3092,10 +3159,7 @@ export default class ReactNativeBleTransport {
3092
3159
  androidPacketLength: tuning.androidPacketLength,
3093
3160
  mtu: transport.mtuSize,
3094
3161
  });
3095
- const perf =
3096
- context.messageName === 'FilesystemFileWrite'
3097
- ? this.protocolV2FileWritePerfs.get(uuid)
3098
- : undefined;
3162
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3099
3163
  const startedAt = perf ? nowMs() : 0;
3100
3164
  const nativeFrameWriter =
3101
3165
  frame.length > packetCapacity
@@ -3145,7 +3209,7 @@ export default class ReactNativeBleTransport {
3145
3209
  context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
3146
3210
  nativeFrameWrite: boolean
3147
3211
  ): ProtocolV2NativeFrameWriter | undefined {
3148
- if (!context.highThroughput || nativeFrameWrite === false) return undefined;
3212
+ if (!context.highThroughput || !nativeFrameWrite) return undefined;
3149
3213
  if (
3150
3214
  shouldWriteProtocolV2WithResponse({
3151
3215
  platform: Platform.OS,
@@ -3163,8 +3227,9 @@ export default class ReactNativeBleTransport {
3163
3227
  /**
3164
3228
  * Writes one frame with a single native call that sends its packets in order without response.
3165
3229
  * Nothing here retries it: a resend could duplicate bytes the device already received. The
3166
- * native transaction is cancelled on abort, watchdog expiry, generation change and link
3167
- * teardown so the native side stops writing a frame nobody waits for any more.
3230
+ * native transaction is cancelled on abort, watchdog expiry and link teardown so the native
3231
+ * side stops writing a frame nobody waits for any more; a generation change detected after
3232
+ * the frame completes still fails the write.
3168
3233
  */
3169
3234
  private async writeProtocolV2NativeFrame(
3170
3235
  uuid: string,
@@ -3189,7 +3254,6 @@ export default class ReactNativeBleTransport {
3189
3254
  rejectCancelled = reject;
3190
3255
  });
3191
3256
  const active: ActiveProtocolV2FrameWrite = {
3192
- transactionId,
3193
3257
  generation: context.generation,
3194
3258
  cancel: error => {
3195
3259
  if (cancelError) return;
@@ -3212,8 +3276,6 @@ export default class ReactNativeBleTransport {
3212
3276
  };
3213
3277
  const onAbort = () => active.cancel(new Error(abortMessage));
3214
3278
  let timer: ReturnType<typeof setTimeout> | undefined;
3215
- let completed = false;
3216
- let nativeError: unknown;
3217
3279
  try {
3218
3280
  const nativeWrite = Promise.resolve(
3219
3281
  manager.writeCharacteristicWithoutResponseFrame(
@@ -3227,54 +3289,40 @@ export default class ReactNativeBleTransport {
3227
3289
  nativeWrite.catch(() => undefined);
3228
3290
  this.protocolV2FrameWrites.set(uuid, active);
3229
3291
  context.signal.addEventListener('abort', onAbort);
3230
- await Promise.race([
3231
- nativeWrite,
3232
- cancelled,
3233
- new Promise<never>((_, reject) => {
3234
- timer = setTimeout(() => {
3235
- const owner = isCurrentOwner();
3236
- const error = ERRORS.TypedError(
3237
- HardwareErrorCode.BleWriteCharacteristicError,
3238
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
3239
- );
3240
- active.cancel(error);
3241
- reject(error);
3242
- if (owner) {
3243
- this.tearDownWedgedLink(uuid);
3244
- } else {
3245
- Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3246
- }
3247
- }, BLE_WRITE_PACKET_TIMEOUT_MS);
3248
- }),
3249
- ]);
3250
- completed = true;
3292
+ timer = setTimeout(() => {
3293
+ const owner = isCurrentOwner();
3294
+ active.cancel(createWedgedWriteError());
3295
+ if (owner) {
3296
+ this.tearDownWedgedLink(uuid);
3297
+ } else {
3298
+ Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3299
+ }
3300
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
3301
+ await Promise.race([nativeWrite, cancelled]);
3251
3302
  } catch (error) {
3252
- nativeError = error;
3303
+ if (cancelError) throw cancelError;
3304
+ if (isNativeBleDisconnectError(error)) {
3305
+ throw toBleDisconnectHardwareError(error);
3306
+ }
3307
+ throw ERRORS.TypedError(
3308
+ HardwareErrorCode.BleWriteCharacteristicError,
3309
+ getNativeBleErrorReason(error)
3310
+ );
3253
3311
  } finally {
3254
3312
  if (timer) clearTimeout(timer);
3255
3313
  context.signal.removeEventListener('abort', onAbort);
3256
- }
3257
-
3258
- if (completed) {
3259
- this.writeTimeoutCounts.delete(uuid);
3260
- try {
3261
- assertCurrentGeneration();
3262
- } catch (error) {
3263
- active.cancel(error instanceof Error ? error : new Error(String(error)));
3314
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3315
+ this.protocolV2FrameWrites.delete(uuid);
3264
3316
  }
3265
3317
  }
3266
- if (this.protocolV2FrameWrites.get(uuid) === active) {
3267
- this.protocolV2FrameWrites.delete(uuid);
3318
+
3319
+ this.writeTimeoutCounts.delete(uuid);
3320
+ try {
3321
+ assertCurrentGeneration();
3322
+ } catch (error) {
3323
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
3268
3324
  }
3269
3325
  if (cancelError) throw cancelError;
3270
- if (completed) return;
3271
- if (isNativeBleDisconnectError(nativeError)) {
3272
- throw toBleDisconnectHardwareError(nativeError);
3273
- }
3274
- throw ERRORS.TypedError(
3275
- HardwareErrorCode.BleWriteCharacteristicError,
3276
- getNativeBleErrorReason(nativeError)
3277
- );
3278
3326
  }
3279
3327
 
3280
3328
  /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
@@ -3296,6 +3344,21 @@ export default class ReactNativeBleTransport {
3296
3344
  }
3297
3345
  }
3298
3346
 
3347
+ private getProtocolV2FileWritePerf(uuid: string, context: ProtocolV2CallContext) {
3348
+ return context.messageName === 'FilesystemFileWrite'
3349
+ ? this.protocolV2FileWritePerfs.get(uuid)
3350
+ : undefined;
3351
+ }
3352
+
3353
+ /** Returns true the first time `signature` is seen for `uuid` on this link. */
3354
+ private markProtocolV2LogSignature(uuid: string, signature: string): boolean {
3355
+ const signatures = this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3356
+ if (signatures.has(signature)) return false;
3357
+ signatures.add(signature);
3358
+ this.protocolV2HighVolumeLogSignatures.set(uuid, signatures);
3359
+ return true;
3360
+ }
3361
+
3299
3362
  private async callProtocolV2(
3300
3363
  uuid: string,
3301
3364
  name: string,
@@ -3330,11 +3393,7 @@ export default class ReactNativeBleTransport {
3330
3393
  const logSignature = `${name}:${writeMode}:${String(
3331
3394
  currentTransport.mtuSize
3332
3395
  )}:${packetCapacity}`;
3333
- const loggedSignatures =
3334
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3335
- if (!loggedSignatures.has(logSignature)) {
3336
- loggedSignatures.add(logSignature);
3337
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3396
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
3338
3397
  Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
3339
3398
  name,
3340
3399
  writeMode,
@@ -3349,10 +3408,7 @@ export default class ReactNativeBleTransport {
3349
3408
  )
3350
3409
  ? 'native-frame'
3351
3410
  : 'per-packet';
3352
- const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
3353
- if (!loggedSignatures.has(frameWriteModeSignature)) {
3354
- loggedSignatures.add(frameWriteModeSignature);
3355
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3411
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
3356
3412
  Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
3357
3413
  platform: Platform.OS,
3358
3414
  mode: frameWriteMode,
@@ -3453,6 +3509,15 @@ export default class ReactNativeBleTransport {
3453
3509
 
3454
3510
  this.clearAndroidPriorityResetTimer(uuid);
3455
3511
  if (this.androidHighPriorityDevices.has(uuid)) return;
3512
+ if (!shouldRequestAndroidHighConnectionPriority()) {
3513
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
3514
+ Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
3515
+ apiLevel: Platform.Version,
3516
+ setting: protocolV2BleTuning.androidHighConnectionPriority,
3517
+ });
3518
+ }
3519
+ return;
3520
+ }
3456
3521
 
3457
3522
  const transport = transportCache[uuid];
3458
3523
  if (!transport) return;
@@ -3531,12 +3596,9 @@ export default class ReactNativeBleTransport {
3531
3596
  assertCurrentGeneration
3532
3597
  );
3533
3598
  },
3534
- readFrame: async (context?: ProtocolV2CallContext) => {
3599
+ readFrame: async (context: ProtocolV2CallContext) => {
3535
3600
  assertCurrentGeneration();
3536
- const perf =
3537
- context?.messageName === 'FilesystemFileWrite'
3538
- ? this.protocolV2FileWritePerfs.get(uuid)
3539
- : undefined;
3601
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3540
3602
  const startedAt = perf ? nowMs() : 0;
3541
3603
  const rxFrame = await this.readProtocolV2Frame(uuid);
3542
3604
  perf?.recordReadWait(nowMs() - startedAt);