-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
78 lines (65 loc) · 1.9 KB
/
index.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
import path from 'path';
import http from 'http';
import websocket from 'websocket-stream';
import {Server as StaticServer} from 'node-static';
import BridgeInputStream from './lib/BridgeInputStream';
let clientId = 0;
let dmxOutput = null;
const clientStates = {};
function updateOutputBuffers(clientId = null, buffers = null) {
if (clientId !== null) {
clientStates[clientId] = buffers;
}
if (!dmxOutput) {
return;
}
const activeClientIds = Object.keys(clientStates);
const numUniverses =
activeClientIds.reduce((max, id) => {
const universeIndices = Object.keys(clientStates[id]).map(Number);
return Math.max(max, ...universeIndices);
}, 0) + 1;
for (let i = 0; i < numUniverses; i++) {
const destBuffer = dmxOutput.getBuffer(i + 1);
const sources = activeClientIds
.map(id => clientStates[id][i])
.filter(Boolean);
for (let j = 0; j < destBuffer.length; j++) {
destBuffer[j] = Math.max(...sources.map(sourceBuffer => sourceBuffer[j]));
}
}
}
export function initFivetwelveBridge(output = null) {
const fileServer = new StaticServer(path.join(__dirname, 'build'));
const server = http.createServer((req, res) => {
req
.addListener('end', function() {
fileServer.serve(req, res);
})
.resume();
});
dmxOutput = output;
websocket.createServer({server}, websocketStream => {
const id = ++clientId;
const inputStream = new BridgeInputStream();
console.log('client connected: ', id);
inputStream.on('dmxdata', buffers => {
updateOutputBuffers(id, buffers);
});
websocketStream.pipe(inputStream);
websocketStream.on('end', () => {
console.log('stream ended');
delete clientStates[id];
updateOutputBuffers();
});
});
return {
server,
listen(...args) {
server.listen(...args);
},
setOutput(output) {
dmxOutput = output;
}
};
}