@onekeyfe/hd-transport-react-native 1.2.8-alpha.115 → 1.2.8-alpha.117
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 +31 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +319 -10
- package/package.json +5 -5
- package/src/__tests__/nativeFrameWrite.test.ts +917 -0
- package/src/__tests__/protocolV2Link.test.ts +103 -0
- package/src/index.ts +459 -17
package/src/index.ts
CHANGED
|
@@ -190,6 +190,16 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
|
|
|
190
190
|
export type ProtocolV2BleTuning = {
|
|
191
191
|
iosPacketLength?: number;
|
|
192
192
|
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';
|
|
193
203
|
};
|
|
194
204
|
|
|
195
205
|
type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
@@ -197,6 +207,8 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
|
197
207
|
const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
|
|
198
208
|
iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
|
|
199
209
|
androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
|
|
210
|
+
nativeFrameWrite: true,
|
|
211
|
+
androidHighConnectionPriority: 'auto',
|
|
200
212
|
};
|
|
201
213
|
|
|
202
214
|
let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
|
|
@@ -217,6 +229,15 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
|
|
|
217
229
|
tuning.androidPacketLength,
|
|
218
230
|
protocolV2BleTuning.androidPacketLength
|
|
219
231
|
),
|
|
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,
|
|
220
241
|
};
|
|
221
242
|
Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
|
|
222
243
|
}
|
|
@@ -230,6 +251,138 @@ export function getProtocolV2BleTuning() {
|
|
|
230
251
|
return { ...protocolV2BleTuning };
|
|
231
252
|
}
|
|
232
253
|
|
|
254
|
+
/**
|
|
255
|
+
* Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
|
|
256
|
+
* the unpatched release, so the shape is declared here and probed at runtime.
|
|
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
|
+
};
|
|
267
|
+
|
|
268
|
+
type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
|
|
269
|
+
|
|
270
|
+
type ActiveProtocolV2FrameWrite = {
|
|
271
|
+
transactionId: string;
|
|
272
|
+
generation: number;
|
|
273
|
+
cancel: (error: Error) => void;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* A newer JS bundle can run on an older native binary that ships the JS wrapper without the
|
|
278
|
+
* native method, so support comes from the wrapper's native check, never from its presence.
|
|
279
|
+
*/
|
|
280
|
+
const getProtocolV2NativeFrameWriter = (
|
|
281
|
+
manager: BlePlxManager | undefined
|
|
282
|
+
): ProtocolV2NativeFrameWriter | undefined => {
|
|
283
|
+
const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
|
|
284
|
+
if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
|
|
289
|
+
? (candidate as ProtocolV2NativeFrameWriter)
|
|
290
|
+
: undefined;
|
|
291
|
+
} catch {
|
|
292
|
+
return undefined;
|
|
293
|
+
}
|
|
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>;
|
|
385
|
+
|
|
233
386
|
function getDeviceDisplayName(device?: Device | null) {
|
|
234
387
|
return device?.name || device?.localName || null;
|
|
235
388
|
}
|
|
@@ -237,6 +390,24 @@ function getDeviceDisplayName(device?: Device | null) {
|
|
|
237
390
|
const IOS_REQUEST_MTU = 247;
|
|
238
391
|
const ANDROID_REQUEST_MTU = 517;
|
|
239
392
|
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
|
+
};
|
|
240
411
|
|
|
241
412
|
const getRequestedBleMtu = () =>
|
|
242
413
|
Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
|
|
@@ -560,6 +731,13 @@ export default class ReactNativeBleTransport {
|
|
|
560
731
|
|
|
561
732
|
private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
|
|
562
733
|
|
|
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
|
+
|
|
563
741
|
private nextMonitorToken = 1;
|
|
564
742
|
|
|
565
743
|
/** Serializes transport lifecycle changes for the same physical device. */
|
|
@@ -1529,11 +1707,13 @@ export default class ReactNativeBleTransport {
|
|
|
1529
1707
|
}
|
|
1530
1708
|
|
|
1531
1709
|
private async releaseUnlocked(uuid: string, onclose = false) {
|
|
1710
|
+
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1532
1711
|
await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
|
|
1533
1712
|
return this.releaseNative(uuid, onclose);
|
|
1534
1713
|
}
|
|
1535
1714
|
|
|
1536
1715
|
private async releaseNative(uuid: string, onclose = false) {
|
|
1716
|
+
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1537
1717
|
const transport = transportCache[uuid];
|
|
1538
1718
|
const manager = this.blePlxManager;
|
|
1539
1719
|
if (this.runPromise && this.runPromiseDeviceId === uuid) {
|
|
@@ -1954,6 +2134,11 @@ export default class ReactNativeBleTransport {
|
|
|
1954
2134
|
}
|
|
1955
2135
|
|
|
1956
2136
|
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'));
|
|
1957
2142
|
await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
|
|
1958
2143
|
const transport = transportCache[session];
|
|
1959
2144
|
const manager = this.blePlxManager;
|
|
@@ -2431,6 +2616,13 @@ export default class ReactNativeBleTransport {
|
|
|
2431
2616
|
consecutiveWriteTimeouts: timeouts,
|
|
2432
2617
|
});
|
|
2433
2618
|
|
|
2619
|
+
this.cancelProtocolV2FrameWrite(
|
|
2620
|
+
uuid,
|
|
2621
|
+
ERRORS.TypedError(
|
|
2622
|
+
HardwareErrorCode.BleWriteCharacteristicError,
|
|
2623
|
+
`BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
|
|
2624
|
+
)
|
|
2625
|
+
);
|
|
2434
2626
|
const wedged = transportCache[uuid];
|
|
2435
2627
|
this.disconnect(uuid).catch(error => {
|
|
2436
2628
|
Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
|
|
@@ -2458,6 +2650,10 @@ export default class ReactNativeBleTransport {
|
|
|
2458
2650
|
const manager = this.blePlxManager;
|
|
2459
2651
|
this.blePlxManager = undefined;
|
|
2460
2652
|
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
|
+
);
|
|
2461
2657
|
// Destroying the shared manager invalidates every peripheral it owns. Notify
|
|
2462
2658
|
// each cached session before clearing generations so Core cannot retain a
|
|
2463
2659
|
// silently stale connection for an unrelated device.
|
|
@@ -2929,22 +3125,208 @@ export default class ReactNativeBleTransport {
|
|
|
2929
3125
|
androidPacketLength: tuning.androidPacketLength,
|
|
2930
3126
|
mtu: transport.mtuSize,
|
|
2931
3127
|
});
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
3128
|
+
const perf =
|
|
3129
|
+
context.messageName === 'FilesystemFileWrite'
|
|
3130
|
+
? this.protocolV2FileWritePerfs.get(uuid)
|
|
3131
|
+
: undefined;
|
|
3132
|
+
const startedAt = perf ? nowMs() : 0;
|
|
3133
|
+
const nativeFrameWriter =
|
|
3134
|
+
frame.length > packetCapacity
|
|
3135
|
+
? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
|
|
3136
|
+
: undefined;
|
|
3137
|
+
perf?.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
|
|
3138
|
+
if (nativeFrameWriter) {
|
|
3139
|
+
await this.writeProtocolV2NativeFrame(
|
|
3140
|
+
uuid,
|
|
3141
|
+
transport,
|
|
3142
|
+
nativeFrameWriter,
|
|
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;
|
|
2947
3223
|
});
|
|
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
|
+
}
|
|
2948
3330
|
}
|
|
2949
3331
|
|
|
2950
3332
|
private async callProtocolV2(
|
|
@@ -2993,20 +3375,50 @@ export default class ReactNativeBleTransport {
|
|
|
2993
3375
|
packetCapacity,
|
|
2994
3376
|
});
|
|
2995
3377
|
}
|
|
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
|
+
}
|
|
2996
3397
|
}
|
|
2997
3398
|
|
|
2998
3399
|
if (highThroughputWrite) {
|
|
2999
3400
|
await this.enableAndroidHighConnectionPriority(uuid);
|
|
3000
3401
|
}
|
|
3001
3402
|
|
|
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
|
+
|
|
3002
3412
|
try {
|
|
3003
|
-
|
|
3413
|
+
const response = await this.protocolV2Links.call(
|
|
3004
3414
|
uuid,
|
|
3005
3415
|
() => this.createProtocolV2Adapter(uuid),
|
|
3006
3416
|
name,
|
|
3007
3417
|
data,
|
|
3008
3418
|
callOptions
|
|
3009
3419
|
);
|
|
3420
|
+
fileWriteOk = response.type !== 'Failure';
|
|
3421
|
+
return response;
|
|
3010
3422
|
} catch (e) {
|
|
3011
3423
|
Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
|
|
3012
3424
|
if (
|
|
@@ -3027,6 +3439,15 @@ export default class ReactNativeBleTransport {
|
|
|
3027
3439
|
if (highThroughputWrite) {
|
|
3028
3440
|
this.scheduleAndroidBalancedConnectionPriority(uuid);
|
|
3029
3441
|
}
|
|
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
|
+
}
|
|
3030
3451
|
}
|
|
3031
3452
|
}
|
|
3032
3453
|
|
|
@@ -3065,6 +3486,19 @@ export default class ReactNativeBleTransport {
|
|
|
3065
3486
|
|
|
3066
3487
|
this.clearAndroidPriorityResetTimer(uuid);
|
|
3067
3488
|
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
|
+
}
|
|
3068
3502
|
|
|
3069
3503
|
const transport = transportCache[uuid];
|
|
3070
3504
|
if (!transport) return;
|
|
@@ -3143,15 +3577,23 @@ export default class ReactNativeBleTransport {
|
|
|
3143
3577
|
assertCurrentGeneration
|
|
3144
3578
|
);
|
|
3145
3579
|
},
|
|
3146
|
-
readFrame: async () => {
|
|
3580
|
+
readFrame: async (context?: ProtocolV2CallContext) => {
|
|
3147
3581
|
assertCurrentGeneration();
|
|
3582
|
+
const perf =
|
|
3583
|
+
context?.messageName === 'FilesystemFileWrite'
|
|
3584
|
+
? this.protocolV2FileWritePerfs.get(uuid)
|
|
3585
|
+
: undefined;
|
|
3586
|
+
const startedAt = perf ? nowMs() : 0;
|
|
3148
3587
|
const rxFrame = await this.readProtocolV2Frame(uuid);
|
|
3588
|
+
perf?.recordReadWait(nowMs() - startedAt);
|
|
3149
3589
|
if (!(rxFrame instanceof Uint8Array)) {
|
|
3150
3590
|
throw new Error('Protocol V2 response is not Uint8Array');
|
|
3151
3591
|
}
|
|
3152
3592
|
return rxFrame;
|
|
3153
3593
|
},
|
|
3154
3594
|
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);
|
|
3155
3597
|
if (this.monitorTokens.get(uuid) !== generation) return;
|
|
3156
3598
|
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3157
3599
|
this.rejectProtocolV2Frames(uuid, new Error(reason));
|