-
Notifications
You must be signed in to change notification settings - Fork 1
/
virtualLeds.js
79 lines (64 loc) · 1.78 KB
/
virtualLeds.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
const path = require('path');
const express = require('express');
const expressWsWrapper = require('express-ws');
const app = new express();
const expressWs = expressWsWrapper(app);
let wsClients = [];
let config;
let colors;
app.get('/', (req, res, next) => {
res.sendFile(path.join(__dirname, 'static', 'index.html'));
});
app.get('/light', (req, res, next) => {
res.sendFile(path.join(__dirname, 'static', 'light.html'));
});
app.get('/light2', (req, res, next) => {
res.sendFile(path.join(__dirname, 'static', 'light2.html'));
});
app.use('/static', express.static(__dirname + '/static'));
expressWs.app.ws('/', (ws) => {
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (msg.cmd === "hi") {
wsClients.push(ws);
if (config) {
ws.send(JSON.stringify({
cmd: "configure",
data: config
}));
}
if (colors) {
ws.send(JSON.stringify({
cmd: "render",
data: colors
}));
}
}
});
ws.on('close', () => {
wsClients = wsClients.filter(c => c.ws !== ws);
});
});
function broadcast(msgObj) {
wsClients.forEach(ws => ws.send(JSON.stringify(msgObj)));
}
const port = parseInt(process.argv[2]) || 8080;
app.listen(port);
console.log("Web Server started on port", port);
const VirutalLeds = {
configure: (newConfig) => {
config = newConfig;
broadcast({
cmd: "configure",
data: config
});
},
render: (newColors) => {
colors = newColors;
broadcast({
cmd: "render",
data: colors
});
}
}
module.exports = VirutalLeds;