open-access-control-api/serial.js

44 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2019-07-07 03:59:45 +00:00
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
2019-07-07 05:03:16 +00:00
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
scores = {};
2019-07-07 03:59:45 +00:00
// listen for new web clients:
server.listen(8080);
// open the serial port. Change the name to the name of your port, just like in Processing and Arduino:
const port = new SerialPort("/dev/ttyUSB0", { baudRate: 9600 });
2019-07-07 05:03:16 +00:00
const parser = new Readline({ delimiter: '\r\n' });
2019-07-07 03:59:45 +00:00
port.pipe(parser)
// respond to web GET requests with the index.html page:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// listen for new serial data:
parser.on('data', line => console.log(`> ${line}`))
// listen for new socket.io connections:
io.on('connection', function (socket) {
2019-07-07 05:03:16 +00:00
// get data from serial and send it to socket
parser.on('data', line => {
socket.emit('data', line)
});
// get data from socket and send it to serial
socket.on('data', function (data) {
console.log('data', socket.conn.remoteAddress, data)
port.write(data+"\r") // we need to end each command with a CR
});
// send and log connect messages
socket.volatile.emit('message', "hi "+socket.conn.remoteAddress);
2019-07-07 03:59:45 +00:00
socket.on('message', function (data) {
2019-07-07 05:03:16 +00:00
console.log('message',socket.conn.remoteAddress,data)
2019-07-07 03:59:45 +00:00
});
});