Skip to content

Commit

Permalink
websocket server to push updates
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-haynes committed May 11, 2020
1 parent 781991e commit 8d681f9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"lodash": "^4.17.10",
"moment": "^2.24.0",
"node-pid-controller": "^1.0.1",
"rpio": "1.3.0"
"rpio": "1.3.0",
"ws": "^7.2.3"
},
"devDependencies": {
"chai": "^4.1.2",
Expand Down
28 changes: 24 additions & 4 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
const bodyParser = require('body-parser');
const express = require('express');
const moment = require('moment');
const WebSocket = require('ws');

const BROADCAST_UPDATE_INTERVAL = moment.duration(5, 'seconds').asMilliseconds();

const app = express();
app.use(bodyParser.json());

function initializeServer({ port }, controller) {
app.get('/alive', (req, res, next) => {
res.json({ alive: true });
next();
function initializeWebSocketServer(controller, port) {
const wss = new WebSocket.Server({ port });
let updateInterval;

wss.on('connection', (ws) => {
updateInterval = setInterval(() => {
ws.send(JSON.stringify({
update: controller.getUpdate(),
}));
}, BROADCAST_UPDATE_INTERVAL);
});

wss.on('close', () => {
if (updateInterval) {
clearInterval(updateInterval);
}
});
}

function initializeServer({ port }, controller) {
initializeWebSocketServer(controller, 4000);

app.get('/update', (req, res, next) => {
const lastUpdate = controller.getUpdate();
res.json({ lastUpdate });
Expand Down

0 comments on commit 8d681f9

Please sign in to comment.