63 lines
No EOL
1.4 KiB
TypeScript
63 lines
No EOL
1.4 KiB
TypeScript
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,
|
|
};
|
|
}
|
|
} |