forked from opendatacam/opendatacam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
189 lines (156 loc) · 5.28 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const express = require('express')();
const csv = require('csv-express');
const bodyParser = require('body-parser');
const http = require('http');
const next = require('next');
const ip = require('ip');
const WebSocketServer = require('websocket').server;
const forever = require('forever-monitor');
const YOLO = require('./server/processes/YOLO');
const WebcamStream = require('./server/processes/WebcamStream');
const Counter = require('./server/counter/Counter');
const request = require('request');
const fs = require('fs');
const cloneDeep = require('lodash.clonedeep');
const SIMULATION_MODE = process.env.NODE_ENV !== 'production'; // When not running on the Jetson
const port = parseInt(process.env.PORT, 10) || 8080
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
let delayStartWebcam = null;
// Init processes
YOLO.init(SIMULATION_MODE);
WebcamStream.init(SIMULATION_MODE);
// First request received ?
let firstRequestReceived = false;
// Is currently counting state
let isCounting = false;
app.prepare()
.then(() => {
// Start HTTP server
const server = http.createServer(express);
express.use(bodyParser.json());
// This render pages/index.js for a request to /
express.get('/', (req, res) => {
if(!firstRequestReceived) {
// Start webcam stream
WebcamStream.start();
firstRequestReceived = true;
}
// Hacky way to pass params to getInitialProps on SSR
let query = req.query;
query.isCounting = isCounting;
// console.log(Counter.getOriginalCountingAreas());
query.countingAreas = Counter.getOriginalCountingAreas();
return app.render(req, res, '/', query)
})
express.post('/counter/start', (req, res) => {
// Save last frame of webcam before shutting down
const url = getWebcamURL(req);
request(url, {encoding: 'binary'}, function(error, response, body) {
fs.writeFile('static/lastwebcamframe.jpg', body, 'binary', function (err) {});
WebcamStream.stop();
YOLO.start();
});
Counter.reset();
Counter.start();
Counter.registerCountingAreas(req.body.countingAreas)
isCounting = true;
res.json(Counter.getCountingDashboard());
});
express.get('/counter/stop', (req, res) => {
YOLO.stop();
if(delayStartWebcam) {
clearTimeout(delayStartWebcam);
}
// Leave time to YOLO to free the webcam before starting it
// TODO Need to put a clearSetTimeout somewhere
delayStartWebcam = setTimeout(() => {
WebcamStream.start();
}, 2000);
isCounting = false;
res.send('Stop counting')
});
express.get('/counter/dashboard', (req, res) => {
res.json(Counter.getCountingDashboard());
});
express.get('/counter/current-tracked-items', (req, res) => {
res.json(Counter.getTrackedItemsThisFrame());
});
express.get('/counter/export', function(req, res) {
var dataToExport = cloneDeep(Counter.getCounterHistory());
// console.log(dataToExport);
res.csv(dataToExport, false ,{'Content-disposition': 'attachment; filename=counterData.csv'});
});
express.get('/counter/trackerdata', function(req, res) {
Counter.getTrackerData().then(() => {
// res.send('OK, file ready to download');
res.download('static/trackerHistoryExport.json', 'trackerHistoryExport.json')
}, () => {
res.status(500).send('Something broke while generating the tracking history!');
})
});
// Global next.js handler
express.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
if (port === 80) {
console.log(`> Ready on http://localhost`)
console.log(`> Ready on http://${ip.address()}`)
} else {
console.log(`> Ready on http://localhost:${port}`)
console.log(`> Ready on http://${ip.address()}:${port}`)
}
})
// Start Websocket server
// Will listen to YOLO detections
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
var connection = request.accept('', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
// console.log('detections from YOLO');
var detectionsOfThisFrame = JSON.parse(message.utf8Data);
Counter.updateWithNewFrame(detectionsOfThisFrame);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
})
// Utilities
function getWebcamURL(req) {
const urlData = getURLData(req)
if(process.env.NODE_ENV !== 'production') {
return `${urlData.protocol}://${urlData.address}:${port}/static/placeholder/webcam.jpg`
} else {
return `${urlData.protocol}://${urlData.address}:8090/webcam.jpg`
}
}
function getURLData(req) {
let protocol = 'http';
if(req.headers['x-forwarded-proto'] === 'https') {
protocol = 'https';
}
const parsedUrl = req.get('Host').split(':');
if(parsedUrl.length > 1) {
return {
address: parsedUrl[0],
port: parsedUrl[1],
protocol
}
} else {
return {
address: parsedUrl[0],
port: 80,
protocol
}
}
}