-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (43 loc) · 1.43 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
const WebSocket = require('ws');
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const wss = new WebSocket.Server({ port: 8000, clientTracking: true });
function broadcast(message) {
for (const client of wss.clients) {
if (client.readyState == WebSocket.OPEN) {
client.send(message);
}
}
}
const port = new SerialPort(process.argv[2]),
parser = port.pipe(new Readline());
port.on('open', () => {
broadcast(JSON.stringify({ type: 'status', connected: true }));
console.log('open');
});
port.on('close', err => {
broadcast(JSON.stringify({ type: 'status', connected: false }));
broadcast(JSON.stringify({ type: 'error', error: err.toString() }));
console.log(`closed: ${err.toString()}`);
setTimeout(() => port.open(), 1000);
});
port.on('error', err => {
broadcast(JSON.stringify({ type: 'error', error: err.toString() }));
console.log(`serialport error: ${err.toString()}`);
if (!port.isOpen) {
setTimeout(() => port.open(), 1000);
}
});
parser.on('data', line => {
let message;
try {
const data = JSON.parse(line);
message = JSON.stringify({ type: 'json', data });
} catch (e) {
message = JSON.stringify({ type: 'text', data: line });
}
broadcast(message);
});
wss.on('connection', client => {
client.send(JSON.stringify({ type: 'status', connected: port.isOpen }));
});