-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
257 lines (233 loc) · 8.45 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
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
var WebSocketServer = require('websocket').server;
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var math = require('mathjs');
var lastPng;
var server = http.createServer(function(req, res){
console.log((new Date())+' Received request for '+req.url);
if(req.url === '/'){
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(fs.readFileSync('./index.html'));
}
else if(req.url === '/favicon.ico'){
res.writeHead(200, {'Content-Type': 'image/vnd.icrosoft.icon'});
res.end(fs.readFileSync('./imgs/favicon.ico', 'binary'));
}else{
//send the named file.
try{
var fileToReturn = fs.readFileSync('.'+req.url);
var isImage = false;
var contentType = 'text/html';
if(strEndsWith(req.url, '.js')){
contentType = 'application/javascript';
}else if(strEndsWith(req.url, '.css')){
contentType = 'text/css';
}else if(strEndsWith(req.url, '.png')){
contentType = 'image/png';
isImage = true;
}else if(strEndsWith(req.url, '.jpg')){
contentType = 'image/jpg';
isImage = true;
}
res.writeHead(200, {'Content-Type': contentType});
if(isImage){
res.end(fileToReturn, 'binary');
}else{
res.end(fileToReturn);
}
}catch(e){
console.log('no path for '+req.url);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end();
}
}
});
server.listen(8080, function(){
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
function setControlEnabled(enabled){
controlEnabled = enabled;
if(controlEnabled){
console.log("control enabled");
}else{
console.log("control disabled");
}
}
var Leap = require('leapjs');
var arDrone = require('ar-drone');
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var droneControl = arDrone.createUdpControl();
var drone = arDrone.createClient({udpControl: droneControl});
//drone.config('general:navdata_demo', 'FALSE'); //enable datas
//var droneControl = drone._udpControl;
var ref = {};
var pcmd = {};
var clientControlEnabled = false; //used to know if the user want to send controls to the drone, or not
var serverControlEnabled = false; //used to know if the drone can receive commands. Example : if the drone is currently taking off, it can't receive anything else
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
//init drone state
connection.send(JSON.stringify({action: "updateDroneBattery", battery: drone._lastBattery}));
connection.send(JSON.stringify({action: "updateDroneAltitude", altitude: drone._lastAltitude}));
var controller = new Leap.Controller();
connection.send(JSON.stringify({action: "updateLeapState", connected: false}));
//var frameCount = 0;
var currentNbOfHands = 0;
controller.on("frame", function(frame) {
//frameCount++;
//console.log(frame);
if(frame.hands.length>0){
serverControlEnabled = true;
var hand = frame.hands[0];
var horizonAngle = math.atan(hand.palmNormal[0]/hand.palmNormal[1]) * (180/math.pi);
var directionAngle = math.atan(hand.palmNormal[2]/hand.palmNormal[1]) * (180/math.pi);
var clockWiseAngle = -(math.atan(hand.direction[0]/hand.direction[2]) * (180/math.pi)-45);
connection.send(JSON.stringify({action: "updateFrame",
leapNumberOfHands: frame.hands.length,
direction: hand.direction,
clockWiseAngle: clockWiseAngle,
directionAngle: directionAngle,
palmNormal: hand.palmNormal,
horizonAngle: horizonAngle,
palmPosition: hand.palmPosition,
handHeight: hand.palmPosition[1],
palmVelocity: hand.palmVelocity,
stabilizedPalmPosition: hand.stabilizedPalmPosition,
sphereCenter: hand.sphereCenter,
sphereRadius: hand.sphereRadius,
valid: hand.valid,
}));
if(clientControlEnabled && serverControlEnabled){
var detectionLimit = 10;
if(horizonAngle < -detectionLimit){
pcmd.left = 0.2;
}else if(horizonAngle > detectionLimit){
pcmd.left = -0.2;
}else{
pcmd.left = 0;
}
if(directionAngle < -detectionLimit){
pcmd.front = 0.2;
}else if(directionAngle > detectionLimit){
pcmd.front = -0.2;
}else{
pcmd.front = 0;
}
if(clockWiseAngle < -detectionLimit){
//movement.clockwise = -0.2;
}else if(clockWiseAngle > detectionLimit){
//movement.clockwise = 0.2;
}else{
//pcmd.clockwise = 0;
}
if(hand.palmPosition[1] > 230){
pcmd.up = 0.2;
}else if(hand.palmPosition[1] < 170){
pcmd.up = -0.2;
}else{
pcmd.up = 0;
}
}
}else if (currentNbOfHands != 0 || clientControlEnabled){
serverControlEnabled = false;
clientControlEnabled = false;
connection.send(JSON.stringify({action: "handLeftLeap"}));
pcmd = {};
}
currentNbOfHands = frame.hands.length;
});
controller.on('ready', function() {
connection.send(JSON.stringify({action: "updateLeapState", connected: true}));
});
controller.on('disconnect', function() {
connection.send(JSON.stringify({action: "updateLeapState", connected: false}));
});
controller.on('focus', function() {
console.log("focus");
});
controller.on('blur', function() {
console.log("blur");
});
controller.on('deviceConnected', function() {
connection.send(JSON.stringify({action: "updateLeapState", connected: true}));
});
controller.on('deviceDisconnected', function() {
connection.send(JSON.stringify({action: "updateLeapState", connected: false}));
});
controller.connect();
//next method receive all messages from client
connection.on('message', function(message) {
if (message.type === 'utf8') {
try{
var json = JSON.parse(message.utf8Data);
}catch(e){
console.log('this is not json : ',message.utf8Data);
return;
}
if(json.action === 'updateControlEnabled'){
clientControlEnabled = json.controlEnabled;
if(!clientControlEnabled){
pcmd = {};
}
}else if(json.action === 'takeOff'){
console.log('taking off...');
ref.fly = true;
pcmd = {};
}else if(json.action === 'land'){
console.log('landing...');
ref.fly = false;
pcmd = {};
}else{
console.log("unknown action : "+json);
}
}
else{
console.log('Received weird message of type : '+message.type);
}
});
//function called when the user leaves
connection.on('close', function(reasonCode, description) {
pcmd = {};
drone.land();
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
//drone events
drone.on('navdata', function(navdata){
//handle more datas ?
});
drone.on("batteryChange", function(battery){
connection.send(JSON.stringify({action: "updateDroneBattery", battery: battery}));
});
drone.on("altitudeChange", function(altitude){
connection.send(JSON.stringify({action: "updateDroneAltitude", altitude: altitude}));
});
//using the low level api, we can't know if the drone has received our orders. We must then send them repetedly, here every 30ms.
setInterval(function(){
//droneControl.ref(ref);
//droneControl.pcmd(pcmd);
drone._ref = ref;
drone._pcmd = pcmd;
//droneControl.flush();
}, 30);
});