summaryrefslogtreecommitdiff
path: root/server.py
blob: 4e567907232c4ba8580a2c5aebdd2765601d9750 (plain)
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
import libardrone.libardrone as libardrone
import pygame
import cv2
import os
import socket
import sys
import threading
import time
import struct

def putStatusText(img, text, pos, activated):
    cv2.putText(img, text, pos, cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255) if activated else (127,127,127), 2 if activated else 1)

def encode_int(i):
    i = int(i)
    return chr( (i/(2**24))%256) + chr( (i/(2**16))%256 ) +\
            chr( (i/(2**8))%256) + chr(i%256)


class ServerThread(threading.Thread):
    def run(self):
        while True:
            # Wait for a connection
            print >>sys.stderr, 'waiting for a connection'
            connection, client_address = sock.accept()
            try:
                print >>sys.stderr, 'connection from', client_address

                while True:
                    data = connection.recv(16)
                    if data:
                        if data=="get\n":
                            lock.acquire()
                            framestr = global_frame.tostring()
                            lenframestr=len(global_framestr)
                            connection.sendall(struct.pack(">i",lenframestr)+framestr+struct.pack("@dddd", global_phi, global_theta, global_psi, global_batt));
                            lock.release()
                        elif data[0:3] == "fly" and data[-1]=="\n":
                            values = data[3:-1].split()
                            lock.acquire()
                            global_cmd_x = float(values[0])
                            global_cmd_y = float(values[1])
                            global_cmd_z = float(values[2])
                            global_cmd_rot = float(values[3])
                            lock.release()
                    else:
                        print >>sys.stderr, 'no more data from', client_address
                        break
            except:
                print "Dingens!!11!1!!!"
            finally:
                # Clean up the connection
                connection.close()





server_address = '/home/flo/uds_socket'
try:
    os.unlink(server_address)
except OSError:
    if os.path.exists(server_address):
        raise

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

# Bind the socket to the port
print >>sys.stderr, 'starting up on %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

no_flight = False

try:
    pygame.init()
    pygame.joystick.init()
    js=pygame.joystick.Joystick(0)
    js.init()
    js_angle_shift = 0.0
except:
    print "no joystick! disabling flight controls"
    no_flight = True

manual_override_xy = True
manual_override_z = True
manual_override_rot = True


drone = libardrone.ARDrone(True, True)
drone.reset()


serverthread=ServerThread()
lock=threading.Lock()


writer = cv2.VideoWriter("flight.avi",cv2.VideoWriter_fourcc(*'MP42'),25,(1280,720),1)
logfile = open("flight.log", "w")


global_phi = 0.
global_theta = 0.
global_psi = 0.
global_batt = 0.
global_frame =  None

serverthread.start()
while True:
    if no_flight == False:
        btn_leftshoulder =  js.get_button(4) or js.get_button(6)
        btn_rightshoulder = js.get_button(5) or js.get_button(7)
        btn_thumb = js.get_button(0) or js.get_button(1) or js.get_button(2) or js.get_button(3)
        btn_all = js.get_button(0) and js.get_button(1) and js.get_button(2) and js.get_button(3)
        btn_readjust = js.get_button(10)

        if btn_thumb:
            drone.land()
            manual_override_xy = True
            manual_override_z = True
            manual_override_rot = True
        if btn_leftshoulder and btn_rightshoulder and js.get_button(10):
            #drone.takeoff()
            manual_override_xy = True
            manual_override_z = True
            manual_override_rot = True
        if btn_all:
            drone.reset()
            manual_override_xy = True
            manual_override_z = True
            manual_override_rot = True
        if btn_readjust:
            js_angle_shift = drone.navdata.get(0, dict()).get('psi',0)

        rel_angle = (drone.navdata.get(0, dict()).get('psi',0) - js_angle_shift)/180.*math.pi

        js_x = js.get_axis(0)
        js_y = js.get_axis(1)
        js_z = -js.get_axis(4)
        js_rot = js.get_axis(3)
        js_radius =  math.sqrt(js_x**2 + js_y**2)
        if btn_leftshoulder==0:
            js_x, js_y =  ( js_x * cos(rel_angle) + js_y * sin(rel_angle) )   ,  ( -js_x * sin(rel_angle) + js_y * cos(rel_angle) )
        
        js_hover = (btn_rightshoulder==0 and (js_radius <= 0.01))

        if (js_radius > OVERRIDE_THRESHOLD): manual_override_xy = True
        if (abs(js_z) > OVERRIDE_THRESHOLD): manual_override_z = True
        if (abs(js_rot) > OVERRIDE_THRESHOLD): manual_override_rot = True

        if manual_override_xy:
            actual_hover, actual_x, actual_y = js_hover, js_x, js_y
        else:
            actual_hover, actual_x, actual_y = global_cmd_hover, global_cmd_x, global_cmd_y

        if manual_override_z:
            actual_z = js_z
        else:
            actual_z = global_cmd_z

        if manual_override_rot:
            actual_rot = js_rot
        else:
            actual_rot = global_cmd_rot

        drone.move_freely( not actual_hover  , actual_x, actual_y, actual_z, actual_rot) 
    
    
    
    lock.acquire()
    rawimg = drone.get_image()
    global_frame = cv2.cvtColor(rawimg, cv2.COLOR_BGR2RGB)
    global_phi = drone.navdata.get(0, dict()).get('phi',1337)
    global_theta = drone.navdata.get(0, dict()).get('theta',1337)
    global_psi = drone.navdata.get(0, dict()).get('psi',1337)
    global_batt = drone.navdata.get(0, dict()).get('batt',1337)
    lock.release()

    smallframe = cv2.resize(global_frame, (640,480))
    cv2.rectangle(smallframe, (0,0), (640,30), (255,255,255), -1)
    cv2.putText(smallframe, "override", (0,20), cv2.FONT_HERSHEY_PLAIN, 1, (255,0,0))
    putStatusText(smallframe, "XY", (100,20), manual_override_xy)
    putStatusText(smallframe, "height", (200,20), manual_override_z)
    putStatusText(smallframe, "rotation", (300,20), manual_override_rot)
    #cv2.putText(smallframe, "XY", (100,20), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255) if manual_override_xy else (127,127,127))
    #cv2.putText(smallframe, "height", (250,20), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255)   f manual_override_z else (127,127,127))
    #cv2.putText(smallframe, "rotation", (400,20), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255) if manual_override_rot else (127,127,127))
    cv2.imshow("frame", smallframe)
    writer.write(global_frame)
    logfile.write(str(global_phi)+"\t"+str(global_theta)+"\t"+str(global_psi)+"\n")
    logfile.flush()



    key = cv2.waitKey(10) & 0xFF

    if key == ord("t"):
        drone.trim()

    if key == ord("z"):
        drone.set_max_vz(750.0000)
        drone.set_max_rotspeed(1.0)
        drone.set_max_angle(0.1)
        print "slow"
    elif key == ord("a"):
        drone.set_max_vz(10000.0000)
        drone.set_max_rotspeed(10)
        drone.set_max_angle(0.6)
        print "fast"
    
    if key == ord("1"):
        manual_override_xy = False
    elif key == ord("2"):
        manual_override_z = False
    elif key == ord("3"):
        manual_override_rot = False