web-flasher-ng/utils/SerialTransport.ts

63 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2024-12-07 16:48:13 +00:00
export class SerialTransport {
private port: SerialPort;
private reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
private writer: WritableStreamDefaultWriter<Uint8Array> | null = null;
constructor(port: SerialPort) {
this.port = port;
}
async connect() {
if (this.reader || this.writer) {
await this.disconnect();
}
const decoder = new TextDecoderStream();
const inputDone = this.port.readable!.pipeTo(decoder.writable);
const inputStream = decoder.readable;
this.reader = inputStream.getReader();
this.writer = this.port.writable!.getWriter();
}
async disconnect() {
if (this.reader) {
await this.reader.cancel();
this.reader.releaseLock();
this.reader = null;
}
if (this.writer) {
await this.writer.close();
this.writer.releaseLock();
this.writer = null;
}
if (this.port.readable) {
await this.port.readable.cancel();
}
}
async write(data: Uint8Array) {
if (!this.writer) {
throw new Error('Transport not connected');
}
await this.writer.write(data);
}
async read() {
if (!this.reader) {
throw new Error('Transport not connected');
}
const { value, done } = await this.reader.read();
if (done) {
throw new Error('Serial port closed');
}
return new TextEncoder().encode(value);
}
get_info() {
return {
transport: 'serial',
baud: 115200,
};
}
}