forked from shehanmunasinghe/serial-monitor-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
113 lines (94 loc) · 2.93 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
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
// Setup basic express server
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3024;
const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
// Chatroom
var numUsers = 0;
//Client connects to the server
io.on('connection', (socket) => {
console.log("New Connection");
SerialPort.list((err, ports) => {
var portsList = [];
ports.forEach((port) => {
portsList.push(port.comName);
console.log("port found: " + port.comName);
});
socket.emit('serialportlist', portsList);
});
var getPortsList = (callback) => {
var portsList = [];
SerialPort.list((err, ports) => {
ports.forEach((port) => {
portsList.push(port.comName);
});
callback(null, portsList);
});
};
socket.on('new session', (data) => {
socket.serialPortPath = data.serialPortPath;
socket.baudrate=data.baudrate;
if(socket.serialPort){
try{
socket.serialPort.close(function (err) {
console.log('port close err', err);
});
console.log('port closed');
}catch(e){
console.error(e)
socket.emit('clsong failed', {});
}
}
try{
socket.serialPort = new SerialPort(socket.serialPortPath, { baudRate: parseInt(socket.baudrate) });
socket.serialPortParser = new Readline()
socket.serialPort.pipe(socket.serialPortParser)
socket.serialPortParser.on('data', (line) =>
//console.log(`> ${line}`)
socket.emit('new message',line)
)
console.log("New Session Started");
socket.emit('session started', {});
}catch(e){
console.error(e)
socket.emit('session failed', {});
}
});
socket.on('writePort', (data) => {
//TODO: Update Open Serial Ports List
console.log("changing mode");
if(socket.serialPort){
socket.serialPort.write(data, function(err) {
if (err) {
return console.log('Error on write: ', err.message)
}
console.log('message written')
})
}
});
socket.on('disconnect', () => {
//TODO: Update Open Serial Ports List
if(socket.serialPort){
try{
socket.serialPort.close(function (err) {
console.log('port close err', err);
});
console.log('port closed');
}catch(e){
console.error(e)
socket.emit('clsong failed', {});
}
}
socket.serialPort = null;
console.log("disconnect");
});
});