-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·87 lines (74 loc) · 2.2 KB
/
server.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
78
79
80
81
82
83
84
85
86
87
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
const port = 3000;
// Command debouncing variables
let isProcessingCommand = false;
const DEBOUNCE_TIME = 2000; // 2 seconds in milliseconds
// Set EJS as templating engine
app.set('view engine', 'ejs');
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Function to handle command processing
function handleCommand(command) {
console.log('Processing command:', command);
if (!isProcessingCommand) {
if (command === 'L' || command === 'R') {
isProcessingCommand = true;
if (command === 'L') {
io.emit('flip', 'next');
} else if (command === 'R') {
io.emit('flip', 'previous');
}
setTimeout(() => {
isProcessingCommand = false;
console.log('Ready for next command');
}, DEBOUNCE_TIME);
}
} else {
console.log('Command ignored - within debounce period');
}
}
// Check if Serial Port should be used
const useSerialPort = true;
if (useSerialPort) {
const { SerialPort } = require('serialport');
const serialPort = new SerialPort({
path: '/dev/tty.usbserial-0001',
baudRate: 115200
});
serialPort.on('open', () => {
console.log('Serial Port Opened');
});
serialPort.on('data', (data) => {
const command = data.toString().trim();
console.log('Received command from Serial Port:', command);
handleCommand(command);
});
serialPort.on('error', (err) => {
console.error('Serial Port Error:', err);
});
}
// Socket.IO connection handling
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('keyCommand', (command) => {
console.log('Received key command from Client:', command);
handleCommand(command);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
// Routes
app.get('/', (req, res) => {
res.render('index', { title: 'Flipbook with Serial/Keyboard Control' });
});
// Start server
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});