forked from thecognifly/YAMSPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleUI_tcp.py
367 lines (288 loc) · 15.3 KB
/
simpleUI_tcp.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
"""simpleUI_tcp.py: Simple UI (toy one really) to test YAMSPy using with TCP.
Check https://github.com/ricardodeazambuja/betaflight/tree/sitl/src/main/target/SITL for more details!
Copyright (C) 2020 Ricardo de Azambuja
This file is part of YAMSPy.
YAMSPy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
YAMSPy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with YAMSPy. If not, see <https://www.gnu.org/licenses/>.
WARNING:
This UI is not fit for flying your drone, it is only useful for testing stuff in a safe place, ok?
Acknowledgement:
This work was possible thanks to the financial support from IVADO.ca (postdoctoral scholarship 2019/2020).
Disclaimer (adapted from Wikipedia):
None of the authors, contributors, supervisors, administrators, employers, friends, family, vandals, or anyone else
connected (or not) with this project, in any way whatsoever, can be made responsible for your use of the information (code)
contained or linked from here.
TODO:
1) The integrator makes it too hard to control things (it winds up). Probably a non-linear thing would be helpful here...
2) Everything is far from optimal so it could be improved... but it's a simpleUI example after all ;)
"""
__author__ = "Ricardo de Azambuja"
__copyright__ = "Copyright 2020, MISTLab.ca"
__credits__ = [""]
__license__ = "GPL"
__version__ = "0.0.1"
__maintainer__ = "Ricardo de Azambuja"
__email__ = "[email protected]"
__status__ = "Development"
import time
import curses
from collections import deque
from itertools import cycle
import argparse
from yamspy import MSPy
# Max periods for:
CTRL_LOOP_TIME = 1/50
SLOW_MSGS_LOOP_TIME = 1/10 # these messages take a lot of time slowing down the loop...
NO_OF_CYCLES_AVERAGE_GUI_TIME = 10
#
# On Linux, your serial port will probably be something like
# /dev/ttyACM0 or /dev/ttyS0 or the same names with numbers different from 0
#
# On Windows, I would expect it to be
# COM1 or COM2 or COM3...
#
# This library uses pyserial, so if you have more questions try to check its docs:
# https://pyserial.readthedocs.io/en/latest/shortintro.html
#
#
# SERIAL_PORT = "/dev/ttyACM0"
def run_curses(external_function):
result=1
try:
# get the curses screen window
screen = curses.initscr()
# turn off input echoing
curses.noecho()
# respond to keys immediately (don't wait for enter)
curses.cbreak()
# non-blocking
screen.timeout(0)
# map arrow keys to special values
screen.keypad(True)
screen.addstr(1, 0, "Press 'q' to quit, 'r' to reboot, 'm' to change mode, 'a' to arm, 'd' to disarm and arrow keys to control", curses.A_BOLD)
result = external_function(screen)
finally:
# shut down cleanly
curses.nocbreak(); screen.keypad(0); curses.echo()
curses.endwin()
if result==1:
print("An error occurred... probably the serial port is not available ;)")
def keyboard_controller(screen):
CMDS = {
'roll': 1500,
'pitch': 1500,
'throttle': 900,
'yaw': 1500,
'aux1': 1000,
'aux2': 1000,
'counter': 0
}
# This order is the important bit: it will depend on how your flight controller is configured.
# Below it is considering the flight controller is set to use AETR.
# The names here don't really matter, they just need to match what is used for the CMDS dictionary.
# In the documentation, iNAV uses CH5, CH6, etc while Betaflight goes AUX1, AUX2...
CMDS_ORDER = ['roll', 'pitch', 'throttle', 'yaw', 'aux1', 'aux2', 'counter']
# "print" doesn't work with curses, use addstr instead
try:
screen.addstr(15, 0, "Connecting to the FC...")
with MSPy(device=SERIAL_PORT, baudrate=115200, use_tcp=True, min_time_between_writes=1/50) as board:
if board == 1: # an error occurred...
return 1
screen.addstr(15, 0, "Connecting to the FC... connected!")
screen.clrtoeol()
screen.move(1,0)
average_cycle = deque([0]*NO_OF_CYCLES_AVERAGE_GUI_TIME)
# It's necessary to send some messages or the RX failsafe will be activated
# and it will not be possible to arm.
command_list = ['MSP_API_VERSION', 'MSP_FC_VARIANT', 'MSP_FC_VERSION', 'MSP_BUILD_INFO',
'MSP_BOARD_INFO', 'MSP_UID', 'MSP_NAME', 'MSP_STATUS', 'MSP_STATUS_EX',
'MSP_BOXNAMES', 'MSP_ANALOG']
if board.INAV:
command_list.append('MSP2_INAV_ANALOG')
command_list.append('MSP_VOLTAGE_METER_CONFIG')
command_list.append('MSP2_INAV_STATUS')
for msg in command_list:
msg_processed = False
code_value = MSPy.MSPCodes[msg]
while not msg_processed:
if board.send_RAW_msg(code_value, data=[]):
dataHandler = board.receive_msg()
if dataHandler['pending'] == 1:
dataHandler = board.receive_msg(dataHandler)
if dataHandler['packet_error']==1:
return 1 # if messages are failing here... it's a bad omen :)
board.process_recv_data(dataHandler)
if dataHandler['code'] == MSPy.MSPCodes[msg]:
msg_processed = True
if board.INAV:
cellCount = board.BATTERY_STATE['cellCount']
else:
cellCount = 0 # MSP2_INAV_ANALOG is necessary
min_voltage = board.BATTERY_CONFIG['vbatmincellvoltage']*cellCount
warn_voltage = board.BATTERY_CONFIG['vbatwarningcellvoltage']*cellCount
max_voltage = board.BATTERY_CONFIG['vbatmaxcellvoltage']*cellCount
screen.addstr(15, 0, "apiVersion: {}".format(board.CONFIG['apiVersion']))
screen.clrtoeol()
screen.addstr(15, 50, "flightControllerIdentifier: {}".format(board.CONFIG['flightControllerIdentifier']))
screen.addstr(16, 0, "flightControllerVersion: {}".format(board.CONFIG['flightControllerVersion']))
screen.addstr(16, 50, "boardIdentifier: {}".format(board.CONFIG['boardIdentifier']))
screen.addstr(17, 0, "boardName: {}".format(board.CONFIG['boardName']))
screen.addstr(17, 50, "name: {}".format(board.CONFIG['name']))
if board.INAV:
slow_msgs = cycle(['MSP_ANALOG', 'MSP2_INAV_STATUS', 'MSP_MOTOR', 'MSP_RC'])
else:
slow_msgs = cycle(['MSP_ANALOG', 'MSP_STATUS_EX', 'MSP_MOTOR', 'MSP_RC'])
cursor_msg = ""
last_loop_time = last_slow_msg_time = last_cycleTime = time.time()
while True:
start_time = time.time()
char = screen.getch() # get keypress
curses.flushinp() # flushes buffer
#
# Key input processing
#
#
# KEYS (NO DELAYS)
#
if char == ord('q') or char == ord('Q'):
break
elif char == ord('d') or char == ord('D'):
cursor_msg = 'Sending Disarm command...'
CMDS['aux1'] = 1000
elif char == ord('r') or char == ord('R'):
screen.addstr(3, 0, 'Sending Reboot command...')
screen.clrtoeol()
board.reboot()
time.sleep(0.5)
break
elif char == ord('a') or char == ord('A'):
cursor_msg = 'Sending Arm command...'
CMDS['aux1'] = 1900
#
# The code below is expecting the drone to have the
# modes set accordingly since everything is hardcoded.
#
elif char == ord('m') or char == ord('M'):
if CMDS['aux2'] <= 1300:
cursor_msg = 'NAS POSHOLD Mode...'
CMDS['aux2'] = 1500
elif 1700 > CMDS['aux2'] > 1300:
cursor_msg = 'NAS ALTHOLD Mode...'
CMDS['aux2'] = 1900
elif CMDS['aux2'] >= 1700:
cursor_msg = 'Angle Mode...'
CMDS['aux2'] = 1000
elif char == ord('w') or char == ord('W'):
CMDS['throttle'] = CMDS['throttle'] + 10 if CMDS['throttle'] + 10 <= 2000 else CMDS['throttle']
cursor_msg = 'W Key - throttle(+):{}'.format(CMDS['throttle'])
elif char == ord('e') or char == ord('E'):
CMDS['throttle'] = CMDS['throttle'] - 10 if CMDS['throttle'] - 10 >= 1000 else CMDS['throttle']
cursor_msg = 'E Key - throttle(-):{}'.format(CMDS['throttle'])
elif char == curses.KEY_RIGHT:
CMDS['roll'] = CMDS['roll'] + 10 if CMDS['roll'] + 10 <= 2000 else CMDS['roll']
cursor_msg = 'Right Key - roll(-):{}'.format(CMDS['roll'])
elif char == curses.KEY_LEFT:
CMDS['roll'] = CMDS['roll'] - 10 if CMDS['roll'] - 10 >= 1000 else CMDS['roll']
cursor_msg = 'Left Key - roll(+):{}'.format(CMDS['roll'])
elif char == curses.KEY_UP:
CMDS['pitch'] = CMDS['pitch'] + 10 if CMDS['pitch'] + 10 <= 2000 else CMDS['pitch']
cursor_msg = 'Up Key - pitch(+):{}'.format(CMDS['pitch'])
elif char == curses.KEY_DOWN:
CMDS['pitch'] = CMDS['pitch'] - 10 if CMDS['pitch'] - 10 >= 1000 else CMDS['pitch']
cursor_msg = 'Down Key - pitch(-):{}'.format(CMDS['pitch'])
#
# IMPORTANT MESSAGES (CTRL_LOOP_TIME based)
#
if (time.time()-last_loop_time) >= CTRL_LOOP_TIME:
last_loop_time = time.time()
CMDS['counter'] = int(last_loop_time)
# Send the RC channel values to the FC
board.send_RAW_RC([CMDS[ki] for ki in CMDS_ORDER])
#
# SLOW MSG processing (user GUI)
#
if (time.time()-last_slow_msg_time) >= SLOW_MSGS_LOOP_TIME:
last_slow_msg_time = time.time()
next_msg = next(slow_msgs) # circular list
# Read info from the FC
if board.send_RAW_msg(MSPy.MSPCodes[next_msg], data=[]):
msg_processed = False
while not msg_processed:
dataHandler = board.receive_msg()
if dataHandler['pending'] == 1:
dataHandler = board.receive_msg(dataHandler)
if dataHandler['code'] == MSPy.MSPCodes[next_msg]:
msg_processed = True
board.process_recv_data(dataHandler)
if dataHandler['packet_error']==1:
msg_processed = True
screen.addstr(20, 0, MSPy.MSPCodes2Str[dataHandler['code']])
screen.clrtoeol()
else:
next_msg = ''
screen.addstr(20, 0, "None")
screen.clrtoeol()
if next_msg == 'MSP_ANALOG':
voltage = board.ANALOG['voltage']
voltage_msg = ""
if min_voltage < voltage <= warn_voltage:
voltage_msg = "LOW BATT WARNING"
elif voltage <= min_voltage:
voltage_msg = "ULTRA LOW BATT!!!"
elif voltage >= max_voltage:
voltage_msg = "VOLTAGE TOO HIGH"
screen.addstr(8, 0, "Battery Voltage: {:2.2f}V".format(board.ANALOG['voltage']))
screen.clrtoeol()
screen.addstr(8, 24, voltage_msg, curses.A_BOLD + curses.A_BLINK)
screen.clrtoeol()
elif next_msg == 'MSP2_INAV_STATUS':
ARMED = board.bit_check(board.CONFIG['mode'],0)
screen.addstr(5, 0, "ARMED: {}".format(ARMED), curses.A_BOLD)
screen.clrtoeol()
screen.addstr(5, 50, "armingDisableFlags: {}".format(board.process_armingDisableFlags(board.CONFIG['armingDisableFlags'])))
# screen.addstr(5, 50, "armingDisableFlags: {0:b}".format(board.CONFIG['armingDisableFlags']))
screen.clrtoeol()
screen.addstr(6, 0, "cpuload: {}".format(board.CONFIG['cpuload']))
screen.clrtoeol()
screen.addstr(6, 50, "cycleTime: {}".format(board.CONFIG['cycleTime']))
screen.clrtoeol()
screen.addstr(7, 0, "mode: {}".format(board.CONFIG['mode']))
screen.clrtoeol()
screen.addstr(7, 50, "Flight Mode: {}".format(board.process_mode(board.CONFIG['mode'])))
screen.clrtoeol()
elif next_msg == 'MSP_MOTOR':
screen.addstr(9, 0, "Motor Values: {}".format(board.MOTOR_DATA))
screen.clrtoeol()
elif next_msg == 'MSP_RC':
screen.addstr(10, 0, "RC Channels Values: {}".format(board.RC['channels']))
screen.clrtoeol()
screen.addstr(11, 0, f"GUI cycleTime: {last_cycleTime*1000:2.2f}ms (average {1/(sum(average_cycle)/len(average_cycle)):2.2f}Hz)")
screen.clrtoeol()
screen.addstr(12, 0, f"{time.asctime()}")
screen.clrtoeol()
screen.addstr(3, 0, cursor_msg)
screen.clrtoeol()
end_time = time.time()
last_cycleTime = end_time-start_time
if (end_time-start_time)<CTRL_LOOP_TIME:
time.sleep(CTRL_LOOP_TIME-(end_time-start_time))
average_cycle.append(time.time()-start_time)
average_cycle.popleft()
finally:
screen.addstr(5, 0, "Disconneced from the FC!")
screen.clrtoeol()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Test YAMSPy using TCP')
parser.add_argument('--port', type=int, required=True,
help='TCP port')
args = parser.parse_args()
SERIAL_PORT = args.port
run_curses(keyboard_controller)