-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathws-server.js
More file actions
58 lines (49 loc) · 1.67 KB
/
ws-server.js
File metadata and controls
58 lines (49 loc) · 1.67 KB
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
const SerialWCProcessor = require('./modules/serialWCprocessor');
const WebSocket = require('ws');
const toiletsNotifier = new SerialWCProcessor.ToiletsEmitter(process.env.SERIAL_PORT, process.env.DEBUG, process.env.SPOILTIME);
const ToiletsLatestStates = {
1: {
state: SerialWCProcessor.TOISTATES.FREE,
updateTime: Date.now()
},
2: {
state: SerialWCProcessor.TOISTATES.FREE,
updateTime: Date.now()
},
3: {
state: SerialWCProcessor.TOISTATES.FREE,
updateTime: Date.now()
}
};
toiletsNotifier.on('data', function (toilet) {
const latestToiletState = ToiletsLatestStates[toilet.index];
if (latestToiletState && latestToiletState.state !== toilet.state) {
latestToiletState.state = toilet.state;
latestToiletState.updateTime = Date.now();
notifyUI();
}
});
//WebSocket Server
const wss = new WebSocket.Server({ port: process.env.WEBSOCKET_PORT || 7777 });
wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log("Got connection from " + ip);
ws.on('message', function incoming(message) {
console.log('received: %s from %s', message, ip);
});
ws.send(getToiletsStates()); //send state on connection established
});
function getToiletsStates() {
return JSON.stringify(ToiletsLatestStates);
}
function notifyUI() {
let latestState = getToiletsStates();
wss.clients.forEach(function (client) {
if (client.readyState === WebSocket.OPEN) {
client.send(latestState);
}
});
if (process.env.DEBUG) {
console.log(latestState);
}
}