forked from ArduPilot/ardupilot
/
arduplane.py
5521 lines (4776 loc) · 205 KB
/
arduplane.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
'''
Fly ArduPlane in SITL
AP_FLAKE8_CLEAN
'''
from __future__ import print_function
import math
import os
import signal
import time
from pymavlink import quaternion
from pymavlink import mavextra
from pymavlink import mavutil
from pymavlink.rotmat import Vector3
import vehicle_test_suite
from vehicle_test_suite import AutoTestTimeoutException
from vehicle_test_suite import NotAchievedException
from vehicle_test_suite import OldpymavlinkException
from vehicle_test_suite import PreconditionFailedException
from vehicle_test_suite import Test
from vehicle_test_suite import WaitModeTimeout
from pysim import vehicleinfo
from pysim import util
import operator
# get location of scripts
testdir = os.path.dirname(os.path.realpath(__file__))
SITL_START_LOCATION = mavutil.location(-35.362938, 149.165085, 585, 354)
WIND = "0,180,0.2" # speed,direction,variance
class AutoTestPlane(vehicle_test_suite.TestSuite):
@staticmethod
def get_not_armable_mode_list():
return []
@staticmethod
def get_not_disarmed_settable_modes_list():
return ["FOLLOW"]
@staticmethod
def get_no_position_not_settable_modes_list():
return []
@staticmethod
def get_position_armable_modes_list():
return ["GUIDED", "AUTO"]
@staticmethod
def get_normal_armable_modes_list():
return ["MANUAL", "STABILIZE", "ACRO"]
def log_name(self):
return "ArduPlane"
def default_speedup(self):
return 100
def test_filepath(self):
return os.path.realpath(__file__)
def sitl_start_location(self):
return SITL_START_LOCATION
def defaults_filepath(self):
return os.path.join(testdir, 'default_params/plane-jsbsim.parm')
def set_current_test_name(self, name):
self.current_test_name_directory = "ArduPlane_Tests/" + name + "/"
def default_frame(self):
return "plane-elevrev"
def apply_defaultfile_parameters(self):
# plane passes in a defaults_filepath in place of applying
# parameters afterwards.
pass
def is_plane(self):
return True
def get_stick_arming_channel(self):
return int(self.get_parameter("RCMAP_YAW"))
def get_disarm_delay(self):
return int(self.get_parameter("LAND_DISARMDELAY"))
def set_autodisarm_delay(self, delay):
self.set_parameter("LAND_DISARMDELAY", delay)
def takeoff(self, alt=150, alt_max=None, relative=True, mode=None, timeout=None):
"""Takeoff to altitude."""
if mode == "TAKEOFF":
return self.takeoff_in_TAKEOFF(alt=alt, relative=relative, timeout=timeout)
return self.takeoff_in_FBWA(alt=alt, alt_max=alt_max, relative=relative, timeout=timeout)
def takeoff_in_TAKEOFF(self, alt=150, relative=True, mode=None, alt_epsilon=2, timeout=None):
if relative is not True:
raise ValueError("Only relative alt supported ATM")
self.change_mode("TAKEOFF")
self.context_push()
self.set_parameter('TKOFF_ALT', alt)
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_altitude(alt-alt_epsilon, alt+alt_epsilon, relative=True, timeout=timeout)
self.context_pop()
def takeoff_in_FBWA(self, alt=150, alt_max=None, relative=True, mode=None, timeout=30):
if alt_max is None:
alt_max = alt + 30
self.change_mode("FBWA")
self.wait_ready_to_arm()
self.arm_vehicle()
# some rudder to counteract the prop torque
self.set_rc(4, 1700)
# some up elevator to keep the tail down
self.set_rc(2, 1200)
# get it moving a bit first
self.set_rc(3, 1300)
self.wait_groundspeed(6, 100)
# a bit faster again, straighten rudder
self.set_rc_from_map({
3: 1600,
4: 1500,
})
self.wait_groundspeed(12, 100)
# hit the gas harder now, and give it some more elevator
self.set_rc_from_map({
2: 1100,
3: 2000,
})
# gain a bit of altitude
self.wait_altitude(alt, alt_max, timeout=timeout, relative=relative)
# level off
self.set_rc(2, 1500)
self.progress("TAKEOFF COMPLETE")
def fly_left_circuit(self):
"""Fly a left circuit, 200m on a side."""
self.change_mode('FBWA')
self.set_rc(3, 2000)
self.wait_level_flight()
self.progress("Flying left circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(1, 1000)
self.wait_heading(270 - (90*i), accuracy=10)
self.set_rc(1, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
def fly_RTL(self):
"""Fly to home."""
self.progress("Flying home in RTL")
target_loc = self.homeloc
target_loc.alt += 100
self.change_mode('RTL')
self.wait_location(target_loc,
accuracy=120,
height_accuracy=20,
timeout=180)
self.progress("RTL Complete")
def NeedEKFToArm(self):
"""Ensure the EKF must be healthy for the vehicle to arm."""
self.progress("Ensuring we need EKF to be healthy to arm")
self.set_parameter("SIM_GPS_DISABLE", 1)
self.context_collect("STATUSTEXT")
tstart = self.get_sim_time()
success = False
for run_cmd in self.run_cmd, self.run_cmd_int:
while not success:
if self.get_sim_time_cached() - tstart > 60:
raise NotAchievedException("Did not get correct failure reason")
run_cmd(mavutil.mavlink.MAV_CMD_RUN_PREARM_CHECKS)
try:
self.wait_statustext(".*AHRS: not using configured AHRS type.*", timeout=1, check_context=True, regex=True)
success = True
continue
except AutoTestTimeoutException:
pass
self.set_parameter("SIM_GPS_DISABLE", 0)
self.wait_ready_to_arm()
def fly_LOITER(self, num_circles=4):
"""Loiter where we are."""
self.progress("Testing LOITER for %u turns" % num_circles)
self.change_mode('LOITER')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
while num_circles > 0:
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
num_circles -= 1
self.progress("Loiter %u circles left" % num_circles)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
self.change_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
self.progress("Completed Loiter OK")
def fly_CIRCLE(self, num_circles=1):
"""Circle where we are."""
self.progress("Testing CIRCLE for %u turns" % num_circles)
self.change_mode('CIRCLE')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
while num_circles > 0:
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
num_circles -= 1
self.progress("CIRCLE %u circles left" % num_circles)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
self.change_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
self.progress("Completed CIRCLE OK")
def wait_level_flight(self, accuracy=5, timeout=30):
"""Wait for level flight."""
tstart = self.get_sim_time()
self.progress("Waiting for level flight")
self.set_rc(1, 1500)
self.set_rc(2, 1500)
self.set_rc(4, 1500)
while self.get_sim_time_cached() < tstart + timeout:
m = self.mav.recv_match(type='ATTITUDE', blocking=True)
roll = math.degrees(m.roll)
pitch = math.degrees(m.pitch)
self.progress("Roll=%.1f Pitch=%.1f" % (roll, pitch))
if math.fabs(roll) <= accuracy and math.fabs(pitch) <= accuracy:
self.progress("Attained level flight")
return
raise NotAchievedException("Failed to attain level flight")
def change_altitude(self, altitude, accuracy=30):
"""Get to a given altitude."""
self.change_mode('FBWA')
alt_error = self.mav.messages['VFR_HUD'].alt - altitude
if alt_error > 0:
self.set_rc(2, 2000)
else:
self.set_rc(2, 1000)
self.wait_altitude(altitude-accuracy/2, altitude+accuracy/2)
self.set_rc(2, 1500)
self.progress("Reached target altitude at %u" %
self.mav.messages['VFR_HUD'].alt)
return self.wait_level_flight()
def axial_left_roll(self, count=1):
"""Fly a left axial roll."""
# full throttle!
self.set_rc(3, 2000)
self.change_altitude(self.homeloc.alt+300)
# fly the roll in manual
self.change_mode('MANUAL')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 1000)
try:
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
except Exception as e:
self.set_rc(1, 1500)
raise e
count -= 1
# back to FBWA
self.set_rc(1, 1500)
self.change_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def inside_loop(self, count=1):
"""Fly a inside loop."""
# full throttle!
self.set_rc(3, 2000)
self.change_altitude(self.homeloc.alt+300)
# fly the loop in manual
self.change_mode('MANUAL')
while count > 0:
self.progress("Starting loop")
self.set_rc(2, 1000)
self.wait_pitch(-60, accuracy=20)
self.wait_pitch(0, accuracy=20)
count -= 1
# back to FBWA
self.set_rc(2, 1500)
self.change_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def set_attitude_target(self, tolerance=10):
"""Test setting of attitude target in guided mode."""
self.change_mode("GUIDED")
steps = [{"name": "roll-over", "roll": 60, "pitch": 0, "yaw": 0, "throttle": 0, "type_mask": 0b10000001},
{"name": "roll-back", "roll": 0, "pitch": 0, "yaw": 0, "throttle": 0, "type_mask": 0b10000001},
{"name": "pitch-up+throttle", "roll": 0, "pitch": 20, "yaw": 0, "throttle": 1, "type_mask": 0b11000010},
{"name": "pitch-back", "roll": 0, "pitch": 0, "yaw": 0, "throttle": 0, "type_mask": 0b10000010}]
state_wait = "wait"
state_hold = "hold"
try:
for step in steps:
step_start = self.get_sim_time_cached()
state = state_wait
state_start = self.get_sim_time_cached()
while True:
m = self.mav.recv_match(type='ATTITUDE',
blocking=True,
timeout=0.1)
now = self.get_sim_time_cached()
if now - step_start > 30:
raise AutoTestTimeoutException("Manuevers not completed")
if m is None:
continue
angle_error = 0
if (step["type_mask"] & 0b00000001) or (step["type_mask"] == 0b10000000):
angle_error += abs(math.degrees(m.roll) - step["roll"])
if (step["type_mask"] & 0b00000010) or (step["type_mask"] == 0b10000000):
angle_error += abs(math.degrees(m.pitch) - step["pitch"])
if (step["type_mask"] & 0b00000100) or (step["type_mask"] == 0b10000000):
# Strictly we should angle wrap, by plane doesn't support yaw correctly anyway so its not tested here
angle_error += abs(math.degrees(m.yaw) - step["yaw"])
# Note were not checking throttle, however the SITL plane needs full throttle to meet the
# target pitch attitude, Pitch test will fail without throttle override
if state == state_wait:
# Reduced tolerance for initial trigger
if angle_error < (tolerance * 0.25):
state = state_hold
state_start = now
# Allow 10 seconds to reach attitude
if (now - state_start) > 10:
raise NotAchievedException(step["name"] + ": Failed to get to set attitude")
elif state == state_hold:
# Give 2 seconds to stabilize
if (now - state_start) > 2 and not (angle_error < tolerance):
raise NotAchievedException(step["name"] + ": Failed to hold set attitude")
# Hold for 10 seconds
if (now - state_start) > 12:
# move onto next step
self.progress("%s Done" % (step["name"]))
break
self.progress("%s %s error: %f" % (step["name"], state, angle_error))
time_boot_millis = 0 # FIXME
target_system = 1 # FIXME
target_component = 1 # FIXME
type_mask = step["type_mask"] ^ 0xFF # FIXME
# attitude in radians:
q = quaternion.Quaternion([math.radians(step["roll"]),
math.radians(step["pitch"]),
math.radians(step["yaw"])])
self.mav.mav.set_attitude_target_send(time_boot_millis,
target_system,
target_component,
type_mask,
q,
0, # roll rate, not used in AP
0, # pitch rate, not used in AP
0, # yaw rate, not used in AP
step["throttle"])
except Exception as e:
self.change_mode('FBWA')
self.set_rc(3, 1700)
raise e
# back to FBWA
self.change_mode('FBWA')
self.set_rc(3, 1700)
self.wait_level_flight()
def test_stabilize(self, count=1):
"""Fly stabilize mode."""
# full throttle!
self.set_rc(3, 2000)
self.set_rc(2, 1300)
self.change_altitude(self.homeloc.alt+300)
self.set_rc(2, 1500)
self.change_mode('STABILIZE')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 2000)
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
count -= 1
self.set_rc(1, 1500)
self.wait_roll(0, accuracy=5)
# back to FBWA
self.change_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def test_acro(self, count=1):
"""Fly ACRO mode."""
# full throttle!
self.set_rc(3, 2000)
self.set_rc(2, 1300)
self.change_altitude(self.homeloc.alt+300)
self.set_rc(2, 1500)
self.change_mode('ACRO')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 1000)
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
count -= 1
self.set_rc(1, 1500)
# back to FBWA
self.change_mode('FBWA')
self.wait_level_flight()
self.change_mode('ACRO')
count = 2
while count > 0:
self.progress("Starting loop")
self.set_rc(2, 1000)
self.wait_pitch(-60, accuracy=20)
self.wait_pitch(0, accuracy=20)
count -= 1
self.set_rc(2, 1500)
# back to FBWA
self.change_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def test_FBWB(self, mode='FBWB'):
"""Fly FBWB or CRUISE mode."""
self.change_mode(mode)
self.set_rc(3, 1700)
self.set_rc(2, 1500)
# lock in the altitude by asking for an altitude change then releasing
self.set_rc(2, 1000)
self.wait_distance(50, accuracy=20)
self.set_rc(2, 1500)
self.wait_distance(50, accuracy=20)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
self.progress("Flying right circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(1, 1800)
try:
self.wait_heading(0 + (90*i), accuracy=20, timeout=60)
except Exception as e:
self.set_rc(1, 1500)
raise e
self.set_rc(1, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
self.progress("Flying rudder left circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(4, 1900)
try:
self.wait_heading(360 - (90*i), accuracy=20, timeout=60)
except Exception as e:
self.set_rc(4, 1500)
raise e
self.set_rc(4, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
# back to FBWA
self.change_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
return self.wait_level_flight()
def fly_mission(self, filename, mission_timeout=60.0, strict=True, quadplane=False):
"""Fly a mission from a file."""
self.progress("Flying mission %s" % filename)
num_wp = self.load_mission(filename, strict=strict)-1
self.fly_mission_waypoints(num_wp, mission_timeout=mission_timeout, quadplane=quadplane)
def fly_mission_waypoints(self, num_wp, mission_timeout=60.0, quadplane=False):
self.set_current_waypoint(0, check_afterwards=False)
self.context_push()
self.context_collect('STATUSTEXT')
self.change_mode('AUTO')
self.wait_waypoint(1, num_wp, max_dist=60, timeout=mission_timeout)
self.wait_groundspeed(0, 0.5, timeout=mission_timeout)
if quadplane:
self.wait_statustext("Throttle disarmed", timeout=200, check_context=True)
else:
self.wait_statustext("Auto disarmed", timeout=60, check_context=True)
self.context_pop()
self.progress("Mission OK")
def DO_REPOSITION(self):
'''Test mavlink DO_REPOSITION command'''
self.progress("Takeoff")
self.takeoff(alt=50)
self.set_rc(3, 1500)
self.progress("Entering guided and flying somewhere constant")
self.change_mode("GUIDED")
loc = self.mav.location()
self.location_offset_ne(loc, 500, 500)
new_alt = 100
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
p5=int(loc.lat * 1e7),
p6=int(loc.lng * 1e7),
p7=new_alt, # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
)
self.wait_altitude(new_alt-10, new_alt, timeout=30, relative=True)
self.install_terrain_handlers_context()
self.location_offset_ne(loc, 500, 500)
terrain_height_wanted = 150
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
0,
0,
0,
0,
int(loc.lat*1e7),
int(loc.lng*1e7),
terrain_height_wanted, # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT,
)
# move to specific terrain-relative altitude and hold for <n> seconds
tstart = self.get_sim_time_cached()
achieve_start = None
tr = None
while True:
if self.get_sim_time_cached() - tstart > 120:
raise NotAchievedException("Did not move to correct terrain alt")
m = self.mav.recv_match(type='TERRAIN_REPORT',
blocking=True,
timeout=1)
tr = m
terrain_height_achieved = m.current_height
self.progress("terrain_alt=%f want=%f" %
(terrain_height_achieved, terrain_height_wanted))
if m is None:
continue
if abs(terrain_height_wanted - terrain_height_achieved) > 5:
if achieve_start is not None:
self.progress("Achieve stop")
achieve_start = None
elif achieve_start is None:
self.progress("Achieve start")
achieve_start = self.get_sim_time_cached()
if achieve_start is not None:
if self.get_sim_time_cached() - achieve_start > 10:
break
m = self.mav.recv_match(type='GLOBAL_POSITION_INT',
blocking=True,
timeout=1)
self.progress("TR: %s" % tr)
self.progress("GPI: %s" % m)
min_delta = 4
delta = abs(m.relative_alt/1000.0 - tr.current_height)
if abs(delta < min_delta):
raise NotAchievedException("Expected altitude delta (want=%f got=%f)" %
(min_delta, delta))
self.fly_home_land_and_disarm(timeout=180)
def ExternalPositionEstimate(self):
'''Test mavlink EXTERNAL_POSITION_ESTIMATE command'''
if not hasattr(mavutil.mavlink, 'MAV_CMD_EXTERNAL_POSITION_ESTIMATE'):
raise OldpymavlinkException("pymavlink too old; upgrade pymavlink to get MAV_CMD_EXTERNAL_POSITION_ESTIMATE") # noqa
self.change_mode("TAKEOFF")
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_altitude(48, 52, relative=True)
loc = self.mav.location()
self.location_offset_ne(loc, 2000, 2000)
# setting external position fail while we have GPS lock
self.progress("set new position with GPS")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_EXTERNAL_POSITION_ESTIMATE,
p1=self.get_sim_time()-1, # transmit time
p2=0.5, # processing delay
p3=50, # accuracy
p5=int(loc.lat * 1e7),
p6=int(loc.lng * 1e7),
p7=float("NaN"), # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL,
want_result=mavutil.mavlink.MAV_RESULT_FAILED,
)
self.progress("disable the GPS")
self.run_auxfunc(
65,
2,
want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED
)
# fly for a bit to get into non-aiding state
self.progress("waiting 20 seconds")
tstart = self.get_sim_time()
while self.get_sim_time() < tstart + 20:
self.wait_heartbeat()
self.progress("getting base position")
gpi = self.mav.recv_match(
type='GLOBAL_POSITION_INT',
blocking=True,
timeout=5
)
loc = mavutil.location(gpi.lat*1e-7, gpi.lon*1e-7, 0, 0)
self.progress("set new position with no GPS")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_EXTERNAL_POSITION_ESTIMATE,
p1=self.get_sim_time()-1, # transmit time
p2=0.5, # processing delay
p3=50, # accuracy
p5=gpi.lat+1,
p6=gpi.lon+1,
p7=float("NaN"), # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL,
want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED
)
self.progress("waiting 3 seconds")
tstart = self.get_sim_time()
while self.get_sim_time() < tstart + 3:
self.wait_heartbeat()
gpi2 = self.mav.recv_match(
type='GLOBAL_POSITION_INT',
blocking=True,
timeout=5
)
loc2 = mavutil.location(gpi2.lat*1e-7, gpi2.lon*1e-7, 0, 0)
dist = self.get_distance(loc, loc2)
self.progress("dist is %.1f" % dist)
if dist > 200:
raise NotAchievedException("Position error dist=%.1f" % dist)
self.progress("re-enable the GPS")
self.run_auxfunc(
65,
0,
want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED
)
self.progress("flying home")
self.fly_home_land_and_disarm()
def DeepStall(self):
'''Test DeepStall Landing'''
# self.fly_deepstall_absolute()
self.fly_deepstall_relative()
def fly_deepstall_absolute(self):
self.start_subtest("DeepStall Relative Absolute")
deepstall_elevator_pwm = 1661
self.set_parameters({
"LAND_TYPE": 1,
"LAND_DS_ELEV_PWM": deepstall_elevator_pwm,
"RTL_AUTOLAND": 1,
})
self.load_mission("plane-deepstall-mission.txt")
self.change_mode("AUTO")
self.wait_ready_to_arm()
self.arm_vehicle()
self.progress("Waiting for deepstall messages")
# note that the following two don't necessarily happen in this
# order, but at very high speedups we may miss the elevator
# PWM if we first look for the text (due to the get_sim_time()
# in wait_servo_channel_value)
self.context_collect('STATUSTEXT')
# assume elevator is on channel 2:
self.wait_servo_channel_value(2, deepstall_elevator_pwm, timeout=240)
self.wait_text("Deepstall: Entry: ", check_context=True)
self.disarm_wait(timeout=120)
self.progress("Flying home")
self.set_current_waypoint(0, check_afterwards=False)
self.takeoff(10)
self.set_parameter("LAND_TYPE", 0)
self.fly_home_land_and_disarm()
def fly_deepstall_relative(self):
self.start_subtest("DeepStall Relative")
deepstall_elevator_pwm = 1661
self.set_parameters({
"LAND_TYPE": 1,
"LAND_DS_ELEV_PWM": deepstall_elevator_pwm,
"RTL_AUTOLAND": 1,
})
self.load_mission("plane-deepstall-relative-mission.txt")
self.change_mode("AUTO")
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_current_waypoint(4)
# assume elevator is on channel 2:
self.wait_servo_channel_value(2, deepstall_elevator_pwm, timeout=240)
self.progress("Waiting for stage DEEPSTALL_STAGE_LAND")
self.assert_receive_message(
'DEEPSTALL',
condition='DEEPSTALL.stage==6',
timeout=240,
)
self.progress("Reached stage DEEPSTALL_STAGE_LAND")
self.disarm_wait(timeout=120)
self.set_current_waypoint(0, check_afterwards=False)
self.progress("Flying home")
self.set_current_waypoint(0, check_afterwards=False)
self.takeoff(100)
self.set_parameter("LAND_TYPE", 0)
self.fly_home_land_and_disarm(timeout=240)
def SmartBattery(self):
'''Test smart battery logging etc'''
self.set_parameters({
"BATT_MONITOR": 16, # Maxell battery monitor
})
# Must reboot sitl after setting montior type for SMBus parameters to be set due to dynamic group
self.reboot_sitl()
self.set_parameters({
"BATT_I2C_BUS": 2, # specified in SIM_I2C.cpp
"BATT_I2C_ADDR": 11, # specified in SIM_I2C.cpp
})
self.reboot_sitl()
self.wait_ready_to_arm()
m = self.assert_receive_message('BATTERY_STATUS', timeout=10)
if m.voltages_ext[0] == 65536:
raise NotAchievedException("Flag value rather than voltage")
if abs(m.voltages_ext[0] - 1000) > 300:
raise NotAchievedException("Did not get good ext voltage (got=%f)" %
(m.voltages_ext[0],))
self.arm_vehicle()
self.delay_sim_time(5)
self.disarm_vehicle()
if not self.current_onboard_log_contains_message("BCL2"):
raise NotAchievedException("Expected BCL2 message")
def context_push_do_change_speed(self):
# the following lines ensure we revert these parameter values
# - DO_CHANGE_AIRSPEED is a permanent vehicle change!
self.context_push()
self.set_parameters({
"AIRSPEED_CRUISE": self.get_parameter("AIRSPEED_CRUISE"),
"MIN_GROUNDSPEED": self.get_parameter("MIN_GROUNDSPEED"),
"TRIM_THROTTLE": self.get_parameter("TRIM_THROTTLE"),
})
def DO_CHANGE_SPEED(self):
'''Test DO_CHANGE_SPEED command/item'''
self.set_parameters({
"RTL_AUTOLAND": 1,
})
self.context_push_do_change_speed()
self.DO_CHANGE_SPEED_mavlink_long()
self.context_pop()
self.set_current_waypoint(1)
self.zero_throttle()
self.context_push_do_change_speed()
self.DO_CHANGE_SPEED_mavlink_int()
self.context_pop()
self.context_push_do_change_speed()
self.DO_CHANGE_SPEED_mission()
self.context_pop()
def DO_CHANGE_SPEED_mission(self):
'''test DO_CHANGE_SPEED as a mission item'''
self.start_subtest("DO_CHANGE_SPEED_mission")
self.load_mission("mission.txt")
self.set_current_waypoint(1)
self.progress("Takeoff")
self.set_rc(3, 1000)
self.takeoff(alt=10)
self.set_rc(3, 1500)
self.start_subtest("Check initial speed")
self.change_mode('AUTO')
checks = [
(1, self.get_parameter("AIRSPEED_CRUISE")),
(3, 10),
(5, 20),
(7, 15),
]
for (current_waypoint, want_airspeed) in checks:
self.wait_current_waypoint(current_waypoint, timeout=150)
self.wait_airspeed(want_airspeed-1, want_airspeed+1, minimum_duration=5, timeout=120)
self.fly_home_land_and_disarm()
def DO_CHANGE_SPEED_mavlink_int(self):
self.DO_CHANGE_SPEED_mavlink(self.run_cmd_int)
def DO_CHANGE_SPEED_mavlink_long(self):
self.DO_CHANGE_SPEED_mavlink(self.run_cmd)
def DO_CHANGE_SPEED_mavlink(self, run_cmd_method):
'''test DO_CHANGE_SPEED as a mavlink command'''
self.progress("Takeoff")
self.takeoff(alt=100, mode="TAKEOFF", timeout=120)
self.set_rc(3, 1500)
# ensure we know what the airspeed is:
self.progress("Entering guided and flying somewhere constant")
self.change_mode("GUIDED")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
p5=12345, # lat* 1e7
p6=12345, # lon* 1e7
p7=100 # alt
)
self.delay_sim_time(10)
self.progress("Ensuring initial speed is known and relatively constant")
initial_speed = 22.0
timeout = 15
self.wait_airspeed(initial_speed-1, initial_speed+1, minimum_duration=5, timeout=timeout)
self.start_subtest("Setting groundspeed")
for new_target_groundspeed in initial_speed + 5, initial_speed + 2:
run_cmd_method(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
p1=1, # groundspeed
p2=new_target_groundspeed,
p3=-1, # throttle / no change
p4=0, # absolute values
)
self.wait_groundspeed(new_target_groundspeed-2, new_target_groundspeed+2, timeout=80, minimum_duration=5)
self.progress("Adding some wind, ensuring groundspeed holds")
self.set_parameter("SIM_WIND_SPD", 5)
self.delay_sim_time(5)
self.wait_groundspeed(new_target_groundspeed-2, new_target_groundspeed+2, timeout=40, minimum_duration=5)
self.set_parameter("SIM_WIND_SPD", 0)
# clear target groundspeed
run_cmd_method(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
p1=1, # groundspeed
p2=0,
p3=-1, # throttle / no change
p4=0, # absolute values
)
self.start_subtest("Setting airspeed")
for new_target_airspeed in initial_speed - 5, initial_speed + 5:
run_cmd_method(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
p1=0, # airspeed
p2=new_target_airspeed,
p3=-1, # throttle / no change
p4=0, # absolute values
)
self.wait_airspeed(new_target_airspeed-2, new_target_airspeed+2, minimum_duration=5)
self.context_push()
self.progress("Adding some wind, hoping groundspeed increases/decreases")
self.set_parameters({
"SIM_WIND_SPD": 7,
"SIM_WIND_DIR": 270,
})
self.delay_sim_time(5)
timeout = 10
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not achieve groundspeed delta")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
delta = abs(m.airspeed - m.groundspeed)
want_delta = 5
self.progress("groundspeed and airspeed should be different (have=%f want=%f)" % (delta, want_delta))
if delta > want_delta:
break
self.context_pop()
# cancel minimum groundspeed:
run_cmd_method(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
p1=0, # groundspeed
p2=-2, # return to default
p3=0, # throttle / no change
p4=0, # absolute values
)
# cancel airspeed:
run_cmd_method(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
p1=1, # airspeed
p2=-2, # return to default
p3=0, # throttle / no change
p4=0, # absolute values
)