test(mavsdk_tests): fold the contingency Go-to checks into the margin flight

The refusal flight repeated unit tests: Navigator and Commander tests
cover the mission, arming and target checks of the margin. Only the
Go-to handling inside Navigator::run() needs a flight. The margin
flight now holds for 8 s, flies a Go-to back to Home out of the margin,
and from there sends a Go-to into the margin, which must leave the Hold
at Home in place. Centered sticks are sent throughout, so a slow
command acknowledgement cannot trigger the RC loss failsafe.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: jonas <jonspero@me.com>
This commit is contained in:
jonas authored and GitHub committed 2026-11-25 10:36:48 +01:00
1 parent 06306ec547
commit 259052bbc2
5 files changed
+53 -64

No files matched your search

+29 -1
View File
@@ -8,6 +8,7 @@ swallowed. Checks done in callbacks are therefore collected with check_in_callba
reported when the tester is closed.
"""
from contextlib import contextmanager
import datetime
import json
import math
@@ -16,7 +17,7 @@ import threading
import time
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
from mavsdk import ComponentType, Configuration, ConnectionResult, Mavsdk # type: ignore
from mavsdk.plugins.action import Action, ActionError # type: ignore
@@ -1017,6 +1018,33 @@ class AutopilotTester:
# Manual control
# ------------------------------------------------------------------
@contextmanager
def keep_manual_control_alive(self) -> Iterator[None]:
"""Send centered sticks during the block.
Once sticks were sent, a gap longer than COM_RC_LOSS_T triggers the RC loss failsafe, also
in automatic modes. SITL sets it to 1 s times the speed factor.
"""
stop = threading.Event()
# Keep the link rate in simulated time, while allowing teardown if PX4 stops.
interval_s = 1.0 / (MANUAL_CONTROL_RATE_HZ * max(1.0, self._speed_factor or 1.0))
def send() -> None:
try:
while not stop.is_set():
self._manual_control.set_manual_control_input(0.0, 0.0, 0.5, 0.0)
stop.wait(interval_s)
except Exception as error:
self.check_in_callback(False, "Manual-control keepalive failed: {}".format(error))
worker = threading.Thread(target=send, daemon=True)
worker.start()
try:
yield
finally:
stop.set()
worker.join()
def _send_manual_control(self, duration_s: float, x: float, y: float, z: float, r: float,
stop_when_landed: bool = False) -> None:
for _ in range(int(duration_s * MANUAL_CONTROL_RATE_HZ)):
+2 -21
View File
@@ -11,8 +11,8 @@ from typing import Any, Callable, List, Optional, Tuple
from mavsdk.plugins.telemetry import FlightMode # type: ignore
from autopilot_tester import (
MANUAL_CONTROL_RATE_HZ, MAV_CMD_COMPONENT_ARM_DISARM, MAV_CMD_NAV_WAYPOINT,
MAV_FRAME_GLOBAL_INT, MAV_FRAME_GLOBAL_RELATIVE_ALT, MissionOptions, log, raw_mission_item)
MANUAL_CONTROL_RATE_HZ, MAV_CMD_NAV_WAYPOINT, MAV_FRAME_GLOBAL_INT,
MAV_FRAME_GLOBAL_RELATIVE_ALT, log, raw_mission_item)
from autopilot_tester_loiter import AutopilotTesterLoiter
from geofence_geometry import (
FenceKind, FenceShape, MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION,
@@ -22,7 +22,6 @@ from geometry import CoordinateTransformation
MAV_CMD_NAV_VTOL_TAKEOFF = 84
MAV_MISSION_TYPE_FENCE = 1
MAV_RESULT_TEMPORARILY_REJECTED = 1
# Values of GF_ACTION and GF_CONT_ACTION.
ACTION_WARNING = 1
@@ -82,10 +81,6 @@ class AutopilotTesterGeofence(AutopilotTesterLoiter):
# PX4 needs time to load the fence.
self.sleep_for(1)
def upload_mission_to(self, north_m: float, options: MissionOptions) -> None:
"""Upload a mission from above Home to a point north of it."""
self._upload_mission([(0.0, 0.0), (north_m, 0.0)], options)
def upload_vtol_mission(self, waypoints: List[Local2], rel_alt_m: float) -> None:
"""Upload a VTOL takeoff followed by the waypoints, without a landing."""
ct = self.get_coordinate_transformation()
@@ -100,16 +95,6 @@ class AutopilotTesterGeofence(AutopilotTesterLoiter):
self.upload_mission_raw(items)
def select_mission_mode(self) -> None:
"""Switch to Mission mode. A disarmed vehicle accepts that even with a rejected mission."""
assert self._try_start_mission(), "Could not switch to Mission mode"
def check_arming_is_denied(self) -> None:
"""One arming attempt, without the retries of arm(). Sent as a command, because
MAVSDK's arm() first switches a vehicle in Mission mode to Hold."""
self.send_command_long(MAV_CMD_COMPONENT_ARM_DISARM, param1=1.0,
expected_result=MAV_RESULT_TEMPORARILY_REJECTED)
def fly_in_position_mode_until_failsafe(self, flight_mode: FlightMode, forward: float = 0.5,
throttle: float = 0.5, timeout_s: float = 60) -> None:
"""Hold the sticks in Position mode until a failsafe takes over, and check its flight mode.
@@ -137,10 +122,6 @@ class AutopilotTesterGeofence(AutopilotTesterLoiter):
self.sleep_for(1.0 / MANUAL_CONTROL_RATE_HZ)
self._manual_control.set_manual_control_input(0.0, 0.0, 0.5, 0.0)
def keep_sticks_centered_for(self, duration_s: float) -> None:
"""Keep the manual control link alive without asking for anything."""
self._send_manual_control(duration_s, 0.0, 0.0, 0.5, 0.0)
# ------------------------------------------------------------------
# How far the vehicle went
# ------------------------------------------------------------------
+8 -1
View File
@@ -46,20 +46,27 @@ class AutopilotTesterLoiter(AutopilotTester):
self.wait_for_flight_mode(FlightMode.HOLD, timeout_s)
@contextmanager
def monitor_hold_position(self) -> Iterator[Tuple[float, float]]:
def monitor_hold_position(
self, expected_center: Optional[Local2] = None) -> Iterator[Tuple[float, float]]:
"""Require Hold and an unchanged loiter center throughout the block.
With expected_center, targets elsewhere are skipped until the commanded one arrives.
Yield the first Hold target as (latitude, longitude). PX4 publishes the loiter center
in POSITION_TARGET_GLOBAL_INT, so moving along a fence edge is detected too.
"""
centers: List[Tuple[int, int]] = []
target_count = 0
ct = self.get_coordinate_transformation() if expected_center is not None else None
def on_target(message: Any, _user_data: Any) -> None:
nonlocal target_count
fields = json.loads(message.fields_json)
center = (int(fields["lat_int"]), int(fields["lon_int"]))
if not centers:
if expected_center is not None and ct is not None:
north_m, east_m = ct.local_from_global(center[0] / 1e7, center[1] / 1e7)
if math.hypot(north_m - expected_center[0], east_m - expected_center[1]) > 1.0:
return
centers.append(center)
target_count += 1
self.check_in_callback(center == centers[0],
+1 -1
View File
@@ -25,7 +25,7 @@ def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption("--url", default="udpin://0.0.0.0:14540",
help="MAVLink connection URL of the vehicle")
parser.addoption("--speed-factor", type=float, default=None,
help="simulation speed factor, for information only")
help="simulation speed factor, sets the rate of keep_manual_control_alive()")
def connected_tester(request: pytest.FixtureRequest, tester_class: Type[T]) -> Iterator[T]:
@@ -5,6 +5,7 @@ from autopilot_tester import MissionOptions, log
from autopilot_tester_geofence import ACTION_RETURN, AutopilotTesterGeofence
from autopilot_tester_loiter import horizontal_distance
HOME = (0.0, 0.0)
TAKEOFF_ALTITUDE_M = 10.0
MISSION_ALTITUDE_M = 15.0
@@ -18,7 +19,8 @@ POSITION_TOLERANCE_M = 2.0
def test_pilot_is_held_at_contingency_geofence_margin(
tester_geofence: AutopilotTesterGeofence) -> None:
"""A pilot flies towards the fence in Position mode. The vehicle is held when it comes within
the margin, and never reaches the fence."""
the margin, and never reaches the fence. A Go-to back out of the margin is flown, and one into
it is refused."""
tester = tester_geofence
tester.wait_until_ready()
tester.store_home()
@@ -29,8 +31,16 @@ def test_pilot_is_held_at_contingency_geofence_margin(
tester.start_tracking()
tester.fly_in_position_mode_until_failsafe(FlightMode.HOLD)
tester.keep_sticks_centered_for(8)
tester.wait_for_flight_mode(FlightMode.HOLD, 1)
with tester.keep_manual_control_alive():
with tester.monitor_hold_position():
tester.sleep_for(8)
# Home is out of the margin, so this Go-to is flown although the vehicle is still in it.
tester.command_reposition(HOME, TAKEOFF_ALTITUDE_M)
with tester.monitor_hold_position(expected_center=HOME):
tester.wait_for_position_ned(lambda s: horizontal_distance(s, HOME) < 3.0, 30)
# In the margin, 10 m from the fence: refused, so the Hold stays at Home.
tester.command_reposition((70.0, 0.0), TAKEOFF_ALTITUDE_M)
tester.sleep_for(3)
closest_m = tester.min_fence_distance_m()
log("Closest to the fence: {:.1f} m".format(closest_m))
@@ -97,40 +107,3 @@ def test_contingency_geofence_return_lands_at_home(
log("Closest to the fence: {:.1f} m".format(closest_m))
assert 150.0 - OVERSHOOT_M < closest_m < 150.0 + POSITION_TOLERANCE_M, \
"Came within {:.1f} m of the fence with a margin of 150 m".format(closest_m)
@pytest.mark.multicopter
def test_contingency_geofence_refuses_arming_missions_and_targets(
tester_geofence: AutopilotTesterGeofence) -> None:
"""Within the margin arming is denied, and a mission or a Go-to that leads there is refused."""
tester = tester_geofence
tester.wait_until_ready()
tester.store_home()
# Home is 30 m from each edge.
tester.upload_inclusion_rectangle(-30.0, 30.0, -30.0, 30.0)
tester.set_param_float("GF_CONT_H_MARGIN", 40.0)
tester.sleep_for(2)
tester.check_arming_is_denied()
tester.set_param_float("GF_CONT_H_MARGIN", 10.0)
tester.sleep_for(2)
options = MissionOptions(relative_altitude_m=TAKEOFF_ALTITUDE_M)
# 5 m from the northern edge: the mission is rejected, so Mission mode cannot be armed.
tester.upload_mission_to(25.0, options)
tester.select_mission_mode()
tester.wait_for_flight_mode(FlightMode.MISSION, 5)
tester.check_arming_is_denied()
# 15 m from the northern edge.
tester.upload_mission_to(15.0, options)
tester.arm()
tester.execute_mission()
# The vehicle now holds at the last waypoint. A target within the margin leaves it there.
tester.command_reposition((25.0, 0.0), TAKEOFF_ALTITUDE_M)
tester.check_stays_within((15.0, 0.0), 3.0, 8)
tester.command_reposition((-15.0, 0.0), TAKEOFF_ALTITUDE_M)
tester.wait_for_position_ned(lambda s: horizontal_distance(s, (-15.0, 0.0)) < 2.0, 30)