@onekeyfe/hd-transport-react-native 1.2.8-alpha.117 → 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';
@@ -122,7 +122,7 @@ declare const PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = 3;
122
122
  /** BLE setup timeouts since the last successful setup before the manager is recreated. */
123
123
  declare const BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
124
124
  declare const BLE_SETUP_WEDGED_MESSAGE = "BLE setup wedged repeatedly";
125
- type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
125
+ type IOneKeyDevice = OneKeyDeviceInfoBase & Device & Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
126
126
  declare class ReactNativeBleTransport {
127
127
  blePlxManager: BleManager | undefined;
128
128
  _messages: ReturnType<typeof transport__default.parseConfigure> | undefined;
@@ -283,13 +283,17 @@ declare class ReactNativeBleTransport {
283
283
  /**
284
284
  * Writes one frame with a single native call that sends its packets in order without response.
285
285
  * Nothing here retries it: a resend could duplicate bytes the device already received. The
286
- * native transaction is cancelled on abort, watchdog expiry, generation change and link
287
- * 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.
288
289
  */
289
290
  private writeProtocolV2NativeFrame;
290
291
  /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
291
292
  private cancelProtocolV2FrameWrite;
292
293
  private cancelNativeTransaction;
294
+ private getProtocolV2FileWritePerf;
295
+ /** Returns true the first time `signature` is seen for `uuid` on this link. */
296
+ private markProtocolV2LogSignature;
293
297
  private callProtocolV2;
294
298
  private ensureProtocolV2HighThroughputMtu;
295
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,sBAAsB,CAAC;AACjF,OAAO,KAAK,YAAY,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEjE,KAAK,8BAA8B,GAAG,eAAe,GAAG;IAMtD,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B,CAAC;AAkBF,KAAK,4BAA4B,GAAG,WAAW,CAAC;AAChD,KAAK,0BAA0B,GAAG;IAChC,mBAAmB,EAAE,cAAc,CAAC;IACpC,oBAAoB,EAAE,cAAc,CAAC;CACtC,CAAC;AAkCF,eAAO,MAAM,+BAA+B,UACnC,OAAO,KACb,4BAA4B,GAAG,IAsBjC,CAAC;AAcF,eAAO,MAAM,2BAA2B,QAAS,CAAC;AAClD,eAAO,MAAM,8BAA8B,OAAQ,CAAC;AAuBpD,eAAO,MAAM,yCAAyC,IAAI,CAAC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oB7B,MAAM;YAoBE,mBAAmB;YA4DnB,eAAe;YA6Bf,kBAAkB;YAkDlB,iCAAiC;IA8D/C,OAAO,CAAC,wBAAwB;IAwChC,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,kBAAkB;YAcZ,cAAc;IAyC5B,OAAO,CAAC,kBAAkB;IA8B1B,OAAO,CAAC,eAAe;IAkEvB,OAAO,CAAC,2BAA2B;IAQnC,OAAO,CAAC,4BAA4B;IAIpC,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,iBAAiB;YAIX,cAAc;YA+Gd,0BAA0B;YAsB1B,iCAAiC;YAoDjC,eAAe;YAsBf,eAAe;IA2B7B,OAAO,CAAC,4BAA4B;IA2BpC,OAAO,CAAC,uBAAuB;IAS/B,OAAO,CAAC,sBAAsB;IAU9B,OAAO,CAAC,qBAAqB;IAI7B,OAAO,CAAC,sBAAsB;YAShB,mBAAmB;YAiBnB,qBAAqB;YA8DrB,oBAAoB;IA2DlC,OAAO,CAAC,kCAAkC;YA2B5B,0BAA0B;IA+FxC,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,uBAAuB;IAY/B,OAAO,CAAC,0BAA0B;IAOlC,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) ||
@@ -483,7 +484,7 @@ const createProtocolV2FileWritePerf = () => {
483
484
  const write = createDurationStats();
484
485
  const readWait = createDurationStats();
485
486
  const packet = createDurationStats();
486
- 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);
487
488
  return {
488
489
  startFrame(mode) {
489
490
  if (mode === 'native-frame')
@@ -498,7 +499,7 @@ const createProtocolV2FileWritePerf = () => {
498
499
  recordPacket(elapsedMs) {
499
500
  packet.add(elapsedMs);
500
501
  const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
501
- packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
502
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
502
503
  },
503
504
  recordReadWait(elapsedMs) {
504
505
  readWait.add(elapsedMs);
@@ -519,6 +520,27 @@ const createProtocolV2FileWritePerf = () => {
519
520
  function getDeviceDisplayName(device) {
520
521
  return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
521
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
+ }
522
544
  const IOS_REQUEST_MTU = 247;
523
545
  const ANDROID_REQUEST_MTU = 517;
524
546
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
@@ -530,7 +552,7 @@ const shouldRequestAndroidHighConnectionPriority = () => {
530
552
  if (typeof androidHighConnectionPriority === 'boolean')
531
553
  return androidHighConnectionPriority;
532
554
  const apiLevel = Number(reactNative.Platform.Version);
533
- return !(Number.isFinite(apiLevel) && apiLevel >= ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL);
555
+ return (!Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL);
534
556
  };
535
557
  const getRequestedBleMtu = () => reactNative.Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
536
558
  const BLE_NATIVE_CONNECT_TIMEOUT_MS = 3000;
@@ -988,7 +1010,7 @@ class ReactNativeBleTransport {
988
1010
  if (error)
989
1011
  reject(error);
990
1012
  else
991
- resolve(deviceList);
1013
+ resolve(deviceList.map(withBleColorCode));
992
1014
  });
993
1015
  return scanCleanup;
994
1016
  };
@@ -1028,6 +1050,7 @@ class ReactNativeBleTransport {
1028
1050
  }
1029
1051
  return;
1030
1052
  }
1053
+ rememberBleColorCode(device);
1031
1054
  const displayName = getDeviceDisplayName(device);
1032
1055
  const isUnnamedIOSPeripheral = reactNative.Platform.OS === 'ios' && !(displayName === null || displayName === void 0 ? void 0 : displayName.trim());
1033
1056
  const isOneKey = !isUnnamedIOSPeripheral &&
@@ -1077,6 +1100,8 @@ class ReactNativeBleTransport {
1077
1100
  deviceId: device.id,
1078
1101
  name: displayName,
1079
1102
  serviceUUIDs: device.serviceUUIDs,
1103
+ manufacturerDataLength: getManufacturerDataLength(device),
1104
+ bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
1080
1105
  });
1081
1106
  }
1082
1107
  };
@@ -1525,8 +1550,9 @@ class ReactNativeBleTransport {
1525
1550
  }
1526
1551
  releaseUnlocked(uuid, onclose = false) {
1527
1552
  return __awaiter(this, void 0, void 0, function* () {
1528
- this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1529
- 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);
1530
1556
  return this.releaseNative(uuid, onclose);
1531
1557
  });
1532
1558
  }
@@ -1862,8 +1888,9 @@ class ReactNativeBleTransport {
1862
1888
  return __awaiter(this, void 0, void 0, function* () {
1863
1889
  this.clearAndroidPriorityResetTimer(session);
1864
1890
  this.androidHighPriorityDevices.delete(session);
1865
- this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
1866
- yield this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1891
+ const reason = 'React Native BLE transport disconnected';
1892
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
1893
+ yield this.protocolV2Links.invalidateLink(session, reason);
1867
1894
  const transport = transportCache[session];
1868
1895
  const manager = this.blePlxManager;
1869
1896
  const monitorToken = (_a = transport === null || transport === void 0 ? void 0 : transport.monitorToken) !== null && _a !== void 0 ? _a : this.monitorTokens.get(session);
@@ -2202,7 +2229,7 @@ class ReactNativeBleTransport {
2202
2229
  new Promise((_, reject) => {
2203
2230
  timer = setTimeout(() => {
2204
2231
  timedOut = true;
2205
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2232
+ reject(createWedgedWriteError());
2206
2233
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2207
2234
  }),
2208
2235
  ]);
@@ -2232,7 +2259,7 @@ class ReactNativeBleTransport {
2232
2259
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE write timed out, tearing down link:', uuid, {
2233
2260
  consecutiveWriteTimeouts: timeouts,
2234
2261
  });
2235
- this.cancelProtocolV2FrameWrite(uuid, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
2262
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2236
2263
  const wedged = transportCache[uuid];
2237
2264
  this.disconnect(uuid).catch(error => {
2238
2265
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2256,7 +2283,7 @@ class ReactNativeBleTransport {
2256
2283
  const manager = this.blePlxManager;
2257
2284
  this.blePlxManager = undefined;
2258
2285
  const reason = 'React Native BLE manager reset';
2259
- Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid => this.cancelProtocolV2FrameWrite(uuid, new Error(reason)));
2286
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2260
2287
  Object.entries(transportCache).forEach(([uuid, cachedTransport]) => {
2261
2288
  var _a, _b, _c, _d;
2262
2289
  try {
@@ -2646,9 +2673,7 @@ class ReactNativeBleTransport {
2646
2673
  androidPacketLength: tuning.androidPacketLength,
2647
2674
  mtu: transport$1.mtuSize,
2648
2675
  });
2649
- const perf = context.messageName === 'FilesystemFileWrite'
2650
- ? this.protocolV2FileWritePerfs.get(uuid)
2651
- : undefined;
2676
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
2652
2677
  const startedAt = perf ? nowMs() : 0;
2653
2678
  const nativeFrameWriter = frame.length > packetCapacity
2654
2679
  ? this.resolveProtocolV2NativeFrameWriter(transport$1, context, tuning.nativeFrameWrite)
@@ -2676,7 +2701,7 @@ class ReactNativeBleTransport {
2676
2701
  });
2677
2702
  }
2678
2703
  resolveProtocolV2NativeFrameWriter(transport, context, nativeFrameWrite) {
2679
- if (!context.highThroughput || nativeFrameWrite === false)
2704
+ if (!context.highThroughput || !nativeFrameWrite)
2680
2705
  return undefined;
2681
2706
  if (shouldWriteProtocolV2WithResponse({
2682
2707
  platform: reactNative.Platform.OS,
@@ -2705,7 +2730,6 @@ class ReactNativeBleTransport {
2705
2730
  rejectCancelled = reject;
2706
2731
  });
2707
2732
  const active = {
2708
- transactionId,
2709
2733
  generation: context.generation,
2710
2734
  cancel: error => {
2711
2735
  if (cancelError)
@@ -2729,61 +2753,48 @@ class ReactNativeBleTransport {
2729
2753
  };
2730
2754
  const onAbort = () => active.cancel(new Error(abortMessage));
2731
2755
  let timer;
2732
- let completed = false;
2733
- let nativeError;
2734
2756
  try {
2735
2757
  const nativeWrite = Promise.resolve(manager.writeCharacteristicWithoutResponseFrame(transport.writeCharacteristic.id, buffer.Buffer.from(frame).toString('base64'), packetCapacity, transactionId));
2736
2758
  nativeWrite.catch(() => undefined);
2737
2759
  this.protocolV2FrameWrites.set(uuid, active);
2738
2760
  context.signal.addEventListener('abort', onAbort);
2739
- yield Promise.race([
2740
- nativeWrite,
2741
- cancelled,
2742
- new Promise((_, reject) => {
2743
- timer = setTimeout(() => {
2744
- const owner = isCurrentOwner();
2745
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`);
2746
- active.cancel(error);
2747
- reject(error);
2748
- if (owner) {
2749
- this.tearDownWedgedLink(uuid);
2750
- }
2751
- else {
2752
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
2753
- }
2754
- }, BLE_WRITE_PACKET_TIMEOUT_MS);
2755
- }),
2756
- ]);
2757
- 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]);
2758
2772
  }
2759
2773
  catch (error) {
2760
- 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));
2761
2780
  }
2762
2781
  finally {
2763
2782
  if (timer)
2764
2783
  clearTimeout(timer);
2765
2784
  context.signal.removeEventListener('abort', onAbort);
2766
- }
2767
- if (completed) {
2768
- this.writeTimeoutCounts.delete(uuid);
2769
- try {
2770
- assertCurrentGeneration();
2771
- }
2772
- catch (error) {
2773
- active.cancel(error instanceof Error ? error : new Error(String(error)));
2785
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
2786
+ this.protocolV2FrameWrites.delete(uuid);
2774
2787
  }
2775
2788
  }
2776
- if (this.protocolV2FrameWrites.get(uuid) === active) {
2777
- 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)));
2778
2795
  }
2779
2796
  if (cancelError)
2780
2797
  throw cancelError;
2781
- if (completed)
2782
- return;
2783
- if (isNativeBleDisconnectError(nativeError)) {
2784
- throw toBleDisconnectHardwareError(nativeError);
2785
- }
2786
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, getNativeBleErrorReason(nativeError));
2787
2798
  });
2788
2799
  }
2789
2800
  cancelProtocolV2FrameWrite(uuid, error, generation) {
@@ -2803,8 +2814,21 @@ class ReactNativeBleTransport {
2803
2814
  logFailure(error);
2804
2815
  }
2805
2816
  }
2806
- 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) {
2807
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) {
2808
2832
  return __awaiter(this, void 0, void 0, function* () {
2809
2833
  if (!this._messages || !this._messagesV2) {
2810
2834
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
@@ -2830,10 +2854,7 @@ class ReactNativeBleTransport {
2830
2854
  });
2831
2855
  const writeMode = writeWithResponse ? 'withResponse' : 'withoutResponse';
2832
2856
  const logSignature = `${name}:${writeMode}:${String(currentTransport.mtuSize)}:${packetCapacity}`;
2833
- const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2834
- if (!loggedSignatures.has(logSignature)) {
2835
- loggedSignatures.add(logSignature);
2836
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2857
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
2837
2858
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
2838
2859
  name,
2839
2860
  writeMode,
@@ -2844,10 +2865,7 @@ class ReactNativeBleTransport {
2844
2865
  const frameWriteMode = this.resolveProtocolV2NativeFrameWriter(currentTransport, { highThroughput: true, writeWithResponse: options === null || options === void 0 ? void 0 : options.writeWithResponse }, tuning.nativeFrameWrite)
2845
2866
  ? 'native-frame'
2846
2867
  : 'per-packet';
2847
- const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
2848
- if (!loggedSignatures.has(frameWriteModeSignature)) {
2849
- loggedSignatures.add(frameWriteModeSignature);
2850
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2868
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
2851
2869
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
2852
2870
  platform: reactNative.Platform.OS,
2853
2871
  mode: frameWriteMode,
@@ -2919,7 +2937,6 @@ class ReactNativeBleTransport {
2919
2937
  }
2920
2938
  }
2921
2939
  enableAndroidHighConnectionPriority(uuid) {
2922
- var _a;
2923
2940
  return __awaiter(this, void 0, void 0, function* () {
2924
2941
  if (reactNative.Platform.OS !== 'android')
2925
2942
  return;
@@ -2927,10 +2944,7 @@ class ReactNativeBleTransport {
2927
2944
  if (this.androidHighPriorityDevices.has(uuid))
2928
2945
  return;
2929
2946
  if (!shouldRequestAndroidHighConnectionPriority()) {
2930
- const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2931
- if (!loggedSignatures.has('androidPriority:peripheral')) {
2932
- loggedSignatures.add('androidPriority:peripheral');
2933
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2947
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
2934
2948
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
2935
2949
  apiLevel: reactNative.Platform.Version,
2936
2950
  setting: protocolV2BleTuning.androidHighConnectionPriority,
@@ -3009,9 +3023,7 @@ class ReactNativeBleTransport {
3009
3023
  }),
3010
3024
  readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
3011
3025
  assertCurrentGeneration();
3012
- const perf = (context === null || context === void 0 ? void 0 : context.messageName) === 'FilesystemFileWrite'
3013
- ? this.protocolV2FileWritePerfs.get(uuid)
3014
- : undefined;
3026
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3015
3027
  const startedAt = perf ? nowMs() : 0;
3016
3028
  const rxFrame = yield this.readProtocolV2Frame(uuid);
3017
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.117",
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.117",
24
- "@onekeyfe/hd-shared": "1.2.8-alpha.117",
25
- "@onekeyfe/hd-transport": "1.2.8-alpha.117",
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": "610f1a979c682817acf9b4d195365dc5ed806138"
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>[] = [];
@@ -2107,11 +2107,16 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
2107
2107
  await harness.transport.call(harness.uuid, 'FileWrite', {});
2108
2108
  };
2109
2109
 
2110
- test('leaves the priority to the peripheral on Android 17 by default', async () => {
2110
+ const createAndroidHarness = (apiLevel: number) => {
2111
2111
  setPlatformOS('android');
2112
- setPlatformVersion(37);
2112
+ setPlatformVersion(apiLevel);
2113
2113
  const harness = createHarness();
2114
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);
2115
2120
 
2116
2121
  await runHighVolumeCalls(harness);
2117
2122
  await harness.transport.release(harness.uuid, true);
@@ -2127,10 +2132,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
2127
2132
  });
2128
2133
 
2129
2134
  test('keeps requesting HIGH below Android 17 by default', async () => {
2130
- setPlatformOS('android');
2131
- setPlatformVersion(36);
2132
- const harness = createHarness();
2133
- harness.device.mtu = 517;
2135
+ const harness = createAndroidHarness(36);
2134
2136
 
2135
2137
  await runHighVolumeCalls(harness);
2136
2138
  expect(harness.device.requestConnectionPriority).toHaveBeenCalledTimes(1);
@@ -2141,27 +2143,21 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
2141
2143
  });
2142
2144
 
2143
2145
  test.each([
2144
- [37, true, true],
2145
- [36, false, false],
2146
- ] as const)(
2147
- 'applies the tuning switch on API %s when set to %s',
2148
- async (apiLevel, setting, expectHigh) => {
2149
- setPlatformOS('android');
2150
- setPlatformVersion(apiLevel);
2151
- configureProtocolV2BleTuning({ androidHighConnectionPriority: setting });
2152
- const harness = createHarness();
2153
- harness.device.mtu = 517;
2154
-
2155
- await runHighVolumeCalls(harness);
2156
-
2157
- if (expectHigh) {
2158
- expect(harness.device.requestConnectionPriority).toHaveBeenCalledWith(1);
2159
- } else {
2160
- expect(harness.device.requestConnectionPriority).not.toHaveBeenCalled();
2161
- }
2162
- await harness.transport.release(harness.uuid, true);
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();
2163
2158
  }
2164
- );
2159
+ await harness.transport.release(harness.uuid, true);
2160
+ });
2165
2161
 
2166
2162
  test('keeps the switch across unrelated tuning and ignores invalid values', () => {
2167
2163
  expect(getProtocolV2BleTuning().androidHighConnectionPriority).toBe('auto');
@@ -2175,10 +2171,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
2175
2171
  });
2176
2172
 
2177
2173
  test('requests HIGH again on the next link after a manual disconnect', async () => {
2178
- setPlatformOS('android');
2179
- setPlatformVersion(36);
2180
- const harness = createHarness();
2181
- harness.device.mtu = 517;
2174
+ const harness = createAndroidHarness(36);
2182
2175
 
2183
2176
  await runHighVolumeCalls(harness);
2184
2177
  expect(harness.device.requestConnectionPriority).toHaveBeenCalledTimes(1);
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
@@ -268,7 +275,6 @@ type ProtocolV2NativeFrameWriteExtension = {
268
275
  type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
269
276
 
270
277
  type ActiveProtocolV2FrameWrite = {
271
- transactionId: string;
272
278
  generation: number;
273
279
  cancel: (error: Error) => void;
274
280
  };
@@ -339,7 +345,10 @@ const createProtocolV2FileWritePerf = () => {
339
345
  const write = createDurationStats();
340
346
  const readWait = createDurationStats();
341
347
  const packet = createDurationStats();
342
- 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
+ );
343
352
 
344
353
  return {
345
354
  /** Called before each frame write so a frame that fails still reports its mode. */
@@ -355,7 +364,7 @@ const createProtocolV2FileWritePerf = () => {
355
364
  recordPacket(elapsedMs: number) {
356
365
  packet.add(elapsedMs);
357
366
  const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
358
- packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
367
+ packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
359
368
  },
360
369
  recordReadWait(elapsedMs: number) {
361
370
  readWait.add(elapsedMs);
@@ -387,6 +396,34 @@ function getDeviceDisplayName(device?: Device | null) {
387
396
  return device?.name || device?.localName || null;
388
397
  }
389
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
+
390
427
  const IOS_REQUEST_MTU = 247;
391
428
  const ANDROID_REQUEST_MTU = 517;
392
429
  const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
@@ -404,8 +441,8 @@ const shouldRequestAndroidHighConnectionPriority = () => {
404
441
  if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
405
442
  const apiLevel = Number(Platform.Version);
406
443
  // Unknown versions keep the long-standing HIGH request.
407
- return !(
408
- Number.isFinite(apiLevel) && apiLevel >= ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
444
+ return (
445
+ !Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
409
446
  );
410
447
  };
411
448
 
@@ -527,7 +564,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
527
564
 
528
565
  type NegotiatedMtuResult = { device: Device; timedOut: boolean };
529
566
 
530
- export type IOneKeyDevice = OneKeyDeviceInfoBase & Device;
567
+ export type IOneKeyDevice = OneKeyDeviceInfoBase &
568
+ Device &
569
+ Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
531
570
 
532
571
  const tryToGetConfiguration = (device: Device) => {
533
572
  if (!device || !device.serviceUUIDs) return null;
@@ -1033,7 +1072,7 @@ export default class ReactNativeBleTransport {
1033
1072
  }).then(() => {
1034
1073
  this.scanCleanups.delete(cancelScan);
1035
1074
  if (error) reject(error);
1036
- else resolve(deviceList);
1075
+ else resolve(deviceList.map(withBleColorCode));
1037
1076
  });
1038
1077
  return scanCleanup;
1039
1078
  };
@@ -1078,6 +1117,9 @@ export default class ReactNativeBleTransport {
1078
1117
  return;
1079
1118
  }
1080
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);
1081
1123
  const displayName = getDeviceDisplayName(device);
1082
1124
  // iOS may report a service-only advertisement before the named scan response.
1083
1125
  // Do not cache that incomplete advertisement as an unknown device.
@@ -1143,6 +1185,9 @@ export default class ReactNativeBleTransport {
1143
1185
  deviceId: device.id,
1144
1186
  name: displayName,
1145
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()),
1146
1191
  });
1147
1192
  }
1148
1193
  };
@@ -1707,8 +1752,9 @@ export default class ReactNativeBleTransport {
1707
1752
  }
1708
1753
 
1709
1754
  private async releaseUnlocked(uuid: string, onclose = false) {
1710
- this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1711
- 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);
1712
1758
  return this.releaseNative(uuid, onclose);
1713
1759
  }
1714
1760
 
@@ -2138,8 +2184,9 @@ export default class ReactNativeBleTransport {
2138
2184
  // Balanced restore from this link must not carry over to it.
2139
2185
  this.clearAndroidPriorityResetTimer(session);
2140
2186
  this.androidHighPriorityDevices.delete(session);
2141
- this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
2142
- await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
2187
+ const reason = 'React Native BLE transport disconnected';
2188
+ this.cancelProtocolV2FrameWrite(session, new Error(reason));
2189
+ await this.protocolV2Links.invalidateLink(session, reason);
2143
2190
  const transport = transportCache[session];
2144
2191
  const manager = this.blePlxManager;
2145
2192
  const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
@@ -2577,12 +2624,7 @@ export default class ReactNativeBleTransport {
2577
2624
  new Promise<never>((_, reject) => {
2578
2625
  timer = setTimeout(() => {
2579
2626
  timedOut = true;
2580
- reject(
2581
- ERRORS.TypedError(
2582
- HardwareErrorCode.BleWriteCharacteristicError,
2583
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2584
- )
2585
- );
2627
+ reject(createWedgedWriteError());
2586
2628
  }, BLE_WRITE_PACKET_TIMEOUT_MS);
2587
2629
  }),
2588
2630
  ]);
@@ -2616,13 +2658,7 @@ export default class ReactNativeBleTransport {
2616
2658
  consecutiveWriteTimeouts: timeouts,
2617
2659
  });
2618
2660
 
2619
- this.cancelProtocolV2FrameWrite(
2620
- uuid,
2621
- ERRORS.TypedError(
2622
- HardwareErrorCode.BleWriteCharacteristicError,
2623
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2624
- )
2625
- );
2661
+ this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
2626
2662
  const wedged = transportCache[uuid];
2627
2663
  this.disconnect(uuid).catch(error => {
2628
2664
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2651,9 +2687,7 @@ export default class ReactNativeBleTransport {
2651
2687
  this.blePlxManager = undefined;
2652
2688
  const reason = 'React Native BLE manager reset';
2653
2689
  // Cancel through the manager that started each frame before destroy() drops its queue.
2654
- Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid =>
2655
- this.cancelProtocolV2FrameWrite(uuid, new Error(reason))
2656
- );
2690
+ this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
2657
2691
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2658
2692
  // each cached session before clearing generations so Core cannot retain a
2659
2693
  // silently stale connection for an unrelated device.
@@ -3125,10 +3159,7 @@ export default class ReactNativeBleTransport {
3125
3159
  androidPacketLength: tuning.androidPacketLength,
3126
3160
  mtu: transport.mtuSize,
3127
3161
  });
3128
- const perf =
3129
- context.messageName === 'FilesystemFileWrite'
3130
- ? this.protocolV2FileWritePerfs.get(uuid)
3131
- : undefined;
3162
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3132
3163
  const startedAt = perf ? nowMs() : 0;
3133
3164
  const nativeFrameWriter =
3134
3165
  frame.length > packetCapacity
@@ -3178,7 +3209,7 @@ export default class ReactNativeBleTransport {
3178
3209
  context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
3179
3210
  nativeFrameWrite: boolean
3180
3211
  ): ProtocolV2NativeFrameWriter | undefined {
3181
- if (!context.highThroughput || nativeFrameWrite === false) return undefined;
3212
+ if (!context.highThroughput || !nativeFrameWrite) return undefined;
3182
3213
  if (
3183
3214
  shouldWriteProtocolV2WithResponse({
3184
3215
  platform: Platform.OS,
@@ -3196,8 +3227,9 @@ export default class ReactNativeBleTransport {
3196
3227
  /**
3197
3228
  * Writes one frame with a single native call that sends its packets in order without response.
3198
3229
  * Nothing here retries it: a resend could duplicate bytes the device already received. The
3199
- * native transaction is cancelled on abort, watchdog expiry, generation change and link
3200
- * 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.
3201
3233
  */
3202
3234
  private async writeProtocolV2NativeFrame(
3203
3235
  uuid: string,
@@ -3222,7 +3254,6 @@ export default class ReactNativeBleTransport {
3222
3254
  rejectCancelled = reject;
3223
3255
  });
3224
3256
  const active: ActiveProtocolV2FrameWrite = {
3225
- transactionId,
3226
3257
  generation: context.generation,
3227
3258
  cancel: error => {
3228
3259
  if (cancelError) return;
@@ -3245,8 +3276,6 @@ export default class ReactNativeBleTransport {
3245
3276
  };
3246
3277
  const onAbort = () => active.cancel(new Error(abortMessage));
3247
3278
  let timer: ReturnType<typeof setTimeout> | undefined;
3248
- let completed = false;
3249
- let nativeError: unknown;
3250
3279
  try {
3251
3280
  const nativeWrite = Promise.resolve(
3252
3281
  manager.writeCharacteristicWithoutResponseFrame(
@@ -3260,54 +3289,40 @@ export default class ReactNativeBleTransport {
3260
3289
  nativeWrite.catch(() => undefined);
3261
3290
  this.protocolV2FrameWrites.set(uuid, active);
3262
3291
  context.signal.addEventListener('abort', onAbort);
3263
- await Promise.race([
3264
- nativeWrite,
3265
- cancelled,
3266
- new Promise<never>((_, reject) => {
3267
- timer = setTimeout(() => {
3268
- const owner = isCurrentOwner();
3269
- const error = ERRORS.TypedError(
3270
- HardwareErrorCode.BleWriteCharacteristicError,
3271
- `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
3272
- );
3273
- active.cancel(error);
3274
- reject(error);
3275
- if (owner) {
3276
- this.tearDownWedgedLink(uuid);
3277
- } else {
3278
- Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3279
- }
3280
- }, BLE_WRITE_PACKET_TIMEOUT_MS);
3281
- }),
3282
- ]);
3283
- 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]);
3284
3302
  } catch (error) {
3285
- 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
+ );
3286
3311
  } finally {
3287
3312
  if (timer) clearTimeout(timer);
3288
3313
  context.signal.removeEventListener('abort', onAbort);
3289
- }
3290
-
3291
- if (completed) {
3292
- this.writeTimeoutCounts.delete(uuid);
3293
- try {
3294
- assertCurrentGeneration();
3295
- } catch (error) {
3296
- active.cancel(error instanceof Error ? error : new Error(String(error)));
3314
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3315
+ this.protocolV2FrameWrites.delete(uuid);
3297
3316
  }
3298
3317
  }
3299
- if (this.protocolV2FrameWrites.get(uuid) === active) {
3300
- 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)));
3301
3324
  }
3302
3325
  if (cancelError) throw cancelError;
3303
- if (completed) return;
3304
- if (isNativeBleDisconnectError(nativeError)) {
3305
- throw toBleDisconnectHardwareError(nativeError);
3306
- }
3307
- throw ERRORS.TypedError(
3308
- HardwareErrorCode.BleWriteCharacteristicError,
3309
- getNativeBleErrorReason(nativeError)
3310
- );
3311
3326
  }
3312
3327
 
3313
3328
  /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
@@ -3329,6 +3344,21 @@ export default class ReactNativeBleTransport {
3329
3344
  }
3330
3345
  }
3331
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
+
3332
3362
  private async callProtocolV2(
3333
3363
  uuid: string,
3334
3364
  name: string,
@@ -3363,11 +3393,7 @@ export default class ReactNativeBleTransport {
3363
3393
  const logSignature = `${name}:${writeMode}:${String(
3364
3394
  currentTransport.mtuSize
3365
3395
  )}:${packetCapacity}`;
3366
- const loggedSignatures =
3367
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3368
- if (!loggedSignatures.has(logSignature)) {
3369
- loggedSignatures.add(logSignature);
3370
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3396
+ if (this.markProtocolV2LogSignature(uuid, logSignature)) {
3371
3397
  Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
3372
3398
  name,
3373
3399
  writeMode,
@@ -3382,10 +3408,7 @@ export default class ReactNativeBleTransport {
3382
3408
  )
3383
3409
  ? 'native-frame'
3384
3410
  : 'per-packet';
3385
- const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
3386
- if (!loggedSignatures.has(frameWriteModeSignature)) {
3387
- loggedSignatures.add(frameWriteModeSignature);
3388
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3411
+ if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
3389
3412
  Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
3390
3413
  platform: Platform.OS,
3391
3414
  mode: frameWriteMode,
@@ -3487,11 +3510,7 @@ export default class ReactNativeBleTransport {
3487
3510
  this.clearAndroidPriorityResetTimer(uuid);
3488
3511
  if (this.androidHighPriorityDevices.has(uuid)) return;
3489
3512
  if (!shouldRequestAndroidHighConnectionPriority()) {
3490
- const loggedSignatures =
3491
- this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
3492
- if (!loggedSignatures.has('androidPriority:peripheral')) {
3493
- loggedSignatures.add('androidPriority:peripheral');
3494
- this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3513
+ if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
3495
3514
  Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
3496
3515
  apiLevel: Platform.Version,
3497
3516
  setting: protocolV2BleTuning.androidHighConnectionPriority,
@@ -3577,12 +3596,9 @@ export default class ReactNativeBleTransport {
3577
3596
  assertCurrentGeneration
3578
3597
  );
3579
3598
  },
3580
- readFrame: async (context?: ProtocolV2CallContext) => {
3599
+ readFrame: async (context: ProtocolV2CallContext) => {
3581
3600
  assertCurrentGeneration();
3582
- const perf =
3583
- context?.messageName === 'FilesystemFileWrite'
3584
- ? this.protocolV2FileWritePerfs.get(uuid)
3585
- : undefined;
3601
+ const perf = this.getProtocolV2FileWritePerf(uuid, context);
3586
3602
  const startedAt = perf ? nowMs() : 0;
3587
3603
  const rxFrame = await this.readProtocolV2Frame(uuid);
3588
3604
  perf?.recordReadWait(nowMs() - startedAt);