forked from chaostreff-flensburg/ArTank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
304 lines (244 loc) · 8.6 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
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
301
302
303
304
// ===============
// Dependencies
// ===============
var express = require("express"),
app = express(),
router = express.Router(),
http = require('http').Server(app),
server = require('http').createServer(app),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
methodOverride = require('method-override'),
SerialPort = require('serialport'),
errorHandler = require('errorhandler'),
hostname = process.env.HOSTNAME || 'localhost',
PORT = process.env.PORT || 80,
publicDir = process.argv[2] || __dirname + '/public',
path = require('path'),
io = require("socket.io")(http, {
serveClient: false
}),
exphbs = require('express-handlebars'),
session = require('express-session');
// ====================
// Express Config
// ====================
app.engine('handlebars', exphbs({}));
app.set('view engine', 'handlebars');
app.set('port', PORT);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
// ====================
// Express Routes
// ====================
router.get('/', function(req, res) {
res.render('panel', []);
});
app.use(router);
// ====================
// ArTank Serial Communication
// ====================
var tank = new SerialPort('/dev/ttyACM0', {
baudRate: 115200
}, function(err) {
if (err) {
return console.log('Error: ', err.message);
}
});
tank.on('data', function(data) {
console.log('Data: ' + data);
});
// ====================
// Socket.io
// ====================
var xy = [0, 0];
var controllingSocket = "";
var controllingTimestamp = 0;
var lastInputTimestamp = 0;
var waitingSockets = [];
const CONTROLTIME = 15000;
const AFKTIME = 10000;
var tankBuffer = new Buffer(16);
//get time it takes for socket to become controller
var waitingTimeCheck = function(socket) {
//check if socket is controlling
if (socket.id === controllingSocket) {
return 0;
}
//get remaining controlling time for current controller
var currentControllerRemainingTime = CONTROLTIME - (Date.now() - controllingTimestamp);
//check position in waiting list and multiply with controltime
var waitingTime = 0;
var waitingListIndex = waitingSockets.indexOf(socket.id);
if (waitingListIndex > -1) {
waitingTime = waitingListIndex * CONTROLTIME;
}
return waitingTime + currentControllerRemainingTime;
};
//function to check if controllingSockets turn is over
var controllerCheck = function() {
//check for multiple id's in case of reload
for (var i = 0; i < waitingSockets.length; i++) {
//delete waiting socket if duplicate of controlling socket
if (waitingSockets[i] === controllingSocket) {
waitingSockets.splice(i, 1);
}
//delete socket if it is a duplicate of a socket on the waiting list which appeared earlier
if (waitingSockets.indexOf(waitingSockets[i]) < i) {
waitingSockets.splice(i, 1);
}
}
//check if controlling Socket is free
if (typeof controllingSocket === "undefined") {
//make first socket in waitinglist controller
controllingSocket = waitingSockets[0];
controllingTimestamp = Date.now();
//inform new controlling socket
io.to(controllingSocket).emit('controlling', {
control: true,
afk: false
});
//initially set lastInputTimestamp
lastInputTimestamp = Date.now();
//remove first socket from waiting list
waitingSockets.splice(0, 1);
return;
}
//replace controller if he is controlling for longer than the allowed controlling time
if (controllingSocket !== "" && Date.now() - controllingTimestamp > CONTROLTIME) {
//inform current controlling socket of controller change
io.to(controllingSocket).emit('controlling', {
control: false
});
//add current controller at the end of the waiting list
waitingSockets.push(controllingSocket);
//make first socket in waiting list the controller and set timestamp
controllingSocket = waitingSockets[0];
controllingTimestamp = Date.now();
//inform new controlling socket
io.to(controllingSocket).emit('controlling', {
control: true,
afk: false
});
//initially set lastInputTimestamp
lastInputTimestamp = Date.now();
//remove first socket from waiting list
waitingSockets.splice(0, 1);
return;
}
//replace controller and remove him from waitinglist if his lastInputTimestamp is older than AFKTIME
if (Date.now() - lastInputTimestamp > AFKTIME) {
//inform current controlling socket of controller change and afk status
io.to(controllingSocket).emit('controlling', {
control: false,
afk: true
});
//make first socket in waiting list the controller and set timestamp (thereby remove last controller from waiting list)
controllingSocket = waitingSockets[0];
controllingTimestamp = Date.now();
//inform new controlling socket
io.to(controllingSocket).emit('controlling', {
control: true
});
//initially set lastInputTimestamp
lastInputTimestamp = Date.now();
//remove first socket from waiting list
waitingSockets.splice(0, 1);
return;
}
};
//connection handling
io.on('connection', function(socket) {
console.log(socket.id+" connected!");
//add socket to waiting pool
waitingSockets.push(socket.id);
//check current controller
controllerCheck();
//tell socket whether it is the controller or not
socket.emit('controlling', {
control: (socket.id === controllingSocket),
waitingTime: waitingTimeCheck(socket)
});
//send initial values to new user
socket.emit('initialize', {
'xy': xy
});
//let clients check if the controller has changed
socket.on('controllercheck', function() {
controllerCheck();
//if socket is not controlling, send it its waiting time
if (controllingSocket !== socket.id) {
socket.emit('controlling', {
control: false,
waitingTime: waitingTimeCheck(socket)
});
}
});
//replace controller on disconnect/ remove socket from waitinglist
socket.on('disconnect', function() {
console.log(socket.id+" disconnected!");
//check if socket is controller
if (socket.id === controllingSocket) {
//make first socket in waitinglist controller
controllingSocket = waitingSockets[0];
controllingTimestamp = Date.now();
//inform new controlling socket
io.to(controllingSocket).emit('controlling', {
control: true
});
}
//check if socket is in waiting list
removeWaitingIndex = waitingSockets.indexOf(socket.id);
if (removeWaitingIndex > -1) {
//remove socket from waiting list
waitingSockets.splice(removeWaitingIndex, 1);
}
});
//handle incoming values
socket.on('xy', function(msg) {
//only process input from currently controlling socket
if (socket.id === controllingSocket) {
//refresh afk timer
lastInputTimestamp = Date.now();
//broadcast current position to all sockets
socket.broadcast.emit('xy', {
'xy': msg.xy
});
//save and validate new position, format for arduino
xy = [parseInt(msg.xy[0]), parseInt(msg.xy[1])];
xy.forEach(function(e, i, a) {
//255 / (value / 2)
e = e * 2.1;
e = Math.floor(e);
e = Math.min(255, e);
e = Math.max(-255, e);
e = -e;
xy[i] = e;
});
//console.log('R Value: ' + msg);
//send current xy values to tank
tankBuffer = new Buffer(xy[0] + ';' + xy[1] + '*');
console.dir(tankBuffer);
tank.write(tankBuffer);
}
});
});
// ====================
// Start the Server
// ====================
//start socket.io listener
http.listen(PORT, function() {
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, PORT);
});
//start express
app.start = app.listen = function() {
return server.listen.apply(server, arguments);
};