-
Notifications
You must be signed in to change notification settings - Fork 468
/
QualisysTab.py
1442 lines (1175 loc) · 56.2 KB
/
QualisysTab.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""
Tab for controlling the Crazyflie using Qualisys Motion Capturing system
"""
import logging
import time
import datetime
import math
from enum import Enum
from PyQt5 import uic
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, pyqtProperty
from PyQt5.QtCore import QStateMachine, QState, QEvent, QTimer
from PyQt5.QtCore import QAbstractTransition
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtGui import QStandardItemModel, QStandardItem
import cfclient
from cfclient.ui.tab import Tab
from cfclient.utils.config import Config
from cflib.crazyflie.log import LogConfig
from cflib.crazyflie.syncLogger import SyncLogger
import xml.etree.cElementTree as ET
import threading
import qtm
import asyncio
__author__ = 'Bitcraze AB'
__all__ = ['QualisysTab']
logger = logging.getLogger(__name__)
qualisys_tab_class, _ = uic.loadUiType(cfclient.module_path +
"/ui/tabs/qualisysTab.ui")
class FlightModeEvent(QEvent):
def __init__(self, mode, parent=None):
super(FlightModeEvent, self).__init__(QEvent.Type(QEvent.User + 1))
self.mode = mode
class FlightModeTransition(QAbstractTransition):
def __init__(self, value, parent=None):
super(FlightModeTransition, self).__init__(parent)
self.value = value
def eventTest(self, event):
if event.type() != QEvent.Type(QEvent.User + 1):
return False
return event.mode == self.value
def onTransition(self, event):
pass
class FlightModeStates(Enum):
LAND = 0
LIFT = 1
FOLLOW = 2
PATH = 3
HOVERING = 4
GROUNDED = 5
DISCONNECTED = 6
CIRCLE = 7
RECORD = 8
COLOR_BLUE = '#3399ff'
COLOR_GREEN = '#00ff60'
COLOR_RED = '#cc0404'
def progressbar_stylesheet(color):
return """
QProgressBar {
border: 1px solid #AAA;
background-color: transparent;
}
QProgressBar::chunk {
background-color: """ + color + """;
}
"""
def start_async_task(task):
return asyncio.ensure_future(task)
class QDiscovery(QObject):
discoveringChanged = pyqtSignal(bool)
discoveredQTM = pyqtSignal(str, str)
def __init__(self, *args):
super().__init__(*args)
self._discovering = False
self._found_qtms = {}
@pyqtProperty(bool, notify=discoveringChanged)
def discovering(self):
return self._discovering
@discovering.setter
def discovering(self, value):
if value != self._discovering:
self._discovering = value
self.discoveringChanged.emit(value)
def discover(self, *, interface='0.0.0.0'):
self.discovering = True
start_async_task(self._discover_qtm(interface))
async def _discover_qtm(self, interface):
try:
async for qtm_instance in qtm.Discover(interface):
info = qtm_instance.info.decode("utf-8").split(",")[0]
self.discoveredQTM.emit(info, qtm_instance.host)
except Exception as e:
logger.info("Exception during qtm discovery: %s", e)
self.discovering = False
class QualisysTab(Tab, qualisys_tab_class):
"""
Tab for controlling the crazyflie using
Qualisys Motion Capturing system
"""
_connected_signal = pyqtSignal(str)
_disconnected_signal = pyqtSignal(str)
_log_data_signal = pyqtSignal(int, object, object)
_log_error_signal = pyqtSignal(object, str)
_param_updated_signal = pyqtSignal(str, str)
_imu_data_signal = pyqtSignal(int, object, object)
_flight_path_select_row = pyqtSignal(int)
_flight_path_set_model = pyqtSignal(object)
_path_selector_add_item = pyqtSignal(str)
_path_selector_set_index = pyqtSignal(int)
statusChanged = pyqtSignal(str)
cfStatusChanged = pyqtSignal(str)
qtmStatusChanged = pyqtSignal(str)
def __init__(self, tabWidget, helper, *args):
super(QualisysTab, self).__init__(*args)
self.setupUi(self)
self._machine = QStateMachine()
self._setup_states()
self._event = threading.Event()
self.tabName = "Qualisys"
self.menuName = "Qualisys Tab"
self.tabWidget = tabWidget
self.qtm_6DoF_labels = None
self._helper = helper
self._qtm_connection = None
self._cf = None
self.model = QStandardItemModel(10, 4)
self._cf_status = self.cfStatusLabel.text()
self._status = self.statusLabel.text()
self._qtm_status = self.qtmStatusLabel.text()
self.flying_enabled = False
self.switch_flight_mode(FlightModeStates.DISCONNECTED)
self.path_pos_threshold = 0.2
self.circle_pos_threshold = 0.1
self.circle_radius = 1.5
self.circle_resolution = 15.0
self.position_hold_timelimit = 0.1
self.length_from_wand = 2.0
self.circle_height = 1.2
self.new_path = []
self.recording = False
self.land_for_recording = False
self.default_flight_paths = [
[
"Path 1: Sandbox",
[0.0, -1.0, 1.0, 0.0],
[0.0, 1.0, 1.0, 0.0]],
[
"Path 2: Height Test",
[0.0, 0.0, 0.5, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 1.5, 0.0],
[0.0, 0.0, 2.0, 0.0],
[0.0, 0.0, 2.3, 0.0],
[0.0, 0.0, 1.8, 0.0],
[0.0, 0.0, 0.5, 0.0],
[0.0, 0.0, 0.3, 0.0],
[0.0, 0.0, 0.15, 0.0]],
[
"Path 3: 'Spiral'",
[0.0, 0.0, 1.0, 0.0],
[0.5, 0.5, 1.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[-0.5, 0.5, 1.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.5, 0.5, 1.2, 0.0],
[0.0, 1.0, 1.4, 0.0],
[-0.5, 0.5, 1.6, 0.0],
[0.0, 0.0, 1.8, 0.0],
[0.5, 0.5, 1.5, 0.0],
[0.0, 1.0, 1.0, 0.0],
[-0.5, 0.5, 0.5, 0.0],
[0.0, 0.0, 0.25, 0.0]]]
# The position and rotation of the cf and wand obtained by the
# camera tracking, if it cant be tracked the position becomes Nan
self.cf_pos = Position(0, 0, 0)
self.wand_pos = Position(0, 0, 0)
# The regular cf_pos can a times due to lost tracing become Nan,
# this the latest known valid cf position
self.valid_cf_pos = Position(0, 0, 0)
try:
self.flight_paths = Config().get("flight_paths")
except Exception:
logger.debug("No flight config")
self.flight_paths = self.default_flight_paths
if self.flight_paths == []:
self.flight_paths = self.default_flight_paths
# Always wrap callbacks from Crazyflie API though QT Signal/Slots
# to avoid manipulating the UI when rendering it
self._connected_signal.connect(self._connected)
self._disconnected_signal.connect(self._disconnected)
self._log_data_signal.connect(self._log_data_received)
self._param_updated_signal.connect(self._param_updated)
self._flight_path_select_row.connect(self._select_flight_path_row)
self._flight_path_set_model.connect(self._set_flight_path_model)
self._path_selector_add_item.connect(self._add_path_selector_item)
self._path_selector_set_index.connect(self._set_path_selector_index)
self.statusChanged.connect(self._update_status)
self.cfStatusChanged.connect(self._update_cf_status)
self.qtmStatusChanged.connect(self._update_qtm_status)
# Connect the Crazyflie API callbacks to the signals
self._helper.cf.connected.add_callback(self._connected_signal.emit)
self._helper.cf.disconnected.add_callback(
self._disconnected_signal.emit)
# Connect the UI elements
self.connectQtmButton.clicked.connect(self.establish_qtm_connection)
self.landButton.clicked.connect(self.set_land_mode)
self.liftButton.clicked.connect(self.set_lift_mode)
self.followButton.clicked.connect(self.set_follow_mode)
self.emergencyButton.clicked.connect(self.set_kill_engine)
self.pathButton.clicked.connect(self.set_path_mode)
self.circleButton.clicked.connect(self.set_circle_mode)
self.recordButton.clicked.connect(self.set_record_mode)
self.removePathButton.clicked.connect(self.remove_current_path)
for i in range(len(self.flight_paths)):
self.pathSelector.addItem(self.flight_paths[i][0])
self.pathSelector.currentIndexChanged.connect(self.path_changed)
self.quadBox.currentIndexChanged[str].connect(self.quad_changed)
self.stickBox.currentIndexChanged[str].connect(self.stick_changed)
self.stickName = 'qstick'
self.quadName = 'crazyflie'
# Populate UI elements
self.posHoldPathBox.setText(str(self.position_hold_timelimit))
self.radiusBox.setText(str(self.circle_radius))
self.posHoldCircleBox.setText(str(self.position_hold_timelimit))
self.resolutionBox.setText(str(self.circle_resolution))
self.path_changed()
self._discovery = QDiscovery()
self._discovery.discoveringChanged.connect(self._is_discovering)
self._discovery.discoveredQTM.connect(self._qtm_discovered)
self.discoverQTM.clicked.connect(self._discovery.discover)
self._discovery.discover()
self._ui_update_timer = QTimer(self)
self._ui_update_timer.timeout.connect(self._update_ui)
def _setup_states(self):
parent_state = QState()
# DISCONNECTED
disconnected = QState(parent_state)
disconnected.assignProperty(self, "status", "Disabled")
disconnected.assignProperty(self.pathButton, "text", "Path Mode")
disconnected.assignProperty(self.followButton, "text", "Follow Mode")
disconnected.assignProperty(self.circleButton, "text", "Circle Mode")
disconnected.assignProperty(self.recordButton, "text", "Record Mode")
disconnected.assignProperty(self.pathButton, "enabled", False)
disconnected.assignProperty(self.emergencyButton, "enabled", False)
disconnected.assignProperty(self.landButton, "enabled", False)
disconnected.assignProperty(self.followButton, "enabled", False)
disconnected.assignProperty(self.liftButton, "enabled", False)
disconnected.assignProperty(self.circleButton, "enabled", False)
disconnected.assignProperty(self.recordButton, "enabled", False)
disconnected.entered.connect(self._flight_mode_disconnected_entered)
# HOVERING
hovering = QState(parent_state)
hovering.assignProperty(self, "status", "Hovering...")
hovering.assignProperty(self.pathButton, "text", "Path Mode")
hovering.assignProperty(self.followButton, "text", "Follow Mode")
hovering.assignProperty(self.circleButton, "text", "Circle Mode")
hovering.assignProperty(self.recordButton, "text", "Record Mode")
hovering.assignProperty(self.pathButton, "enabled", True)
hovering.assignProperty(self.emergencyButton, "enabled", True)
hovering.assignProperty(self.landButton, "enabled", True)
hovering.assignProperty(self.followButton, "enabled", True)
hovering.assignProperty(self.liftButton, "enabled", False)
hovering.assignProperty(self.circleButton, "enabled", True)
hovering.assignProperty(self.recordButton, "enabled", True)
hovering.entered.connect(self._flight_mode_hovering_entered)
# GROUNDED
grounded = QState(parent_state)
grounded.assignProperty(self, "status", "Landed")
grounded.assignProperty(self.pathButton, "text", "Path Mode")
grounded.assignProperty(self.followButton, "text", "Follow Mode")
grounded.assignProperty(self.circleButton, "text", "Circle Mode")
grounded.assignProperty(self.recordButton, "text", "Record Mode")
grounded.assignProperty(self.pathButton, "enabled", True)
grounded.assignProperty(self.emergencyButton, "enabled", True)
grounded.assignProperty(self.landButton, "enabled", False)
grounded.assignProperty(self.followButton, "enabled", False)
grounded.assignProperty(self.liftButton, "enabled", True)
grounded.assignProperty(self.circleButton, "enabled", True)
grounded.assignProperty(self.recordButton, "enabled", True)
grounded.entered.connect(self._flight_mode_grounded_entered)
# PATH
path = QState(parent_state)
path.assignProperty(self, "status", "Path Mode")
path.assignProperty(self.pathButton, "text", "Stop")
path.assignProperty(self.followButton, "text", "Follow Mode")
path.assignProperty(self.circleButton, "text", "Circle Mode")
path.assignProperty(self.recordButton, "text", "Record Mode")
path.assignProperty(self.pathButton, "enabled", True)
path.assignProperty(self.emergencyButton, "enabled", True)
path.assignProperty(self.landButton, "enabled", True)
path.assignProperty(self.followButton, "enabled", False)
path.assignProperty(self.liftButton, "enabled", False)
path.assignProperty(self.circleButton, "enabled", False)
path.assignProperty(self.recordButton, "enabled", False)
path.entered.connect(self._flight_mode_path_entered)
# FOLLOW
follow = QState(parent_state)
follow.assignProperty(self, "status", "Follow Mode")
follow.assignProperty(self.pathButton, "text", "Path Mode")
follow.assignProperty(self.followButton, "text", "Stop")
follow.assignProperty(self.circleButton, "text", "Circle Mode")
follow.assignProperty(self.recordButton, "text", "Record Mode")
follow.assignProperty(self.pathButton, "enabled", False)
follow.assignProperty(self.emergencyButton, "enabled", True)
follow.assignProperty(self.landButton, "enabled", True)
follow.assignProperty(self.followButton, "enabled", False)
follow.assignProperty(self.liftButton, "enabled", False)
follow.assignProperty(self.circleButton, "enabled", False)
follow.assignProperty(self.recordButton, "enabled", False)
follow.entered.connect(self._flight_mode_follow_entered)
# LIFT
lift = QState(parent_state)
lift.assignProperty(self, "status", "Lifting...")
lift.assignProperty(self.pathButton, "enabled", False)
lift.assignProperty(self.emergencyButton, "enabled", True)
lift.assignProperty(self.landButton, "enabled", True)
lift.assignProperty(self.followButton, "enabled", False)
lift.assignProperty(self.liftButton, "enabled", False)
lift.assignProperty(self.circleButton, "enabled", False)
lift.assignProperty(self.recordButton, "enabled", False)
lift.entered.connect(self._flight_mode_lift_entered)
# LAND
land = QState(parent_state)
land.assignProperty(self, "status", "Landing...")
land.assignProperty(self.pathButton, "enabled", False)
land.assignProperty(self.emergencyButton, "enabled", True)
land.assignProperty(self.landButton, "enabled", False)
land.assignProperty(self.followButton, "enabled", False)
land.assignProperty(self.liftButton, "enabled", False)
land.assignProperty(self.circleButton, "enabled", False)
land.assignProperty(self.recordButton, "enabled", False)
land.entered.connect(self._flight_mode_land_entered)
# CIRCLE
circle = QState(parent_state)
circle.assignProperty(self, "status", "Circle Mode")
circle.assignProperty(self.pathButton, "text", "Path Mode")
circle.assignProperty(self.followButton, "text", "Follow Mode")
circle.assignProperty(self.circleButton, "text", "Stop")
circle.assignProperty(self.recordButton, "text", "Record Mode")
circle.assignProperty(self.pathButton, "enabled", False)
circle.assignProperty(self.emergencyButton, "enabled", True)
circle.assignProperty(self.landButton, "enabled", True)
circle.assignProperty(self.followButton, "enabled", False)
circle.assignProperty(self.liftButton, "enabled", False)
circle.assignProperty(self.circleButton, "enabled", True)
circle.assignProperty(self.recordButton, "enabled", False)
circle.entered.connect(self._flight_mode_circle_entered)
# RECORD
record = QState(parent_state)
record.assignProperty(self, "status", "Record Mode")
record.assignProperty(self.pathButton, "text", "Path Mode")
record.assignProperty(self.followButton, "text", "Follow Mode")
record.assignProperty(self.circleButton, "text", "Circle Mode")
record.assignProperty(self.recordButton, "text", "Stop")
record.assignProperty(self.pathButton, "enabled", False)
record.assignProperty(self.emergencyButton, "enabled", True)
record.assignProperty(self.landButton, "enabled", False)
record.assignProperty(self.followButton, "enabled", False)
record.assignProperty(self.liftButton, "enabled", False)
record.assignProperty(self.circleButton, "enabled", False)
record.assignProperty(self.recordButton, "enabled", True)
record.entered.connect(self._flight_mode_record_entered)
def add_transition(mode, child_state, parent):
transition = FlightModeTransition(mode)
transition.setTargetState(child_state)
parent.addTransition(transition)
add_transition(FlightModeStates.LAND, land, parent_state)
add_transition(FlightModeStates.LIFT, lift, parent_state)
add_transition(FlightModeStates.FOLLOW, follow, parent_state)
add_transition(FlightModeStates.PATH, path, parent_state)
add_transition(FlightModeStates.HOVERING, hovering, parent_state)
add_transition(FlightModeStates.GROUNDED, grounded, parent_state)
add_transition(FlightModeStates.DISCONNECTED, disconnected,
parent_state)
add_transition(FlightModeStates.CIRCLE, circle, parent_state)
add_transition(FlightModeStates.RECORD, record, parent_state)
parent_state.setInitialState(disconnected)
self._machine.addState(parent_state)
self._machine.setInitialState(parent_state)
self._machine.start()
def _update_flight_status(self):
prev_flying_enabled = self.flying_enabled
self.flying_enabled = self._cf is not None and \
self._qtm_connection is not None
if not prev_flying_enabled and self.flying_enabled:
self.switch_flight_mode(FlightModeStates.GROUNDED)
t = threading.Thread(target=self.flight_controller)
t.start()
if prev_flying_enabled and not self.flying_enabled:
self.switch_flight_mode(FlightModeStates.DISCONNECTED)
def _is_discovering(self, discovering):
if discovering:
self.qtmIpBox.clear()
self.discoverQTM.setEnabled(not discovering)
def _qtm_discovered(self, info, ip):
self.qtmIpBox.addItem("{} {}".format(ip, info))
@pyqtSlot(str)
def _update_status(self, status):
self.statusLabel.setText("Status: {}".format(status))
@pyqtSlot(str)
def _update_cf_status(self, status):
self.cfStatusLabel.setText(status)
@pyqtSlot(str)
def _update_qtm_status(self, status):
self.qtmStatusLabel.setText(status)
@pyqtSlot(str)
def quad_changed(self, quad):
self.quadName = quad
@pyqtSlot(str)
def stick_changed(self, stick):
self.stickName = stick
# Properties
@pyqtProperty(str, notify=statusChanged)
def status(self):
return self._status
@status.setter
def status(self, value):
if value != self._status:
self._status = value
self.statusChanged.emit(value)
@pyqtProperty(str, notify=qtmStatusChanged)
def qtmStatus(self):
return self._qtm_status
@qtmStatus.setter
def qtmStatus(self, value):
if value != self._qtm_status:
self._qtm_status = value
self.qtmStatusChanged.emit(value)
@pyqtProperty(str, notify=cfStatusChanged)
def cfStatus(self):
return self._qtm_status
@cfStatus.setter
def cfStatus(self, value):
if value != self._cf_status:
self._cf_status = value
self.cfStatusChanged.emit(value)
def _select_flight_path_row(self, row):
self.flightPathDataTable.selectRow(row)
def _set_flight_path_model(self, model):
self.flightPathDataTable.setModel(model)
def _add_path_selector_item(self, item):
self.pathSelector.addItem(item)
def _set_path_selector_index(self, index):
self.pathSelector.setCurrentIndex(index)
def path_changed(self):
if self.flight_mode == FlightModeStates.PATH:
self.switch_flight_mode(FlightModeStates.HOVERING)
time.sleep(0.1)
# Flight path ui table setup
self.model = QStandardItemModel(10, 4)
self.model.setHorizontalHeaderItem(0, QStandardItem('X (m)'))
self.model.setHorizontalHeaderItem(1, QStandardItem('Y (m)'))
self.model.setHorizontalHeaderItem(2, QStandardItem('Z (m)'))
self.model.setHorizontalHeaderItem(3, QStandardItem('Yaw (deg)'))
# Populate the table with data
if (len(self.flight_paths) == 0):
return
current = self.flight_paths[self.pathSelector.currentIndex()]
for i in range(1, len(current)):
for j in range(0, 4):
self.model.setItem(i - 1, j,
QStandardItem(str(current[i][j])))
self._flight_path_set_model.emit(self.model)
Config().set("flight_paths", self.flight_paths)
def remove_current_path(self):
if self.flight_mode == FlightModeStates.PATH:
self.switch_flight_mode(FlightModeStates.HOVERING)
time.sleep(0.1)
if len(self.flight_paths) == 0:
return
current_index = self.pathSelector.currentIndex()
answer = QMessageBox.question(
self, "CFClient: Qualisystab", "Delete the flightpath: {}?".format(
self.flight_paths[current_index][0]),
QMessageBox.Yes | QMessageBox.No)
if answer == QMessageBox.Yes:
self.flight_paths.pop(current_index)
self.pathSelector.clear()
for j in range(len(self.flight_paths)):
self.pathSelector.addItem(self.flight_paths[j][0])
if current_index == 0:
self.pathSelector.setCurrentIndex(0)
else:
self.pathSelector.setCurrentIndex(current_index - 1)
self.path_changed()
def set_lift_mode(self):
self.switch_flight_mode(FlightModeStates.LIFT)
def set_land_mode(self):
self.switch_flight_mode(FlightModeStates.LAND)
def set_circle_mode(self):
# Toggle circle mode on and off
if self.flight_mode == FlightModeStates.CIRCLE:
self.switch_flight_mode(FlightModeStates.HOVERING)
else:
try:
self.position_hold_timelimit = float(
self.posHoldCircleBox.text())
self.circle_radius = float(self.radiusBox.text())
self.circle_resolution = float(self.resolutionBox.text())
self.circle_pos_threshold = (2 * self.circle_radius * round(
math.sin(math.radians(
(self.circle_resolution / 2))), 4)) * 2
logger.info(self.circle_pos_threshold)
except ValueError as err:
self.status = ("illegal character used in circle"
" settings: {}").format(str(err))
logger.info(self.status)
return
self.switch_flight_mode(FlightModeStates.CIRCLE)
def set_record_mode(self):
# Toggle record mode on and off
if self.flight_mode == FlightModeStates.RECORD:
# Cancel the recording
self.recording = False
self.switch_flight_mode(FlightModeStates.GROUNDED)
self.land_for_recording = False
elif self.flight_mode != FlightModeStates.GROUNDED:
# If the cf is flying, start by landing
self.land_for_recording = True
self.switch_flight_mode(FlightModeStates.LAND)
else:
self.switch_flight_mode(FlightModeStates.RECORD)
def set_follow_mode(self):
# Toggle follow mode on and off
if self.flight_mode == FlightModeStates.FOLLOW:
self.switch_flight_mode(FlightModeStates.HOVERING)
else:
self.switch_flight_mode(FlightModeStates.FOLLOW)
def set_path_mode(self):
logger.info(self.model.item(0, 0))
# Toggle path mode on and off
# Path mode on, return to hovering
if self.flight_mode == FlightModeStates.PATH:
self.switch_flight_mode(FlightModeStates.HOVERING)
elif self.model.item(0, 0) is None:
self.status = "missing Flight Plan"
return
# Path mode off, read data from UI table and start path mode
else:
try:
self.position_hold_timelimit = float(
self.posHoldPathBox.text())
except ValueError as err:
self.status = ("illegal character used in path"
" settings: {}").format(str(err))
logger.info(self.status)
return
# Get the flightpath from the GUI table
x, y = 0, 0
temp = self.model.item(x, y)
reading_data = True
list = ''
while reading_data:
try:
element = str(temp.text())
if element != "":
list += temp.text()
# a "," gets added after the last element,
# remove that later for neatness
list += ','
try:
float(element)
except ValueError:
self._flight_path_select_row.emit(y)
self.status = ("Value at cell x:{} y:{} "
"must be a number").format(x, y)
logger.info(self.status)
break
x += 1
if x % 4 == 0:
x = 0
y += 1
# list += temp_position
# temp_position = []
temp = self.model.item(y, x)
except Exception:
reading_data = False
# remove the last "," element
list = list[:(len(list) - 1)]
list = list.split(',')
list = [float(i) for i in list]
if (len(list) % 4) != 0:
self.status = ("Missing value to create a valid"
" flight path")
logger.info(self.status)
break
list = [list[i:i + 4] for i in range(0, len(list), 4)]
list.insert(
0,
self.flight_paths[self.pathSelector.currentIndex()][0])
self.flight_paths[self.pathSelector.currentIndex()] = list
Config().set("flight_paths", self.flight_paths)
self.switch_flight_mode(FlightModeStates.PATH)
def set_kill_engine(self):
self.send_setpoint(Position(0, 0, 0))
self.switch_flight_mode(FlightModeStates.GROUNDED)
logger.info('Stop button pressed, kill engines')
def establish_qtm_connection(self):
if self.qtmIpBox.count() == 0 and self.qtmIpBox.currentText() == "":
return
if self._qtm_connection is None:
try:
ip = self.qtmIpBox.currentText().split(" ")[0]
except Exception as e:
logger.error("Incorrect entry: %s", e)
return
self.connectQtmButton.setEnabled(False)
start_async_task(self.qtm_connect(ip))
else:
self._qtm_connection.disconnect()
self._qtm_connection = None
async def qtm_connect(self, ip):
connection = await qtm.connect(
ip,
on_event=self.on_qtm_event,
on_disconnect=lambda reason: start_async_task(
self.on_qtm_disconnect(reason)))
if connection is None:
start_async_task(self.on_qtm_disconnect("Failed to connect"))
return
self._qtm_connection = connection
await self.setup_qtm_connection()
def setup_6dof_comboboxes(self):
quadName = self.quadName
stickName = self.stickName
self.quadBox.clear()
self.stickBox.clear()
for label in self.qtm_6DoF_labels:
self.quadBox.addItem(label)
self.stickBox.addItem(label)
if quadName in self.qtm_6DoF_labels:
self.quadBox.setCurrentIndex(
self.qtm_6DoF_labels.index(quadName))
if stickName in self.qtm_6DoF_labels:
self.stickBox.setCurrentIndex(
self.qtm_6DoF_labels.index(stickName))
async def setup_qtm_connection(self):
self.connectQtmButton.setEnabled(True)
self.connectQtmButton.setText('Disconnect QTM')
self.qtmStatus = ': connected : Waiting QTM to start sending data'
try:
result = await self._qtm_connection.get_parameters(
parameters=['6d'])
# Parse the returned xml
xml = ET.fromstring(result)
self.qtm_6DoF_labels = [label.text for label in xml.iter('Name')]
# Make all names lowercase
self.qtm_6DoF_labels = [x.lower() for x in self.qtm_6DoF_labels]
logger.info('6Dof bodies active in qtm: {}'.format(
self.qtm_6DoF_labels))
self.setup_6dof_comboboxes()
# Gui
self.qtmStatus = ': connected'
self.qtmCfPositionBox.setEnabled(True)
self.qtmWandPositionBox.setEnabled(True)
self.discoverQTM.setEnabled(False)
self.qtmIpBox.setEnabled(False)
self._update_flight_status()
self._ui_update_timer.start(200)
# Make sure this is the last thing done with the qtm_connection
# (due to qtmRTProtocol structure)
await self._qtm_connection.stream_frames(
components=['6deuler', '3d'], on_packet=self.on_packet)
except Exception as err:
logger.info(err)
async def on_qtm_disconnect(self, reason):
"""Callback when QTM has been disconnected"""
self._ui_update_timer.stop()
self._update_flight_status()
self._qtm_connection = None
logger.info(reason)
# Gui
self.qtmCfPositionBox.setEnabled(False)
self.qtmWandPositionBox.setEnabled(False)
self.discoverQTM.setEnabled(True)
self.qtmIpBox.setEnabled(True)
self.connectQtmButton.setEnabled(True)
self.connectQtmButton.setText('Connect QTM')
self.qtmStatus = ': not connected : {}'.format(
reason if reason is not None else '')
def on_qtm_event(self, event):
logger.info(event)
if event == qtm.QRTEvent.EventRTfromFileStarted:
self.qtmStatus = ': connected'
self.qtmCfPositionBox.setEnabled(True)
self.qtmWandPositionBox.setEnabled(True)
elif event == qtm.QRTEvent.EventRTfromFileStopped:
self.qtmStatus = ': connected : Waiting QTM to start sending data'
self.qtmCfPositionBox.setEnabled(False)
self.qtmWandPositionBox.setEnabled(False)
def on_packet(self, packet):
# Callback when QTM sends a 'packet' of the requested data,
# one every tracked frame.
# The speed depends on QTM settings
header, bodies = packet.get_6d_euler()
# Cf not created yet or no packet received due to various reasons...
# Wait for the two asynchronous calls in 'setup connection'
# to return with data
if bodies is None or self.qtm_6DoF_labels is None:
return
try:
temp_cf_pos = bodies[self.qtm_6DoF_labels.index(self.quadName)]
# QTM returns in mm in the order x, y, z, the Crazyflie api need
# data in meters, divide by thousand
# QTM returns euler rotations in deg in the order
# yaw, pitch, roll, not Qualisys Standard!
self.cf_pos = Position(
temp_cf_pos[0][0] / 1000,
temp_cf_pos[0][1] / 1000,
temp_cf_pos[0][2] / 1000,
roll=temp_cf_pos[1][2],
pitch=temp_cf_pos[1][1],
yaw=temp_cf_pos[1][0])
except ValueError:
self.qtmStatus = ' : connected : No 6DoF body found'
try:
temp_wand_pos = bodies[self.qtm_6DoF_labels.index(self.stickName)]
self.wand_pos = Position(
temp_wand_pos[0][0] / 1000,
temp_wand_pos[0][1] / 1000,
temp_wand_pos[0][2] / 1000,
roll=temp_wand_pos[1][2],
pitch=temp_wand_pos[1][1],
yaw=temp_wand_pos[1][0])
except ValueError:
self.qtmStatus = ' : connected : No 6DoF body found'
if self._cf is not None and self.cf_pos.is_valid():
# If a cf exists and the position is valid
# Feed the current position of the cf back to the cf to
# allow for self correction
self._cf.extpos.send_extpos(self.cf_pos.x, self.cf_pos.y,
self.cf_pos.z)
def _update_ui(self):
# Update the data in the GUI
self.qualisysX.setText(("%0.4f" % self.cf_pos.x))
self.qualisysY.setText(("%0.4f" % self.cf_pos.y))
self.qualisysZ.setText(("%0.4f" % self.cf_pos.z))
self.qualisysRoll.setText(("%0.2f" % self.cf_pos.roll))
self.qualisysPitch.setText(("%0.2f" % self.cf_pos.pitch))
self.qualisysYaw.setText(("%0.2f" % self.cf_pos.yaw))
self.qualisysWandX.setText(("%0.4f" % self.wand_pos.x))
self.qualisysWandY.setText(("%0.4f" % self.wand_pos.y))
self.qualisysWandZ.setText(("%0.4f" % self.wand_pos.z))
self.qualisysWandRoll.setText(("%0.2f" % self.wand_pos.roll))
self.qualisysWandPitch.setText(("%0.2f" % self.wand_pos.pitch))
self.qualisysWandYaw.setText(("%0.2f" % self.wand_pos.yaw))
def _flight_mode_land_entered(self):
self.current_goal_pos = self.valid_cf_pos
logger.info('Trying to land at: x: {} y: {}'.format(
self.current_goal_pos.x, self.current_goal_pos.y))
self.land_rate = 1
self._event.set()
def _flight_mode_path_entered(self):
self.path_index = 1
current = self.flight_paths[self.pathSelector.currentIndex()]
self.current_goal_pos = Position(
current[self.path_index][0],
current[self.path_index][1],
current[self.path_index][2],
yaw=current[self.path_index][3])
logger.info('Setting position {}'.format(
self.current_goal_pos))
self._flight_path_select_row.emit(self.path_index - 1)
self._event.set()
def _flight_mode_circle_entered(self):
self.current_goal_pos = Position(
round(math.cos(math.radians(self.circle_angle)),
8) * self.circle_radius,
round(math.sin(math.radians(self.circle_angle)), 8)
* self.circle_radius,
self.circle_height,
yaw=self.circle_angle)
logger.info('Setting position {}'.format(
self.current_goal_pos))
self._event.set()
def _flight_mode_follow_entered(self):
self.last_valid_wand_pos = Position(0, 0, 1)
self._event.set()
def _flight_mode_record_entered(self):
self.new_path = []
self._event.set()
def _flight_mode_lift_entered(self):
self.current_goal_pos = self.valid_cf_pos
logger.info('Trying to lift at: {}'.format(
self.current_goal_pos))
self._event.set()
def _flight_mode_hovering_entered(self):
self.current_goal_pos = self.valid_cf_pos
logger.info('Hovering at: {}'.format(
self.current_goal_pos))
self._event.set()
def _flight_mode_grounded_entered(self):
self._event.set()
def _flight_mode_disconnected_entered(self):
self._event.set()
def flight_controller(self):