-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (64 loc) · 2 KB
/
index.js
File metadata and controls
75 lines (64 loc) · 2 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
const { networkInterfaces } = require("os");
const { WebSocketServer } = require("ws");
const { SerialPort } = require("serialport");
const { ReadlineParser } = require("@serialport/parser-readline");
const express = require("express");
const { join } = require("path");
const path = require("path");
const { readFileSync } = require("fs");
const config = JSON.parse(readFileSync(join(__dirname, "config.json")));
const app = express();
const expressPort = config.HTTP_PORT;
const wsPort = config.WS_PORT;
const wsServer = new WebSocketServer({ port: wsPort });
let sockets = [];
let serials = [];
let dataState = '{"uninitialized":true}';
wsServer.on("connection", (s) => {
s.on("message", (m) => serials.forEach((s) => s.write(m)));
sockets.push(s);
});
wsServer.on(
"close",
(closing) => (sockets = sockets.filter((s) => s != closing))
);
SerialPort.list().then((portListings) => {
portListings.forEach((portListing) => {
try {
const port = new SerialPort({ path: portListing.path, baudRate: 115200 });
serials.push(port);
port.on("close", () => {
serials = serials.filter((s) => s != port);
});
port.on("error", (e) => console.error(e));
const parser = port.pipe(new ReadlineParser({ delimiter: "\r\n" }));
parser.on("data", (data) => {
dataState = data;
console.log(`${data} => ${dataState}`);
sockets.forEach((s) => s.send(dataState));
});
} catch (e) {
console.error(e);
}
});
});
app.get("/", (req, res) => {
res.send(
"The server is online, but this is probably not the URL you want to use. Try the <a href='/example.html'>example</a> maybe?"
);
});
app.get("/config", (req, res) => {
res.sendFile(path.join(__dirname, "config.json"));
});
app.use(express.static("pages"));
app.listen(expressPort, () => {
console.log(getDebugInfo());
console.log(networkInterfaces());
});
function getDebugInfo() {
return `
HTTP port : ${expressPort}
WS port : ${wsPort}
dataState : ${dataState}
`;
}