fix(usb-deployer): drain stray bytes until quiet window

This commit is contained in:
a2nr 2026-07-17 10:37:08 +07:00
parent 3d941191e3
commit 84827350af
1 changed files with 12 additions and 7 deletions

View File

@ -494,31 +494,36 @@ export class USBHardwareDeployer implements HardwareDeployer {
} }
/** /**
* Drain any stray bytes from the serial input (short timeout). * Drain any stray bytes from the serial input.
* Drains repeatedly until no more bytes arrive or 50ms elapsed. * Keeps reading until no bytes arrive for DRAIN_BYTE_TIMEOUT_MS,
* or DRAIN_TOTAL_MS has elapsed.
*/ */
private async drainStray(): Promise<void> { private async drainStray(): Promise<void> {
const deadline = Date.now() + 50; const deadline = Date.now() + DRAIN_TOTAL_MS;
let totalDrained = 0; let totalDrained = 0;
while (Date.now() < deadline) { while (Date.now() < deadline) {
try { try {
const { value, done } = await Promise.race([ const { value, done } = await Promise.race([
this.reader!.read(), this.reader!.read(),
new Promise<never>((_, reject) => new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('timeout')), 10) setTimeout(() => reject(new Error('timeout')), DRAIN_BYTE_TIMEOUT_MS)
) )
]); ]);
if (done) break; if (done) break;
if (value && value.length > 0) { if (value && value.length > 0) {
totalDrained += value.length; totalDrained += value.length;
/* Got bytes; keep looping inside the same deadline window. */
continue;
} }
/* Empty chunk: treat same as a quiet window. */
break;
} catch { } catch {
/* timeout — no more bytes available */ /* No bytes available for DRAIN_BYTE_TIMEOUT_MS -> channel is clean. */
break; break;
} }
} }
if (totalDrained > 0) { if (totalDrained > 0) {
console.log(`[USB] drained ${totalDrained} stray bytes`); console.log(`[USB] drained ${totalDrained} stray bytes`);
} }