75 lines
2.0 KiB
JavaScript
75 lines
2.0 KiB
JavaScript
const express = require('express');
|
|
const { createServer } = require('node:http');
|
|
// socket
|
|
const { Server } = require('socket.io');
|
|
// usb serial (arduino)
|
|
var { SerialPort } = require("serialport");
|
|
const { ReadlineParser } = require('@serialport/parser-readline')
|
|
|
|
const app = express();
|
|
const server = createServer(app);
|
|
const io = new Server(server);
|
|
|
|
const port = 3000
|
|
|
|
// https://serialport.io/docs/guide-usage
|
|
|
|
var arduinoCOMPort = "/dev/ttyUSB0";
|
|
var arduinoSerialPort = new SerialPort({
|
|
path: arduinoCOMPort,
|
|
baudRate: 9600
|
|
});
|
|
|
|
arduinoSerialPort.on('open',function() {
|
|
console.log('Serial Port ' + arduinoCOMPort + ' is opened.');
|
|
});
|
|
|
|
|
|
// // Read data that is available but keep the stream in "paused mode"
|
|
// arduinoSerialPort.on('readable', function () {
|
|
// console.log('Data:', arduinoSerialPort.read())
|
|
// })
|
|
|
|
// // Switches the port into "flowing mode"
|
|
// arduinoSerialPort.on('data', function (data) {
|
|
// console.log('Data:', data)
|
|
// })
|
|
|
|
// const serialParser = arduinoSerialPort.pipe(new Readline({ delimiter: '\n' }));
|
|
|
|
// serialParser.on('data', data =>{
|
|
// console.log('got word from arduino:', data);
|
|
// });
|
|
|
|
app.set('view engine', 'pug')
|
|
app.use(express.static('assets'))
|
|
|
|
app.get('/', (req, res) => {
|
|
// res.send('Hello World!')
|
|
// res.render('index', { title: 'Hey', message: 'Hello there PUG!' })
|
|
res.sendFile('assets/main.html', { root : __dirname});
|
|
})
|
|
|
|
io.on('connection', (socket) => {
|
|
console.log('a user connected');
|
|
// let speed = 0.1;
|
|
// setInterval(() => {
|
|
// speed+=0.1;
|
|
// socket.emit('speed', speed);
|
|
// }, 2000);
|
|
|
|
// Listening to arduino through serial port
|
|
const parser = arduinoSerialPort.pipe(new ReadlineParser({ delimiter: '\n' }))
|
|
parser.on('data', data => {
|
|
console.log('got word from arduino:', data);
|
|
const position = parseFloat(data);
|
|
if (!isNaN(position)) {
|
|
socket.emit('position', position);
|
|
}
|
|
});
|
|
|
|
});
|
|
|
|
server.listen(port, () => {
|
|
console.log(`Example app listening on port ${port}`)
|
|
}) |