@onekeyfe/hd-transport-react-native 1.2.8-alpha.117 → 1.2.8-alpha.119
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 +2 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +35 -320
- package/package.json +5 -5
- package/src/__tests__/enumerate.test.ts +139 -0
- package/src/__tests__/protocolV2Link.test.ts +0 -103
- package/src/index.ts +54 -458
- package/src/__tests__/nativeFrameWrite.test.ts +0 -917
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';
|
|
@@ -190,16 +192,6 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
|
|
|
190
192
|
export type ProtocolV2BleTuning = {
|
|
191
193
|
iosPacketLength?: number;
|
|
192
194
|
androidPacketLength?: number;
|
|
193
|
-
/**
|
|
194
|
-
* Write each multi-packet high-throughput frame with one native call when the native
|
|
195
|
-
* BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
|
|
196
|
-
*/
|
|
197
|
-
nativeFrameWrite?: boolean;
|
|
198
|
-
/**
|
|
199
|
-
* Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
|
|
200
|
-
* default) requests it below Android 17 only; true or false forces it on every version.
|
|
201
|
-
*/
|
|
202
|
-
androidHighConnectionPriority?: boolean | 'auto';
|
|
203
195
|
};
|
|
204
196
|
|
|
205
197
|
type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
@@ -207,8 +199,6 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
|
207
199
|
const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
|
|
208
200
|
iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
|
|
209
201
|
androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
|
|
210
|
-
nativeFrameWrite: true,
|
|
211
|
-
androidHighConnectionPriority: 'auto',
|
|
212
202
|
};
|
|
213
203
|
|
|
214
204
|
let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
|
|
@@ -229,15 +219,6 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
|
|
|
229
219
|
tuning.androidPacketLength,
|
|
230
220
|
protocolV2BleTuning.androidPacketLength
|
|
231
221
|
),
|
|
232
|
-
nativeFrameWrite:
|
|
233
|
-
typeof tuning.nativeFrameWrite === 'boolean'
|
|
234
|
-
? tuning.nativeFrameWrite
|
|
235
|
-
: protocolV2BleTuning.nativeFrameWrite,
|
|
236
|
-
androidHighConnectionPriority:
|
|
237
|
-
typeof tuning.androidHighConnectionPriority === 'boolean' ||
|
|
238
|
-
tuning.androidHighConnectionPriority === 'auto'
|
|
239
|
-
? tuning.androidHighConnectionPriority
|
|
240
|
-
: protocolV2BleTuning.androidHighConnectionPriority,
|
|
241
222
|
};
|
|
242
223
|
Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
|
|
243
224
|
}
|
|
@@ -251,163 +232,41 @@ export function getProtocolV2BleTuning() {
|
|
|
251
232
|
return { ...protocolV2BleTuning };
|
|
252
233
|
}
|
|
253
234
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
*/
|
|
258
|
-
type ProtocolV2NativeFrameWriteExtension = {
|
|
259
|
-
isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
|
|
260
|
-
writeCharacteristicWithoutResponseFrame?: (
|
|
261
|
-
characteristicIdentifier: number,
|
|
262
|
-
base64Frame: string,
|
|
263
|
-
packetSize: number,
|
|
264
|
-
transactionId: string
|
|
265
|
-
) => Promise<void>;
|
|
266
|
-
};
|
|
235
|
+
function getDeviceDisplayName(device?: Device | null) {
|
|
236
|
+
return device?.name || device?.localName || null;
|
|
237
|
+
}
|
|
267
238
|
|
|
268
|
-
|
|
239
|
+
// The color is only in the primary advertisement, and the name only in the scan
|
|
240
|
+
// response, so the callback a scan keeps may not carry it. A connected device stops
|
|
241
|
+
// advertising. Keep the last valid color per device for the life of the process.
|
|
242
|
+
// iOS reports connected peripherals with lowercased ids, so key case-insensitively.
|
|
243
|
+
const bleColorCodesById = new Map<string, string>();
|
|
269
244
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
cancel: (error: Error) => void;
|
|
274
|
-
};
|
|
245
|
+
function getManufacturerDataLength(device?: Device | null) {
|
|
246
|
+
return device?.manufacturerData ? Buffer.from(device.manufacturerData, 'base64').length : 0;
|
|
247
|
+
}
|
|
275
248
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
}
|
|
287
|
-
try {
|
|
288
|
-
return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
|
|
289
|
-
? (candidate as ProtocolV2NativeFrameWriter)
|
|
290
|
-
: undefined;
|
|
291
|
-
} catch {
|
|
292
|
-
return undefined;
|
|
249
|
+
function rememberBleColorCode(device?: Device | null) {
|
|
250
|
+
if (!device?.id || !device.manufacturerData) return;
|
|
251
|
+
const colorCode = parseOnekeyBleColorCode(Buffer.from(device.manufacturerData, 'base64'));
|
|
252
|
+
const key = device.id.toLowerCase();
|
|
253
|
+
if (colorCode && bleColorCodesById.get(key) !== colorCode) {
|
|
254
|
+
bleColorCodesById.set(key, colorCode);
|
|
255
|
+
Log?.debug('[ReactNativeBleTransport] BLE color code', {
|
|
256
|
+
deviceId: device.id,
|
|
257
|
+
bleColorCode: colorCode,
|
|
258
|
+
});
|
|
293
259
|
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
const getNativeBleErrorReason = (error: unknown): string | undefined => {
|
|
297
|
-
const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
|
|
298
|
-
if (typeof reason === 'string' && reason) return reason;
|
|
299
|
-
return typeof message === 'string' && message ? message : undefined;
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
|
|
303
|
-
|
|
304
|
-
const nowMs = () =>
|
|
305
|
-
typeof performance !== 'undefined' && typeof performance.now === 'function'
|
|
306
|
-
? performance.now()
|
|
307
|
-
: Date.now();
|
|
308
|
-
|
|
309
|
-
const roundMs = (ms: number) => Math.round(ms * 10) / 10;
|
|
310
|
-
|
|
311
|
-
/** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
|
|
312
|
-
const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
|
|
313
|
-
|
|
314
|
-
const createDurationStats = () => {
|
|
315
|
-
let total = 0;
|
|
316
|
-
let count = 0;
|
|
317
|
-
let max = 0;
|
|
318
|
-
return {
|
|
319
|
-
add(ms: number) {
|
|
320
|
-
total += ms;
|
|
321
|
-
count += 1;
|
|
322
|
-
max = Math.max(max, ms);
|
|
323
|
-
},
|
|
324
|
-
summarize: () => ({
|
|
325
|
-
total: roundMs(total),
|
|
326
|
-
avg: count ? roundMs(total / count) : 0,
|
|
327
|
-
max: roundMs(max),
|
|
328
|
-
}),
|
|
329
|
-
};
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
/** Scalar-only timing of one pipelined FilesystemFileWrite call. */
|
|
333
|
-
const createProtocolV2FileWritePerf = () => {
|
|
334
|
-
const startedAt = nowMs();
|
|
335
|
-
let nativeFrames = 0;
|
|
336
|
-
let frames = 0;
|
|
337
|
-
let packets = 0;
|
|
338
|
-
let frameBytes = 0;
|
|
339
|
-
const write = createDurationStats();
|
|
340
|
-
const readWait = createDurationStats();
|
|
341
|
-
const packet = createDurationStats();
|
|
342
|
-
const packetHistogram = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.map(() => 0).concat(0);
|
|
343
|
-
|
|
344
|
-
return {
|
|
345
|
-
/** Called before each frame write so a frame that fails still reports its mode. */
|
|
346
|
-
startFrame(mode: ProtocolV2FrameWriteMode) {
|
|
347
|
-
if (mode === 'native-frame') nativeFrames += 1;
|
|
348
|
-
},
|
|
349
|
-
recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
|
|
350
|
-
frames += 1;
|
|
351
|
-
packets += framePackets;
|
|
352
|
-
frameBytes += bytes;
|
|
353
|
-
write.add(elapsedMs);
|
|
354
|
-
},
|
|
355
|
-
recordPacket(elapsedMs: number) {
|
|
356
|
-
packet.add(elapsedMs);
|
|
357
|
-
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;
|
|
359
|
-
},
|
|
360
|
-
recordReadWait(elapsedMs: number) {
|
|
361
|
-
readWait.add(elapsedMs);
|
|
362
|
-
},
|
|
363
|
-
summarize(ok: boolean) {
|
|
364
|
-
const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
|
|
365
|
-
const packetStats = packet.summarize();
|
|
366
|
-
return {
|
|
367
|
-
platform: Platform.OS,
|
|
368
|
-
mode,
|
|
369
|
-
ok,
|
|
370
|
-
frames,
|
|
371
|
-
packets,
|
|
372
|
-
frameBytes,
|
|
373
|
-
elapsedMs: roundMs(nowMs() - startedAt),
|
|
374
|
-
writeMs: write.summarize(),
|
|
375
|
-
readWaitMs: readWait.summarize(),
|
|
376
|
-
...(mode === 'per-packet'
|
|
377
|
-
? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
|
|
378
|
-
: {}),
|
|
379
|
-
};
|
|
380
|
-
},
|
|
381
|
-
};
|
|
382
|
-
};
|
|
383
|
-
|
|
384
|
-
type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
|
|
260
|
+
}
|
|
385
261
|
|
|
386
|
-
function
|
|
387
|
-
|
|
262
|
+
function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
|
|
263
|
+
const bleColorCode = bleColorCodesById.get(device.id.toLowerCase());
|
|
264
|
+
return bleColorCode ? ({ ...device, bleColorCode } as IOneKeyDevice) : device;
|
|
388
265
|
}
|
|
389
266
|
|
|
390
267
|
const IOS_REQUEST_MTU = 247;
|
|
391
268
|
const ANDROID_REQUEST_MTU = 517;
|
|
392
269
|
const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
|
|
393
|
-
/**
|
|
394
|
-
* Android 17 maps CONNECTION_PRIORITY_HIGH to 11.25-15 ms with peripheral latency 1. OneKey BLE
|
|
395
|
-
* firmware accepts any latency at its 15 ms interval, and latency 1 roughly halves Protocol V2
|
|
396
|
-
* FileWrite throughput. BLE 1.0.23 requests 15 ms with latency 0 by itself; older BLE firmware
|
|
397
|
-
* asks for 15-30 ms or nothing and has not been measured on Android 17 without HIGH.
|
|
398
|
-
*/
|
|
399
|
-
const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
|
|
400
|
-
|
|
401
|
-
const shouldRequestAndroidHighConnectionPriority = () => {
|
|
402
|
-
if (Platform.OS !== 'android') return false;
|
|
403
|
-
const { androidHighConnectionPriority } = protocolV2BleTuning;
|
|
404
|
-
if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
|
|
405
|
-
const apiLevel = Number(Platform.Version);
|
|
406
|
-
// Unknown versions keep the long-standing HIGH request.
|
|
407
|
-
return !(
|
|
408
|
-
Number.isFinite(apiLevel) && apiLevel >= ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
|
|
409
|
-
);
|
|
410
|
-
};
|
|
411
270
|
|
|
412
271
|
const getRequestedBleMtu = () =>
|
|
413
272
|
Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
|
|
@@ -527,7 +386,9 @@ const isMtuOrCancelledConnectError = (error: unknown): boolean => {
|
|
|
527
386
|
|
|
528
387
|
type NegotiatedMtuResult = { device: Device; timedOut: boolean };
|
|
529
388
|
|
|
530
|
-
export type IOneKeyDevice = OneKeyDeviceInfoBase &
|
|
389
|
+
export type IOneKeyDevice = OneKeyDeviceInfoBase &
|
|
390
|
+
Device &
|
|
391
|
+
Pick<OneKeyMobileDeviceInfo, 'bleColorCode'>;
|
|
531
392
|
|
|
532
393
|
const tryToGetConfiguration = (device: Device) => {
|
|
533
394
|
if (!device || !device.serviceUUIDs) return null;
|
|
@@ -731,13 +592,6 @@ export default class ReactNativeBleTransport {
|
|
|
731
592
|
|
|
732
593
|
private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
|
|
733
594
|
|
|
734
|
-
/** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
|
|
735
|
-
private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
|
|
736
|
-
|
|
737
|
-
private protocolV2FrameWriteCounter = 0;
|
|
738
|
-
|
|
739
|
-
private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
|
|
740
|
-
|
|
741
595
|
private nextMonitorToken = 1;
|
|
742
596
|
|
|
743
597
|
/** Serializes transport lifecycle changes for the same physical device. */
|
|
@@ -1033,7 +887,7 @@ export default class ReactNativeBleTransport {
|
|
|
1033
887
|
}).then(() => {
|
|
1034
888
|
this.scanCleanups.delete(cancelScan);
|
|
1035
889
|
if (error) reject(error);
|
|
1036
|
-
else resolve(deviceList);
|
|
890
|
+
else resolve(deviceList.map(withBleColorCode));
|
|
1037
891
|
});
|
|
1038
892
|
return scanCleanup;
|
|
1039
893
|
};
|
|
@@ -1078,6 +932,9 @@ export default class ReactNativeBleTransport {
|
|
|
1078
932
|
return;
|
|
1079
933
|
}
|
|
1080
934
|
|
|
935
|
+
// The native scan is filtered to the OneKey communication service, so an
|
|
936
|
+
// unnamed iOS advertisement rejected below can still carry the color.
|
|
937
|
+
rememberBleColorCode(device);
|
|
1081
938
|
const displayName = getDeviceDisplayName(device);
|
|
1082
939
|
// iOS may report a service-only advertisement before the named scan response.
|
|
1083
940
|
// Do not cache that incomplete advertisement as an unknown device.
|
|
@@ -1143,6 +1000,9 @@ export default class ReactNativeBleTransport {
|
|
|
1143
1000
|
deviceId: device.id,
|
|
1144
1001
|
name: displayName,
|
|
1145
1002
|
serviceUUIDs: device.serviceUUIDs,
|
|
1003
|
+
// 5 = advertises a color slot; 4 = BLE firmware before 1.0.23.
|
|
1004
|
+
manufacturerDataLength: getManufacturerDataLength(device),
|
|
1005
|
+
bleColorCode: bleColorCodesById.get(device.id.toLowerCase()),
|
|
1146
1006
|
});
|
|
1147
1007
|
}
|
|
1148
1008
|
};
|
|
@@ -1707,13 +1567,11 @@ export default class ReactNativeBleTransport {
|
|
|
1707
1567
|
}
|
|
1708
1568
|
|
|
1709
1569
|
private async releaseUnlocked(uuid: string, onclose = false) {
|
|
1710
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1711
1570
|
await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
|
|
1712
1571
|
return this.releaseNative(uuid, onclose);
|
|
1713
1572
|
}
|
|
1714
1573
|
|
|
1715
1574
|
private async releaseNative(uuid: string, onclose = false) {
|
|
1716
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1717
1575
|
const transport = transportCache[uuid];
|
|
1718
1576
|
const manager = this.blePlxManager;
|
|
1719
1577
|
if (this.runPromise && this.runPromiseDeviceId === uuid) {
|
|
@@ -2134,11 +1992,6 @@ export default class ReactNativeBleTransport {
|
|
|
2134
1992
|
}
|
|
2135
1993
|
|
|
2136
1994
|
private async disconnectUnlocked(session: string) {
|
|
2137
|
-
// The next link starts at the stack's default priority; a cached HIGH or a pending
|
|
2138
|
-
// Balanced restore from this link must not carry over to it.
|
|
2139
|
-
this.clearAndroidPriorityResetTimer(session);
|
|
2140
|
-
this.androidHighPriorityDevices.delete(session);
|
|
2141
|
-
this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
|
|
2142
1995
|
await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
|
|
2143
1996
|
const transport = transportCache[session];
|
|
2144
1997
|
const manager = this.blePlxManager;
|
|
@@ -2616,13 +2469,6 @@ export default class ReactNativeBleTransport {
|
|
|
2616
2469
|
consecutiveWriteTimeouts: timeouts,
|
|
2617
2470
|
});
|
|
2618
2471
|
|
|
2619
|
-
this.cancelProtocolV2FrameWrite(
|
|
2620
|
-
uuid,
|
|
2621
|
-
ERRORS.TypedError(
|
|
2622
|
-
HardwareErrorCode.BleWriteCharacteristicError,
|
|
2623
|
-
`BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
|
|
2624
|
-
)
|
|
2625
|
-
);
|
|
2626
2472
|
const wedged = transportCache[uuid];
|
|
2627
2473
|
this.disconnect(uuid).catch(error => {
|
|
2628
2474
|
Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
|
|
@@ -2650,10 +2496,6 @@ export default class ReactNativeBleTransport {
|
|
|
2650
2496
|
const manager = this.blePlxManager;
|
|
2651
2497
|
this.blePlxManager = undefined;
|
|
2652
2498
|
const reason = 'React Native BLE manager reset';
|
|
2653
|
-
// 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
|
-
);
|
|
2657
2499
|
// Destroying the shared manager invalidates every peripheral it owns. Notify
|
|
2658
2500
|
// each cached session before clearing generations so Core cannot retain a
|
|
2659
2501
|
// silently stale connection for an unrelated device.
|
|
@@ -3125,208 +2967,22 @@ export default class ReactNativeBleTransport {
|
|
|
3125
2967
|
androidPacketLength: tuning.androidPacketLength,
|
|
3126
2968
|
mtu: transport.mtuSize,
|
|
3127
2969
|
});
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
frame,
|
|
3144
|
-
packetCapacity,
|
|
3145
|
-
context,
|
|
3146
|
-
assertCurrentGeneration
|
|
3147
|
-
);
|
|
3148
|
-
} else {
|
|
3149
|
-
await writeProtocolV2BleFrame({
|
|
3150
|
-
frame,
|
|
3151
|
-
packetCapacity,
|
|
3152
|
-
assertActive: assertCurrentGeneration,
|
|
3153
|
-
signal: context.signal,
|
|
3154
|
-
abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
|
|
3155
|
-
wait: delay,
|
|
3156
|
-
writePacket: async packet => {
|
|
3157
|
-
const packetStartedAt = perf ? nowMs() : 0;
|
|
3158
|
-
await this.writeProtocolV2Packet(
|
|
3159
|
-
uuid,
|
|
3160
|
-
transport,
|
|
3161
|
-
Buffer.from(packet).toString('base64'),
|
|
3162
|
-
context,
|
|
3163
|
-
assertCurrentGeneration
|
|
3164
|
-
);
|
|
3165
|
-
perf?.recordPacket(nowMs() - packetStartedAt);
|
|
3166
|
-
},
|
|
3167
|
-
});
|
|
3168
|
-
}
|
|
3169
|
-
perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
|
|
3170
|
-
}
|
|
3171
|
-
|
|
3172
|
-
/**
|
|
3173
|
-
* The native frame write only replaces the per-packet loop where its JS<->native round trips
|
|
3174
|
-
* dominate: multi-packet (checked by the caller) high-throughput frames written without response.
|
|
3175
|
-
*/
|
|
3176
|
-
private resolveProtocolV2NativeFrameWriter(
|
|
3177
|
-
transport: BleTransport,
|
|
3178
|
-
context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
|
|
3179
|
-
nativeFrameWrite: boolean
|
|
3180
|
-
): ProtocolV2NativeFrameWriter | undefined {
|
|
3181
|
-
if (!context.highThroughput || nativeFrameWrite === false) return undefined;
|
|
3182
|
-
if (
|
|
3183
|
-
shouldWriteProtocolV2WithResponse({
|
|
3184
|
-
platform: Platform.OS,
|
|
3185
|
-
highThroughput: context.highThroughput,
|
|
3186
|
-
requestedWithResponse: context.writeWithResponse,
|
|
3187
|
-
characteristic: transport.writeCharacteristic,
|
|
3188
|
-
})
|
|
3189
|
-
) {
|
|
3190
|
-
return undefined;
|
|
3191
|
-
}
|
|
3192
|
-
if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
|
|
3193
|
-
return getProtocolV2NativeFrameWriter(this.blePlxManager);
|
|
3194
|
-
}
|
|
3195
|
-
|
|
3196
|
-
/**
|
|
3197
|
-
* Writes one frame with a single native call that sends its packets in order without response.
|
|
3198
|
-
* 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.
|
|
3201
|
-
*/
|
|
3202
|
-
private async writeProtocolV2NativeFrame(
|
|
3203
|
-
uuid: string,
|
|
3204
|
-
transport: BleTransport,
|
|
3205
|
-
manager: ProtocolV2NativeFrameWriter,
|
|
3206
|
-
frame: Uint8Array,
|
|
3207
|
-
packetCapacity: number,
|
|
3208
|
-
context: ProtocolV2CallContext,
|
|
3209
|
-
assertCurrentGeneration: () => void
|
|
3210
|
-
) {
|
|
3211
|
-
const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
|
|
3212
|
-
assertCurrentGeneration();
|
|
3213
|
-
if (context.signal.aborted) {
|
|
3214
|
-
throw new Error(abortMessage);
|
|
3215
|
-
}
|
|
3216
|
-
|
|
3217
|
-
this.protocolV2FrameWriteCounter += 1;
|
|
3218
|
-
const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
|
|
3219
|
-
let cancelError: Error | undefined;
|
|
3220
|
-
let rejectCancelled: (error: Error) => void = () => undefined;
|
|
3221
|
-
const cancelled = new Promise<never>((_, reject) => {
|
|
3222
|
-
rejectCancelled = reject;
|
|
2970
|
+
await writeProtocolV2BleFrame({
|
|
2971
|
+
frame,
|
|
2972
|
+
packetCapacity,
|
|
2973
|
+
assertActive: assertCurrentGeneration,
|
|
2974
|
+
signal: context.signal,
|
|
2975
|
+
abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
|
|
2976
|
+
wait: delay,
|
|
2977
|
+
writePacket: packet =>
|
|
2978
|
+
this.writeProtocolV2Packet(
|
|
2979
|
+
uuid,
|
|
2980
|
+
transport,
|
|
2981
|
+
Buffer.from(packet).toString('base64'),
|
|
2982
|
+
context,
|
|
2983
|
+
assertCurrentGeneration
|
|
2984
|
+
),
|
|
3223
2985
|
});
|
|
3224
|
-
const active: ActiveProtocolV2FrameWrite = {
|
|
3225
|
-
transactionId,
|
|
3226
|
-
generation: context.generation,
|
|
3227
|
-
cancel: error => {
|
|
3228
|
-
if (cancelError) return;
|
|
3229
|
-
cancelError = error;
|
|
3230
|
-
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3231
|
-
this.protocolV2FrameWrites.delete(uuid);
|
|
3232
|
-
}
|
|
3233
|
-
rejectCancelled(error);
|
|
3234
|
-
this.cancelNativeTransaction(manager, transactionId);
|
|
3235
|
-
},
|
|
3236
|
-
};
|
|
3237
|
-
// Same rule as writeBlePacket: a superseded generation must not tear down the current link.
|
|
3238
|
-
const isCurrentOwner = () => {
|
|
3239
|
-
try {
|
|
3240
|
-
assertCurrentGeneration();
|
|
3241
|
-
return !context.signal.aborted;
|
|
3242
|
-
} catch {
|
|
3243
|
-
return false;
|
|
3244
|
-
}
|
|
3245
|
-
};
|
|
3246
|
-
const onAbort = () => active.cancel(new Error(abortMessage));
|
|
3247
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
3248
|
-
let completed = false;
|
|
3249
|
-
let nativeError: unknown;
|
|
3250
|
-
try {
|
|
3251
|
-
const nativeWrite = Promise.resolve(
|
|
3252
|
-
manager.writeCharacteristicWithoutResponseFrame(
|
|
3253
|
-
transport.writeCharacteristic.id,
|
|
3254
|
-
Buffer.from(frame).toString('base64'),
|
|
3255
|
-
packetCapacity,
|
|
3256
|
-
transactionId
|
|
3257
|
-
)
|
|
3258
|
-
);
|
|
3259
|
-
// A cancelled or timed-out frame still settles natively later; that outcome is ignored.
|
|
3260
|
-
nativeWrite.catch(() => undefined);
|
|
3261
|
-
this.protocolV2FrameWrites.set(uuid, active);
|
|
3262
|
-
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;
|
|
3284
|
-
} catch (error) {
|
|
3285
|
-
nativeError = error;
|
|
3286
|
-
} finally {
|
|
3287
|
-
if (timer) clearTimeout(timer);
|
|
3288
|
-
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)));
|
|
3297
|
-
}
|
|
3298
|
-
}
|
|
3299
|
-
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3300
|
-
this.protocolV2FrameWrites.delete(uuid);
|
|
3301
|
-
}
|
|
3302
|
-
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
|
-
}
|
|
3312
|
-
|
|
3313
|
-
/** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
|
|
3314
|
-
private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
|
|
3315
|
-
const active = this.protocolV2FrameWrites.get(uuid);
|
|
3316
|
-
if (!active || (generation !== undefined && active.generation !== generation)) return;
|
|
3317
|
-
active.cancel(error);
|
|
3318
|
-
}
|
|
3319
|
-
|
|
3320
|
-
private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
|
|
3321
|
-
const logFailure = (error: unknown) =>
|
|
3322
|
-
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
|
|
3323
|
-
error: error instanceof Error ? error.message : String(error),
|
|
3324
|
-
});
|
|
3325
|
-
try {
|
|
3326
|
-
Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
|
|
3327
|
-
} catch (error) {
|
|
3328
|
-
logFailure(error);
|
|
3329
|
-
}
|
|
3330
2986
|
}
|
|
3331
2987
|
|
|
3332
2988
|
private async callProtocolV2(
|
|
@@ -3375,50 +3031,20 @@ export default class ReactNativeBleTransport {
|
|
|
3375
3031
|
packetCapacity,
|
|
3376
3032
|
});
|
|
3377
3033
|
}
|
|
3378
|
-
const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
|
|
3379
|
-
currentTransport,
|
|
3380
|
-
{ highThroughput: true, writeWithResponse: options?.writeWithResponse },
|
|
3381
|
-
tuning.nativeFrameWrite
|
|
3382
|
-
)
|
|
3383
|
-
? 'native-frame'
|
|
3384
|
-
: 'per-packet';
|
|
3385
|
-
const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
|
|
3386
|
-
if (!loggedSignatures.has(frameWriteModeSignature)) {
|
|
3387
|
-
loggedSignatures.add(frameWriteModeSignature);
|
|
3388
|
-
this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
|
|
3389
|
-
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
|
|
3390
|
-
platform: Platform.OS,
|
|
3391
|
-
mode: frameWriteMode,
|
|
3392
|
-
nativeFrameWrite: tuning.nativeFrameWrite,
|
|
3393
|
-
nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
|
|
3394
|
-
packetCapacity,
|
|
3395
|
-
});
|
|
3396
|
-
}
|
|
3397
3034
|
}
|
|
3398
3035
|
|
|
3399
3036
|
if (highThroughputWrite) {
|
|
3400
3037
|
await this.enableAndroidHighConnectionPriority(uuid);
|
|
3401
3038
|
}
|
|
3402
3039
|
|
|
3403
|
-
const fileWritePerf =
|
|
3404
|
-
name === 'FilesystemFileWrite' && options?.fileWritePipeline
|
|
3405
|
-
? createProtocolV2FileWritePerf()
|
|
3406
|
-
: undefined;
|
|
3407
|
-
if (fileWritePerf) {
|
|
3408
|
-
this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
|
|
3409
|
-
}
|
|
3410
|
-
let fileWriteOk = false;
|
|
3411
|
-
|
|
3412
3040
|
try {
|
|
3413
|
-
|
|
3041
|
+
return await this.protocolV2Links.call(
|
|
3414
3042
|
uuid,
|
|
3415
3043
|
() => this.createProtocolV2Adapter(uuid),
|
|
3416
3044
|
name,
|
|
3417
3045
|
data,
|
|
3418
3046
|
callOptions
|
|
3419
3047
|
);
|
|
3420
|
-
fileWriteOk = response.type !== 'Failure';
|
|
3421
|
-
return response;
|
|
3422
3048
|
} catch (e) {
|
|
3423
3049
|
Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
|
|
3424
3050
|
if (
|
|
@@ -3439,15 +3065,6 @@ export default class ReactNativeBleTransport {
|
|
|
3439
3065
|
if (highThroughputWrite) {
|
|
3440
3066
|
this.scheduleAndroidBalancedConnectionPriority(uuid);
|
|
3441
3067
|
}
|
|
3442
|
-
if (fileWritePerf) {
|
|
3443
|
-
if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
|
|
3444
|
-
this.protocolV2FileWritePerfs.delete(uuid);
|
|
3445
|
-
}
|
|
3446
|
-
Log?.debug(
|
|
3447
|
-
'[ReactNativeBleTransport] FileWrite perf',
|
|
3448
|
-
fileWritePerf.summarize(fileWriteOk)
|
|
3449
|
-
);
|
|
3450
|
-
}
|
|
3451
3068
|
}
|
|
3452
3069
|
}
|
|
3453
3070
|
|
|
@@ -3486,19 +3103,6 @@ export default class ReactNativeBleTransport {
|
|
|
3486
3103
|
|
|
3487
3104
|
this.clearAndroidPriorityResetTimer(uuid);
|
|
3488
3105
|
if (this.androidHighPriorityDevices.has(uuid)) return;
|
|
3489
|
-
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);
|
|
3495
|
-
Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
|
|
3496
|
-
apiLevel: Platform.Version,
|
|
3497
|
-
setting: protocolV2BleTuning.androidHighConnectionPriority,
|
|
3498
|
-
});
|
|
3499
|
-
}
|
|
3500
|
-
return;
|
|
3501
|
-
}
|
|
3502
3106
|
|
|
3503
3107
|
const transport = transportCache[uuid];
|
|
3504
3108
|
if (!transport) return;
|
|
@@ -3577,23 +3181,15 @@ export default class ReactNativeBleTransport {
|
|
|
3577
3181
|
assertCurrentGeneration
|
|
3578
3182
|
);
|
|
3579
3183
|
},
|
|
3580
|
-
readFrame: async (
|
|
3184
|
+
readFrame: async () => {
|
|
3581
3185
|
assertCurrentGeneration();
|
|
3582
|
-
const perf =
|
|
3583
|
-
context?.messageName === 'FilesystemFileWrite'
|
|
3584
|
-
? this.protocolV2FileWritePerfs.get(uuid)
|
|
3585
|
-
: undefined;
|
|
3586
|
-
const startedAt = perf ? nowMs() : 0;
|
|
3587
3186
|
const rxFrame = await this.readProtocolV2Frame(uuid);
|
|
3588
|
-
perf?.recordReadWait(nowMs() - startedAt);
|
|
3589
3187
|
if (!(rxFrame instanceof Uint8Array)) {
|
|
3590
3188
|
throw new Error('Protocol V2 response is not Uint8Array');
|
|
3591
3189
|
}
|
|
3592
3190
|
return rxFrame;
|
|
3593
3191
|
},
|
|
3594
3192
|
reset: (reason: string) => {
|
|
3595
|
-
// The frame belongs to this link even after a newer monitor generation took over.
|
|
3596
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
|
|
3597
3193
|
if (this.monitorTokens.get(uuid) !== generation) return;
|
|
3598
3194
|
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3599
3195
|
this.rejectProtocolV2Frames(uuid, new Error(reason));
|