-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
76 lines (57 loc) · 1.72 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
// 'use strict';
var webport;
// var portDevice = '/dev/ttyUSB1';
var portDevice;
if(process.argv.length > 2){
portDevice = process.argv[2];
}else{
portDevice = '/dev/ttyS0';
}
webport = (process.argv[3] != undefined)? process.argv[3] : 8080;
console.log("Opening port on " + portDevice);
const SerialPort = require('serialport');
const port = new SerialPort(portDevice);
const express= require('express');
const WebSocket = require('ws');
const randomId = require('random-id');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('public'));
app.use(bodyParser.json());
var server = require('http').createServer(app);
server.listen(webport,function(){
console.log("Web Server listening on port " + webport);
});
var wsServer = new WebSocket.Server({server});
var wsConnections = {};
port.on('open', () => {
console.log('Connected to Serial Port.');
});
port.on('data', (data) => {
console.log("Response from Hardware: " + data.toString());
});
port.on('error',(e) => {
console.error(e);
})
app.post("/message", function(req,res,next){
var m = req.body;
console.log("Message from " + req.connection.remoteAddress + ": " +m.message + " Color:" + m.color );
port.write(m.message + ";" + m.color);
res.send("Message Sent!");
wsServer.broadcast(JSON.stringify(m));
})
wsServer.broadcast = function broadcast(data) {
wsServer.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wsServer.on('connection',(ws,req)=>{
console.log("User Connected: ", ws._socket.remoteAddress);
})
wsServer.on('close',function(ws,req){
console.log("socket close");
console.log(ws)
connections.splice(connections.indexOf(ws));
})