@onekeyfe/hd-transport-react-native 1.2.8-alpha.120 → 1.2.8-alpha.121
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 +0 -35
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -315
- package/package.json +5 -5
- package/src/__tests__/protocolV2Link.test.ts +0 -96
- package/src/index.ts +30 -450
- package/src/__tests__/nativeFrameWrite.test.ts +0 -910
package/src/index.ts
CHANGED
|
@@ -168,11 +168,6 @@ const isWedgedWriteError = (error: unknown): boolean =>
|
|
|
168
168
|
(error as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleWriteCharacteristicError &&
|
|
169
169
|
typeof (error as { message?: unknown })?.message === 'string' &&
|
|
170
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
|
-
);
|
|
176
171
|
const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
|
|
177
172
|
const code = (error as { errorCode?: unknown })?.errorCode;
|
|
178
173
|
// Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
|
|
@@ -197,16 +192,6 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
|
|
|
197
192
|
export type ProtocolV2BleTuning = {
|
|
198
193
|
iosPacketLength?: number;
|
|
199
194
|
androidPacketLength?: number;
|
|
200
|
-
/**
|
|
201
|
-
* Write each multi-packet high-throughput frame with one native call when the native
|
|
202
|
-
* BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
|
|
203
|
-
*/
|
|
204
|
-
nativeFrameWrite?: boolean;
|
|
205
|
-
/**
|
|
206
|
-
* Android CONNECTION_PRIORITY_HIGH around Protocol V2 high-throughput calls. 'auto' (the
|
|
207
|
-
* default) requests it below Android 17 only; true or false forces it on every version.
|
|
208
|
-
*/
|
|
209
|
-
androidHighConnectionPriority?: boolean | 'auto';
|
|
210
195
|
};
|
|
211
196
|
|
|
212
197
|
type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
@@ -214,8 +199,6 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
|
|
|
214
199
|
const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
|
|
215
200
|
iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
|
|
216
201
|
androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
|
|
217
|
-
nativeFrameWrite: true,
|
|
218
|
-
androidHighConnectionPriority: 'auto',
|
|
219
202
|
};
|
|
220
203
|
|
|
221
204
|
let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
|
|
@@ -236,15 +219,6 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
|
|
|
236
219
|
tuning.androidPacketLength,
|
|
237
220
|
protocolV2BleTuning.androidPacketLength
|
|
238
221
|
),
|
|
239
|
-
nativeFrameWrite:
|
|
240
|
-
typeof tuning.nativeFrameWrite === 'boolean'
|
|
241
|
-
? tuning.nativeFrameWrite
|
|
242
|
-
: protocolV2BleTuning.nativeFrameWrite,
|
|
243
|
-
androidHighConnectionPriority:
|
|
244
|
-
typeof tuning.androidHighConnectionPriority === 'boolean' ||
|
|
245
|
-
tuning.androidHighConnectionPriority === 'auto'
|
|
246
|
-
? tuning.androidHighConnectionPriority
|
|
247
|
-
: protocolV2BleTuning.androidHighConnectionPriority,
|
|
248
222
|
};
|
|
249
223
|
Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
|
|
250
224
|
}
|
|
@@ -258,140 +232,6 @@ export function getProtocolV2BleTuning() {
|
|
|
258
232
|
return { ...protocolV2BleTuning };
|
|
259
233
|
}
|
|
260
234
|
|
|
261
|
-
/**
|
|
262
|
-
* Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
|
|
263
|
-
* the unpatched release, so the shape is declared here and probed at runtime.
|
|
264
|
-
*/
|
|
265
|
-
type ProtocolV2NativeFrameWriteExtension = {
|
|
266
|
-
isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
|
|
267
|
-
writeCharacteristicWithoutResponseFrame?: (
|
|
268
|
-
characteristicIdentifier: number,
|
|
269
|
-
base64Frame: string,
|
|
270
|
-
packetSize: number,
|
|
271
|
-
transactionId: string
|
|
272
|
-
) => Promise<void>;
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
|
|
276
|
-
|
|
277
|
-
type ActiveProtocolV2FrameWrite = {
|
|
278
|
-
generation: number;
|
|
279
|
-
cancel: (error: Error) => void;
|
|
280
|
-
};
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* A newer JS bundle can run on an older native binary that ships the JS wrapper without the
|
|
284
|
-
* native method, so support comes from the wrapper's native check, never from its presence.
|
|
285
|
-
*/
|
|
286
|
-
const getProtocolV2NativeFrameWriter = (
|
|
287
|
-
manager: BlePlxManager | undefined
|
|
288
|
-
): ProtocolV2NativeFrameWriter | undefined => {
|
|
289
|
-
const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
|
|
290
|
-
if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
|
|
291
|
-
return undefined;
|
|
292
|
-
}
|
|
293
|
-
try {
|
|
294
|
-
return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
|
|
295
|
-
? (candidate as ProtocolV2NativeFrameWriter)
|
|
296
|
-
: undefined;
|
|
297
|
-
} catch {
|
|
298
|
-
return undefined;
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
const getNativeBleErrorReason = (error: unknown): string | undefined => {
|
|
303
|
-
const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
|
|
304
|
-
if (typeof reason === 'string' && reason) return reason;
|
|
305
|
-
return typeof message === 'string' && message ? message : undefined;
|
|
306
|
-
};
|
|
307
|
-
|
|
308
|
-
type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
|
|
309
|
-
|
|
310
|
-
const nowMs = () =>
|
|
311
|
-
typeof performance !== 'undefined' && typeof performance.now === 'function'
|
|
312
|
-
? performance.now()
|
|
313
|
-
: Date.now();
|
|
314
|
-
|
|
315
|
-
const roundMs = (ms: number) => Math.round(ms * 10) / 10;
|
|
316
|
-
|
|
317
|
-
/** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
|
|
318
|
-
const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
|
|
319
|
-
|
|
320
|
-
const createDurationStats = () => {
|
|
321
|
-
let total = 0;
|
|
322
|
-
let count = 0;
|
|
323
|
-
let max = 0;
|
|
324
|
-
return {
|
|
325
|
-
add(ms: number) {
|
|
326
|
-
total += ms;
|
|
327
|
-
count += 1;
|
|
328
|
-
max = Math.max(max, ms);
|
|
329
|
-
},
|
|
330
|
-
summarize: () => ({
|
|
331
|
-
total: roundMs(total),
|
|
332
|
-
avg: count ? roundMs(total / count) : 0,
|
|
333
|
-
max: roundMs(max),
|
|
334
|
-
}),
|
|
335
|
-
};
|
|
336
|
-
};
|
|
337
|
-
|
|
338
|
-
/** Scalar-only timing of one pipelined FilesystemFileWrite call. */
|
|
339
|
-
const createProtocolV2FileWritePerf = () => {
|
|
340
|
-
const startedAt = nowMs();
|
|
341
|
-
let nativeFrames = 0;
|
|
342
|
-
let frames = 0;
|
|
343
|
-
let packets = 0;
|
|
344
|
-
let frameBytes = 0;
|
|
345
|
-
const write = createDurationStats();
|
|
346
|
-
const readWait = createDurationStats();
|
|
347
|
-
const packet = createDurationStats();
|
|
348
|
-
const packetHistogram = Array.from(
|
|
349
|
-
{ length: FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length + 1 },
|
|
350
|
-
() => 0
|
|
351
|
-
);
|
|
352
|
-
|
|
353
|
-
return {
|
|
354
|
-
/** Called before each frame write so a frame that fails still reports its mode. */
|
|
355
|
-
startFrame(mode: ProtocolV2FrameWriteMode) {
|
|
356
|
-
if (mode === 'native-frame') nativeFrames += 1;
|
|
357
|
-
},
|
|
358
|
-
recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
|
|
359
|
-
frames += 1;
|
|
360
|
-
packets += framePackets;
|
|
361
|
-
frameBytes += bytes;
|
|
362
|
-
write.add(elapsedMs);
|
|
363
|
-
},
|
|
364
|
-
recordPacket(elapsedMs: number) {
|
|
365
|
-
packet.add(elapsedMs);
|
|
366
|
-
const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
|
|
367
|
-
packetHistogram[bucket < 0 ? packetHistogram.length - 1 : bucket] += 1;
|
|
368
|
-
},
|
|
369
|
-
recordReadWait(elapsedMs: number) {
|
|
370
|
-
readWait.add(elapsedMs);
|
|
371
|
-
},
|
|
372
|
-
summarize(ok: boolean) {
|
|
373
|
-
const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
|
|
374
|
-
const packetStats = packet.summarize();
|
|
375
|
-
return {
|
|
376
|
-
platform: Platform.OS,
|
|
377
|
-
mode,
|
|
378
|
-
ok,
|
|
379
|
-
frames,
|
|
380
|
-
packets,
|
|
381
|
-
frameBytes,
|
|
382
|
-
elapsedMs: roundMs(nowMs() - startedAt),
|
|
383
|
-
writeMs: write.summarize(),
|
|
384
|
-
readWaitMs: readWait.summarize(),
|
|
385
|
-
...(mode === 'per-packet'
|
|
386
|
-
? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
|
|
387
|
-
: {}),
|
|
388
|
-
};
|
|
389
|
-
},
|
|
390
|
-
};
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
|
|
394
|
-
|
|
395
235
|
function getDeviceDisplayName(device?: Device | null) {
|
|
396
236
|
return device?.name || device?.localName || null;
|
|
397
237
|
}
|
|
@@ -427,24 +267,6 @@ function withBleColorCode(device: IOneKeyDevice): IOneKeyDevice {
|
|
|
427
267
|
const IOS_REQUEST_MTU = 247;
|
|
428
268
|
const ANDROID_REQUEST_MTU = 517;
|
|
429
269
|
const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
|
|
430
|
-
/**
|
|
431
|
-
* Android 17 maps CONNECTION_PRIORITY_HIGH to 11.25-15 ms with peripheral latency 1. OneKey BLE
|
|
432
|
-
* firmware accepts any latency at its 15 ms interval, and latency 1 roughly halves Protocol V2
|
|
433
|
-
* FileWrite throughput. BLE 1.0.23 requests 15 ms with latency 0 by itself; older BLE firmware
|
|
434
|
-
* asks for 15-30 ms or nothing and has not been measured on Android 17 without HIGH.
|
|
435
|
-
*/
|
|
436
|
-
const ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL = 37;
|
|
437
|
-
|
|
438
|
-
const shouldRequestAndroidHighConnectionPriority = () => {
|
|
439
|
-
if (Platform.OS !== 'android') return false;
|
|
440
|
-
const { androidHighConnectionPriority } = protocolV2BleTuning;
|
|
441
|
-
if (typeof androidHighConnectionPriority === 'boolean') return androidHighConnectionPriority;
|
|
442
|
-
const apiLevel = Number(Platform.Version);
|
|
443
|
-
// Unknown versions keep the long-standing HIGH request.
|
|
444
|
-
return (
|
|
445
|
-
!Number.isFinite(apiLevel) || apiLevel < ANDROID_HIGH_PRIORITY_PERIPHERAL_LATENCY_API_LEVEL
|
|
446
|
-
);
|
|
447
|
-
};
|
|
448
270
|
|
|
449
271
|
const getRequestedBleMtu = () =>
|
|
450
272
|
Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
|
|
@@ -770,13 +592,6 @@ export default class ReactNativeBleTransport {
|
|
|
770
592
|
|
|
771
593
|
private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
|
|
772
594
|
|
|
773
|
-
/** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
|
|
774
|
-
private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
|
|
775
|
-
|
|
776
|
-
private protocolV2FrameWriteCounter = 0;
|
|
777
|
-
|
|
778
|
-
private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
|
|
779
|
-
|
|
780
595
|
private nextMonitorToken = 1;
|
|
781
596
|
|
|
782
597
|
/** Serializes transport lifecycle changes for the same physical device. */
|
|
@@ -1752,14 +1567,11 @@ export default class ReactNativeBleTransport {
|
|
|
1752
1567
|
}
|
|
1753
1568
|
|
|
1754
1569
|
private async releaseUnlocked(uuid: string, onclose = false) {
|
|
1755
|
-
|
|
1756
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error(reason));
|
|
1757
|
-
await this.protocolV2Links.invalidateLink(uuid, reason);
|
|
1570
|
+
await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
|
|
1758
1571
|
return this.releaseNative(uuid, onclose);
|
|
1759
1572
|
}
|
|
1760
1573
|
|
|
1761
1574
|
private async releaseNative(uuid: string, onclose = false) {
|
|
1762
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
|
|
1763
1575
|
const transport = transportCache[uuid];
|
|
1764
1576
|
const manager = this.blePlxManager;
|
|
1765
1577
|
if (this.runPromise && this.runPromiseDeviceId === uuid) {
|
|
@@ -2180,13 +1992,7 @@ export default class ReactNativeBleTransport {
|
|
|
2180
1992
|
}
|
|
2181
1993
|
|
|
2182
1994
|
private async disconnectUnlocked(session: string) {
|
|
2183
|
-
|
|
2184
|
-
// Balanced restore from this link must not carry over to it.
|
|
2185
|
-
this.clearAndroidPriorityResetTimer(session);
|
|
2186
|
-
this.androidHighPriorityDevices.delete(session);
|
|
2187
|
-
const reason = 'React Native BLE transport disconnected';
|
|
2188
|
-
this.cancelProtocolV2FrameWrite(session, new Error(reason));
|
|
2189
|
-
await this.protocolV2Links.invalidateLink(session, reason);
|
|
1995
|
+
await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
|
|
2190
1996
|
const transport = transportCache[session];
|
|
2191
1997
|
const manager = this.blePlxManager;
|
|
2192
1998
|
const monitorToken = transport?.monitorToken ?? this.monitorTokens.get(session);
|
|
@@ -2624,7 +2430,12 @@ export default class ReactNativeBleTransport {
|
|
|
2624
2430
|
new Promise<never>((_, reject) => {
|
|
2625
2431
|
timer = setTimeout(() => {
|
|
2626
2432
|
timedOut = true;
|
|
2627
|
-
reject(
|
|
2433
|
+
reject(
|
|
2434
|
+
ERRORS.TypedError(
|
|
2435
|
+
HardwareErrorCode.BleWriteCharacteristicError,
|
|
2436
|
+
`BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
|
|
2437
|
+
)
|
|
2438
|
+
);
|
|
2628
2439
|
}, BLE_WRITE_PACKET_TIMEOUT_MS);
|
|
2629
2440
|
}),
|
|
2630
2441
|
]);
|
|
@@ -2658,7 +2469,6 @@ export default class ReactNativeBleTransport {
|
|
|
2658
2469
|
consecutiveWriteTimeouts: timeouts,
|
|
2659
2470
|
});
|
|
2660
2471
|
|
|
2661
|
-
this.cancelProtocolV2FrameWrite(uuid, createWedgedWriteError());
|
|
2662
2472
|
const wedged = transportCache[uuid];
|
|
2663
2473
|
this.disconnect(uuid).catch(error => {
|
|
2664
2474
|
Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
|
|
@@ -2686,8 +2496,6 @@ export default class ReactNativeBleTransport {
|
|
|
2686
2496
|
const manager = this.blePlxManager;
|
|
2687
2497
|
this.blePlxManager = undefined;
|
|
2688
2498
|
const reason = 'React Native BLE manager reset';
|
|
2689
|
-
// Cancel through the manager that started each frame before destroy() drops its queue.
|
|
2690
|
-
this.protocolV2FrameWrites.forEach(active => active.cancel(new Error(reason)));
|
|
2691
2499
|
// Destroying the shared manager invalidates every peripheral it owns. Notify
|
|
2692
2500
|
// each cached session before clearing generations so Core cannot retain a
|
|
2693
2501
|
// silently stale connection for an unrelated device.
|
|
@@ -3159,204 +2967,22 @@ export default class ReactNativeBleTransport {
|
|
|
3159
2967
|
androidPacketLength: tuning.androidPacketLength,
|
|
3160
2968
|
mtu: transport.mtuSize,
|
|
3161
2969
|
});
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
assertCurrentGeneration
|
|
3178
|
-
);
|
|
3179
|
-
} else {
|
|
3180
|
-
await writeProtocolV2BleFrame({
|
|
3181
|
-
frame,
|
|
3182
|
-
packetCapacity,
|
|
3183
|
-
assertActive: assertCurrentGeneration,
|
|
3184
|
-
signal: context.signal,
|
|
3185
|
-
abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
|
|
3186
|
-
wait: delay,
|
|
3187
|
-
writePacket: async packet => {
|
|
3188
|
-
const packetStartedAt = perf ? nowMs() : 0;
|
|
3189
|
-
await this.writeProtocolV2Packet(
|
|
3190
|
-
uuid,
|
|
3191
|
-
transport,
|
|
3192
|
-
Buffer.from(packet).toString('base64'),
|
|
3193
|
-
context,
|
|
3194
|
-
assertCurrentGeneration
|
|
3195
|
-
);
|
|
3196
|
-
perf?.recordPacket(nowMs() - packetStartedAt);
|
|
3197
|
-
},
|
|
3198
|
-
});
|
|
3199
|
-
}
|
|
3200
|
-
perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
|
|
3201
|
-
}
|
|
3202
|
-
|
|
3203
|
-
/**
|
|
3204
|
-
* The native frame write only replaces the per-packet loop where its JS<->native round trips
|
|
3205
|
-
* dominate: multi-packet (checked by the caller) high-throughput frames written without response.
|
|
3206
|
-
*/
|
|
3207
|
-
private resolveProtocolV2NativeFrameWriter(
|
|
3208
|
-
transport: BleTransport,
|
|
3209
|
-
context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
|
|
3210
|
-
nativeFrameWrite: boolean
|
|
3211
|
-
): ProtocolV2NativeFrameWriter | undefined {
|
|
3212
|
-
if (!context.highThroughput || !nativeFrameWrite) return undefined;
|
|
3213
|
-
if (
|
|
3214
|
-
shouldWriteProtocolV2WithResponse({
|
|
3215
|
-
platform: Platform.OS,
|
|
3216
|
-
highThroughput: context.highThroughput,
|
|
3217
|
-
requestedWithResponse: context.writeWithResponse,
|
|
3218
|
-
characteristic: transport.writeCharacteristic,
|
|
3219
|
-
})
|
|
3220
|
-
) {
|
|
3221
|
-
return undefined;
|
|
3222
|
-
}
|
|
3223
|
-
if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
|
|
3224
|
-
return getProtocolV2NativeFrameWriter(this.blePlxManager);
|
|
3225
|
-
}
|
|
3226
|
-
|
|
3227
|
-
/**
|
|
3228
|
-
* Writes one frame with a single native call that sends its packets in order without response.
|
|
3229
|
-
* Nothing here retries it: a resend could duplicate bytes the device already received. The
|
|
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.
|
|
3233
|
-
*/
|
|
3234
|
-
private async writeProtocolV2NativeFrame(
|
|
3235
|
-
uuid: string,
|
|
3236
|
-
transport: BleTransport,
|
|
3237
|
-
manager: ProtocolV2NativeFrameWriter,
|
|
3238
|
-
frame: Uint8Array,
|
|
3239
|
-
packetCapacity: number,
|
|
3240
|
-
context: ProtocolV2CallContext,
|
|
3241
|
-
assertCurrentGeneration: () => void
|
|
3242
|
-
) {
|
|
3243
|
-
const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
|
|
3244
|
-
assertCurrentGeneration();
|
|
3245
|
-
if (context.signal.aborted) {
|
|
3246
|
-
throw new Error(abortMessage);
|
|
3247
|
-
}
|
|
3248
|
-
|
|
3249
|
-
this.protocolV2FrameWriteCounter += 1;
|
|
3250
|
-
const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
|
|
3251
|
-
let cancelError: Error | undefined;
|
|
3252
|
-
let rejectCancelled: (error: Error) => void = () => undefined;
|
|
3253
|
-
const cancelled = new Promise<never>((_, reject) => {
|
|
3254
|
-
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
|
+
),
|
|
3255
2985
|
});
|
|
3256
|
-
const active: ActiveProtocolV2FrameWrite = {
|
|
3257
|
-
generation: context.generation,
|
|
3258
|
-
cancel: error => {
|
|
3259
|
-
if (cancelError) return;
|
|
3260
|
-
cancelError = error;
|
|
3261
|
-
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3262
|
-
this.protocolV2FrameWrites.delete(uuid);
|
|
3263
|
-
}
|
|
3264
|
-
rejectCancelled(error);
|
|
3265
|
-
this.cancelNativeTransaction(manager, transactionId);
|
|
3266
|
-
},
|
|
3267
|
-
};
|
|
3268
|
-
// Same rule as writeBlePacket: a superseded generation must not tear down the current link.
|
|
3269
|
-
const isCurrentOwner = () => {
|
|
3270
|
-
try {
|
|
3271
|
-
assertCurrentGeneration();
|
|
3272
|
-
return !context.signal.aborted;
|
|
3273
|
-
} catch {
|
|
3274
|
-
return false;
|
|
3275
|
-
}
|
|
3276
|
-
};
|
|
3277
|
-
const onAbort = () => active.cancel(new Error(abortMessage));
|
|
3278
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
3279
|
-
try {
|
|
3280
|
-
const nativeWrite = Promise.resolve(
|
|
3281
|
-
manager.writeCharacteristicWithoutResponseFrame(
|
|
3282
|
-
transport.writeCharacteristic.id,
|
|
3283
|
-
Buffer.from(frame).toString('base64'),
|
|
3284
|
-
packetCapacity,
|
|
3285
|
-
transactionId
|
|
3286
|
-
)
|
|
3287
|
-
);
|
|
3288
|
-
// A cancelled or timed-out frame still settles natively later; that outcome is ignored.
|
|
3289
|
-
nativeWrite.catch(() => undefined);
|
|
3290
|
-
this.protocolV2FrameWrites.set(uuid, active);
|
|
3291
|
-
context.signal.addEventListener('abort', onAbort);
|
|
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]);
|
|
3302
|
-
} catch (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
|
-
);
|
|
3311
|
-
} finally {
|
|
3312
|
-
if (timer) clearTimeout(timer);
|
|
3313
|
-
context.signal.removeEventListener('abort', onAbort);
|
|
3314
|
-
if (this.protocolV2FrameWrites.get(uuid) === active) {
|
|
3315
|
-
this.protocolV2FrameWrites.delete(uuid);
|
|
3316
|
-
}
|
|
3317
|
-
}
|
|
3318
|
-
|
|
3319
|
-
this.writeTimeoutCounts.delete(uuid);
|
|
3320
|
-
try {
|
|
3321
|
-
assertCurrentGeneration();
|
|
3322
|
-
} catch (error) {
|
|
3323
|
-
active.cancel(error instanceof Error ? error : new Error(String(error)));
|
|
3324
|
-
}
|
|
3325
|
-
if (cancelError) throw cancelError;
|
|
3326
|
-
}
|
|
3327
|
-
|
|
3328
|
-
/** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
|
|
3329
|
-
private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
|
|
3330
|
-
const active = this.protocolV2FrameWrites.get(uuid);
|
|
3331
|
-
if (!active || (generation !== undefined && active.generation !== generation)) return;
|
|
3332
|
-
active.cancel(error);
|
|
3333
|
-
}
|
|
3334
|
-
|
|
3335
|
-
private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
|
|
3336
|
-
const logFailure = (error: unknown) =>
|
|
3337
|
-
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
|
|
3338
|
-
error: error instanceof Error ? error.message : String(error),
|
|
3339
|
-
});
|
|
3340
|
-
try {
|
|
3341
|
-
Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
|
|
3342
|
-
} catch (error) {
|
|
3343
|
-
logFailure(error);
|
|
3344
|
-
}
|
|
3345
|
-
}
|
|
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
2986
|
}
|
|
3361
2987
|
|
|
3362
2988
|
private async callProtocolV2(
|
|
@@ -3393,7 +3019,11 @@ export default class ReactNativeBleTransport {
|
|
|
3393
3019
|
const logSignature = `${name}:${writeMode}:${String(
|
|
3394
3020
|
currentTransport.mtuSize
|
|
3395
3021
|
)}:${packetCapacity}`;
|
|
3396
|
-
|
|
3022
|
+
const loggedSignatures =
|
|
3023
|
+
this.protocolV2HighVolumeLogSignatures.get(uuid) ?? new Set<string>();
|
|
3024
|
+
if (!loggedSignatures.has(logSignature)) {
|
|
3025
|
+
loggedSignatures.add(logSignature);
|
|
3026
|
+
this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
|
|
3397
3027
|
Log?.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
|
|
3398
3028
|
name,
|
|
3399
3029
|
writeMode,
|
|
@@ -3401,47 +3031,20 @@ export default class ReactNativeBleTransport {
|
|
|
3401
3031
|
packetCapacity,
|
|
3402
3032
|
});
|
|
3403
3033
|
}
|
|
3404
|
-
const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
|
|
3405
|
-
currentTransport,
|
|
3406
|
-
{ highThroughput: true, writeWithResponse: options?.writeWithResponse },
|
|
3407
|
-
tuning.nativeFrameWrite
|
|
3408
|
-
)
|
|
3409
|
-
? 'native-frame'
|
|
3410
|
-
: 'per-packet';
|
|
3411
|
-
if (this.markProtocolV2LogSignature(uuid, `frameWriteMode:${frameWriteMode}`)) {
|
|
3412
|
-
Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
|
|
3413
|
-
platform: Platform.OS,
|
|
3414
|
-
mode: frameWriteMode,
|
|
3415
|
-
nativeFrameWrite: tuning.nativeFrameWrite,
|
|
3416
|
-
nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
|
|
3417
|
-
packetCapacity,
|
|
3418
|
-
});
|
|
3419
|
-
}
|
|
3420
3034
|
}
|
|
3421
3035
|
|
|
3422
3036
|
if (highThroughputWrite) {
|
|
3423
3037
|
await this.enableAndroidHighConnectionPriority(uuid);
|
|
3424
3038
|
}
|
|
3425
3039
|
|
|
3426
|
-
const fileWritePerf =
|
|
3427
|
-
name === 'FilesystemFileWrite' && options?.fileWritePipeline
|
|
3428
|
-
? createProtocolV2FileWritePerf()
|
|
3429
|
-
: undefined;
|
|
3430
|
-
if (fileWritePerf) {
|
|
3431
|
-
this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
|
|
3432
|
-
}
|
|
3433
|
-
let fileWriteOk = false;
|
|
3434
|
-
|
|
3435
3040
|
try {
|
|
3436
|
-
|
|
3041
|
+
return await this.protocolV2Links.call(
|
|
3437
3042
|
uuid,
|
|
3438
3043
|
() => this.createProtocolV2Adapter(uuid),
|
|
3439
3044
|
name,
|
|
3440
3045
|
data,
|
|
3441
3046
|
callOptions
|
|
3442
3047
|
);
|
|
3443
|
-
fileWriteOk = response.type !== 'Failure';
|
|
3444
|
-
return response;
|
|
3445
3048
|
} catch (e) {
|
|
3446
3049
|
Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
|
|
3447
3050
|
if (
|
|
@@ -3462,15 +3065,6 @@ export default class ReactNativeBleTransport {
|
|
|
3462
3065
|
if (highThroughputWrite) {
|
|
3463
3066
|
this.scheduleAndroidBalancedConnectionPriority(uuid);
|
|
3464
3067
|
}
|
|
3465
|
-
if (fileWritePerf) {
|
|
3466
|
-
if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
|
|
3467
|
-
this.protocolV2FileWritePerfs.delete(uuid);
|
|
3468
|
-
}
|
|
3469
|
-
Log?.debug(
|
|
3470
|
-
'[ReactNativeBleTransport] FileWrite perf',
|
|
3471
|
-
fileWritePerf.summarize(fileWriteOk)
|
|
3472
|
-
);
|
|
3473
|
-
}
|
|
3474
3068
|
}
|
|
3475
3069
|
}
|
|
3476
3070
|
|
|
@@ -3509,15 +3103,6 @@ export default class ReactNativeBleTransport {
|
|
|
3509
3103
|
|
|
3510
3104
|
this.clearAndroidPriorityResetTimer(uuid);
|
|
3511
3105
|
if (this.androidHighPriorityDevices.has(uuid)) return;
|
|
3512
|
-
if (!shouldRequestAndroidHighConnectionPriority()) {
|
|
3513
|
-
if (this.markProtocolV2LogSignature(uuid, 'androidPriority:peripheral')) {
|
|
3514
|
-
Log?.debug('[ReactNativeBleTransport] Android BLE connection priority left to peripheral', {
|
|
3515
|
-
apiLevel: Platform.Version,
|
|
3516
|
-
setting: protocolV2BleTuning.androidHighConnectionPriority,
|
|
3517
|
-
});
|
|
3518
|
-
}
|
|
3519
|
-
return;
|
|
3520
|
-
}
|
|
3521
3106
|
|
|
3522
3107
|
const transport = transportCache[uuid];
|
|
3523
3108
|
if (!transport) return;
|
|
@@ -3596,20 +3181,15 @@ export default class ReactNativeBleTransport {
|
|
|
3596
3181
|
assertCurrentGeneration
|
|
3597
3182
|
);
|
|
3598
3183
|
},
|
|
3599
|
-
readFrame: async (
|
|
3184
|
+
readFrame: async () => {
|
|
3600
3185
|
assertCurrentGeneration();
|
|
3601
|
-
const perf = this.getProtocolV2FileWritePerf(uuid, context);
|
|
3602
|
-
const startedAt = perf ? nowMs() : 0;
|
|
3603
3186
|
const rxFrame = await this.readProtocolV2Frame(uuid);
|
|
3604
|
-
perf?.recordReadWait(nowMs() - startedAt);
|
|
3605
3187
|
if (!(rxFrame instanceof Uint8Array)) {
|
|
3606
3188
|
throw new Error('Protocol V2 response is not Uint8Array');
|
|
3607
3189
|
}
|
|
3608
3190
|
return rxFrame;
|
|
3609
3191
|
},
|
|
3610
3192
|
reset: (reason: string) => {
|
|
3611
|
-
// The frame belongs to this link even after a newer monitor generation took over.
|
|
3612
|
-
this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
|
|
3613
3193
|
if (this.monitorTokens.get(uuid) !== generation) return;
|
|
3614
3194
|
this.protocolV2Assemblers.get(uuid)?.reset();
|
|
3615
3195
|
this.rejectProtocolV2Frames(uuid, new Error(reason));
|