-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial.ts
More file actions
71 lines (53 loc) · 1.54 KB
/
serial.ts
File metadata and controls
71 lines (53 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { close, createReadStream, existsSync, open, read, write } from "fs";
import { Message, LoginMessage } from "@packtrack/protocol";
import { SerialPort as NativePort } from "serialport";
import { Device } from "@packtrack/layout";
export class SerialPort {
private static ports: SerialPort[] = [];
private handle: NativePort;
device: Device;
private messageQueue: Buffer[] = [];
private messageBuffer = Buffer.from([]);
constructor(
private port: string,
private handleMessage: (message: Message) => void
) {}
async attach() {
this.handle = new NativePort({
path: this.port,
baudRate: 9600,
autoOpen: false
});
SerialPort.ports.push(this);
this.handle.on('data', data => {
console.log('*', data.toString());
this.messageBuffer = Message.dispatch(this.messageBuffer, data, message => {
if (message.routes(...LoginMessage.route)) {
this.device = new Device(message.headers.device);
// the processor needs quite some time to process the messages
setInterval(() => {
const message = this.messageQueue.shift();
if (message) {
this.handle.write(message);
}
}, 100);
return;
}
this.handleMessage(message);
});
});
this.handle.on('error', error => {
console.log('cannot open handle', error);
});
await new Promise<void>((done, fail) => this.handle.open(error => {
if (error) {
return fail(error);
}
console.log(`attached to '${this.port}'`);
done();
}));
}
send(message: Message) {
this.messageQueue.push(message.toBuffer());
}
}