-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
62 lines (45 loc) · 1.22 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
const express = require('express');
const app = express();
const path = require('path');
const server = app.listen(3000, () => {
console.log('Listening on port %d', server.address().port);
});
const io = require('socket.io')(server);
const five = require('johnny-five');
const board = new five.Board();
const ledPins = [9, 11, 13];
const leds = {};
let boardIsReady = false;
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
const createLead = (ledPin) => (leds[`led${ledPin}`] = new five.Pin(ledPin));
const queryLead = (ledPin) => leds[`led${ledPin}`].query((state) => {
io.emit('changeLed', {
led: `led${ledPin}`,
state: state.value
});
});
board.on('ready', () => {
boardIsReady = true;
io.emit('statusBoard', boardIsReady);
ledPins.forEach(createLead);
});
io.on('connection', (socket) => {
io.emit('statusBoard', boardIsReady);
if (!boardIsReady) {
return false;
}
ledPins.forEach(queryLead);
socket.on('led', (data) => {
if (!boardIsReady) {
return false;
}
io.emit('changeLed', data);
if (data.state) {
return leds[data.led].high();
}
leds[data.led].low();
});
});