Initial commit
This commit is contained in:
commit
a892dfb3ba
27 changed files with 6607 additions and 0 deletions
63
utils/SerialTransport.ts
Normal file
63
utils/SerialTransport.ts
Normal file
|
@ -0,0 +1,63 @@
|
|||
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,
|
||||
};
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue