diff --git a/packages/transport-web-serial/src/transport.ts b/packages/transport-web-serial/src/transport.ts index aeaaa684..1c1706dc 100644 --- a/packages/transport-web-serial/src/transport.ts +++ b/packages/transport-web-serial/src/transport.ts @@ -6,7 +6,7 @@ export class TransportWebSerial implements Types.Transport { private _fromDevice: ReadableStream; private connection: SerialPort; private pipePromise: Promise | null = null; - private abortController = new AbortController(); + private abortController: AbortController; public static async create(baudRate?: number): Promise { const port = await navigator.serial.requestPort(); @@ -28,6 +28,7 @@ export class TransportWebSerial implements Types.Transport { } this.connection = connection; + this.abortController = new AbortController(); // Set up the pipe with abort signal for clean cancellation this.pipePromise = Utils.toDeviceStream.readable.pipeTo( @@ -84,4 +85,19 @@ export class TransportWebSerial implements Types.Transport { console.warn('Could not cleanly disconnect serial port:', error); } } + + /** + * Reconnects the transport by creating a new AbortController and re-establishing + * the pipe connection. Only call this after disconnect() or if the connection failed. + */ + async reconnect() { + // Create a new AbortController for the new connection + this.abortController = new AbortController(); + + // Re-establish the pipe connection + this.pipePromise = Utils.toDeviceStream.readable.pipeTo( + this.connection.writable, + { signal: this.abortController.signal } + ); + } }