-
Notifications
You must be signed in to change notification settings - Fork 2
/
groundstation.py
491 lines (426 loc) · 20 KB
/
groundstation.py
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# data processor/logger for monocopter avionics with vicon
import serial
import curses
from curses.textpad import Textbox, rectangle
import datetime,time,platform
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import warnings
from math import pi,sin,cos
import matplotlib.pyplot as plt
from time import time,sleep
from vicon import Vicon
import threading
from threading import Lock
import os.path
import pygame
# ------- Settings ------------
formatISfullsensor = False
enablePlot = False
enableVicon = False
enableJoystick = False
logFolder = "./log/"
logPrefix = "richrun"
logSuffix = ".txt"
# from bottom, how far up do we display rolling data
rolling_offset = 10
screenHandle = None
# ---- threading
# vicon_state: (x,y,z,rx,ry,rz)
vicon_state = None
lock_vicon_state = Lock()
thread_vicon = None
thread_joystick = None
# avionics_state: voltage,flapPWM,throttlePWM,isAutomaticControl
avionics_state = None
lock_avionics_state = Lock()
# joystick locks etc
js_flap = None
js_throttle = None
lock_js = Lock()
lock_logfile = Lock()
quit = False
isLogging = False
logFilename = None
logBuffer = []
def displayText(text):
global ymax,xmax,rolling_offset, screenHandle
screen = screenHandle
#display a human readable text slip
screen.scroll()
screen.addstr(ymax-rolling_offset,0,text)
return
def displayLineno(n,text):
global screenHandle
screen = screenHandle
# display text at line n (counting from bottom up, bottom line is 1)
assert n>0
screen.move(ymax-n,0)
screen.clrtoeol()
screen.addstr(ymax-n,0,text)
debug_joy_update_interval_ms = 0.0
debug_joy_ts = 0.0
def joystickUpdateDaemon(js,avionics):
global js_throttle,js_flap,lock_js,quit,enableJoystick
global debug_joy_update_interval_ms,debug_joy_ts
fmap = lambda x,a,b,c,d: c+(x-a)/(b-a)*(d-c)
while (not quit and enableJoystick):
pygame.event.pump()
throttle = fmap(js.get_axis(5),-1.0,1.0,1098,1939)
flap = fmap(js.get_axis(1),-1.0,1.0,1099,1939)
lock_js.acquire()
js_throttle = throttle
js_flap = flap
lock_js.release()
avionics.write(("ctrl %d %d\r\n"%(throttle,flap)).encode())
debug_joy_update_interval_ms = (time()-debug_joy_ts)*1000
debug_joy_ts = time()
sleep(0.03)
js_throttle = None
js_flap = None
def viconUpdateDaemon(vi):
global quit,lock_vicon_state,vicon_state,avionics_state,lock_avionics_state
global isLogging,logFilename,logBuffer,lock_logfile
while (not quit):
local_vicon_state = vi.getViconUpdate()
lock_vicon_state.acquire()
vicon_state = local_vicon_state
lock_vicon_state.release()
if (isLogging):
lock_avionics_state.acquire()
local_avionics_state = avionics_state
lock_avionics_state.release()
if (local_vicon_state is None):
# should not happen
continue
x,y,z,rx,ry,rz = local_vicon_state
voltage,flapPWM,throttlePWM,isAutomaticControl = local_avionics_state
dataFrame = str(time())+","+str(x)+","+str(y)+","+str(z)+","+str(rx)+","+str(ry)+","+str(rz)+","+str(throttlePWM)+","+str(flapPWM)+","+str(voltage)+","+ str(1 if isAutomaticControl else 0) + "\n"
logBuffer.append(dataFrame)
if len(logBuffer)>1000:
lock_logfile.acquire()
with open(logFilename, 'a') as filehandle:
for entry in logBuffer:
filehandle.write('%s' % entry)
logBuffer = []
lock_logfile.release()
return
def main(screen, avionics):
global screenHandle,formatISfullsensor,quit
global enableVicon,enableJoystick,enablePlot
global thread_joystick,thread_vicon
global lock_logfile,lock_avionics_state,lock_vicon_state,lock_js
global vicon_state,avionics_state,js_flap,js_throttle
global isLogging,logFilename,logBuffer
global debug_joy_update_interval_ms
screenHandle = screen
curses.curs_set(0) # Set cursor visibility where 0 = invisible,
screen.nodelay(True) # Set getch() to be non-blocking - important!
curses.noecho()
curses.use_default_colors() # Lets your terminal client set the fonts and colors
global ymax,xmax
ymax, xmax = screen.getmaxyx() # Get the screen dimensions
screen.setscrreg(0,ymax-rolling_offset)
screen.scrollok(True)
command = ""
# ---------- display format ------------
# --- human readable text ----- (scrollable,non-erasing)
# line 5: joystick output, throttle, flap, in that order
# line 4: avionics stream, machine
# line 3: vicon stream, machine
# line 2 last command executed
# line 1: interactive command in buffer (ymax-1)
# main loop, print,parse arduino output and send command
start_ts = datetime.datetime.now()
flag_calibrated = False
flap_new_plot_data = True
flag_ping_in_progress = False
flag_vicon_not_ready = True
calibration_data = []
R_12 = None
scale_12 = None
epoch = datetime.datetime.now()
debugdata = []
serial_buffer = ""
while not(quit):
global curve00,curve01,curve10,curve11, ptr, data00,data01,data10
# show loop freq
#screen.addstr(ymax-1,xmax-20,"loop freq = "+str(int(1.0/(datetime.datetime.now()-start_ts).total_seconds())))
screen.addstr(ymax-1,xmax-20,"ts = "+str(int((datetime.datetime.now()-epoch).total_seconds())))
# read from avionics serial (thru xbee)
if (avionics.in_waiting > 0 ):
line = avionics.readline()
# machine readable data start with #
if (chr(line[0])=='#'):
# display data, remove trailing \r\n which mess up curser
screen.move(ymax-4,0)
screen.clrtoeol()
screen.addstr(ymax-4,0,"Avionics Datastream: "+line.decode()[:-2])
# attempt to parse data
try:
# sample parsing, need more work TODO
# remove prefix #, suffix \r\n
data = [float(i) for i in line[1:-2].split(b',')]
# two protocols, one with 13 fields
if (formatISfullsensor):
if (len(data)==13):
# TODO complete the parsing
avionics_ts = data[0]
mx = data[1]
my = data[2]
mz = data[3]
mag = np.matrix(data[1:4]).T
acc1_x = data[4]
acc1_y = data[5]
acc1_z = data[6]
acc1 = np.matrix(data[4:7]).T
acc2_x = data[7]
acc2_y = data[8]
acc2_z = data[9]
acc2 = np.matrix(data[7:10]).T
voltage = data[10]
# azimuth (degree) from avionics
kf_azimuth = data[11]
# omega (rev/s) from avionics
kf_omega = data[12]
#screen.addstr(ymax-9,0,"acc1 = "+str(acc1))
#screen.addstr(ymax-9,int(xmax/2),"acc2 = "+str(acc2))
else: # the other protocol contains seq_no, voltage, flap, throttle, isAutomaticControl
if (len(data)==5):
seq_no = int(data[0])
voltage = data[1]
flapPWM = int(data[2])
throttlePWM = int(data[3])
isAutomaticControl = data[4]>0.5
lock_avionics_state.acquire()
avionics_state = voltage,flapPWM,throttlePWM,isAutomaticControl
lock_avionics_state.release()
except ValueError:
pass
elif (chr(line[0])=='$'):
# inquiry response, e.g. ping response
try:
response = line.decode()[1:-2]
except UnicodeDecodeError:
pass
displayText("[avionics response]:"+response)
if (response == "ping"):
tac = time()
flag_ping_in_progress = False
if tic is None:
displayLineno(2, "Error.. Unsolicited ping response")
else:
displayText("[avionics]: ping success, dt = " + str(tac-tic)+"s")
tic = 0.0
else:
#human readable
screen.scroll()
# may throw UnicodeDecodeError, not big deal
try:
text = line.decode()[:-2]
screen.addstr(ymax-rolling_offset,0,"[avionics]: "+text)
except UnicodeDecodeError:
pass
# Vicon display
# NOTE disable vicon does not actually disable the daemon, just display
if (enableVicon):
lock_vicon_state.acquire()
local_vicon_state = vicon_state
lock_vicon_state.release()
if (vicon_state is None):
displayLineno(2,"Vicon unavailable")
#enableVicon = False
# flag indicating that "vicon not ready" is currently displayed on line 2
flag_vicon_not_ready = True
else:
if (flag_vicon_not_ready):
flag_vicon_not_ready = False
displayLineno(2,"Vicon Capture Enabled")
x,y,z,rx,ry,rz = vicon_state
text = str(x)+","+str(y)+","+str(z)+","+str(rx)+","+str(ry)+","+str(rz)
text = "%.2f, %.2f, %.2f, %.2f, %.2f, %.2f"%(x,y,z,rx,ry,rz)
displayLineno(3,"Vicon Stream: "+text)
if (enableJoystick):
lock_js.acquire()
local_throttle = js_throttle
local_flap = js_flap
lock_js.release()
displayLineno(5,"Joystick: T: %d F: %d ,interval(ms) %d"%(local_throttle,local_flap,debug_joy_update_interval_ms))
screen.refresh()
# read user input, store in buffer
user_input = screen.getch()
while (user_input != -1):
command += chr(user_input)
user_input = screen.getch()
# display user typed command TODO add curser, editing
# currently no backspace allowed
screen.addstr(ymax-1,0,"Command: "+command)
#screen.refresh()
# process command when return is sent
# command here includes a trailing \n, remove that before parsing
if (len(command)>0 and command[-1] == '\n'):
curses.beep() #doesn't seem to work
if (command[:-1] == 'quit') or (command[:-1] == 'q'):
quit = True
elif command[:-1] == 'clear':
screen.clear()
elif command[:-1] == 'flush':
avionics.reset_input_buffer()
elif command[:-1] == 'ping':
flag_ping_in_progress = True
tic = time()
avionics.write("ping\r\n".encode())
displayLineno(2,"Ping...")
elif command[:-1] == 'vicon':
enableVicon = not enableVicon
if (enableVicon):
displayLineno(2,"Vicon Capture Enabled")
else:
displayLineno(2,"Vicon Capture Disabled")
elif command[:-1] == 'log':
# toggle logging, start a new file each time
if (isLogging):
# logging was enabled, now stopping logging
isLogging = False
lock_logfile.acquire()
with open(logFilename, 'a') as filehandle:
for entry in logBuffer:
filehandle.write('%s' % entry)
logBuffer = []
lock_logfile.release()
displayLineno(2,"logfile saved: "+logFilename)
else:
no = 1
logBuffer = []
while os.path.isfile(logFolder+logPrefix+str(no)+logSuffix):
no += 1
logFilename = logFolder+logPrefix+str(no)+logSuffix
isLogging = True
displayLineno(2,"log started: "+logFilename)
elif command[:-1] == 'joy':
# toggle joystick
if enableJoystick:
enableJoystick = False
displayLineno(2,"Joystick Disabled")
thread_joystick.join()
else:
try:
js = pygame.joystick.Joystick(0)
js.init()
enableJoystick = True
thread_joystick = threading.Thread(name="joystickUpdate",target=joystickUpdateDaemon,args=(js,avionics))
thread_joystick.start()
displayLineno(2,"Joystick Enabled : "+str(js.get_name()))
except pygame.error as e:
displayLineno(2,"Joystick Not available: " + str(e))
else:
# command start with single letter 't': intended for teststand
# command start with single letter 'a': intended for avionics
# e.g. "t sync" -> send "sync" to teststand (with additional trailing \r\n)
# similarly 'a' for avionics
# it's ok to send the trailing \n, default behavior or arduino IDE's serial monitor
if command[0] == 'a':
# avionics
avionics.write(command[2:].encode())
screen.move(ymax-2,0)
screen.clrtoeol()
screen.addstr(ymax-2,0,"Command Sent[avionics]: "+command[2:])
else:
screen.move(ymax-2,0)
screen.clrtoeol()
screen.addstr(ymax-2,0,"Unrecognized command: "+command)
# clear user input
screen.move(ymax-1,0)
screen.clrtoeol()
screen.addstr(ymax-1,0,"Command: ")
screen.refresh()
command = ""
screen.refresh()
# display new data
if (enablePlot and flap_new_plot_data):
if (flag_calibrated):
# update plot (avionics related)
data00[:-1,:] = data00[1:,:] # shift data in the temporal mean 1 sample left
#data01[:-1,:] = data01[1:,:] # shift data in the temporal mean 1 sample left
data10[:-1,:] = data10[1:,:] # shift data in the temporal mean 1 sample left
#data11[:-1,:] = data11[1:,:] # shift data in the temporal mean 1 sample left
# x axis
data00[-1,0] = avionics_ts/1000.0 # in second
# y axis
#data00[-1,1] = np.linalg.norm(acc1-R_12*acc2) # vector containing the instantaneous values
data00[-1,1] = 0
# x axis
data10[-1,0] = avionics_ts/1000.0 # in second
# y axis
#data00[-1,1] = np.linalg.norm(acc1-R_12*acc2) # vector containing the instantaneous values
data10[-1,1] = 0
#data10[-1,0] = testStand_ts/1000.0 # in second
# mag angle dot product
#data10[-1,1] = np.dot(np.array([0,1,0]),mag/np.linalg.norm(mag))
# estimated omega from avionics
#data10[-1,1] = kf_omega
#data11[-1,0] = testStand_ts/1000.0 # in second
# angle diff
#data11[-1,1] = min(abs(int(kf_azimuth) - int(azimuth)),360-abs(int(kf_azimuth) - int(azimuth)))
#data11[-1,1] = kf_omega - omega
#screen.addstr(ymax-5,0,str(data01[-1,1]))
screen.refresh()
curve00.setData(data00) # set the curve with this data
#curve01.setData(data01) # set the curve with this data
curve10.setData(data10) # set the curve with this data
#curve11.setData(data11) # set the curve with this data
QtGui.QApplication.processEvents() # you MUST process the plot now
flap_new_plot_data = False
if __name__ == '__main__':
#establish serial comm to teststand and avionics,XXX not sure how to determine order, just plug them in in order...
vi = Vicon()
pygame.display.init()
pygame.joystick.init()
host_system = platform.system()
# automatically identifies Linux or MacOS
if host_system == "Linux":
avionicsCommPort = '/dev/ttyUSB0'
#avionicsCommPort = '/dev/ttyACM0'
elif host_system == "Darwin":
testStandCommPort = '/dev/tty.wchusbserial1420'
avionicsCommPort = '/dev/tty.SLAB_USBtoUART'
try:
if (enablePlot):
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Avionics Feed") # create a window
plot00 = win.addPlot(title="Phase",row=0,col=0,labels={'left':"Phase(deg)",'bottom':"Time(s)"}) # creates empty space for the plot in the window
#plot01 = win.addPlot(title="mag",row=0,col=1,labels={'left':"ref",'bottom':"Time(s)"}) # creates empty space for the plot in the window
plot10 = win.addPlot(title="Omega",row=1,col=0,labels={'left':"rev/s",'bottom':"Time(s)"}) # creates empty space for the plot in the window
#plot11 = win.addPlot(title="omega difference",row=1,col=1,labels={'left':"d_theta(deg)",'bottom':"Time(s)"}) # creates empty space for the plot in the window
curve00 = plot00.plot() # create an empty "plot" (a curve to plot)
#curve01 = plot01.plot() # create an empty "plot" (a curve to plot)
curve10 = plot10.plot() # create an empty "plot" (a curve to plot)
#curve11 = plot11.plot() # create an empty "plot" (a curve to plot)
#plot11.setYRange(0,180)
windowWidth = 200 # width of the window displaying the curve
data00 = np.vstack([np.linspace(0,0,windowWidth),np.linspace(0,0,windowWidth)]).T # create array that will contain the relevant time series
#data00 = np.linspace(0,0,windowWidth)
data01 = np.vstack([np.linspace(0,0,windowWidth),np.linspace(0,0,windowWidth)]).T # create array that will contain the relevant time series
data10 = np.vstack([np.linspace(0,0,int(windowWidth/2)),np.linspace(0,0,int(windowWidth/2))]).T # create array that will contain the relevant time series
data11 = np.vstack([np.linspace(0,0,int(windowWidth/2)),np.linspace(0,0,int(windowWidth/2))]).T # create array that will contain the relevant time series
ptr = -windowWidth # set first x position
# prepare post experiment data
mag_offset = []
# start vicon update loop
thread_vicon = threading.Thread(name="viconUpdate",target=viconUpdateDaemon,args=(vi,))
thread_vicon.start()
# start main update loop
try:
with serial.Serial(avionicsCommPort,115200, timeout=0.1) as avionics:
curses.wrapper(main,avionics)
except serial.serialutil.SerialException as e:
print(e)
finally:
quit = True
thread_vicon.join()
if (enableJoystick):
thread_joystick.join()
if (enablePlot):
print("Please close the plot window")
pg.QtGui.QApplication.exec_()