open-access-control-api/serial.js

44 lines
1.4 KiB
JavaScript

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
scores = {};
// 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 });
const parser = new Readline({ delimiter: '\r\n' });
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) {
// 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);
socket.on('message', function (data) {
console.log('message',socket.conn.remoteAddress,data)
});
});