-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (64 loc) · 1.71 KB
/
index.js
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
// server/index.js
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
const SerialPort = require("serialport");
var getPortsList = () => {
var portsList = [];
SerialPort.list().then((ports) => {
ports.forEach((port) => {
portsList.push(port.path);
});
});
return portsList.includes("COM3");
};
console.log(getPortsList());
const port = new SerialPort("COM3", {
baudRate: 9600,
});
let boardstatus = 0;
app.get("/boardstatus", (req, res) => {
res.writeHead(200, {
Connection: "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
// enabling CORS
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept",
});
if (getPortsList()) {
boardstatus = 1;
} else {
boardstatus = 0;
}
res.write(
"data:" +
JSON.stringify({ data: boardstatus}) +
"\n\n"
);
});
app.get("/api", (req, res) => {
res.writeHead(200, {
Connection: "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
// enabling CORS
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept",
});
port.on("data", function (data) {
if (data.toString().trim() != "") {
res.write(
"data:" +
JSON.stringify({ data: data.toString().trim(), time: +new Date() }) +
"\n\n"
);
console.log("Data:", data.toString(), "Time:", Date.now());
}
});
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});