-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (53 loc) · 2.08 KB
/
server.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
var Light = require('./lib/light'),
LightsController = require('./lib/lightscontroller');
var ns = new Light('red'),
ew = new Light('red'),
controller = new LightsController(ns, ew);
var express = require('express'),
app = express();
app.use('/public', express.static('public'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.get('/', function (req, res) {
res.render('index.html');
});
app.get('/run', function (req, res) {
ns.changeColor(req.query.ns);
ew.changeColor(req.query.ew);
controller.run(req.query.timechange, req.query.timeyellow);
res.send('Running with intervals: ' + req.query.timechange + ' ' + req.query.timeyellow);
});
app.get('/ns', function (req, res) {
res.send(ns.getColor());
});
app.get('/ew', function (req, res) {
res.send(ew.getColor());
});
//Server Sent Events
app.get('/socket', function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
//When the traffic lights emitter emits events, we send those events to the socket as JSON packages representing the current state of the app
controller.getEmitter().on('initiateChange', function() {
var message = {ns: ns.getColor(), ew: ew.getColor(), type: 'initiateChange', secondsElapsed: controller.getSecondsElapsed(), status: 'ok'};
res.write('data: ' + JSON.stringify(message) + '\n\n');
});
controller.getEmitter().on('changeDirection', function() {
var message = {ns: ns.getColor(), ew: ew.getColor(), type: 'changeDirection', secondsElapsed: controller.getSecondsElapsed(), status: 'ok'};
res.write('data: ' + JSON.stringify(message) + '\n\n');
});
controller.getEmitter().on('tick', function() {
var message = {ns: ns.getColor(), ew: ew.getColor(), type: 'tick', secondsElapsed: controller.getSecondsElapsed(), status: 'ok'};
res.write('data: ' + JSON.stringify(message) + '\n\n');
});
});
app.get('/stop', function (req, res) {
controller.stop();
res.send('Stopped');
});
app.listen(3000, function () {
console.log('Traffic Lights application listening on port 3000')
});