Simplify class usage
This commit is contained in:
parent
1826475284
commit
e9364c73bf
1 changed files with 15 additions and 21 deletions
|
@ -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;
|
||||||
|
|
Reference in a new issue