Simplify class usage

This commit is contained in:
GHOSCHT 2021-12-31 22:18:35 +01:00
parent 1826475284
commit e9364c73bf
No known key found for this signature in database
GPG key ID: A35BD466B8871994

View file

@ -1,35 +1,33 @@
import SerialPort, { parsers } from "serialport"; import SerialPort, { parsers } from "serialport";
class PortController { class PortController {
path: null | string; path: string;
port: null | SerialPort; port: SerialPort;
parser: any; parser: any;
onCloseCallback: (error:Error)=>void; onCloseCallback: (error:Error)=>void;
constructor() { constructor(path: string) {
this.path = null;
this.port = null;
this.onCloseCallback = () => {};
}
get isOpen() {
if (!this.port) {
return false;
}
return this.port.isOpen;
}
create(path: string) {
this.path = path; this.path = path;
this.port = new SerialPort(path, { this.port = new SerialPort(path, {
baudRate: 9600, baudRate: 9600,
autoOpen: false, autoOpen: false,
}); });
this.parser = this.port.pipe(new parsers.Readline({ delimiter: "\r\n" })); this.parser = this.port.pipe(new parsers.Readline({ delimiter: "\r\n" }));
this.onCloseCallback = () => {};
}
get isOpen(): boolean {
if (this.port == null) {
return false;
}
return this.port.isOpen;
}
get getParser(): any {
return this.parser;
} }
open(callback: (error:Error | null | undefined)=>void, onCloseCallback:(error:Error | null | undefined)=>void) { open(callback: (error:Error | null | undefined)=>void, onCloseCallback:(error:Error | null | undefined)=>void) {
@ -37,10 +35,6 @@ class PortController {
throw new Error("Port already open"); throw new Error("Port already open");
} }
if (this.port === null) {
throw new Error("Port must be created first");
}
this.port.open((error) => callback(error)); this.port.open((error) => callback(error));
this.port.on("close", onCloseCallback); this.port.on("close", onCloseCallback);
this.onCloseCallback = onCloseCallback; this.onCloseCallback = onCloseCallback;