-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.ts
300 lines (266 loc) · 9.35 KB
/
app.ts
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import express from 'express';
import path from 'path';
// import moment = require('moment');
import moment = require('moment-timezone');
import * as busStopLocationData from './routes';
const app = express();
const port = process.env.PORT || 3000;
const TIMEOUT_MS = 2 * 60 * 1000;
const WEEKEND_START_TIME = moment().set({'hour': 7});
const WEEKEND_STOP_TIME = moment().set({'hour': 23});
const WEEKDAY_START_TIME = moment().set({'hour': 5});
const WEEKDAY_STOP_TIME = moment().set({'hour': 23});
// Global variables for storing locations in memory. Persistance isn't necessary.
var blueLoc = 1;
var orangeLoc = 1;
var blueStatus = 'Bus running without tracking.';
var orangeStatus = 'Bus running without tracking.';
var blueInTransit = false
var orangeInTransit = false
var blueLastUpdateTimestamp = moment();
var orangeLastUpdateTimestamp = moment();
var routeLength: number;
interface Route {
stops: { name: String,
lat: Number,
lon: Number,
blue_time: Number[],
orange_time: Number[]
}[]
}
interface Route_min {
stops: Number[]
}
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get('/', (req: any, res: any) => {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
var prev_loc_map = new Map();
var route_map = new Map();
app.get('/updateLocation', (req: any, res: any) => {
// should come in like /updateLocation?id=1&loc=4&inTransit=true
// parse out each param
// figure out what route this bus id is on
// update bus status
console.log(`ID: ${req.query.id}`);
console.log(`Location: ${req.query.loc}`);
console.log(`inTransit: ${req.query.inTransit}`);
let loc: number = Number(req.query.loc);
let inTransit: boolean = (req.query.inTransit == 'true');
let id: string = req.query.id;
if (loc <= 0) {
// The device doesn't know where it's at yet.
res.sendStatus(200);
return;
}
// setting initial conditions
if (!prev_loc_map.has(id)) {
prev_loc_map.set(id, loc);
if (loc < routeLength / 2) {
blueLoc = loc;
blueStatus = '';
blueLastUpdateTimestamp = moment();
route_map.set(id, "blue");
} else {
orangeLoc = loc;
orangeStatus = '';
orangeLastUpdateTimestamp = moment();
route_map.set(id, "orange");
}
}
// update route at stop
if (!inTransit) {
if (prev_loc_map.get(id) < loc) {
blueLoc = loc;
prev_loc_map.set(id, loc);
blueInTransit = false;
blueStatus = '';
blueLastUpdateTimestamp = moment();
route_map.set(id, "blue");
} else if (prev_loc_map.get(id) > loc) {
orangeLoc = loc;
prev_loc_map.set(id, loc);
orangeInTransit = false;
orangeStatus = '';
orangeLastUpdateTimestamp = moment();
route_map.set(id, "orange");
}
} else { // if it is in transit...
if (loc == blueLoc && route_map.get(id) == "blue") {
blueInTransit = true;
blueLastUpdateTimestamp = moment();
route_map.set(id, "blue");
}
if (loc == orangeLoc && route_map.get(id) == "orange") {
orangeInTransit = true;
orangeLastUpdateTimestamp = moment();
route_map.set(id, "orange");
}
}
// edge case where bus turns around.
if (blueLoc == 1 && orangeLoc == routeLength || blueLoc == routeLength && orangeLoc == 1) {
if (inTransit) {
if (prev_loc_map.get(id) == 1) {
blueInTransit = true;
blueStatus = '';
blueLastUpdateTimestamp = moment();
route_map.set(id, "blue");
} else if (prev_loc_map.get(id) == routeLength) {
orangeInTransit = true;
orangeStatus = '';
orangeLastUpdateTimestamp = moment();
route_map.set(id, "orange");
}
} else { // both busses at end of routes, so swap.
blueLoc = 1;
orangeLoc = routeLength;
blueStatus = '';
orangeStatus = '';
blueLastUpdateTimestamp = moment();
orangeLastUpdateTimestamp = moment();
route_map.set(id, "blue");
route_map.set(id, "orange");
}
}
// handle when one bus times out while the other is still running and is at end of route.
if (Number(moment()) - Number(blueLastUpdateTimestamp) > TIMEOUT_MS) {
if (orangeLoc == 1) {
orangeStatus = "Bus is currently running without tracking.";
blueLoc = 1;
blueStatus = "";
blueLastUpdateTimestamp = moment();
}
}
if (Number(moment()) - Number(orangeLastUpdateTimestamp) > TIMEOUT_MS) {
if (blueLoc == routeLength) {
blueStatus = "Bus is currently running without tracking.";
orangeLoc = routeLength;
orangeStatus = "";
orangeLastUpdateTimestamp = moment();
}
}
res.sendStatus(200);
});
// the endpoint for the client to update it's bus location
app.get('/api', (req: any, res: any) => {
let locationData: {[k: string]: any} = {
"blue": {
"loc": blueLoc,
"intransit": blueInTransit
},
"orange": {
"loc": orangeLoc,
"intransit": orangeInTransit
}
};
if (blueStatus != '') {
locationData.blue.err = blueStatus;
}
if (orangeStatus != '') {
locationData.orange.err = orangeStatus;
}
checkTimeout();
res.json(locationData);
});
// The endpoint for getting the bus stop gps data.
app.get('/routes', (req: any, res: any) => {
const day = moment().tz('asia/seoul').format('dddd');
const isWeekend = day === 'Sunday' || day === 'Saturday';
const currentTime = moment().tz('asia/seoul');
console.log(`Weekend stop time: ${WEEKEND_STOP_TIME}`);
console.log(`Today is ${day} at ${currentTime.format('HH:mm:ss')}, and isWeekend = ${isWeekend}`);
console.log(`In between? ${currentTime.isBetween(WEEKEND_START_TIME, WEEKEND_STOP_TIME)}`);
if (isWeekend) {
if (!currentTime.isBetween(WEEKEND_START_TIME, WEEKEND_STOP_TIME)) {
blueStatus = `Weekend running hours are 0700-2300`;
orangeStatus = `Busses are not currently running.`;
}
routeLength = busStopLocationData.weekendRoute.stops.length;
res.json(busStopLocationData.weekendRoute);
} else {
if (!currentTime.isBetween(WEEKDAY_START_TIME, WEEKDAY_STOP_TIME)) {
blueStatus = `Weekday running hours are 0500-2300`;
orangeStatus = `Busses are not currently running.`;
}
routeLength = busStopLocationData.weekdayRoute.stops.length;
res.json(busStopLocationData.weekdayRoute);
}
});
// The endpoint for getting the bus stop gps data in a very minimal form.
app.get('/routes_min', (req: any, res: any) => {
const day = moment().tz('asia/seoul').format('dddd');
const isWeekend = day === 'Sunday' || day === 'Saturday';
const currentTime = moment().tz('asia/seoul');
console.log(`Weekend stop time: ${WEEKEND_STOP_TIME}`);
console.log(`Today is ${day} at ${currentTime.format('HH:mm:ss')}, and isWeekend = ${isWeekend}`);
console.log(`In between? ${currentTime.isBetween(WEEKEND_START_TIME, WEEKEND_STOP_TIME)}`);
if (isWeekend) {
if (!currentTime.isBetween(WEEKEND_START_TIME, WEEKEND_STOP_TIME)) {
blueStatus = `Weekend running hours are 0700-2300`;
orangeStatus = `Busses are not currently running.`;
}
routeLength = busStopLocationData.weekendRoute.stops.length;
res.json(minifyBusRouteInfo(busStopLocationData.weekendRoute));
} else {
if (!currentTime.isBetween(WEEKDAY_START_TIME, WEEKDAY_STOP_TIME)) {
blueStatus = `Weekday running hours are 0500-2300`;
orangeStatus = `Busses are not currently running.`;
}
routeLength = busStopLocationData.weekdayRoute.stops.length;
res.json(minifyBusRouteInfo(busStopLocationData.weekdayRoute));
}
});
// the endpoint for the bus to post data to.
// updates the global variables location for each one.
/**
* Example incoming data
*
* {stop: 1, route: "blue", intransit: true, status: ''}
*/
app.post('/pi', (req: any, res: any) => {
switch (String(req.body.route)) {
case "blue":
blueLoc = parseInt(req.body.stop);
blueStatus = req.body.status;
blueInTransit = JSON.parse(req.body.intransit);
blueLastUpdateTimestamp = moment();
break;
case "orange":
orangeLoc = parseInt(req.body.stop);
orangeStatus = req.body.status;
orangeInTransit = JSON.parse(req.body.intransit);
orangeLastUpdateTimestamp = moment();
break;
default:
blueStatus = req.body.status;
orangeStatus = req.body.status;
}
checkTimeout();
console.log(`------ ------ ------`);
console.log(`Route: ${String(req.body.route)}`)
console.log(`Location: ${parseInt(req.body.stop)}`);
console.log(`In Transit: ${JSON.parse(req.body.intransit)}`);
console.log(`Status: ${req.body.status}`);
res.sendStatus(200);
});
app.listen(port, () => console.log(`bus GPS server listening on port ${port}!`));
// Check if each bus hasn't been updated after a certain amount of time.
// If it fails to update then, set a status that says it's lost connection with the bus.
function checkTimeout() {
if (Number(moment()) - Number(blueLastUpdateTimestamp) > TIMEOUT_MS) {
blueStatus = "Bus is currently running without tracking.";
}
if (Number(moment()) - Number(orangeLastUpdateTimestamp) > TIMEOUT_MS) {
orangeStatus = "Bus is currently running without tracking.";
}
}
function minifyBusRouteInfo(routes: Route): Route_min {
let routes_minified: Route_min = {stops: []};
routes.stops.forEach(stop => {
routes_minified.stops.push(stop.lat);
routes_minified.stops.push(stop.lon);
});
return routes_minified;
}