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";
class PortController {
path: null | string;
path: string;
port: null | SerialPort;
port: SerialPort;
parser: any;
onCloseCallback: (error:Error)=>void;
constructor() {
this.path = null;
this.port = null;
this.onCloseCallback = () => {};
}
get isOpen() {
if (!this.port) {
return false;
}
return this.port.isOpen;
}
create(path: string) {
constructor(path: string) {
this.path = path;
this.port = new SerialPort(path, {
baudRate: 9600,
autoOpen: false,
});
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) {
@ -37,10 +35,6 @@ class PortController {
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.on("close", onCloseCallback);
this.onCloseCallback = onCloseCallback;