-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (64 loc) · 1.85 KB
/
app.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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const parser = new parsers.Readline({ delimiter: '\r\n' });
let port;
try {
port = new SerialPort('/dev/cu.usbmodem1301', {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
port.pipe(parser);
port.on('open', () => {
console.log('Serial Port Opened');
});
port.on('error', function (err) {
console.error('Serial port error:', err.message);
});
} catch (err) {
console.error('Failed to open serial port:', err.message);
}
io.on('connection', (socket) => {
console.log('A client connected.');
socket.on('toggle', (data) => {
console.log('Received toggle command:', data);
if (data === '1') {
port.write(data, (err) => {
if (err) {
console.error('Error writing to serial port:', err.message);
}
}); // Turn on the LED immediately
setTimeout(() => {
port.write('0', (err) => {
if (err) {
console.error('Error writing to serial port:', err.message);
}
}); // Turn off the LED after 10 seconds
}, 10000);
} else if (data === '0') {
port.write(data, (err) => {
if (err) {
console.error('Error writing to serial port:', err.message);
}
}); // Turn off the LED immediately
}
});
socket.on('disconnect', () => {
console.log('A client disconnected.');
});
});
app.use(express.static(__dirname)); // Serve static files
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});