Skip to content

Instantly share code, notes, and snippets.

@modeswitch
Last active August 29, 2015 14:05
Show Gist options
  • Save modeswitch/ea6f18996fe07749655d to your computer and use it in GitHub Desktop.
Save modeswitch/ea6f18996fe07749655d to your computer and use it in GitHub Desktop.
var dgram = require('dgram');
var path = require('path');
var express = require('express');
var EventEmitter = require('events').EventEmitter;
var app = express();
var port = process.env.PORT = 9080;
var router = express.Router();
var socket = dgram.createSocket('udp4');
var scanEvents = new EventEmitter();
router.route('/stream').get(function(req, res) {
console.log('/api/stream');
var msgCount = 0;
function handleMessage(msg) {
++ msgCount;
msg = JSON.parse(msg.toString());
switch(msg.data.type) {
case "SignalStrength":
msg.data.value = (200 - msg.data.value)/2; // convert poor signal value (200-0) to signal quality (0-100);
break;
case "EEG":
break
default:
break;
}
res.write('id: ' + msgCount + '\n');
res.write('data: ' + JSON.stringify(msg) + '\n\n');
console.log(JSON.stringify(msg));
}
scanEvents.on('message', handleMessage);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write('\n');
res.on('close', function() {
scanEvents.removeListener('message', handleMessage);
});
});
router.get('/', function(req, res) {
res.json("API");
});
app.use(express.static(path.join(__dirname, 'html')));
app.use('/api', router);
app.get('/', function(req, res) {
res.sendfile(path.join(__dirname, '/html/index.html'));
});
app.listen(port, function() {
console.log("Listening on port %d", port);
socket.bind(9000);
socket.on('message', function(msg, rinfo) {
scanEvents.emit('message', msg);
});
});
<html>
<body>
[blah]
</body>
<script>
var DEFAULT_DELAY = 2000;
var source;
function connect(msg, delay) {
setTimeout(function() {
console.log(msg);
try {
source = new EventSource('api/stream');
source.onopen = function(e) {
console.log('open');
};
source.onmessage = function(e) {
console.log('message', e.data);
};
source.onerror = function(e) {
switch(e.target.readyState) {
case EventSource.CONNECTING:
console.error('reconnecting ...');
break;
case EventSource.CLOSED:
console.error('connection failed; no retry');
connect('reconnecting ...', DEFAULT_DELAY);
break;
}
};
} catch(e) {
console.error(e);
connect('reconnecting ...', DEFAULT_DELAY);
}
}, delay);
}
connect('connecting ...', 0);
</script>
</html>
{
"name": "blah",
"description": "blah",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment