-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerial.js
More file actions
113 lines (98 loc) · 2.67 KB
/
Copy pathSerial.js
File metadata and controls
113 lines (98 loc) · 2.67 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");
const Ready = require("@serialport/parser-ready");
const Delimiter = require("@serialport/parser-delimiter");
var NanoTimer = require("nanotimer");
const { timer } = require("./Utilities");
const { performance } = require("perf_hooks");
class Serial {
constructor() {
this.port = null;
this.reader = null;
this.readyChar = "%";
this.readyForWrite = false;
this.timer = new NanoTimer();
}
init() {
return new Promise(resolve => {
// Setup the serial port
this.port = new SerialPort(process.env.SERIAL_PORT, {
baudRate: Number(process.env.BAUD_RATE)
});
let ready = false;
const readyParser = this.port.pipe(new Ready({ delimiter: "READY" }));
readyParser.on("ready", () => {
ready = true;
});
this.reader = this.port.pipe(new Readline({ delimiter: "\r\n" }));
this.reader.on("data", data => {
if (data != this.readyChar) {
console.log(data);
} else {
// console.log(data);
this.readyForWrite = true;
}
});
const check = setInterval(() => {
if (ready) {
clearInterval(check);
resolve(true);
}
}, 1);
});
}
async list() {
const list = await SerialPort.list();
console.log(list);
}
write(string) {
this.port.write(string);
}
// Expects formatted list of IO Arrays, from Mapper
output(ioArrays) {
const delay = 5;
return new Promise(async resolve => {
for (const arrayName in ioArrays) {
const ioArray = ioArrays[arrayName];
let data = ioArray.data;
if (ioArray.wasEmpty && data.every(item => item == 1)) {
await timer(delay);
continue;
}
data = data.reverse();
const hex = this.convertToHex(data.join(""));
let cmd = `[${arrayName}es${hex}]`;
await this.writeAndDrain(cmd);
await timer(delay);
if (data.every(item => item == 1)) {
ioArray.wasEmpty = true;
} else {
ioArray.wasEmpty = false;
}
}
resolve();
});
}
convertToHex(binary) {
let output = "";
let buffer = "";
[...binary].forEach((item, index) => {
buffer += item;
if ((index + 1) % 4 === 0) {
output += parseInt(buffer, 2).toString(16);
buffer = "";
}
});
return output;
}
writeAndDrain(data) {
return new Promise(resolve => {
const t0 = performance.now();
this.port.write(data);
this.port.drain(() => {
resolve();
});
});
}
}
module.exports = new Serial();