-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
88 lines (73 loc) · 1.78 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
88
/**
* server.js
*/
const express = require('express');
const gpio = require('rpi-gpio');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const sockets = {};
const port = process.env.PORT || '3000';
// express
app.use(express.json())
app.use(express.static('public'));
app.set('view engine', 'ejs');
// index
app.get('/', function (req, res) {
res.render('index.ejs', {});
});
// timer
app.get('/timer', function (req, res) {
res.render('timer.ejs', {
min: 4
});
});
// timer with limit
app.get('/timer/:min', function (req, res) {
const min = req.params.min;
res.render('timer.ejs', {
min: min
});
});
// emit name
app.get('/emit/:name', function (req, res) {
const name = req.params.name;
io.sockets.emit('timer', name);
return res.status(200).json({
result: true,
timer: name,
});
});
// sockets
io.on('connection', function (socket) {
console.log('connection : ', socket.id);
sockets[socket.id] = socket;
socket.on('disconnect', function () {
console.log('disconnect : ', socket.id);
delete sockets[socket.id];
// no more sockets
if (Object.keys(sockets).length == 0) {
console.log('no more sockets.');
}
});
socket.on('timer', function (name) {
console.log('timer : ', socket.id, name);
io.sockets.emit('timer', name);
});
});
// http
http.listen(port, function () {
console.log(`Listening on port ${port}!`);
});
// gpio
gpio.on('change', function (channel, value) {
console.log(`Channel ${channel} value is now ${value} \t- ${(Math.random() * 100000)}`);
switch (channel) {
case 11:
case 13:
io.sockets.emit('timer', 'passed');
break;
}
});
gpio.setup(11, gpio.DIR_IN, gpio.EDGE_BOTH);
gpio.setup(13, gpio.DIR_IN, gpio.EDGE_BOTH);