diff --git a/.github/workflows/python_checks.yml b/.github/workflows/python_checks.yml index ce6ea0674e2..05877897dd7 100644 --- a/.github/workflows/python_checks.yml +++ b/.github/workflows/python_checks.yml @@ -27,13 +27,15 @@ jobs: python-version: "3.10" - name: Install tools - run: pip install mypy types-requests types-PyYAML flake8 pyyaml + run: | + pip install mypy types-requests types-PyYAML flake8 pyyaml + pip install -r Tools/setup/test-requirements.txt - name: Check MAVSDK test scripts with mypy run: mypy --strict test/mavsdk_tests/*.py - name: Check MAVSDK test scripts with flake8 - run: flake8 test/mavsdk_tests/*.py + run: flake8 --config test/mavsdk_tests/.flake8 test/mavsdk_tests/*.py - name: Check USB ID tooling with mypy and flake8 working-directory: Tools/ci diff --git a/.github/workflows/sitl_tests.yml b/.github/workflows/sitl_tests.yml index 1dce520275d..9ee1eff3f5f 100644 --- a/.github/workflows/sitl_tests.yml +++ b/.github/workflows/sitl_tests.yml @@ -63,11 +63,11 @@ jobs: shell: bash run: ccache -s - - name: Download MAVSDK - run: wget "https://github.com/mavlink/MAVSDK/releases/download/v$(cat test/mavsdk_tests/MAVSDK_VERSION)/libmavsdk-dev_$(cat test/mavsdk_tests/MAVSDK_VERSION)_ubuntu22.04_amd64.deb" - - - name: Install MAVSDK - run: dpkg -i "libmavsdk-dev_$(cat test/mavsdk_tests/MAVSDK_VERSION)_ubuntu22.04_amd64.deb" + - name: Install MAVSDK tests requirements + env: + # Needed where pip refuses to touch the system Python (PEP 668). + PIP_BREAK_SYSTEM_PACKAGES: 1 + run: pip3 install -r Tools/setup/test-requirements.txt - name: Check PX4 Environment Variables env: @@ -78,11 +78,6 @@ jobs: export ulimit -a - - name: Build PX4 / MAVSDK tests - env: - DONT_RUN: 1 - run: make px4_sitl_default mavsdk_tests - - uses: ./.github/actions/save-ccache if: always() with: diff --git a/.gitignore b/.gitignore index e495f700cfb..36f07279dff 100644 --- a/.gitignore +++ b/.gitignore @@ -94,7 +94,6 @@ rules.ninja /generated_params/ /googletest-*/ /logs -/mavsdk_tests /unit-* /uORB/ DartConfiguration.tcl diff --git a/CMakeLists.txt b/CMakeLists.txt index 94c9a574557..c6633f070e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -378,11 +378,6 @@ if(${PX4_PLATFORM} STREQUAL "posix") if (NOT CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "Install path prefix" FORCE) endif() - - # mavsdk integration tests — defined as an ExternalProject_Add target; - # EXCLUDE_FROM_ALL, so only built when explicitly requested - # (e.g. `make mavsdk_tests` or `make tests_integration`). - include(mavsdk_tests) endif() if(NOT PX4_SUBPROJECT) diff --git a/Makefile b/Makefile index 994c4d63062..3f136cc931c 100644 --- a/Makefile +++ b/Makefile @@ -511,13 +511,11 @@ rostest: px4_sitl_default @$(MAKE) --no-print-directory px4_sitl_default sitl_gazebo-classic tests_integration: px4_sitl_default - @$(MAKE) --no-print-directory px4_sitl_default mavsdk_tests @"$(SRC_DIR)"/test/mavsdk_tests/mavsdk_test_runner.py --speed-factor 20 test/mavsdk_tests/configs/sih-sitl.json tests_integration_coverage: @$(MAKE) clean @$(MAKE) --no-print-directory px4_sitl_default PX4_CMAKE_BUILD_TYPE=Coverage - @$(MAKE) --no-print-directory px4_sitl_default mavsdk_tests @"$(SRC_DIR)"/test/mavsdk_tests/mavsdk_test_runner.py --speed-factor 20 test/mavsdk_tests/configs/sih-sitl.json @mkdir -p coverage @lcov --directory build/px4_sitl_default --base-directory build/px4_sitl_default --gcov-tool gcov --capture -o coverage/lcov.info diff --git a/Tools/astyle/files_to_check_code_style.sh b/Tools/astyle/files_to_check_code_style.sh index dc0f3c67ca4..b8db45c1644 100755 --- a/Tools/astyle/files_to_check_code_style.sh +++ b/Tools/astyle/files_to_check_code_style.sh @@ -30,7 +30,6 @@ exec find boards msg src platforms test \ -path src/modules/mc_raptor/blob -prune -o \ -path src/modules/simulation/gz_plugins/optical_flow/PX4-OpticalFlow -prune -o \ -path test/fuzztest -prune -o \ - -path test/mavsdk_tests/catch2 -prune -o \ -path src/lib/crypto/monocypher -prune -o \ -path src/lib/crypto/libtomcrypt -prune -o \ -path src/lib/crypto/libtommath -prune -o \ diff --git a/Tools/packaging/containers/test_sih_mission.py b/Tools/packaging/containers/test_sih_mission.py index 07ef27d53ab..93d7ebc78ac 100644 --- a/Tools/packaging/containers/test_sih_mission.py +++ b/Tools/packaging/containers/test_sih_mission.py @@ -8,7 +8,7 @@ Validates that the SIH Docker container works end-to-end with MAVSDK. Prerequisites: - Docker container running: docker run --rm --network host px4io/px4-sitl:v1.17.0-alpha1 - - pip install mavsdk + - pip install -r Tools/setup/test-requirements.txt (MAVSDK v4) - mavsim-viewer running (optional): /path/to/mavsim-viewer -n 1 @@ -17,112 +17,126 @@ Usage: python3 Tools/packaging/containers/test_sih_mission.py --speed 10 # faster-than-realtime """ -import asyncio import argparse +import math import sys import time -from mavsdk import System -from mavsdk.mission import MissionItem, MissionPlan +from mavsdk import ComponentType, Configuration, ConnectionResult, Mavsdk +from mavsdk.plugins.action import Action, ActionError +from mavsdk.plugins.mission import Mission, MissionItem, MissionPlan +from mavsdk.plugins.telemetry import Telemetry + +CONNECTION_URL = "udpin://0.0.0.0:14540" -async def run_mission(speed_factor: int = 1): - drone = System() - print(f"Connecting to drone on udp://:14540 ...") - await drone.connect(system_address="udp://:14540") +def make_mission_item(latitude_deg, longitude_deg): + # All fields need to be set. + nan = float("nan") + return MissionItem( + latitude_deg=latitude_deg, + longitude_deg=longitude_deg, + relative_altitude_m=100, + speed_m_s=10, + is_fly_through=True, + gimbal_pitch_deg=nan, + gimbal_yaw_deg=nan, + camera_action=MissionItem.CameraAction.NONE, + loiter_time_s=nan, + camera_photo_interval_s=nan, + acceptance_radius_m=nan, + yaw_deg=nan, + camera_photo_distance_m=nan, + vehicle_action=MissionItem.VehicleAction.NONE, + ) + + +def wait_for(condition, poll_s=0.1): + while not condition(): + time.sleep(poll_s) + + +def run_mission(speed_factor): + mavsdk = Mavsdk(Configuration.create_with_component_type(ComponentType.GROUND_STATION)) + + print(f"Connecting to drone on {CONNECTION_URL} ...") + result = mavsdk.add_any_connection(CONNECTION_URL) + if result != ConnectionResult.SUCCESS: + raise RuntimeError(f"Connection failed: {result.name}") print("Waiting for drone to connect...") - async for state in drone.core.connection_state(): - if state.is_connected: - print(f"Connected (UUID: {state.uuid if hasattr(state, 'uuid') else 'N/A'})") - break + drone = mavsdk.first_autopilot(timeout_s=-1) + print(f"Connected (system ID: {drone.get_system_id()})") + + action = Action(drone) + mission = Mission(drone) + telemetry = Telemetry(drone) print("Waiting for global position estimate...") - async for health in drone.telemetry.health(): - if health.is_global_position_ok and health.is_home_position_ok: - print("Global position OK") - break + wait_for(lambda: telemetry.health().is_global_position_ok + and telemetry.health().is_home_position_ok) + print("Global position OK") # Get home position for reference - async for pos in drone.telemetry.position(): - home_lat = pos.latitude_deg - home_lon = pos.longitude_deg - print(f"Home position: {home_lat:.6f}, {home_lon:.6f}") - break + wait_for(lambda: math.isfinite(telemetry.position().latitude_deg)) + position = telemetry.position() + home_lat = position.latitude_deg + home_lon = position.longitude_deg + print(f"Home position: {home_lat:.6f}, {home_lon:.6f}") # Build a small box mission at 100m AGL # ~100m offset in each direction offset = 0.001 # roughly 111m at equator mission_items = [ - MissionItem( - home_lat + offset, home_lon, - 100, 10, True, float('nan'), float('nan'), - MissionItem.CameraAction.NONE, - float('nan'), float('nan'), float('nan'), - float('nan'), float('nan'), - MissionItem.VehicleAction.NONE, - ), - MissionItem( - home_lat + offset, home_lon + offset, - 100, 10, True, float('nan'), float('nan'), - MissionItem.CameraAction.NONE, - float('nan'), float('nan'), float('nan'), - float('nan'), float('nan'), - MissionItem.VehicleAction.NONE, - ), - MissionItem( - home_lat, home_lon + offset, - 100, 10, True, float('nan'), float('nan'), - MissionItem.CameraAction.NONE, - float('nan'), float('nan'), float('nan'), - float('nan'), float('nan'), - MissionItem.VehicleAction.NONE, - ), - MissionItem( - home_lat, home_lon, - 100, 10, True, float('nan'), float('nan'), - MissionItem.CameraAction.NONE, - float('nan'), float('nan'), float('nan'), - float('nan'), float('nan'), - MissionItem.VehicleAction.NONE, - ), + make_mission_item(home_lat + offset, home_lon), + make_mission_item(home_lat + offset, home_lon + offset), + make_mission_item(home_lat, home_lon + offset), + make_mission_item(home_lat, home_lon), ] - mission_plan = MissionPlan(mission_items) - print(f"Uploading mission ({len(mission_items)} waypoints, 100m AGL)...") - await drone.mission.upload_mission(mission_plan) + mission.upload_mission(MissionPlan(mission_items=mission_items)) print("Mission uploaded") print("Arming...") - await drone.action.arm() + action.arm() print("Armed") t0 = time.time() print("Starting mission...") - await drone.mission.start_mission() + mission.start_mission() # Monitor mission progress - async for progress in drone.mission.mission_progress(): + last_current = -1 + while True: + progress = mission.mission_progress() elapsed = time.time() - t0 - print(f" [{elapsed:6.1f}s] Waypoint {progress.current}/{progress.total}") - if progress.current == progress.total: + if progress.current != last_current: + print(f" [{elapsed:6.1f}s] Waypoint {progress.current}/{progress.total}") + last_current = progress.current + if progress.total > 0 and progress.current == progress.total: print(f"Mission complete in {elapsed:.1f}s (speed factor: {speed_factor}x)") break + time.sleep(0.1) print("Returning to launch...") - await drone.action.return_to_launch() + action.return_to_launch() # Wait for landing - async for in_air in drone.telemetry.in_air(): - if not in_air: - print("Landed") - break + wait_for(lambda: not telemetry.in_air()) + print("Landed") print("Disarming...") - await drone.action.disarm() + try: + action.disarm() + except ActionError: + # PX4 usually disarms by itself after landing. + if telemetry.armed(): + raise print("Test PASSED") + mavsdk.destroy() + def main(): parser = argparse.ArgumentParser(description="PX4 SIH Docker mission test") @@ -131,7 +145,7 @@ def main(): args = parser.parse_args() try: - asyncio.run(run_mission(args.speed)) + run_mission(args.speed) except KeyboardInterrupt: print("\nInterrupted") sys.exit(1) diff --git a/Tools/setup/Dockerfile b/Tools/setup/Dockerfile index 6d07b492c01..4b2a89a7f0e 100644 --- a/Tools/setup/Dockerfile +++ b/Tools/setup/Dockerfile @@ -19,6 +19,7 @@ COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh # Install PX4 Requirements COPY requirements.txt /tmp/requirements.txt +COPY test-requirements.txt /tmp/test-requirements.txt COPY ubuntu.sh /tmp/ubuntu.sh RUN bash /tmp/ubuntu.sh --no-sim-tools diff --git a/Tools/setup/arch.sh b/Tools/setup/arch.sh index 9b1e947bb24..972761e31d7 100755 --- a/Tools/setup/arch.sh +++ b/Tools/setup/arch.sh @@ -68,6 +68,9 @@ sudo pacman -Sy --noconfirm --needed \ # Python dependencies echo "Installing PX4 Python3 dependencies" pip install --break-system-packages -r ${DIR}/${REQUIREMENTS_FILE} +if [[ -f "${DIR}/test-requirements.txt" ]]; then + pip install --break-system-packages -r ${DIR}/test-requirements.txt +fi # NuttX toolchain (arm-none-eabi-gcc) if [[ $INSTALL_NUTTX == "true" ]]; then diff --git a/Tools/setup/macos.sh b/Tools/setup/macos.sh index ac7838f8c0d..96d3945972d 100755 --- a/Tools/setup/macos.sh +++ b/Tools/setup/macos.sh @@ -140,6 +140,7 @@ fi # We need to have future to install pymavlink later. "$VENV_DIR/bin/pip" install future "$VENV_DIR/bin/pip" install -r "${DIR}/requirements.txt" +"$VENV_DIR/bin/pip" install -r "${DIR}/test-requirements.txt" # Optional, but recommended additional simulation tools: if [[ $INSTALL_SIM == "--sim-tools" ]]; then diff --git a/Tools/setup/test-requirements.txt b/Tools/setup/test-requirements.txt new file mode 100644 index 00000000000..cf8c4a2511f --- /dev/null +++ b/Tools/setup/test-requirements.txt @@ -0,0 +1,4 @@ +# Integration tests in test/mavsdk_tests. mavsdk is the native MAVSDK binding (v4+), +# pinned to a patch range so test behaviour only changes with a deliberate bump. +mavsdk~=4.0.6 +pytest>=8,<10 diff --git a/Tools/setup/ubuntu.sh b/Tools/setup/ubuntu.sh index 842eb571245..c947aff2b25 100755 --- a/Tools/setup/ubuntu.sh +++ b/Tools/setup/ubuntu.sh @@ -111,16 +111,22 @@ echo echo "[ubuntu.sh] Installing PX4 Python3 dependencies" PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}') REQUIRED_VERSION="3.11" -if [[ "$(printf '%s\n' "$REQUIRED_VERSION" "$PYTHON_VERSION" | sort -V | head -n1)" == "$REQUIRED_VERSION" ]]; then - python3 -m pip install --break-system-packages -r ${DIR}/requirements.txt -else - if [ -n "$VIRTUAL_ENV" ]; then - # virtual environments don't allow --user option - python -m pip install -r ${DIR}/requirements.txt - else - python3 -m pip install --user -r ${DIR}/requirements.txt +# The integration test requirements are not staged into every container build context. +for REQUIREMENTS in requirements.txt test-requirements.txt; do + if [[ ! -f "${DIR}/${REQUIREMENTS}" ]]; then + continue fi -fi + if [[ "$(printf '%s\n' "$REQUIRED_VERSION" "$PYTHON_VERSION" | sort -V | head -n1)" == "$REQUIRED_VERSION" ]]; then + python3 -m pip install --break-system-packages -r ${DIR}/${REQUIREMENTS} + else + if [ -n "$VIRTUAL_ENV" ]; then + # virtual environments don't allow --user option + python -m pip install -r ${DIR}/${REQUIREMENTS} + else + python3 -m pip install --user -r ${DIR}/${REQUIREMENTS} + fi + fi +done # NuttX toolchain (arm-none-eabi-gcc) if [[ $INSTALL_NUTTX == "true" ]]; then diff --git a/cmake/mavsdk_tests.cmake b/cmake/mavsdk_tests.cmake deleted file mode 100644 index 0a2ef6533f9..00000000000 --- a/cmake/mavsdk_tests.cmake +++ /dev/null @@ -1,49 +0,0 @@ -############################################################################ -# -# Copyright (c) 2026 PX4 Development Team. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# 3. Neither the name PX4 nor the names of its contributors may be -# used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -############################################################################ - -# mavsdk_tests is a black-box MAVLink integration-test driver that talks to a -# running PX4 over UDP. It does not depend on any specific simulator backend -# (sitl_gazebo-classic, gz, sih, ...): it just needs a PX4 binary -# to be running. Defined here at the top level rather than under any sitl -# backend file so the dependency graph is honest. -include(ExternalProject) -ExternalProject_Add(mavsdk_tests - SOURCE_DIR ${PX4_SOURCE_DIR}/test/mavsdk_tests - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} - BINARY_DIR ${PX4_BINARY_DIR}/mavsdk_tests - INSTALL_COMMAND "" - USES_TERMINAL_CONFIGURE true - USES_TERMINAL_BUILD true - EXCLUDE_FROM_ALL true - BUILD_ALWAYS 1 -) diff --git a/docs/en/debug/failure_injection.md b/docs/en/debug/failure_injection.md index 26879f134db..1d0591fdf8f 100644 --- a/docs/en/debug/failure_injection.md +++ b/docs/en/debug/failure_injection.md @@ -126,7 +126,7 @@ While the selected aux switch is on the configured failure is injected; switchin ## MAVSDK Failure Plugin The [MAVSDK failure plugin](https://mavsdk.mavlink.io/main/en/cpp/api_reference/classmavsdk_1_1_failure.html) can be used to programmatically inject failures. -It is used in [PX4 Integration Testing](../test_and_ci/integration_testing_mavsdk.md) to simulate failure cases (for example, see [PX4-Autopilot/test/mavsdk_tests/autopilot_tester.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester.cpp)). +It is used in [PX4 Integration Testing](../test_and_ci/integration_testing_mavsdk.md) to simulate failure cases (for example, see [PX4-Autopilot/test/mavsdk_tests/test_multicopter_failsafe.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/test_multicopter_failsafe.py)). The plugin API is a direct mapping of the failure command shown above, with a few additional error signals related to the connection. diff --git a/docs/en/test_and_ci/integration_testing_mavsdk.md b/docs/en/test_and_ci/integration_testing_mavsdk.md index 9e82f3d2626..458bc8dfe17 100644 --- a/docs/en/test_and_ci/integration_testing_mavsdk.md +++ b/docs/en/test_and_ci/integration_testing_mavsdk.md @@ -1,11 +1,12 @@ # Integration Testing using MAVSDK -PX4 can be tested end to end to using integration tests based on [MAVSDK](https://mavsdk.mavlink.io). +PX4 can be tested end to end using integration tests based on [MAVSDK](https://mavsdk.mavlink.io). -The tests are primarily developed against SITL and run in continuous integration (CI). +The tests are written in Python using the [MAVSDK Python package](https://pypi.org/project/mavsdk/) and [pytest](https://pytest.org). +They are primarily developed against SITL and run in continuous integration (CI). In future we plan to generalise them for any platform/hardware. -The instructions below explain how to setup and run the tests locally. +The instructions below explain how to set up and run the tests locally, and how to write new ones. ::: info This is the recommended integration test framework for PX4. @@ -18,7 +19,6 @@ This is the recommended integration test framework for PX4. If you haven't done so already: - Install the development toolchain for [Linux](../dev_setup/dev_env_linux_ubuntu.md) or [macOS](../dev_setup/dev_env_mac.md) (Windows not supported). - [Gazebo Classic](../sim_gazebo_classic/index.md) is required, and should be installed by default. - [Get the PX4 source code](../dev_setup/building_px4.md#download-the-px4-source-code): ```sh @@ -28,20 +28,23 @@ If you haven't done so already: ### Build PX4 for Testing -To build PX4 source code for simulator testing, use: +The tests run in the [SIH](../sim_sih/index.md) simulator, which is built into PX4. +To build PX4 for SITL, use: ```sh -DONT_RUN=1 make px4_sitl gazebo-classic mavsdk_tests +make px4_sitl_default ``` -### Install the MAVSDK C++ Library +### Install the Test Dependencies -The tests need the MAVSDK C++ library installed system-wide (e.g. in `/usr/lib` or `/usr/local/lib`). +The tests need the `mavsdk` and `pytest` Python packages, in the versions given in `Tools/setup/test-requirements.txt`. +They are installed by the [setup scripts](../dev_setup/dev_env.md), or manually with: -Install either from binaries or source: +```sh +pip install -r Tools/setup/test-requirements.txt +``` -- [MAVSDK > C++ > C++ QuickStart](https://mavsdk.mavlink.io/main/en/cpp/quickstart.html): Install as a prebuilt library on supported platforms (recommended) -- [MAVSDK > C++ Guide > Building from Source](https://mavsdk.mavlink.io/main/en/cpp/guide/build.html): Build C++ library from source. +The `mavsdk` package is a native binding of the MAVSDK C++ library, so no separate MAVSDK installation is needed. ## Run All PX4 Tests @@ -52,6 +55,7 @@ test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sih-sitl.json ``` This will list all the tests and then run them sequentially. +Each test case is run against a freshly started PX4 instance. To see all possible command line arguments use the `-h` argument: @@ -87,79 +91,93 @@ options: ## Run a Single Test Run a single test by specifying the `model` and test `case` as command line options. +A test case is a pytest test ID, and wildcards are supported. For example, to test a multicopter mission using the SIH simulator: ```sh -test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sih-sitl.json --speed-factor 10 --model quadx --case 'Fly square Multicopter Missions including Return' +test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sih-sitl.json --speed-factor 10 --model quadx --case 'test_multicopter_mission.py::test_square_mission_with_return' ``` -The easiest way to find out the current set of models and their associated test cases is to run all PX4 tests [as shown above](#run-all-px4-tests) (note, you can then cancel the build if you wish to test just one). - -At time of writing the list generated by running all tests is: +Or to run all the failsafe tests: ```sh -About to run 39 test cases for 3 selected models (1 iteration): - - iris: - - 'Land on GPS lost during mission (baro height mode)' - - 'Land on GPS lost during mission (GPS height mode)' - - 'Continue on mag lost during mission' - - 'Continue on baro lost during mission (baro height mode)' - - 'Continue on baro lost during mission (GPS height mode)' - - 'Continue on baro stuck during mission (baro height mode)' - - 'Continue on baro stuck during mission (GPS height mode)' - - 'Takeoff and Land' - - 'Fly square Multicopter Missions including Return' - - 'Fly square Multicopter Missions with manual Return' - - 'Fly straight Multicopter Mission' - - 'Offboard takeoff and land' - - 'Offboard position control' - - 'Fly forward in position control' - - 'Fly forward in altitude control' - - standard_vtol: - - 'Land on GPS lost during mission (baro height mode)' - - 'Land on GPS lost during mission (GPS height mode)' - - 'Continue on mag lost during mission' - - 'Continue on baro lost during mission (baro height mode)' - - 'Continue on baro lost during mission (GPS height mode)' - - 'Continue on baro stuck during mission (baro height mode)' - - 'Continue on baro stuck during mission (GPS height mode)' - - 'Takeoff and Land' - - 'Fly square Multicopter Missions including Return' - - 'Fly square Multicopter Missions with manual Return' - - 'Fly forward in position control' - - 'Fly forward in altitude control' - - tailsitter: - - 'Land on GPS lost during mission (baro height mode)' - - 'Land on GPS lost during mission (GPS height mode)' - - 'Continue on mag lost during mission' - - 'Continue on baro lost during mission (baro height mode)' - - 'Continue on baro lost during mission (GPS height mode)' - - 'Continue on baro stuck during mission (baro height mode)' - - 'Continue on baro stuck during mission (GPS height mode)' - - 'Takeoff and Land' - - 'Fly square Multicopter Missions including Return' - - 'Fly square Multicopter Missions with manual Return' - - 'Fly forward in position control' - - 'Fly forward in altitude control' +test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sih-sitl.json --speed-factor 10 --model quadx --case 'test_multicopter_failsafe.py::*' ``` +To list all test cases, use pytest from the test directory: + +```sh +cd test/mavsdk_tests +pytest --collect-only -q +``` + +## Run a Test Against a Running PX4 + +While developing a test, it can be quicker to start PX4 yourself and run the test directly with pytest. +Start PX4 with SIH in one terminal: + +```sh +make px4_sitl sihsim_quadx +``` + +And run a test in another terminal: + +```sh +cd test/mavsdk_tests +pytest -v -s 'test_multicopter_mission.py::test_takeoff_and_land' +``` + +The `-s` option shows the test output while it runs. +Most tests expect a vehicle that is freshly started and on the ground, so restart PX4 between tests. + +## Write a Test + +Tests are plain pytest functions in `test/mavsdk_tests/test_*.py`. +A test gets a tester that is connected to the vehicle through a fixture, and is selected for vehicles by markers: + +```py +import pytest + +from autopilot_tester import AutopilotTester, MissionOptions + + +@pytest.mark.multicopter +def test_square_mission_with_return(tester: AutopilotTester) -> None: + tester.wait_until_ready() + tester.prepare_square_mission(MissionOptions(rtl_at_end=True)) + tester.arm() + tester.execute_mission() + tester.wait_until_disarmed(180) +``` + +The testers wrap MAVSDK with the building blocks the tests need, such as missions, offboard control, failure injection and trajectory checks: + +- `tester`: [autopilot_tester.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester.py) with the common functionality. +- `tester_rtl`: [autopilot_tester_rtl.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester_rtl.py) adds rally points and geofences. +- `tester_loiter`: [autopilot_tester_loiter.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester_loiter.py) adds fixed-wing loiter, reposition and figure eight. +- `tester_follow_me`: [autopilot_tester_follow_me.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester_follow_me.py) adds follow-me. +- `tester_vision_target`: [autopilot_tester_vision_target.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester_vision_target.py) simulates landing target sensors for precision landing. + +Things to keep in mind: + +- Timeouts and sleeps of the testers are in simulation time, so a test behaves the same at any speed factor. +- A failing `assert` in a MAVSDK callback is not reported by MAVSDK. + Use `check_in_callback()` in callbacks instead, which fails the test once it finishes. +- MAVLink messages that MAVSDK has no plugin for can be sent and received with MAVSDK's `MavlinkDirect` plugin, see for example `send_command_int()`. +- Markers have to be listed in `pytest.ini`. + The `test_filter` of each entry in the config files is a pytest marker expression, such as `multicopter or offboard`. + +The tests are checked in CI with `mypy --strict` and `flake8`. + ## Implementation Notes -- The tests are invoked from the test runner script [mavsdk_test_runner.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/mavsdk_test_runner.py), which is written in Python. +- The tests are invoked from the test runner script [mavsdk_test_runner.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/mavsdk_test_runner.py). - In addition to MAVSDK, this runner starts `px4` as well as Gazebo for SITL tests, and collects the logs of these processes. + For each test case, the runner starts `px4` (and Gazebo Classic if configured) with a fresh root filesystem, runs the test with pytest, and collects the logs of these processes. -- The test runner is a C++ binary that contains: - - The [main](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/test_main.cpp) function to parse the arguments. - - An abstraction around MAVSDK called [autopilot_tester](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester.h). - - The actual tests using the abstraction around MAVSDK as e.g. [test_multicopter_mission.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/test_multicopter_mission.cpp). - - The tests use the [catch2](https://github.com/catchorg/Catch2) unit testing framework. - The reasons for using this framework are: - - Asserts (`REQUIRE`) which are needed to abort a test can be inside of functions (and not just in the top level test as is [the case with gtest](https://github.com/google/googletest/blob/main/docs/advanced.md#assertion-placement)). - - Dependency management is easier because _catch2_ can just be included as a header-only library. - - _Catch2_ supports [tags](https://github.com/catchorg/Catch2/blob/devel/docs/test-cases-and-sections.md#tags), which allows for flexible composition of tests. +- The config files in `test/mavsdk_tests/configs/` define which models are tested with which tests, and per model settings such as the timeout, environment variables or the Gazebo world. Terms used: -- "model": This is the selected Gazebo model, e.g. `iris`. -- "test case": This is a [catch2 test case](https://github.com/catchorg/Catch2/blob/devel/docs/test-cases-and-sections.md). +- "model": This is the selected simulation model, e.g. `quadx`. +- "test case": This is a pytest test, identified by its test ID, e.g. `test_multicopter_mission.py::test_takeoff_and_land`. diff --git a/test/mavsdk_tests/.flake8 b/test/mavsdk_tests/.flake8 new file mode 100644 index 00000000000..7da1f9608ee --- /dev/null +++ b/test/mavsdk_tests/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 100 diff --git a/test/mavsdk_tests/CMakeLists.txt b/test/mavsdk_tests/CMakeLists.txt deleted file mode 100644 index 374b468f1c6..00000000000 --- a/test/mavsdk_tests/CMakeLists.txt +++ /dev/null @@ -1,69 +0,0 @@ -cmake_minimum_required(VERSION 3.5.1) - -project(mavsdk_tests CXX) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -file(READ MAVSDK_VERSION MAVSDK_VERSION) -string(STRIP ${MAVSDK_VERSION} MAVSDK_VERSION) - -find_package(MAVSDK "${MAVSDK_VERSION}" REQUIRED) -find_package(Threads REQUIRED) - -if(MAVSDK_FOUND) - add_executable(mavsdk_tests - test_main.cpp - autopilot_tester.cpp - autopilot_tester_failure.cpp - autopilot_tester_rtl.cpp - autopilot_tester_figure_eight.cpp - autopilot_tester_loiter.cpp - autopilot_tester_vision_target.cpp - # follow-me needs a MAVSDK update: - # https://github.com/mavlink/MAVSDK/pull/1770 - # autopilot_tester_follow_me.cpp - test_multicopter_basics.cpp - test_multicopter_control_allocation.cpp - test_multicopter_failure_injection.cpp - test_multicopter_failsafe.cpp - test_multicopter_mission.cpp - test_multicopter_mission_do_jump.cpp - test_multicopter_rtl.cpp - test_multicopter_offboard.cpp - test_multicopter_manual.cpp - test_multicopter_rtl_with_geofence.cpp - test_sih_xvert_transition.cpp - test_vtol_mission.cpp - test_vtol_figure_eight.cpp - test_vtol_loiter_reposition.cpp - test_vtol_rtl.cpp - test_vtol_mission_wind.cpp - test_vtol_loiter_airspeed_failure_blockage.cpp - test_multicopter_home.cpp - test_param_ftp.cpp - test_vision_target.cpp - # test_multicopter_follow_me.cpp - ) - - target_link_libraries(mavsdk_tests - MAVSDK::mavsdk - ${CMAKE_THREAD_LIBS_INIT} - ) - - target_include_directories(mavsdk_tests PUBLIC ${CMAKE_BINARY_DIR}/..) - - set_source_files_properties(autopilot_tester_vision_target.cpp PROPERTIES COMPILE_DEFINITIONS - "PX4_MAVLINK_XML_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/../../src/modules/mavlink/mavlink/message_definitions/v1.0\"") - - target_compile_options(mavsdk_tests - PRIVATE - -Wall - -Wextra - -Werror - -Wno-error=deprecated-declarations - ) -else() - message("MAVSDK C++ not found, skipping mavsdk_tests build..") -endif() diff --git a/test/mavsdk_tests/MAVSDK_VERSION b/test/mavsdk_tests/MAVSDK_VERSION deleted file mode 100644 index 7290025ecc0..00000000000 --- a/test/mavsdk_tests/MAVSDK_VERSION +++ /dev/null @@ -1 +0,0 @@ -3.17.2 diff --git a/test/mavsdk_tests/autopilot_tester.cpp b/test/mavsdk_tests/autopilot_tester.cpp deleted file mode 100644 index 46c0c95fabe..00000000000 --- a/test/mavsdk_tests/autopilot_tester.cpp +++ /dev/null @@ -1,1152 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester.h" -#include "math_helpers.h" -#include -#include -#include -#include -#include -#include - -std::string connection_url {"udp://"}; -std::optional speed_factor {std::nullopt}; - -AutopilotTester::AutopilotTester() : - _real_time_report_thread([this]() -{ - report_speed_factor(); -}) -{ -} - -AutopilotTester::~AutopilotTester() -{ - _events->unsubscribe_events(_events_handle); - _should_exit = true; - _real_time_report_thread.join(); -} - -void AutopilotTester::connect(const std::string uri) -{ - ConnectionResult ret = _mavsdk.add_any_connection(uri); - REQUIRE(ret == ConnectionResult::Success); - - std::cout << time_str() << "Waiting for system connect" << std::endl; - REQUIRE(poll_condition_with_timeout( - [this]() { return _mavsdk.systems().size() > 0; }, std::chrono::seconds(25))); - - auto system = get_system(); - - _action.reset(new Action(system)); - _failure.reset(new Failure(system)); - _info.reset(new Info(system)); - _manual_control.reset(new ManualControl(system)); - _mission.reset(new Mission(system)); - _mission_raw.reset(new MissionRaw(system)); - _offboard.reset(new Offboard(system)); - _param.reset(new Param(system)); - _telemetry.reset(new Telemetry(system)); - _events.reset(new Events(system)); - _mavlink_passthrough.reset(new MavlinkPassthrough(system)); - - _events_handle = _events->subscribe_events([](const Events::Event & event) { - std::cout << "[" << event.log_level << "] " << event.message << std::endl; - - if (!event.description.empty()) { - std::cout << " Description: " << event.description << std::endl; - } - - std::cout << " Event name: " << event.event_namespace << "/" << event.event_name - << std::endl; - }); -} - -void AutopilotTester::wait_until_ready() -{ - std::cout << time_str() << "Waiting for system to be ready (system health ok & able to arm)" << std::endl; - - // Wait until the system is healthy - CHECK(poll_condition_with_timeout( - [this]() { return _telemetry->health_all_ok(); }, std::chrono::seconds(30))); - - // Note: There is a known bug in MAVSDK (https://github.com/mavlink/MAVSDK/issues/1852), - // where `health_all_ok()` returning true doesn't actually mean vehicle is ready to accept - // global position estimate as valid (due to hysteresis). This needs to be fixed properly. - - // However, this is mitigated by the `is_armable` check below as a side effect, since - // when the vehicle considers global position to be valid, it will then allow arming - - // Wait until we can arm - CHECK(poll_condition_with_timeout( - [this]() { return _telemetry->health().is_armable; }, std::chrono::seconds(45))); -} - -void AutopilotTester::store_home() -{ - request_ground_truth(); - std::cout << time_str() << "Waiting to get home position" << std::endl; - CHECK(poll_condition_with_timeout( - [this]() { - _home = _telemetry->ground_truth(); - return std::isfinite(_home.latitude_deg) && std::isfinite(_home.longitude_deg); - }, std::chrono::seconds(10))); -} - -void AutopilotTester::check_home_within(float acceptance_radius_m) -{ - CHECK(ground_truth_horizontal_position_close_to(_home, acceptance_radius_m)); -} - -void AutopilotTester::check_home_not_within(float min_distance_m) -{ - CHECK(ground_truth_horizontal_position_far_from(_home, min_distance_m)); -} - -void AutopilotTester::set_takeoff_altitude(const float altitude_m) -{ - CHECK(Action::Result::Success == _action->set_takeoff_altitude(altitude_m)); - const auto result = _action->get_takeoff_altitude(); - CHECK(result.first == Action::Result::Success); - CHECK(result.second == Approx(altitude_m)); -} - -void AutopilotTester::set_rtl_altitude(const float altitude_m) -{ - CHECK(Action::Result::Success == _action->set_return_to_launch_altitude(altitude_m)); - const auto result = _action->get_return_to_launch_altitude(); - CHECK(result.first == Action::Result::Success); - CHECK(result.second == Approx(altitude_m)); -} - -void AutopilotTester::set_height_source(AutopilotTester::HeightSource height_source) -{ - switch (height_source) { - case HeightSource::Baro: - CHECK(_param->set_param_int("EKF2_HGT_REF", 0) == Param::Result::Success); - break; - - case HeightSource::Gps: - CHECK(_param->set_param_int("EKF2_HGT_REF", 1) == Param::Result::Success); - } -} - -void AutopilotTester::set_rc_loss_exception(AutopilotTester::RcLossException mask) -{ - switch (mask) { - case RcLossException::Mission: - CHECK(_param->set_param_int("COM_RCL_EXCEPT", 1 << 0) == Param::Result::Success); - break; - - case RcLossException::Hold: - CHECK(_param->set_param_int("COM_RCL_EXCEPT", 1 << 1) == Param::Result::Success); - break; - - case RcLossException::Offboard: - CHECK(_param->set_param_int("COM_RCL_EXCEPT", 1 << 2) == Param::Result::Success); - } -} - -void AutopilotTester::set_param_vt_fwd_thrust_en(int value) -{ - CHECK(_param->set_param_int("VT_FWD_THRUST_EN", value) == Param::Result::Success); -} - -void AutopilotTester::arm() -{ - // Even after wait_until_ready() passes, the is_armable health flag can - // transiently flicker (e.g. the estimator's heading reference briefly - // dropping out during startup), causing the arm command to be denied. - // Retry until the autopilot actually accepts it. - REQUIRE(poll_condition_with_timeout( - [this]() { return _action->arm() == Action::Result::Success; }, std::chrono::seconds(30))); -} - -void AutopilotTester::takeoff() -{ - const auto result = _action->takeoff(); - REQUIRE(result == Action::Result::Success); -} - -void AutopilotTester::land() -{ - const auto result = _action->land(); - REQUIRE(result == Action::Result::Success); -} - -void AutopilotTester::transition_to_fixedwing() -{ - const auto result = _action->transition_to_fixedwing(); - REQUIRE(result == Action::Result::Success); -} - -void AutopilotTester::transition_to_multicopter() -{ - const auto result = _action->transition_to_multicopter(); - REQUIRE(result == Action::Result::Success); -} - -void AutopilotTester::wait_until_multicopter(std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [this]() { return _telemetry->vtol_state() == Telemetry::VtolState::Mc; }, timeout)); -} - -void AutopilotTester::wait_until_disarmed(std::chrono::seconds timeout_duration) -{ - REQUIRE(poll_condition_with_timeout( - [this]() { return !_telemetry->armed(); }, timeout_duration)); -} - -void AutopilotTester::wait_until_hovering() -{ - wait_for_landed_state(Telemetry::LandedState::InAir, std::chrono::seconds(45)); -} - -void AutopilotTester::wait_until_altitude(float rel_altitude_m, std::chrono::seconds timeout, float delta) -{ - REQUIRE(poll_condition_with_timeout( - [this, rel_altitude_m, delta]() { - return fabs(rel_altitude_m + _telemetry->position_velocity_ned().position.down_m) <= delta; - }, timeout)); -} - -void AutopilotTester::wait_until_fixedwing(std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [this]() { return _telemetry->vtol_state() == Telemetry::VtolState::Fw; }, timeout)); -} - -void AutopilotTester::prepare_square_mission(MissionOptions mission_options) -{ - const auto ct = get_coordinate_transformation(); - - Mission::MissionPlan mission_plan {}; - mission_plan.mission_items.push_back(create_mission_item({mission_options.leg_length_m, 0.}, mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({mission_options.leg_length_m, mission_options.leg_length_m}, - mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({0., mission_options.leg_length_m}, mission_options, ct)); - - _mission->set_return_to_launch_after_mission(mission_options.rtl_at_end); - - REQUIRE(_mission->upload_mission(mission_plan) == Mission::Result::Success); - // PX4 needs time to realize that it now has a mission available, so we need to wait a bit here. - sleep_for(std::chrono::seconds(1)); -} - -void AutopilotTester::prepare_straight_mission(MissionOptions mission_options) -{ - const auto ct = get_coordinate_transformation(); - - Mission::MissionPlan mission_plan {}; - mission_plan.mission_items.push_back(create_mission_item({0, 0.}, mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({mission_options.leg_length_m, 0}, mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({2 * mission_options.leg_length_m, 0}, mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({3 * mission_options.leg_length_m, 0}, mission_options, ct)); - mission_plan.mission_items.push_back(create_mission_item({4 * mission_options.leg_length_m, 0}, mission_options, ct)); - - _mission->set_return_to_launch_after_mission(mission_options.rtl_at_end); - - REQUIRE(_mission->upload_mission(mission_plan) == Mission::Result::Success); - // PX4 needs time to realize that it now has a mission available, so we need to wait a bit here. - sleep_for(std::chrono::seconds(1)); -} - -void AutopilotTester::execute_mission() -{ - std::promise prom; - auto fut = prom.get_future(); - - - REQUIRE(poll_condition_with_timeout( - [this]() { return _mission->start_mission() == Mission::Result::Success; }, std::chrono::seconds(3))); - - // poll_condition_with_timeout uses autopilot sim time, so pass sim-time timeout directly - wait_for_mission_finished(std::chrono::seconds(500)); -} - -void AutopilotTester::execute_mission_and_lose_gps() -{ - CHECK(_param->set_param_int("SYS_FAILURE_EN", 1) == Param::Result::Success); - - start_and_wait_for_mission_sequence(1); - - CHECK(_failure->inject(Failure::FailureUnit::SensorGps, Failure::FailureType::Off, 0) == Failure::Result::Success); - - // With no position aiding left, a blind descend is performed. MAVSDK has no - // Descend flight mode, so the caller just waits for the disarm after landing. -} - -void AutopilotTester::execute_mission_and_lose_mag() -{ - CHECK(_param->set_param_int("SYS_FAILURE_EN", 1) == Param::Result::Success); - - start_and_wait_for_mission_sequence(1); - - CHECK(_failure->inject(Failure::FailureUnit::SensorMag, Failure::FailureType::Off, 0) == Failure::Result::Success); - - // We except the mission to continue without mag just fine. - REQUIRE(poll_condition_with_timeout( - [this]() { - auto result = _mission->is_mission_finished(); - return result.first == Mission::Result::Success && result.second; - }, std::chrono::seconds(90))); -} - -void AutopilotTester::execute_mission_and_lose_baro() -{ - CHECK(_param->set_param_int("SYS_FAILURE_EN", 1) == Param::Result::Success); - - start_and_wait_for_mission_sequence(1); - - CHECK(_failure->inject(Failure::FailureUnit::SensorBaro, Failure::FailureType::Off, 0) == Failure::Result::Success); - - // We except the mission to continue without baro just fine. - REQUIRE(poll_condition_with_timeout( - [this]() { - auto result = _mission->is_mission_finished(); - return result.first == Mission::Result::Success && result.second; - }, std::chrono::seconds(90))); -} - -void AutopilotTester::execute_mission_and_get_baro_stuck() -{ - CHECK(_param->set_param_int("SYS_FAILURE_EN", 1) == Param::Result::Success); - - start_and_wait_for_mission_sequence(1); - - CHECK(_failure->inject(Failure::FailureUnit::SensorBaro, Failure::FailureType::Stuck, 0) == Failure::Result::Success); - - // We except the mission to continue with a stuck baro just fine. - REQUIRE(poll_condition_with_timeout( - [this]() { - auto result = _mission->is_mission_finished(); - return result.first == Mission::Result::Success && result.second; - }, std::chrono::seconds(90))); -} - -void AutopilotTester::execute_mission_and_get_mag_stuck() -{ - CHECK(_param->set_param_int("SYS_FAILURE_EN", 1) == Param::Result::Success); - - start_and_wait_for_mission_sequence(1); - - CHECK(_failure->inject(Failure::FailureUnit::SensorMag, Failure::FailureType::Stuck, 0) == Failure::Result::Success); - - // We except the mission to continue with a stuck mag just fine. - REQUIRE(poll_condition_with_timeout( - [this]() { - auto result = _mission->is_mission_finished(); - return result.first == Mission::Result::Success && result.second; - }, std::chrono::seconds(120))); -} - -CoordinateTransformation AutopilotTester::get_coordinate_transformation() -{ - const auto home = _telemetry->home(); - CHECK(std::isfinite(home.latitude_deg)); - CHECK(std::isfinite(home.longitude_deg)); - return CoordinateTransformation({home.latitude_deg, home.longitude_deg}); -} - -Mission::MissionItem AutopilotTester::create_mission_item( - const CoordinateTransformation::LocalCoordinate &local_coordinate, - const MissionOptions &mission_options, - const CoordinateTransformation &ct) -{ - auto mission_item = Mission::MissionItem{}; - const auto pos_north = ct.global_from_local(local_coordinate); - mission_item.latitude_deg = pos_north.latitude_deg; - mission_item.longitude_deg = pos_north.longitude_deg; - mission_item.relative_altitude_m = mission_options.relative_altitude_m; - mission_item.is_fly_through = mission_options.fly_through; - return mission_item; -} - -void AutopilotTester::load_qgc_mission_raw_and_move_here(const std::string &plan_file) -{ - auto import_result = _mission_raw->import_qgroundcontrol_mission(plan_file); - REQUIRE(import_result.first == MissionRaw::Result::Success); - - move_mission_raw_here(import_result.second.mission_items); - - REQUIRE(_mission_raw->upload_mission(import_result.second.mission_items) == MissionRaw::Result::Success); - // PX4 needs time to realize that it now has a mission available, so we need to wait a bit here. - sleep_for(std::chrono::seconds(1)); -} - -void AutopilotTester::execute_mission_raw() -{ - REQUIRE(_mission->start_mission() == Mission::Result::Success); - - wait_for_mission_raw_finished(std::chrono::seconds(300)); -} - -namespace -{ -MissionRaw::MissionItem make_raw_mission_item(uint32_t seq, uint32_t command, uint32_t frame, - float param1, float param2, int32_t x, int32_t y, float z, uint32_t current) -{ - MissionRaw::MissionItem item{}; - item.seq = seq; - item.frame = frame; - item.command = command; - item.current = current; - item.autocontinue = 1; - item.param1 = param1; - item.param2 = param2; - item.param3 = 0.f; - item.param4 = 0.f; - item.x = x; - item.y = y; - item.z = z; - item.mission_type = MAV_MISSION_TYPE_MISSION; - return item; -} -} // namespace - -int AutopilotTester::prepare_multicopter_mission_with_do_jump(const MissionOptions &mission_options, int jump_repeats) -{ - const auto ct = get_coordinate_transformation(); - const float altitude_m = static_cast(mission_options.relative_altitude_m); - const double leg_m = mission_options.leg_length_m; - - // Convert a local (north, east) offset from home into a GLOBAL_RELATIVE_ALT mission item. - auto position_item = [&](uint32_t seq, uint32_t command, double north_m, double east_m, float z, - uint32_t current) { - const auto global = ct.global_from_local({north_m, east_m}); - return make_raw_mission_item(seq, command, MAV_FRAME_GLOBAL_RELATIVE_ALT, 0.f, 0.f, - static_cast(std::lround(global.latitude_deg * 1e7)), - static_cast(std::lround(global.longitude_deg * 1e7)), z, current); - }; - - // A simple square-ish path with a DO_JUMP that loops back to waypoint 1. The DO_JUMP is at seq 3. - const int jump_index = 3; - std::vector items; - items.push_back(position_item(0, MAV_CMD_NAV_TAKEOFF, 0., 0., altitude_m, /*current*/ 1)); - items.push_back(position_item(1, MAV_CMD_NAV_WAYPOINT, leg_m, 0., altitude_m, 0)); - items.push_back(position_item(2, MAV_CMD_NAV_WAYPOINT, leg_m, leg_m, altitude_m, 0)); - items.push_back(make_raw_mission_item(jump_index, MAV_CMD_DO_JUMP, MAV_FRAME_MISSION, - /*param1: target seq*/ 1.f, /*param2: repeats*/ static_cast(jump_repeats), - 0, 0, 0.f, 0)); - items.push_back(position_item(4, MAV_CMD_NAV_WAYPOINT, 0., leg_m, altitude_m, 0)); - items.push_back(position_item(5, MAV_CMD_NAV_LAND, 0., 0., 0.f, 0)); - - REQUIRE(_mission_raw->upload_mission(items) == MissionRaw::Result::Success); - // PX4 needs time to realize that it now has a mission available, so we need to wait a bit here. - sleep_for(std::chrono::seconds(1)); - - return jump_index; -} - -void AutopilotTester::start_mission_raw_and_wait_for_sequence(int sequence_number) -{ - start_and_wait_for_mission_sequence_raw(sequence_number); -} - -void AutopilotTester::send_set_current_mission_item(int index) -{ - // Send a single raw MISSION_SET_CURRENT, fire-and-forget - this mimics a one-shot operator/GCS - // action. We deliberately do NOT use MissionRaw::set_current_mission_item(): that call keeps - // retransmitting MISSION_SET_CURRENT until the autopilot echoes back MISSION_CURRENT with the - // exact requested seq. When the requested item is a DO_JUMP the navigator resolves it to the - // jump target and reports a different seq, so MAVSDK would re-send indefinitely and continuously - // reset the mission, which is not the scenario we want to exercise here. - const uint8_t target_sysid = _mavlink_passthrough->get_target_sysid(); - const uint16_t seq = static_cast(index); - - const MavlinkPassthrough::Result result = _mavlink_passthrough->queue_message( - [target_sysid, seq](MavlinkAddress mavlink_address, uint8_t channel) { - mavlink_message_t message; - mavlink_msg_mission_set_current_pack_chan( - mavlink_address.system_id, - mavlink_address.component_id, - channel, - &message, - target_sysid, - MAV_COMP_ID_AUTOPILOT1, - seq); - return message; - }); - - // Extra parentheses stop Catch2 from decomposing the expression: stringifying - // MavlinkPassthrough::Result pulls in an operator<< that the MAVSDK lib does not export. - REQUIRE((result == MavlinkPassthrough::Result::Success)); -} - -void AutopilotTester::execute_rtl() -{ - REQUIRE(Action::Result::Success == _action->return_to_launch()); -} - -void AutopilotTester::execute_land() -{ - REQUIRE(Action::Result::Success == _action->land()); -} - -void AutopilotTester::start_offboard_with_retry(const std::function &resend_setpoint) -{ - // MAVSDK's offboard watchdog resets the setpoint state to NotActive when a - // heartbeat without offboard mode arrives more than 3 s after _last_started - // — which is only ever set by start(), so before the first start() it is - // epoch zero and the guard is always true. At high sim speed factors - // heartbeats arrive every few milliseconds of wall time, so one can slip in - // between set_*() and start(), making start() fail with NoSetpointSet. - // Re-send the setpoint and retry until the command goes out. - Offboard::Result result{}; - - for (int i = 0; i < 10; ++i) { - result = _offboard->start(); - - if (result == Offboard::Result::Success) { - return; - } - - resend_setpoint(); - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - } - - REQUIRE(result == Offboard::Result::Success); -} - -void AutopilotTester::offboard_goto(const Offboard::PositionNedYaw &target, float acceptance_radius_m, - std::chrono::seconds timeout_duration) -{ - _offboard->set_position_ned(target); - start_offboard_with_retry([this, target]() { _offboard->set_position_ned(target); }); - CHECK(poll_condition_with_timeout( - [ = ]() { return estimated_position_close_to(target, acceptance_radius_m); }, timeout_duration)); - std::cout << time_str() << "Target position reached" << std::endl; -} - -void AutopilotTester::check_mission_item_speed_above(int item_index, float min_speed_m_s) -{ - - _telemetry->set_rate_velocity_ned(10); - _telemetry->subscribe_velocity_ned([item_index, min_speed_m_s, this](Telemetry::VelocityNed velocity) { - float horizontal = std::hypot(velocity.north_m_s, velocity.east_m_s); - auto progress = _mission->mission_progress(); - - if (progress.current == item_index) { - CHECK(horizontal > min_speed_m_s); - } - }); -} - -void AutopilotTester::fly_forward_in_posctl() -{ - const unsigned manual_control_rate_hz = 50; - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - CHECK(_manual_control->start_position_control() == ManualControl::Result::Success); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - store_home(); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - wait_until_ready(); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - arm(); - - // Climb up for 5 seconds - for (unsigned i = 0; i < 5 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 1.f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - // Fly forward for 10 seconds - for (unsigned i = 0; i < 10 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.5f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - // Descend until disarmed - for (unsigned i = 0; i < 60 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.0f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - - if (!_telemetry->in_air()) { - break; - } - } -} - -void AutopilotTester::fly_forward_in_altctl() -{ - const unsigned manual_control_rate_hz = 50; - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - CHECK(_manual_control->start_altitude_control() == ManualControl::Result::Success); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - store_home(); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - wait_until_ready(); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - arm(); - - // Send something to make sure RC is available. - for (unsigned i = 0; i < 1 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - // Climb up for 5 seconds - for (unsigned i = 0; i < 5 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 1.f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - // Fly forward for 10 seconds - for (unsigned i = 0; i < 10 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.5f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - } - - // Descend until disarmed - for (unsigned i = 0; i < 60 * manual_control_rate_hz; ++i) { - CHECK(_manual_control->set_manual_control_input(0.f, 0.f, 0.0f, 0.f) == ManualControl::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / manual_control_rate_hz)); - - if (!_telemetry->in_air()) { - break; - } - } -} -void AutopilotTester::fly_forward_in_offboard_attitude() -{ - // This test does not depend on valid position estimate. - // Wait for raw gps & stable attitude estimate - CHECK(poll_condition_with_timeout( - [this]() { - auto attitude = _telemetry->attitude_euler(); - return _telemetry->raw_gps().altitude_ellipsoid_m > 0.f && fabsf(attitude.roll_deg) < 5.f - && fabsf(attitude.pitch_deg) < 5.f; - }, std::chrono::seconds(20))); - - const float start_altitude_ellipsoid_m = _telemetry->raw_gps().altitude_ellipsoid_m; - - Offboard::Attitude attitude{}; - _offboard->set_attitude(attitude); - start_offboard_with_retry([this, attitude]() { _offboard->set_attitude(attitude); }); - - // Wait until we can arm - CHECK(poll_condition_with_timeout( - [this]() { return _telemetry->health().is_armable; }, std::chrono::seconds(20))); - arm(); - - const unsigned offboard_rate_hz = 50; - - // Climb - const float climb_altitude_m = 10.f; - attitude.thrust_value = 0.8f; - - while (_telemetry->raw_gps().altitude_ellipsoid_m - start_altitude_ellipsoid_m < climb_altitude_m) { - CHECK(_offboard->set_attitude(attitude) == Offboard::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / offboard_rate_hz)); - } - - // Fly forward for 3s - attitude.thrust_value = 0.8f; - attitude.pitch_deg = -20.f; - - for (unsigned i = 0; i < 3 * offboard_rate_hz; ++i) { - CHECK(_offboard->set_attitude(attitude) == Offboard::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / offboard_rate_hz)); - } - - // Check attitude - auto attitude_estimate = _telemetry->attitude_euler(); - CHECK(fabsf(attitude.roll_deg - attitude_estimate.roll_deg) < 5.f); - CHECK(fabsf(attitude.pitch_deg - attitude_estimate.pitch_deg) < 5.f); - - // Descend - attitude.thrust_value = 0.4f; - attitude.pitch_deg = 0.f; - - for (unsigned i = 0; i < 6 * offboard_rate_hz; ++i) { - CHECK(_offboard->set_attitude(attitude) == Offboard::Result::Success); - sleep_for(std::chrono::milliseconds(1000 / offboard_rate_hz)); - } - - attitude.thrust_value = 0.0f; - CHECK(_offboard->set_attitude(attitude) == Offboard::Result::Success); -} - -void AutopilotTester::start_checking_altitude(const float max_deviation_m) -{ - std::array initial_position = get_current_position_ned(); - float target_altitude = initial_position[2]; - - _check_altitude_handle = _telemetry->subscribe_position_velocity_ned([target_altitude, max_deviation_m, - this](Telemetry::PositionVelocityNed new_position) { - const float current_deviation = fabs(target_altitude - new_position.position.down_m); - CHECK(current_deviation <= max_deviation_m); - }); -} - -void AutopilotTester::stop_checking_altitude() -{ - _telemetry->unsubscribe_position_velocity_ned(_check_altitude_handle); -} - -void AutopilotTester::check_tracks_mission_raw(float corridor_radius_m, bool reverse) -{ - auto mission_raw = _mission_raw->download_mission(); - CHECK(mission_raw.first == MissionRaw::Result::Success); - - auto mission_items = mission_raw.second; - auto ct = get_coordinate_transformation(); - - _telemetry->set_rate_position_velocity_ned(5); - _telemetry->subscribe_position_velocity_ned([ct, mission_items, corridor_radius_m, reverse, - this](Telemetry::PositionVelocityNed position_velocity_ned) { - auto progress = _mission_raw->mission_progress(); - - - std::function(std::vector, unsigned, mavsdk::geometry::CoordinateTransformation)> - get_waypoint_for_sequence = [](std::vector mission_items, int sequence, auto ct) { - for (auto waypoint : mission_items) { - - if (waypoint.seq == (uint32_t)sequence) { - return get_local_mission_item_from_raw_item(waypoint, ct); - } - } - - return std::array({0.0f, 0.0f, 0.0f}); - }; - - if (progress.current > 0 && progress.current < progress.total) { - // Get shortest distance of current position to 3D line between previous and next waypoint - - std::array current { position_velocity_ned.position.north_m, - position_velocity_ned.position.east_m, - position_velocity_ned.position.down_m }; - std::array wp_prev = get_waypoint_for_sequence(mission_items, - reverse ? progress.current + 1 : progress.current - 1, ct); - std::array wp_next = get_waypoint_for_sequence(mission_items, progress.current, ct); - - float distance_to_trajectory = point_to_line_distance(current, wp_prev, wp_next); - - CHECK(distance_to_trajectory < corridor_radius_m); - } - }); -} - -void AutopilotTester::check_mission_land_within(float acceptance_radius_m) -{ - auto mission_raw = _mission_raw->download_mission(); - CHECK(mission_raw.first == MissionRaw::Result::Success); - - // Get last mission item - MissionRaw::MissionItem land_mission_item = mission_raw.second.back(); - bool is_landing_item = (land_mission_item.command == 85) || (land_mission_item.command == 21); - CHECK(is_landing_item); - Telemetry::GroundTruth land_coord{}; - land_coord.latitude_deg = static_cast(land_mission_item.x) / 1E7; - land_coord.longitude_deg = static_cast(land_mission_item.y) / 1E7; - - CHECK(ground_truth_horizontal_position_close_to(land_coord, acceptance_radius_m)); -} - -void AutopilotTester::check_tracks_mission(float corridor_radius_m) -{ - auto mission = _mission->download_mission(); - CHECK(mission.first == Mission::Result::Success); - - std::vector mission_items = mission.second.mission_items; - auto ct = get_coordinate_transformation(); - - _telemetry->set_rate_position_velocity_ned(5); - _telemetry->subscribe_position_velocity_ned([ct, mission_items, corridor_radius_m, - this](Telemetry::PositionVelocityNed position_velocity_ned) { - auto progress = _mission->mission_progress(); - - if (progress.current > 0 && progress.current < progress.total) { - // Get shortest distance of current position to 3D line between previous and next waypoint - - std::array current { position_velocity_ned.position.north_m, - position_velocity_ned.position.east_m, - position_velocity_ned.position.down_m }; - std::array wp_prev = get_local_mission_item(mission_items[progress.current - 1], ct); - std::array wp_next = get_local_mission_item(mission_items[progress.current], ct); - - float distance_to_trajectory = point_to_line_distance(current, wp_prev, wp_next); - - CHECK(distance_to_trajectory < corridor_radius_m); - } - }); -} - -void AutopilotTester::check_current_altitude(float target_rel_altitude_m, float max_distance_m) -{ - CHECK(std::abs(_telemetry->position().relative_altitude_m - target_rel_altitude_m) <= max_distance_m); -} - -void AutopilotTester::execute_rtl_when_reaching_mission_sequence(int sequence_number) -{ - start_and_wait_for_mission_sequence_raw(sequence_number); - execute_rtl(); -} - -void AutopilotTester::send_custom_mavlink_command(const MavlinkPassthrough::CommandInt &command) -{ - _mavlink_passthrough->send_command_int(command); -} - -void AutopilotTester::add_mavlink_message_callback(uint16_t message_id, - std::function< void(const mavlink_message_t &)> callback) -{ - _mavlink_passthrough->subscribe_message(message_id, std::move(callback)); -} - -mavlink_home_position_t AutopilotTester::get_home_position(std::chrono::seconds timeout) -{ - auto home_position = std::make_shared(); - auto received = std::make_shared>(false); - - auto handle = _mavlink_passthrough->subscribe_message( - MAVLINK_MSG_ID_HOME_POSITION, - [home_position, received](const mavlink_message_t &message) { - mavlink_msg_home_position_decode(&message, home_position.get()); - received->store(true); - }); - - // Ask for a fresh HOME_POSITION so we don't rely on the periodic stream timing. - MavlinkPassthrough::CommandLong request{}; - request.target_sysid = _mavlink_passthrough->get_target_sysid(); - request.target_compid = _mavlink_passthrough->get_target_compid(); - request.command = MAV_CMD_REQUEST_MESSAGE; - request.param1 = static_cast(MAVLINK_MSG_ID_HOME_POSITION); - _mavlink_passthrough->send_command_long(request); - - const bool got_it = poll_condition_with_timeout([received]() { return received->load(); }, timeout); - _mavlink_passthrough->unsubscribe_message(MAVLINK_MSG_ID_HOME_POSITION, handle); - REQUIRE(got_it); - return *home_position; -} - -Telemetry::EulerAngle AutopilotTester::get_attitude_euler() -{ - return _telemetry->attitude_euler(); -} - -std::array AutopilotTester::get_current_position_ned() -{ - mavsdk::Telemetry::PositionVelocityNed position_velocity_ned = _telemetry->position_velocity_ned(); - std::array position_ned{position_velocity_ned.position.north_m, position_velocity_ned.position.east_m, position_velocity_ned.position.down_m}; - return position_ned; -} - -void AutopilotTester::offboard_land() -{ - Offboard::VelocityNedYaw land_velocity; - land_velocity.north_m_s = 0.0f; - land_velocity.east_m_s = 0.0f; - land_velocity.down_m_s = 1.0f; - land_velocity.yaw_deg = 0.0f; - _offboard->set_velocity_ned(land_velocity); -} - -bool AutopilotTester::estimated_position_close_to(const Offboard::PositionNedYaw &target_pos, float acceptance_radius_m) -{ - Telemetry::PositionNed est_pos = _telemetry->position_velocity_ned().position; - const float distance_m = std::sqrt(sq(est_pos.north_m - target_pos.north_m) + - sq(est_pos.east_m - target_pos.east_m) + - sq(est_pos.down_m - target_pos.down_m)); - const bool pass = distance_m < acceptance_radius_m; - - if (!pass) { - std::cout << time_str() << "distance: " << distance_m << ", " << "acceptance: " << acceptance_radius_m << std::endl; - } - - return pass; -} - -bool AutopilotTester::estimated_horizontal_position_close_to(const Offboard::PositionNedYaw &target_pos, - float acceptance_radius_m) -{ - Telemetry::PositionNed est_pos = _telemetry->position_velocity_ned().position; - return sq(est_pos.north_m - target_pos.north_m) + - sq(est_pos.east_m - target_pos.east_m) < sq(acceptance_radius_m); -} - -void AutopilotTester::request_ground_truth() -{ - CHECK(_telemetry->set_rate_ground_truth(15) == Telemetry::Result::Success); -} - -bool AutopilotTester::ground_truth_horizontal_position_close_to(const Telemetry::GroundTruth &target_pos, - float acceptance_radius_m) -{ - CHECK(std::isfinite(target_pos.latitude_deg)); - CHECK(std::isfinite(target_pos.longitude_deg)); - using GlobalCoordinate = CoordinateTransformation::GlobalCoordinate; - using LocalCoordinate = CoordinateTransformation::LocalCoordinate; - CoordinateTransformation ct(GlobalCoordinate{target_pos.latitude_deg, target_pos.longitude_deg}); - - Telemetry::GroundTruth current_pos = _telemetry->ground_truth(); - CHECK(std::isfinite(current_pos.latitude_deg)); - CHECK(std::isfinite(current_pos.longitude_deg)); - GlobalCoordinate global_current; - global_current.latitude_deg = current_pos.latitude_deg; - global_current.longitude_deg = current_pos.longitude_deg; - LocalCoordinate local_pos = ct.local_from_global(global_current); - const double distance_m = sqrt(sq(local_pos.north_m) + sq(local_pos.east_m)); - const bool pass = distance_m < acceptance_radius_m; - - if (!pass) { - std::cout << time_str() << "target_pos.lat: " << target_pos.latitude_deg << std::endl; - std::cout << time_str() << "target_pos.lon: " << target_pos.longitude_deg << std::endl; - std::cout << time_str() << "current.lat: " << current_pos.latitude_deg << std::endl; - std::cout << time_str() << "current.lon: " << current_pos.longitude_deg << std::endl; - std::cout << time_str() << "Distance: " << distance_m << std::endl; - std::cout << time_str() << "Acceptance radius: " << acceptance_radius_m << std::endl; - } - - return pass; -} - -bool AutopilotTester::ground_truth_horizontal_position_far_from(const Telemetry::GroundTruth &target_pos, - float min_distance_m) -{ - CHECK(std::isfinite(target_pos.latitude_deg)); - CHECK(std::isfinite(target_pos.longitude_deg)); - using GlobalCoordinate = CoordinateTransformation::GlobalCoordinate; - using LocalCoordinate = CoordinateTransformation::LocalCoordinate; - CoordinateTransformation ct(GlobalCoordinate{target_pos.latitude_deg, target_pos.longitude_deg}); - - Telemetry::GroundTruth current_pos = _telemetry->ground_truth(); - CHECK(std::isfinite(current_pos.latitude_deg)); - CHECK(std::isfinite(current_pos.longitude_deg)); - GlobalCoordinate global_current; - global_current.latitude_deg = current_pos.latitude_deg; - global_current.longitude_deg = current_pos.longitude_deg; - LocalCoordinate local_pos = ct.local_from_global(global_current); - const double distance_m = sqrt(sq(local_pos.north_m) + sq(local_pos.east_m)); - const bool pass = distance_m > min_distance_m; - - if (!pass) { - std::cout << time_str() << "target_pos.lat: " << target_pos.latitude_deg << std::endl; - std::cout << time_str() << "target_pos.lon: " << target_pos.longitude_deg << std::endl; - std::cout << time_str() << "current.lat: " << current_pos.latitude_deg << std::endl; - std::cout << time_str() << "current.lon: " << current_pos.longitude_deg << std::endl; - std::cout << time_str() << "Distance: " << distance_m << std::endl; - std::cout << time_str() << "Min distance: " << min_distance_m << std::endl; - } - - return pass; -} - -void AutopilotTester::start_and_wait_for_mission_sequence(int sequence_number) -{ - REQUIRE(_mission->start_mission() == Mission::Result::Success); - REQUIRE(poll_condition_with_timeout( - [this, sequence_number]() { - return _mission->mission_progress().current >= sequence_number; - }, std::chrono::seconds(60))); -} - -void AutopilotTester::start_and_wait_for_mission_sequence_raw(int sequence_number) -{ - auto prom = std::promise {}; - auto fut = prom.get_future(); - // Guards against bunched progress events (e.g. under high sim speed factor) firing the - // callback twice before unsubscribe takes effect, which would set the promise twice. - std::atomic done{false}; - - MissionRaw::MissionProgressHandle handle = _mission_raw->subscribe_mission_progress( - [&prom, &handle, &done, this, sequence_number](MissionRaw::MissionProgress progress) { - std::cout << time_str() << "Progress: " << progress.current << "/" << progress.total << std::endl; - - if (progress.current >= sequence_number && !done.exchange(true)) { - _mission_raw->unsubscribe_mission_progress(handle); - prom.set_value(); - } - }); - - REQUIRE(_mission_raw->start_mission() == MissionRaw::Result::Success); - - REQUIRE(fut.wait_for(std::chrono::seconds(60)) == std::future_status::ready); -} - -void AutopilotTester::wait_for_flight_mode(Telemetry::FlightMode flight_mode, std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [this, flight_mode]() { - return _telemetry->flight_mode() == flight_mode; - }, timeout)); -} - -void AutopilotTester::wait_for_landed_state(Telemetry::LandedState landed_state, std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [this, landed_state]() { - return _telemetry->landed_state() == landed_state; - }, timeout)); -} - -void AutopilotTester::wait_until_speed_lower_than(float speed, std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [this, speed]() { - auto vel = _telemetry->position_velocity_ned().velocity; - return std::sqrt(vel.north_m_s * vel.north_m_s + - vel.east_m_s * vel.east_m_s + - vel.down_m_s * vel.down_m_s) < speed; - }, timeout)); -} - -void AutopilotTester::wait_for_mission_finished(std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [ = ]() { - auto result = _mission->is_mission_finished(); - return result.first == Mission::Result::Success && result.second; - }, timeout)); -} - -void AutopilotTester::wait_for_mission_raw_finished(std::chrono::seconds timeout) -{ - REQUIRE(poll_condition_with_timeout( - [ = ]() { - auto result = _mission_raw->is_mission_finished(); - return result.first == MissionRaw::Result::Success && result.second; - }, timeout)); -} - -void AutopilotTester::move_mission_raw_here(std::vector &mission_items) -{ - const auto position = _telemetry->position(); - REQUIRE(std::isfinite(position.latitude_deg)); - REQUIRE(std::isfinite(position.longitude_deg)); - - auto offset_x = mission_items[0].x - static_cast(1e7 * position.latitude_deg); - auto offset_y = mission_items[0].y - static_cast(1e7 * position.longitude_deg); - - for (auto &item : mission_items) { - if (item.frame == 3) { // MAV_FRAME_GLOBAL_RELATIVE_ALT - item.x -= offset_x; - } - - item.y -= offset_y; - } -} - -void AutopilotTester::report_speed_factor() -{ - // We check the exit flag more often than the speed factor. - unsigned counter = 0; - - while (!_should_exit) { - if (counter++ % 10 == 0) { - if (_info != nullptr) { - std::cout << "Current speed factor: " << _info->get_speed_factor().second ; - - if (speed_factor.has_value()) { - std::cout << " (set: " << speed_factor.value() << ')'; - } - - std::cout << std::endl; - } - } - - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } -} - -void AutopilotTester::enable_fixedwing_mectrics() -{ - CHECK(getTelemetry()->set_rate_fixedwing_metrics(10.f) == Telemetry::Result::Success); -} - -void AutopilotTester::check_airspeed_is_valid() -{ - // If the airspeed was invalidated during the flight, the airspeed is sent in the - // telemetry is NAN and stays so with the default parameter settings. - const Telemetry::FixedwingMetrics &metrics = getTelemetry()->fixedwing_metrics(); - REQUIRE(std::isfinite(metrics.airspeed_m_s)); -} - -void AutopilotTester::check_airspeed_is_invalid() -{ - // If the airspeed was invalidated during the flight, the airspeed is sent in the - // telemetry is NAN and stays so with the default parameter settings. - const Telemetry::FixedwingMetrics &metrics = getTelemetry()->fixedwing_metrics(); - std::cout << "Reported airspeed after failure: " << metrics.airspeed_m_s ; - REQUIRE(!std::isfinite(metrics.airspeed_m_s)); -} diff --git a/test/mavsdk_tests/autopilot_tester.h b/test/mavsdk_tests/autopilot_tester.h deleted file mode 100644 index f0d44edbedc..00000000000 --- a/test/mavsdk_tests/autopilot_tester.h +++ /dev/null @@ -1,323 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "catch2/catch.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -extern std::string connection_url; -extern std::optional speed_factor; - -using namespace mavsdk; -using namespace mavsdk::geometry; - - -inline std::string time_str() -{ - time_t rawtime; - time(&rawtime); - struct tm *timeinfo = localtime(&rawtime); - char time_buffer[18]; - strftime(time_buffer, 18, "[%I:%M:%S|Info ] ", timeinfo); - return time_buffer; -} - -class AutopilotTester -{ -public: - struct MissionOptions { - double leg_length_m {20.0}; - double relative_altitude_m {10.0}; - bool rtl_at_end {false}; - bool fly_through {false}; - }; - - enum class HeightSource { - Baro, - Gps - }; - - enum class RcLossException { - Mission = 0, - Hold = 1, - Offboard = 2 - }; - - AutopilotTester(); - ~AutopilotTester(); - - void connect(const std::string uri); - - /** - * @brief Wait until vehicle's system status is healthy & is able to arm - */ - void wait_until_ready(); - - void store_home(); - void check_home_within(float acceptance_radius_m); - void check_home_not_within(float min_distance_m); - void set_takeoff_altitude(const float altitude_m); - void set_rtl_altitude(const float altitude_m); - void set_height_source(HeightSource height_source); - void set_rc_loss_exception(RcLossException mask); - void set_param_vt_fwd_thrust_en(int value); - void arm(); - void takeoff(); - void land(); - void transition_to_fixedwing(); - void transition_to_multicopter(); - void wait_until_multicopter(std::chrono::seconds timeout); - void wait_until_disarmed(std::chrono::seconds timeout_duration = std::chrono::seconds(60)); - void wait_until_hovering(); // TODO: name suggests, that function waits for drone velocity to be zero and not just drone in the air - void wait_until_altitude(float rel_altitude_m, std::chrono::seconds timeout, float delta = 0.5f); - void wait_until_fixedwing(std::chrono::seconds timeout); - void wait_until_speed_lower_than(float speed, std::chrono::seconds timeout); - void prepare_square_mission(MissionOptions mission_options); - void prepare_straight_mission(MissionOptions mission_options); - void execute_mission(); - void execute_mission_and_lose_gps(); - void execute_mission_and_lose_mag(); - void execute_mission_and_get_mag_stuck(); - void execute_mission_and_lose_baro(); - void execute_mission_and_get_baro_stuck(); - void load_qgc_mission_raw_and_move_here(const std::string &plan_file); - void execute_mission_raw(); - // Build and upload a multicopter mission (relative to home) that contains a DO_JUMP item looping - // back to an earlier waypoint. The mission lands at the end so it terminates on its own. Returns - // the sequence index of the DO_JUMP item. - int prepare_multicopter_mission_with_do_jump(const MissionOptions &mission_options, int jump_repeats); - // Start the (raw) mission and block until the vehicle reaches the given sequence number. - void start_mission_raw_and_wait_for_sequence(int sequence_number); - // Send MISSION_SET_CURRENT for the given sequence index (mimics an operator/GCS command). - void send_set_current_mission_item(int index); - void execute_rtl(); - void execute_land(); - void offboard_goto(const Offboard::PositionNedYaw &target, float acceptance_radius_m = 0.3f, - std::chrono::seconds timeout_duration = std::chrono::seconds(60)); - void offboard_land(); - void fly_forward_in_posctl(); - void fly_forward_in_altctl(); - void fly_forward_in_offboard_attitude(); - void request_ground_truth(); - void check_mission_item_speed_above(int item_index, float min_speed_m_s); - void check_tracks_mission(float corridor_radius_m = 1.5f); - void check_tracks_mission_raw(float corridor_radius_m = 1.f, bool reverse = false); - void check_mission_land_within(float acceptance_radius_m); - void start_checking_altitude(const float max_deviation_m); - void stop_checking_altitude(); - void check_current_altitude(float target_rel_altitude_m, float max_distance_m = 1.5f); - void execute_rtl_when_reaching_mission_sequence(int sequence_number); - void send_custom_mavlink_command(const MavlinkPassthrough::CommandInt &command); - void add_mavlink_message_callback(uint16_t message_id, std::function< void(const mavlink_message_t &)> callback); - - mavlink_home_position_t get_home_position(std::chrono::seconds timeout = std::chrono::seconds(10)); - - Telemetry::EulerAngle get_attitude_euler(); - - void enable_fixedwing_mectrics(); - void check_airspeed_is_valid(); - void check_airspeed_is_invalid(); - - // Blocking call to get the drone's current position in NED frame - std::array get_current_position_ned(); - - void set_param_int(const std::string ¶m, int32_t value) - { - CHECK(_param->set_param_int(param, value) == Param::Result::Success); - } - - template - void sleep_for(std::chrono::duration duration) - { - const std::chrono::microseconds duration_us(duration); - - if (_telemetry && _telemetry->attitude_quaternion().timestamp_us != 0) { - - const int64_t start_time_us = _telemetry->attitude_quaternion().timestamp_us; - - while (true) { - // Hopefully this is often enough not to have PX4 time out on us. - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - - const int64_t elapsed_time_us = _telemetry->attitude_quaternion().timestamp_us - start_time_us; - - if (elapsed_time_us > duration_us.count()) { - return; - } - } - - } else { - std::this_thread::sleep_for(duration); - } - } - -protected: - mavsdk::Action *getAction() const { return _action.get();} - mavsdk::Param *getParams() const { return _param.get();} - mavsdk::Telemetry *getTelemetry() const { return _telemetry.get();} - mavsdk::MissionRaw *getMissionRaw() const { return _mission_raw.get();} - mavsdk::ManualControl *getManualControl() const { return _manual_control.get();} - MavlinkPassthrough *getMavlinkPassthrough() const { return _mavlink_passthrough.get();} - std::shared_ptr get_system() { return _mavsdk.systems().at(0);} - mavsdk::geometry::CoordinateTransformation get_coordinate_transformation(); - bool ground_truth_horizontal_position_close_to(const Telemetry::GroundTruth &target_pos, float acceptance_radius_m); - - const Telemetry::GroundTruth &getHome() - { - // Check if home was stored before it is accessed - CHECK(_home.absolute_altitude_m != NAN); - CHECK(_home.latitude_deg != NAN); - CHECK(_home.longitude_deg != NAN); - return _home; - } - -private: - void start_offboard_with_retry(const std::function &resend_setpoint); - - mavsdk::Mission::MissionItem create_mission_item( - const mavsdk::geometry::CoordinateTransformation::LocalCoordinate &local_coordinate, - const MissionOptions &mission_options, - const mavsdk::geometry::CoordinateTransformation &ct); - - bool ground_truth_horizontal_position_far_from(const Telemetry::GroundTruth &target_pos, float min_distance_m); - bool estimated_position_close_to(const Offboard::PositionNedYaw &target_pos, float acceptance_radius_m); - bool estimated_horizontal_position_close_to(const Offboard::PositionNedYaw &target_pos, float acceptance_radius_m); - void start_and_wait_for_mission_sequence(int sequence_number); - void start_and_wait_for_mission_sequence_raw(int sequence_number); - void wait_for_flight_mode(Telemetry::FlightMode flight_mode, std::chrono::seconds timeout); - void wait_for_landed_state(Telemetry::LandedState landed_state, std::chrono::seconds timeout); - void wait_for_mission_finished(std::chrono::seconds timeout); - void wait_for_mission_raw_finished(std::chrono::seconds timeout); - void move_mission_raw_here(std::vector &mission_items); - - void report_speed_factor(); - - /** - * @brief Continue polling until condition returns true or we have a timeout - * - * @param fun Boolean returning function. When true, the polling terminates. - * @param duration Timeout for polling in `std::chrono::` time unit - */ - template - bool poll_condition_with_timeout( - std::function fun, std::chrono::duration duration) - { - static constexpr unsigned check_resolution = 100; - - const std::chrono::microseconds duration_us(duration); - - if (_telemetry && _telemetry->attitude_quaternion().timestamp_us != 0) { - // A system is connected. We can base the timeouts on the autopilot time. - const int64_t start_time_us = _telemetry->attitude_quaternion().timestamp_us; - - while (!fun()) { - std::this_thread::sleep_for(duration_us / check_resolution); - - // This might potentially loop forever and the test needs to be killed by a watchdog outside. - // The reason not to include an absolute timeout here is that it can happen if the host is - // busy and PX4 doesn't run fast enough. - const int64_t elapsed_time_us = _telemetry->attitude_quaternion().timestamp_us - start_time_us; - - if (elapsed_time_us > duration_us.count()) { - std::cout << time_str() << "Timeout, connected to vehicle but waiting for test for " << static_cast - (elapsed_time_us) / 1e6 << " seconds\n"; - return false; - } - } - - } else { - // Nothing is connected yet. Use the host time. - const auto start_time = std::chrono::steady_clock::now(); - - while (!fun()) { - std::this_thread::sleep_for(duration_us / check_resolution); - const auto elapsed_time_us = std::chrono::duration_cast(std::chrono::steady_clock::now() - - start_time); - - if (elapsed_time_us > duration_us) { - std::cout << time_str() << "Timeout, waiting for the vehicle for " - << elapsed_time_us.count() * std::chrono::steady_clock::period::num - / static_cast(std::chrono::steady_clock::period::den) - << " seconds\n"; - return false; - } - } - } - - return true; - } - - - mavsdk::Mavsdk _mavsdk{Mavsdk::Configuration{ComponentType::GroundStation}}; - std::unique_ptr _action{}; - std::unique_ptr _failure{}; - std::unique_ptr _info{}; - std::unique_ptr _manual_control{}; - std::unique_ptr _mavlink_passthrough; - std::unique_ptr _mission{}; - std::unique_ptr _mission_raw{}; - std::unique_ptr _offboard{}; - std::unique_ptr _param{}; - std::unique_ptr _telemetry{}; - std::unique_ptr _events{}; - - Telemetry::GroundTruth _home{NAN, NAN, NAN}; - - mavsdk::Telemetry::PositionVelocityNedHandle _check_altitude_handle{}; - - std::atomic _should_exit {false}; - std::thread _real_time_report_thread {}; - - mavsdk::Events::EventsHandle _events_handle{}; -}; diff --git a/test/mavsdk_tests/autopilot_tester.py b/test/mavsdk_tests/autopilot_tester.py new file mode 100644 index 00000000000..b3f8f6c6f82 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester.py @@ -0,0 +1,1097 @@ +"""Helper around MAVSDK to drive PX4 through integration tests. + +Timeouts and sleeps are in autopilot (simulation) time once a vehicle is connected, so tests +behave the same at any simulation speed factor. + +Telemetry callbacks run on a MAVSDK thread, where a failed assert would only be printed and +swallowed. Checks done in callbacks are therefore collected with check_in_callback() and +reported when the tester is closed. +""" + +import datetime +import json +import math +import os +import threading +import time +from dataclasses import dataclass +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Tuple + +from mavsdk import ComponentType, Configuration, ConnectionResult, Mavsdk # type: ignore +from mavsdk.plugins.action import Action, ActionError # type: ignore +from mavsdk.plugins.events import Events # type: ignore +from mavsdk.plugins.failure import Failure, FailureError, FailureResult # type: ignore +from mavsdk.plugins.ftp import Ftp, FtpResult # type: ignore +from mavsdk.plugins.info import Info, InfoError # type: ignore +from mavsdk.plugins.manual_control import ManualControl # type: ignore +from mavsdk.plugins.mavlink_direct import MavlinkDirect, MavlinkMessage # type: ignore +from mavsdk.plugins.mission import Mission, MissionError, MissionItem, MissionPlan # type: ignore +from mavsdk.plugins.mission_raw import ( # type: ignore + MissionItem as RawMissionItem, MissionRaw, MissionRawError) +from mavsdk.plugins.offboard import ( # type: ignore + Attitude, Offboard, OffboardError, PositionNedYaw, VelocityNedYaw) +from mavsdk.plugins.param import Param # type: ignore +from mavsdk.plugins.telemetry import FlightMode, LandedState, Telemetry, VtolState # type: ignore + +from geometry import CoordinateTransformation, Vec3, point_to_line_distance + +# Only print the first few callback check failures, they can come at telemetry rate. +MAX_PRINTED_CALLBACK_FAILURES = 10 + +# MAVLink constants used in raw mission items and messages. +MAV_CMD_NAV_WAYPOINT = 16 +MAV_CMD_NAV_LAND = 21 +MAV_CMD_NAV_TAKEOFF = 22 +MAV_CMD_NAV_VTOL_LAND = 85 +MAV_CMD_DO_JUMP = 177 +MAV_CMD_REQUEST_MESSAGE = 512 +MAV_FRAME_GLOBAL_INT = 5 +MAV_FRAME_GLOBAL_RELATIVE_ALT = 3 +MAV_FRAME_MISSION = 2 +MAV_MISSION_TYPE_MISSION = 0 +MAV_COMP_ID_AUTOPILOT1 = 1 +MAVLINK_MSG_ID_HOME_POSITION = 242 +MAV_RESULT_ACCEPTED = 0 +MAV_RESULT_IN_PROGRESS = 5 + +# Like MAVSDK's command sender, but in host time with a longer timeout for sanitizer builds. +COMMAND_ACK_TIMEOUT_S = 1.0 +COMMAND_ATTEMPTS = 3 + +# Frames in which x/y of a raw mission item are latitude/longitude. +MAV_GLOBAL_FRAMES = (0, 3, 5, 6, 10, 11) + +MANUAL_CONTROL_RATE_HZ = 50 +OFFBOARD_RATE_HZ = 50 + + +TEST_DIR = os.path.dirname(os.path.abspath(__file__)) + + +def plan_file(name: str) -> str: + """Path of a QGC .plan file next to the tests.""" + return os.path.join(TEST_DIR, name) + + +def raw_mission_item(seq: int, command: int, frame: int, x: int = 0, y: int = 0, z: float = 0.0, + param1: float = 0.0, param2: float = 0.0, current: int = 0, + autocontinue: int = 1, mission_type: int = MAV_MISSION_TYPE_MISSION) -> Any: + return RawMissionItem( + seq=seq, frame=frame, command=command, current=current, autocontinue=autocontinue, + param1=param1, param2=param2, param3=0.0, param4=0.0, x=x, y=y, z=z, + mission_type=mission_type) + + +def raw_item_local(item: Any, ct: CoordinateTransformation) -> Vec3: + """Local NED position of a raw mission item in a global frame.""" + north_m, east_m = ct.local_from_global(item.x / 1e7, item.y / 1e7) + return north_m, east_m, -item.z + + +def log(message: str) -> None: + timestamp = datetime.datetime.now().strftime("%H:%M:%S") + print("[{}|Info ] {}".format(timestamp, message), flush=True) + + +@dataclass +class MissionOptions: + leg_length_m: float = 20.0 + relative_altitude_m: float = 10.0 + rtl_at_end: bool = False + fly_through: bool = False + + +class HeightSource(Enum): + BARO = 0 + GPS = 1 + + +class RcLossException(Enum): + MISSION = 0 + HOLD = 1 + OFFBOARD = 2 + + +class AutopilotTester: + + def __init__(self, speed_factor: Optional[float] = None) -> None: + self._speed_factor = speed_factor + self._mavsdk: Any = None + self._system: Any = None + self._action: Any = None + self._events: Any = None + self._failure: Any = None + self._ftp: Any = None + self._info: Any = None + self._manual_control: Any = None + self._mavlink_direct: Any = None + self._mission: Any = None + self._mission_raw: Any = None + self._offboard: Any = None + self._param: Any = None + self._telemetry: Any = None + + self._home: Optional[Tuple[float, float]] = None + self._home_altitude_m: Optional[float] = None + self._check_altitude_handle: Any = None + + self._failures_lock = threading.Lock() + self._callback_failures: List[str] = [] + + self._retired_subscriptions: List[Any] = [] + + self._should_exit = threading.Event() + self._speed_factor_thread = threading.Thread(target=self._report_speed_factor, daemon=True) + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + def connect(self, url: str) -> None: + self._mavsdk = Mavsdk(Configuration.create_with_component_type( + ComponentType.GROUND_STATION)) + result = self._mavsdk.add_any_connection(url) + assert result == ConnectionResult.SUCCESS, \ + "Connecting to {} failed: {}".format(url, result) + + log("Waiting for system connect") + system = self._mavsdk.first_autopilot(timeout_s=25.0) + assert system is not None, "No autopilot found within 25 s" + self._system = system + + self._action = Action(system) + self._events = Events(system) + self._failure = Failure(system) + self._ftp = Ftp(system) + self._info = Info(system) + self._manual_control = ManualControl(system) + self._mavlink_direct = MavlinkDirect(system) + self._mission = Mission(system) + self._mission_raw = MissionRaw(system) + self._offboard = Offboard(system) + self._param = Param(system) + self._telemetry = Telemetry(system) + + self._events.subscribe_events(self._print_event) + self._speed_factor_thread.start() + + def close(self) -> List[str]: + """Shut down MAVSDK and return the checks that failed in callbacks.""" + self._should_exit.set() + if self._speed_factor_thread.is_alive(): + self._speed_factor_thread.join() + + if self._mavsdk is not None: + # Also releases the plugins and their subscriptions. + self._mavsdk.destroy() + self._mavsdk = None + self._retired_subscriptions.clear() + + with self._failures_lock: + failures = list(self._callback_failures) + + if len(failures) > MAX_PRINTED_CALLBACK_FAILURES: + log("{} checks failed in callbacks in total".format(len(failures))) + return failures + + # ------------------------------------------------------------------ + # Checks and waiting + # ------------------------------------------------------------------ + + def unsubscribe(self, plugin: Any, unsubscribe: Callable[[Any], None], handle: Any) -> None: + """Unsubscribe a MAVSDK subscription. + + Workaround: up to MAVSDK-Python 4.0.6, unsubscribe_*() releases the callback trampoline + before the C unsubscribe returns, so a callback in flight can crash the process. Keep the + subscription entry until the tester is closed. Remove once the pin includes the fix. + """ + self._retired_subscriptions.append(plugin._subscriptions.get(handle)) + unsubscribe(handle) + + def check_in_callback(self, ok: bool, message: str) -> None: + """Record a failed check from a MAVSDK callback thread.""" + if ok: + return + with self._failures_lock: + self._callback_failures.append(message) + count = len(self._callback_failures) + if count <= MAX_PRINTED_CALLBACK_FAILURES: + log("Check failed: {}".format(message)) + + def _autopilot_time_us(self) -> int: + if self._telemetry is None: + return 0 + return int(self._telemetry.attitude_quaternion().timestamp_us) + + def poll_condition_with_timeout(self, condition: Callable[[], bool], timeout_s: float) -> bool: + """Poll until condition() is true. Return False on timeout. + + Once a vehicle is connected the timeout is in autopilot time. There is deliberately no + wall-clock limit on top: a busy host can slow PX4 down, and the runner has its own + per-test timeout. + """ + check_interval_s = min(timeout_s / 100.0, 0.02) + start_us = self._autopilot_time_us() + + if start_us != 0: + while not condition(): + time.sleep(check_interval_s) + elapsed_s = (self._autopilot_time_us() - start_us) / 1e6 + if elapsed_s > timeout_s: + log("Timeout, connected to vehicle but waiting for test for {:.1f} seconds" + .format(elapsed_s)) + # It might have become true while sleeping. + return condition() + else: + start = time.monotonic() + while not condition(): + time.sleep(check_interval_s) + elapsed_s = time.monotonic() - start + if elapsed_s > timeout_s: + log("Timeout, waiting for the vehicle for {:.1f} seconds".format(elapsed_s)) + return condition() + return True + + def sleep_for(self, duration_s: float) -> None: + """Sleep in autopilot time (host time if nothing is connected).""" + start_us = self._autopilot_time_us() + if start_us == 0: + time.sleep(duration_s) + return + + while (self._autopilot_time_us() - start_us) / 1e6 < duration_s: + # Often enough not to have PX4 time out on us. + time.sleep(0.001) + + def wait_until_ready(self) -> None: + log("Waiting for system to be ready (system health ok & able to arm)") + assert self.poll_condition_with_timeout( + lambda: bool(self._telemetry.health_all_ok()), 30), "System health not ok" + + # health_all_ok() can be true before the global position is considered valid (MAVSDK + # issue #1852). Waiting for is_armable covers that, since arming needs a valid global + # position. + assert self.poll_condition_with_timeout( + lambda: bool(self._telemetry.health().is_armable), 45), "System not armable" + + def wait_until_disarmed(self, timeout_s: float = 60) -> None: + assert self.poll_condition_with_timeout( + lambda: not self._telemetry.armed(), timeout_s), \ + "Not disarmed within {} s".format(timeout_s) + + def wait_until_hovering(self) -> None: + self.wait_for_landed_state(LandedState.IN_AIR, 45) + + def wait_until_altitude(self, rel_altitude_m: float, timeout_s: float, + delta: float = 0.5) -> None: + def reached() -> bool: + down_m = float(self._telemetry.position_velocity_ned().position.down_m) + return abs(rel_altitude_m + down_m) <= delta + + assert self.poll_condition_with_timeout(reached, timeout_s), \ + "Altitude {} m (+-{} m) not reached within {} s".format( + rel_altitude_m, delta, timeout_s) + + def wait_until_multicopter(self, timeout_s: float) -> None: + assert self.poll_condition_with_timeout( + lambda: self._telemetry.vtol_state() == VtolState.MC, timeout_s), \ + "Not in multicopter mode within {} s".format(timeout_s) + + def wait_until_fixedwing(self, timeout_s: float) -> None: + assert self.poll_condition_with_timeout( + lambda: self._telemetry.vtol_state() == VtolState.FW, timeout_s), \ + "Not in fixed-wing mode within {} s".format(timeout_s) + + def wait_until_speed_lower_than(self, speed_m_s: float, timeout_s: float) -> None: + def slow_enough() -> bool: + vel = self._telemetry.position_velocity_ned().velocity + speed = math.sqrt(vel.north_m_s ** 2 + vel.east_m_s ** 2 + vel.down_m_s ** 2) + return bool(speed < speed_m_s) + + assert self.poll_condition_with_timeout(slow_enough, timeout_s), \ + "Speed not below {} m/s within {} s".format(speed_m_s, timeout_s) + + def wait_for_flight_mode(self, flight_mode: FlightMode, timeout_s: float) -> None: + assert self.poll_condition_with_timeout( + lambda: self._telemetry.flight_mode() == flight_mode, timeout_s), \ + "Flight mode {} not reached within {} s".format(flight_mode, timeout_s) + + def wait_for_landed_state(self, landed_state: LandedState, timeout_s: float) -> None: + assert self.poll_condition_with_timeout( + lambda: self._telemetry.landed_state() == landed_state, timeout_s), \ + "Landed state {} not reached within {} s".format(landed_state, timeout_s) + + # ------------------------------------------------------------------ + # Parameters and settings + # ------------------------------------------------------------------ + + def set_param_int(self, name: str, value: int) -> None: + self._param.set_param_int(name, value) + + def set_param_float(self, name: str, value: float) -> None: + self._param.set_param_float(name, value) + + def get_param_float(self, name: str) -> float: + return float(self._param.get_param_float(name)) + + def get_all_params(self) -> Any: + """All parameters, downloaded with the PARAM_VALUE stream.""" + return self._param.get_all_params() + + def set_takeoff_altitude(self, altitude_m: float) -> None: + self._action.set_takeoff_altitude(altitude_m) + actual = float(self._action.get_takeoff_altitude()) + assert math.isclose(actual, altitude_m, rel_tol=1e-5), \ + "Takeoff altitude is {}, expected {}".format(actual, altitude_m) + + def set_rtl_altitude(self, altitude_m: float) -> None: + self._action.set_return_to_launch_altitude(altitude_m) + actual = float(self._action.get_return_to_launch_altitude()) + assert math.isclose(actual, altitude_m, rel_tol=1e-5), \ + "RTL altitude is {}, expected {}".format(actual, altitude_m) + + def set_height_source(self, height_source: HeightSource) -> None: + self.set_param_int("EKF2_HGT_REF", height_source.value) + + def set_rc_loss_exception(self, exception: RcLossException) -> None: + self.set_param_int("COM_RCL_EXCEPT", 1 << exception.value) + + # ------------------------------------------------------------------ + # Actions + # ------------------------------------------------------------------ + + def arm(self) -> None: + # Even after wait_until_ready() passes, is_armable can briefly flicker (e.g. the + # heading reference dropping out during startup), so the arm command gets denied. + # Retry until it is accepted. + def try_arm() -> bool: + try: + self._action.arm() + return True + except ActionError as e: + log("Arming failed: {}".format(e)) + return False + + assert self.poll_condition_with_timeout(try_arm, 30), "Could not arm within 30 s" + + def takeoff(self) -> None: + self._action.takeoff() + + def land(self) -> None: + self._action.land() + + def execute_land(self) -> None: + self._action.land() + + def execute_rtl(self) -> None: + self._action.return_to_launch() + + def transition_to_fixedwing(self) -> None: + self._action.transition_to_fixedwing() + + def transition_to_multicopter(self) -> None: + self._action.transition_to_multicopter() + + def hold(self) -> None: + self._action.hold() + + # ------------------------------------------------------------------ + # Failure injection + # ------------------------------------------------------------------ + + def inject_failure(self, unit: Any, failure_type: Any, instance: int = 0, + expected_result: Any = FailureResult.SUCCESS) -> None: + """Inject a failure. Needs SYS_FAILURE_EN to be set to succeed.""" + try: + self._failure.inject(unit, failure_type, instance) + result = FailureResult.SUCCESS + except FailureError as e: + result = e.result + assert result == expected_result, \ + "Failure injection returned {}, expected {}".format(result, expected_result) + + def enable_actuator_output_status(self) -> None: + self._telemetry.set_rate_actuator_output_status(20.0) + + def ensure_motors_stopped(self, stopped_mask: int, num_motors: int) -> None: + """Check that exactly the motors in stopped_mask (0-based bits) are stopped.""" + status = self._telemetry.actuator_output_status() + assert status.active >= num_motors, \ + "Only {} actuators active, expected {}".format(status.active, num_motors) + + for i in range(num_motors): + if stopped_mask & (1 << i): + assert status.actuator[i] <= 901.0, \ + "Motor {} output {}, expected stopped".format(i, status.actuator[i]) + else: + assert status.actuator[i] >= 999.0, \ + "Motor {} output {}, expected running".format(i, status.actuator[i]) + + # ------------------------------------------------------------------ + # Position and home + # ------------------------------------------------------------------ + + def request_ground_truth(self) -> None: + self._telemetry.set_rate_ground_truth(15) + + def store_home(self) -> None: + self.request_ground_truth() + log("Waiting to get home position") + + def got_home() -> bool: + gt = self._telemetry.ground_truth() + if math.isfinite(gt.latitude_deg) and math.isfinite(gt.longitude_deg): + self._home = (float(gt.latitude_deg), float(gt.longitude_deg)) + self._home_altitude_m = float(gt.absolute_altitude_m) + return True + return False + + assert self.poll_condition_with_timeout(got_home, 10), "No ground truth position received" + + def _home_or_fail(self) -> Tuple[float, float]: + assert self._home is not None, "store_home() was not called" + return self._home + + def home_absolute_altitude_m(self) -> float: + assert self._home_altitude_m is not None, "store_home() was not called" + return self._home_altitude_m + + def check_home_within(self, acceptance_radius_m: float) -> None: + distance_m = self._ground_truth_horizontal_distance_to(*self._home_or_fail()) + assert distance_m < acceptance_radius_m, \ + "Distance to home {:.2f} m, expected < {} m".format(distance_m, acceptance_radius_m) + + def check_home_not_within(self, min_distance_m: float) -> None: + distance_m = self._ground_truth_horizontal_distance_to(*self._home_or_fail()) + assert distance_m > min_distance_m, \ + "Distance to home {:.2f} m, expected > {} m".format(distance_m, min_distance_m) + + def _ground_truth_horizontal_distance_to(self, latitude_deg: float, + longitude_deg: float) -> float: + assert math.isfinite(latitude_deg) and math.isfinite(longitude_deg) + current = self._telemetry.ground_truth() + assert math.isfinite(current.latitude_deg) and math.isfinite(current.longitude_deg), \ + "No ground truth position" + + ct = CoordinateTransformation(latitude_deg, longitude_deg) + north_m, east_m = ct.local_from_global(current.latitude_deg, current.longitude_deg) + distance_m = math.hypot(north_m, east_m) + log("Target: {:.7f}, {:.7f}, current: {:.7f}, {:.7f}, distance: {:.2f} m".format( + latitude_deg, longitude_deg, current.latitude_deg, current.longitude_deg, + distance_m)) + return distance_m + + def get_current_position_ned(self) -> Vec3: + position = self._telemetry.position_velocity_ned().position + return float(position.north_m), float(position.east_m), float(position.down_m) + + def get_attitude_euler(self) -> Any: + return self._telemetry.attitude_euler() + + def get_home_position(self, timeout_s: float = 10) -> Dict[str, Any]: + """Request a fresh HOME_POSITION message and return its fields.""" + received: List[Dict[str, Any]] = [] + + def on_message(message: Any, _user_data: Any) -> None: + if not received: + received.append(json.loads(message.fields_json)) + + handle = self._mavlink_direct.subscribe_message("HOME_POSITION", on_message) + try: + # Ask for it rather than relying on the periodic stream timing. + self.send_command_long(MAV_CMD_REQUEST_MESSAGE, param1=MAVLINK_MSG_ID_HOME_POSITION) + assert self.poll_condition_with_timeout(lambda: bool(received), timeout_s), \ + "No HOME_POSITION received" + finally: + self.unsubscribe(self._mavlink_direct, self._mavlink_direct.unsubscribe_message, handle) + return received[0] + + def get_coordinate_transformation(self) -> CoordinateTransformation: + home = self._telemetry.home() + assert math.isfinite(home.latitude_deg) and math.isfinite(home.longitude_deg), \ + "No home position" + return CoordinateTransformation(home.latitude_deg, home.longitude_deg) + + def check_current_altitude(self, target_rel_altitude_m: float, + max_distance_m: float = 1.5) -> None: + altitude_m = self._telemetry.position().relative_altitude_m + assert abs(altitude_m - target_rel_altitude_m) <= max_distance_m, \ + "Relative altitude {:.2f} m, expected {} m (+-{} m)".format( + altitude_m, target_rel_altitude_m, max_distance_m) + + def start_checking_altitude(self, max_deviation_m: float) -> None: + """Fail the test if the altitude deviates from the current one by more than + max_deviation_m, until stop_checking_altitude().""" + target_down_m = self.get_current_position_ned()[2] + + def check(position_velocity_ned: Any, _user_data: Any) -> None: + deviation_m = abs(target_down_m - position_velocity_ned.position.down_m) + self.check_in_callback( + deviation_m <= max_deviation_m, + "Altitude deviation {:.3f} m exceeds {} m".format(deviation_m, max_deviation_m)) + + self._check_altitude_handle = self._telemetry.subscribe_position_velocity_ned(check) + + def stop_checking_altitude(self) -> None: + if self._check_altitude_handle is not None: + self.unsubscribe(self._telemetry, self._telemetry.unsubscribe_position_velocity_ned, + self._check_altitude_handle) + self._check_altitude_handle = None + + # ------------------------------------------------------------------ + # Missions + # ------------------------------------------------------------------ + + @staticmethod + def _create_mission_item(north_m: float, east_m: float, options: MissionOptions, + ct: CoordinateTransformation) -> Any: + latitude_deg, longitude_deg = ct.global_from_local(north_m, east_m) + # All fields need to be set, the Python defaults are None. + nan = float("nan") + return MissionItem( + latitude_deg=latitude_deg, + longitude_deg=longitude_deg, + relative_altitude_m=options.relative_altitude_m, + speed_m_s=nan, + is_fly_through=options.fly_through, + gimbal_pitch_deg=nan, + gimbal_yaw_deg=nan, + camera_action=MissionItem.CameraAction.NONE, + loiter_time_s=nan, + camera_photo_interval_s=1.0, + acceptance_radius_m=nan, + yaw_deg=nan, + camera_photo_distance_m=nan, + vehicle_action=MissionItem.VehicleAction.NONE) + + def _upload_mission(self, local_positions: List[Tuple[float, float]], + options: MissionOptions) -> None: + ct = self.get_coordinate_transformation() + items = [self._create_mission_item(north_m, east_m, options, ct) + for north_m, east_m in local_positions] + + self._mission.set_return_to_launch_after_mission(options.rtl_at_end) + self._mission.upload_mission(MissionPlan(mission_items=items)) + # PX4 needs time to realize that it now has a mission available. + self.sleep_for(1) + + def prepare_square_mission(self, options: MissionOptions) -> None: + leg = options.leg_length_m + self._upload_mission([(leg, 0.0), (leg, leg), (0.0, leg)], options) + + def prepare_straight_mission(self, options: MissionOptions) -> None: + leg = options.leg_length_m + self._upload_mission([(i * leg, 0.0) for i in range(5)], options) + + def _try_start_mission(self) -> bool: + try: + self._mission.start_mission() + return True + except MissionError as e: + log("Starting mission failed: {}".format(e)) + return False + + def _is_mission_finished(self) -> bool: + try: + return bool(self._mission.is_mission_finished()) + except MissionError: + return False + + def execute_mission(self) -> None: + assert self.poll_condition_with_timeout(self._try_start_mission, 3), \ + "Could not start mission" + self.wait_for_mission_finished(500) + + def start_and_wait_for_mission_sequence(self, sequence_number: int) -> None: + self._mission.start_mission() + assert self.poll_condition_with_timeout( + lambda: self._mission.mission_progress().current >= sequence_number, 60), \ + "Mission item {} not reached within 60 s".format(sequence_number) + + def wait_for_mission_finished(self, timeout_s: float) -> None: + assert self.poll_condition_with_timeout(self._is_mission_finished, timeout_s), \ + "Mission not finished within {} s".format(timeout_s) + + def check_tracks_mission(self, corridor_radius_m: float = 1.5) -> None: + """Fail the test if the vehicle leaves the corridor around the line between the + previous and the current mission item.""" + items = self._mission.download_mission().mission_items + ct = self.get_coordinate_transformation() + + def local(item: Any) -> Vec3: + north_m, east_m = ct.local_from_global(item.latitude_deg, item.longitude_deg) + return north_m, east_m, -item.relative_altitude_m + + waypoints = [local(item) for item in items] + + def check(position_velocity_ned: Any, _user_data: Any) -> None: + progress = self._mission.mission_progress() + if not 0 < progress.current < progress.total: + return + position = position_velocity_ned.position + distance_m = point_to_line_distance( + (position.north_m, position.east_m, position.down_m), + waypoints[progress.current - 1], + waypoints[progress.current]) + self.check_in_callback( + distance_m < corridor_radius_m, + "Distance to mission track {:.2f} m exceeds {} m".format( + distance_m, corridor_radius_m)) + + self._telemetry.set_rate_position_velocity_ned(5) + self._telemetry.subscribe_position_velocity_ned(check) + + def check_tracks_mission_raw(self, corridor_radius_m: float = 1.0, + reverse: bool = False) -> None: + """Like check_tracks_mission(), for a mission uploaded with MissionRaw.""" + items = self._mission_raw.download_mission() + ct = self.get_coordinate_transformation() + waypoints = {item.seq: raw_item_local(item, ct) for item in items} + + def check(position_velocity_ned: Any, _user_data: Any) -> None: + progress = self._mission_raw.mission_progress() + if not 0 < progress.current < progress.total: + return + previous = progress.current + 1 if reverse else progress.current - 1 + position = position_velocity_ned.position + distance_m = point_to_line_distance( + (position.north_m, position.east_m, position.down_m), + waypoints.get(previous, (0.0, 0.0, 0.0)), + waypoints.get(progress.current, (0.0, 0.0, 0.0))) + self.check_in_callback( + distance_m < corridor_radius_m, + "Distance to mission track {:.2f} m exceeds {} m".format( + distance_m, corridor_radius_m)) + + self._telemetry.set_rate_position_velocity_ned(5) + self._telemetry.subscribe_position_velocity_ned(check) + + def check_mission_land_within(self, acceptance_radius_m: float) -> None: + """Check that the vehicle is close to the landing item at the end of the mission.""" + land_item = self._mission_raw.download_mission()[-1] + assert land_item.command in (MAV_CMD_NAV_LAND, MAV_CMD_NAV_VTOL_LAND), \ + "Last mission item is command {}, not a landing".format(land_item.command) + distance_m = self._ground_truth_horizontal_distance_to(land_item.x / 1e7, + land_item.y / 1e7) + assert distance_m < acceptance_radius_m, \ + "Distance to mission landing {:.2f} m, expected < {} m".format( + distance_m, acceptance_radius_m) + + def check_mission_item_speed_above(self, item_index: int, min_speed_m_s: float) -> None: + """Fail the test if the horizontal speed is not above min_speed_m_s while flying to + mission item item_index.""" + def check(velocity: Any, _user_data: Any) -> None: + if self._mission.mission_progress().current != item_index: + return + speed_m_s = math.hypot(velocity.north_m_s, velocity.east_m_s) + self.check_in_callback( + speed_m_s > min_speed_m_s, + "Speed {:.2f} m/s to mission item {} not above {} m/s".format( + speed_m_s, item_index, min_speed_m_s)) + + self._telemetry.set_rate_velocity_ned(10) + self._telemetry.subscribe_velocity_ned(check) + + # ------------------------------------------------------------------ + # Raw missions + # ------------------------------------------------------------------ + + def upload_mission_raw(self, items: List[Any]) -> None: + self._mission_raw.upload_mission(items) + # PX4 needs time to realize that it now has a mission available. + self.sleep_for(1) + + def load_qgc_mission_raw_and_move_here(self, plan_file: str) -> None: + """Upload a QGC .plan mission, shifted so that it starts at the current position.""" + items = self._mission_raw.import_qgroundcontrol_mission(plan_file).mission_items + self._move_mission_raw_here(items) + self.upload_mission_raw(items) + + def _move_mission_raw_here(self, items: List[Any]) -> None: + position = self._telemetry.position() + assert math.isfinite(position.latitude_deg) and math.isfinite(position.longitude_deg), \ + "No global position" + + offset_x = items[0].x - int(1e7 * position.latitude_deg) + offset_y = items[0].y - int(1e7 * position.longitude_deg) + for item in items: + if item.frame == MAV_FRAME_GLOBAL_RELATIVE_ALT: + item.x -= offset_x + item.y -= offset_y + + def prepare_multicopter_mission_with_do_jump(self, options: MissionOptions, + jump_repeats: int) -> int: + """Upload a mission (relative to home) with a DO_JUMP looping back to an earlier waypoint. + The mission lands at the end so it terminates on its own. Return the index of the + DO_JUMP item.""" + ct = self.get_coordinate_transformation() + altitude_m = options.relative_altitude_m + leg_m = options.leg_length_m + + def position_item(seq: int, command: int, north_m: float, east_m: float, z: float, + current: int = 0) -> Any: + latitude_deg, longitude_deg = ct.global_from_local(north_m, east_m) + return raw_mission_item(seq, command, MAV_FRAME_GLOBAL_RELATIVE_ALT, + x=round(latitude_deg * 1e7), y=round(longitude_deg * 1e7), + z=z, current=current) + + jump_index = 3 + self.upload_mission_raw([ + position_item(0, MAV_CMD_NAV_TAKEOFF, 0.0, 0.0, altitude_m, current=1), + position_item(1, MAV_CMD_NAV_WAYPOINT, leg_m, 0.0, altitude_m), + position_item(2, MAV_CMD_NAV_WAYPOINT, leg_m, leg_m, altitude_m), + raw_mission_item(jump_index, MAV_CMD_DO_JUMP, MAV_FRAME_MISSION, + param1=1.0, param2=float(jump_repeats)), + position_item(4, MAV_CMD_NAV_WAYPOINT, 0.0, leg_m, altitude_m), + position_item(5, MAV_CMD_NAV_LAND, 0.0, 0.0, 0.0), + ]) + return jump_index + + def start_mission_raw_and_wait_for_sequence(self, sequence_number: int, + timeout_s: float = 180) -> None: + self._mission_raw.start_mission() + assert self.poll_condition_with_timeout( + lambda: self._mission_raw.mission_progress().current >= sequence_number, timeout_s), \ + "Mission item {} not reached within {} s".format(sequence_number, timeout_s) + + def execute_rtl_when_reaching_mission_sequence(self, sequence_number: int, + timeout_s: float = 180) -> None: + self.start_mission_raw_and_wait_for_sequence(sequence_number, timeout_s) + self.execute_rtl() + + def execute_mission_raw(self) -> None: + self._mission_raw.start_mission() + + def finished() -> bool: + try: + return bool(self._mission_raw.is_mission_finished()) + except MissionRawError: + return False + + assert self.poll_condition_with_timeout(finished, 300), \ + "Mission not finished within 300 s" + + def send_set_current_mission_item(self, index: int) -> None: + """Send a single MISSION_SET_CURRENT, like a one-shot operator/GCS action. + + MissionRaw.set_current_mission_item() is deliberately not used: it re-sends until + MISSION_CURRENT echoes the requested seq. For a DO_JUMP item the navigator reports the + jump target instead, so MAVSDK would keep re-sending and resetting the mission. + """ + self.send_mavlink_message("MISSION_SET_CURRENT", { + "target_system": self._target_system_id(), + "target_component": MAV_COMP_ID_AUTOPILOT1, + "seq": index, + }) + + # ------------------------------------------------------------------ + # MAVLink + # ------------------------------------------------------------------ + + def _target_system_id(self) -> int: + return int(self._system.get_system_id()) + + def send_mavlink_message(self, name: str, fields: Dict[str, Any]) -> None: + # NaN is not valid JSON; MAVSDK takes null as NaN for float fields. + def nan_to_null(value: Any) -> Any: + if isinstance(value, float) and math.isnan(value): + return None + if isinstance(value, list): + return [nan_to_null(v) for v in value] + return value + + fields_json = json.dumps({k: nan_to_null(v) for k, v in fields.items()}, allow_nan=False) + # The sender IDs are filled in by MAVSDK. + self._mavlink_direct.send_message(MavlinkMessage( + message_name=name, system_id=0, component_id=0, target_system_id=0, + target_component_id=0, fields_json=fields_json)) + + def send_command_long(self, command: int, param1: float = 0.0, param2: float = 0.0, + param3: float = 0.0, param4: float = 0.0, param5: float = 0.0, + param6: float = 0.0, param7: float = 0.0, + expected_result: int = MAV_RESULT_ACCEPTED) -> None: + """Send a COMMAND_LONG and check its COMMAND_ACK.""" + self._send_command("COMMAND_LONG", { + "target_system": self._target_system_id(), + "target_component": MAV_COMP_ID_AUTOPILOT1, + "command": command, "confirmation": 0, + "param1": param1, "param2": param2, "param3": param3, "param4": param4, + "param5": param5, "param6": param6, "param7": param7, + }, expected_result) + + def send_command_int(self, command: int, param1: float = 0.0, param2: float = 0.0, + param3: float = 0.0, param4: float = 0.0, x: int = 0, y: int = 0, + z: float = 0.0, frame: int = MAV_FRAME_GLOBAL_INT, + expected_result: int = MAV_RESULT_ACCEPTED) -> None: + """Send a COMMAND_INT and check its COMMAND_ACK.""" + self._send_command("COMMAND_INT", { + "target_system": self._target_system_id(), + "target_component": MAV_COMP_ID_AUTOPILOT1, + "frame": frame, "command": command, "current": 0, "autocontinue": 0, + "param1": param1, "param2": param2, "param3": param3, "param4": param4, + "x": x, "y": y, "z": z, + }, expected_result) + + def _send_command(self, message_name: str, fields: Dict[str, Any], + expected_result: int) -> None: + """Send a command until it is acked, then check the result.""" + command = fields["command"] + results: List[int] = [] + acked = threading.Event() + + def on_ack(message: Any, _user_data: Any) -> None: + ack = json.loads(message.fields_json) + if ack["command"] == command and ack["result"] != MAV_RESULT_IN_PROGRESS: + results.append(int(ack["result"])) + acked.set() + + handle = self._mavlink_direct.subscribe_message("COMMAND_ACK", on_ack) + try: + for attempt in range(COMMAND_ATTEMPTS): + if message_name == "COMMAND_LONG": + fields["confirmation"] = attempt + self.send_mavlink_message(message_name, fields) + if acked.wait(COMMAND_ACK_TIMEOUT_S): + break + finally: + self.unsubscribe(self._mavlink_direct, self._mavlink_direct.unsubscribe_message, + handle) + + assert results, "No COMMAND_ACK for command {} after {} attempts".format( + command, COMMAND_ATTEMPTS) + assert results[0] == expected_result, \ + "Command {} result {}, expected {}".format(command, results[0], expected_result) + + # ------------------------------------------------------------------ + # Position monitors + # ------------------------------------------------------------------ + + def wait_for_position_ned(self, condition: Callable[[Any], bool], timeout_s: float, + rate_hz: float = 10.0) -> None: + """Wait until condition(position_velocity_ned) is true for a telemetry sample. Unlike + polling, this sees every sample, so a short crossing cannot be missed.""" + reached = threading.Event() + + def on_sample(sample: Any, _user_data: Any) -> None: + if condition(sample): + reached.set() + + self._telemetry.set_rate_position_velocity_ned(rate_hz) + handle = self._telemetry.subscribe_position_velocity_ned(on_sample) + try: + assert self.poll_condition_with_timeout(reached.is_set, timeout_s), \ + "Position condition not met within {} s".format(timeout_s) + finally: + self.unsubscribe(self._telemetry, self._telemetry.unsubscribe_position_velocity_ned, + handle) + + def check_position_ned_for(self, check: Callable[[Any], Optional[str]], duration_s: float, + rate_hz: float = 10.0) -> None: + """Run check(position_velocity_ned) on every sample for duration_s. It returns an error + message when the check fails, which then fails the test.""" + def on_sample(sample: Any, _user_data: Any) -> None: + error = check(sample) + self.check_in_callback(error is None, error or "") + + self._telemetry.set_rate_position_velocity_ned(rate_hz) + handle = self._telemetry.subscribe_position_velocity_ned(on_sample) + try: + self.sleep_for(duration_s) + finally: + self.unsubscribe(self._telemetry, self._telemetry.unsubscribe_position_velocity_ned, + handle) + self._assert_no_callback_failures() + + def _assert_no_callback_failures(self) -> None: + with self._failures_lock: + failures = list(self._callback_failures) + assert not failures, "{} checks failed, first: {}".format(len(failures), failures[0]) + + # ------------------------------------------------------------------ + # Fixed-wing metrics + # ------------------------------------------------------------------ + + def enable_fixedwing_metrics(self) -> None: + self._telemetry.set_rate_fixedwing_metrics(10.0) + + def check_airspeed_is_valid(self) -> None: + # Once the airspeed is invalidated, it is sent as NaN and stays so with the default + # parameters. + airspeed = self._telemetry.fixedwing_metrics().airspeed_m_s + assert math.isfinite(airspeed), "Airspeed is invalid" + + def check_airspeed_is_invalid(self) -> None: + airspeed = self._telemetry.fixedwing_metrics().airspeed_m_s + assert not math.isfinite(airspeed), "Airspeed {} m/s is still valid".format(airspeed) + + # ------------------------------------------------------------------ + # FTP + # ------------------------------------------------------------------ + + def _wait_for_ftp(self, start: Callable[[Callable[[Any, Any, Any], None]], None], + timeout_s: float) -> None: + results: List[Any] = [] + done = threading.Event() + + def on_progress(result: Any, _progress: Any, _user_data: Any) -> None: + if result != FtpResult.NEXT and not done.is_set(): + results.append(result) + done.set() + + start(on_progress) + # Host time: the transfer is not tied to the simulation. + assert done.wait(timeout_s), "FTP transfer did not finish within {} s".format(timeout_s) + assert results[0] == FtpResult.SUCCESS, "FTP transfer failed: {}".format(results[0]) + + def ftp_download(self, remote_path: str, local_dir: str, use_burst: bool = True, + timeout_s: float = 60) -> None: + self._wait_for_ftp( + lambda cb: self._ftp.download_async(remote_path, local_dir, use_burst, cb), timeout_s) + + def ftp_upload(self, local_path: str, remote_dir: str, timeout_s: float = 60) -> None: + self._wait_for_ftp( + lambda cb: self._ftp.upload_async(local_path, remote_dir, cb), timeout_s) + + # ------------------------------------------------------------------ + # Manual control + # ------------------------------------------------------------------ + + 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)): + self._manual_control.set_manual_control_input(x, y, z, r) + self.sleep_for(1.0 / MANUAL_CONTROL_RATE_HZ) + if stop_when_landed and not self._telemetry.in_air(): + return + + def _fly_forward_manually(self, start_mode: Callable[[], None]) -> None: + # Keep sending centered sticks in between so RC stays available. + self._send_manual_control(1, 0.0, 0.0, 0.5, 0.0) + start_mode() + self._send_manual_control(1, 0.0, 0.0, 0.5, 0.0) + self.store_home() + self._send_manual_control(1, 0.0, 0.0, 0.5, 0.0) + self.wait_until_ready() + self._send_manual_control(1, 0.0, 0.0, 0.5, 0.0) + self.arm() + self._send_manual_control(1, 0.0, 0.0, 0.5, 0.0) + + log("Climbing") + self._send_manual_control(5, 0.0, 0.0, 1.0, 0.0) + log("Flying forward") + self._send_manual_control(10, 0.5, 0.0, 0.5, 0.0) + log("Descending until landed") + self._send_manual_control(60, 0.0, 0.0, 0.0, 0.0, stop_when_landed=True) + + def fly_forward_in_posctl(self) -> None: + self._fly_forward_manually(self._manual_control.start_position_control) + + def fly_forward_in_altctl(self) -> None: + self._fly_forward_manually(self._manual_control.start_altitude_control) + + # ------------------------------------------------------------------ + # Offboard + # ------------------------------------------------------------------ + + def _send_attitude(self, duration_s: float, attitude: Any) -> None: + for _ in range(int(duration_s * OFFBOARD_RATE_HZ)): + self._offboard.set_attitude(attitude) + self.sleep_for(1.0 / OFFBOARD_RATE_HZ) + + def fly_forward_in_offboard_attitude(self) -> None: + # This does not depend on a valid position estimate. Wait for raw GPS and a stable + # attitude estimate. + def ready() -> bool: + attitude = self._telemetry.attitude_euler() + return bool(self._telemetry.raw_gps().altitude_ellipsoid_m > 0.0 + and abs(attitude.roll_deg) < 5.0 and abs(attitude.pitch_deg) < 5.0) + + assert self.poll_condition_with_timeout(ready, 20), "No raw GPS or attitude not stable" + start_altitude_m = float(self._telemetry.raw_gps().altitude_ellipsoid_m) + + level = Attitude(roll_deg=0.0, pitch_deg=0.0, yaw_deg=0.0, thrust_value=0.0) + self._offboard.set_attitude(level) + self._start_offboard_with_retry(lambda: self._offboard.set_attitude(level)) + + assert self.poll_condition_with_timeout( + lambda: bool(self._telemetry.health().is_armable), 20), "System not armable" + self.arm() + + log("Climbing") + climb = Attitude(roll_deg=0.0, pitch_deg=0.0, yaw_deg=0.0, thrust_value=0.8) + while self._telemetry.raw_gps().altitude_ellipsoid_m - start_altitude_m < 10.0: + self._offboard.set_attitude(climb) + self.sleep_for(1.0 / OFFBOARD_RATE_HZ) + + log("Flying forward") + forward = Attitude(roll_deg=0.0, pitch_deg=-20.0, yaw_deg=0.0, thrust_value=0.8) + self._send_attitude(3, forward) + + estimate = self._telemetry.attitude_euler() + assert abs(forward.roll_deg - estimate.roll_deg) < 5.0, \ + "Roll {:.1f} deg, expected {}".format(estimate.roll_deg, forward.roll_deg) + assert abs(forward.pitch_deg - estimate.pitch_deg) < 5.0, \ + "Pitch {:.1f} deg, expected {}".format(estimate.pitch_deg, forward.pitch_deg) + + log("Descending") + self._send_attitude(6, Attitude(roll_deg=0.0, pitch_deg=0.0, yaw_deg=0.0, + thrust_value=0.4)) + self._offboard.set_attitude(level) + + def _start_offboard_with_retry(self, resend_setpoint: Callable[[], None]) -> None: + # MAVSDK's offboard watchdog resets the setpoint state when a heartbeat without + # offboard mode arrives before the first start(). At high speed factors one can slip + # in between set_*() and start(), so start() fails with NoSetpointSet. Re-send and + # retry. + for _ in range(10): + try: + self._offboard.start() + return + except OffboardError as e: + error = e + resend_setpoint() + time.sleep(0.02) + raise error + + def offboard_goto(self, target: PositionNedYaw, acceptance_radius_m: float = 0.3, + timeout_s: float = 60) -> None: + self._offboard.set_position_ned(target) + self._start_offboard_with_retry(lambda: self._offboard.set_position_ned(target)) + + def close_enough() -> bool: + position = self._telemetry.position_velocity_ned().position + distance_m = math.sqrt((position.north_m - target.north_m) ** 2 + + (position.east_m - target.east_m) ** 2 + + (position.down_m - target.down_m) ** 2) + return bool(distance_m < acceptance_radius_m) + + assert self.poll_condition_with_timeout(close_enough, timeout_s), \ + "Offboard target not reached within {} s".format(timeout_s) + log("Target position reached") + + def offboard_land(self) -> None: + self._offboard.set_velocity_ned(VelocityNedYaw( + north_m_s=0.0, east_m_s=0.0, down_m_s=1.0, yaw_deg=0.0)) + + # ------------------------------------------------------------------ + # Internals + # ------------------------------------------------------------------ + + @staticmethod + def _print_event(event: Any, _user_data: Any) -> None: + print("[{}] {}".format(event.log_level, event.message), flush=True) + if event.description: + print(" Description: {}".format(event.description), flush=True) + print(" Event name: {}/{}".format(event.event_namespace, event.event_name), flush=True) + + def _report_speed_factor(self) -> None: + while not self._should_exit.wait(1.0): + try: + current = float(self._info.get_speed_factor()) + except InfoError: + continue + message = "Current speed factor: {:.2f}".format(current) + if self._speed_factor is not None: + message += " (set: {})".format(self._speed_factor) + print(message, flush=True) diff --git a/test/mavsdk_tests/autopilot_tester_failure.cpp b/test/mavsdk_tests/autopilot_tester_failure.cpp deleted file mode 100644 index 7f46269fb74..00000000000 --- a/test/mavsdk_tests/autopilot_tester_failure.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_failure.h" - -#include "math_helpers.h" -#include -#include -#include -#include - - -void AutopilotTesterFailure::connect(const std::string uri) -{ - AutopilotTester::connect(uri); - - auto system = get_system(); - _failure.reset(new Failure(system)); -} - -void AutopilotTesterFailure::set_param_sys_failure_en(bool value) -{ - CHECK(getParams()->set_param_int("SYS_FAILURE_EN", value) == Param::Result::Success); -} - -void AutopilotTesterFailure::set_param_fd_act_en(bool value) -{ - CHECK(getParams()->set_param_int("FD_ACT_EN", value) == Param::Result::Success); -} - -void AutopilotTesterFailure::set_param_mc_airmode(int value) -{ - CHECK(getParams()->set_param_int("MC_AIRMODE", value) == Param::Result::Success); -} - -void AutopilotTesterFailure::set_param_ca_failure_mode(int value) -{ - CHECK(getParams()->set_param_int("CA_FAILURE_MODE", value) == Param::Result::Success); -} - -void AutopilotTesterFailure::set_param_com_act_fail_act(int value) -{ - CHECK(getParams()->set_param_int("COM_ACT_FAIL_ACT", value) == Param::Result::Success); -} - -void AutopilotTesterFailure::inject_failure(mavsdk::Failure::FailureUnit failure_unit, - mavsdk::Failure::FailureType failure_type, int instance, mavsdk::Failure::Result expected_result) -{ - CHECK(_failure->inject(failure_unit, failure_type, instance) == expected_result); -} - -void AutopilotTesterFailure::enable_actuator_output_status() -{ - CHECK(getTelemetry()->set_rate_actuator_output_status(20.f) == Telemetry::Result::Success); -} - -void AutopilotTesterFailure::ensure_motors_stopped(uint32_t stopped_mask, unsigned num_motors) -{ - const Telemetry::ActuatorOutputStatus &status = getTelemetry()->actuator_output_status(); - CHECK(status.active >= num_motors); - - for (unsigned i = 0; i < num_motors; ++i) { - if (stopped_mask & (1u << i)) { - CHECK(status.actuator[i] <= 901.f); - - } else { // ensure all others are still running - CHECK(status.actuator[i] >= 999.f); - } - } -} diff --git a/test/mavsdk_tests/autopilot_tester_failure.h b/test/mavsdk_tests/autopilot_tester_failure.h deleted file mode 100644 index 7accbab31f0..00000000000 --- a/test/mavsdk_tests/autopilot_tester_failure.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2021 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" - -#include -#include -#include - - -class AutopilotTesterFailure : public AutopilotTester -{ -public: - AutopilotTesterFailure() = default; - ~AutopilotTesterFailure() = default; - - void set_param_sys_failure_en(bool value); - void set_param_fd_act_en(bool value); - void set_param_mc_airmode(int value); - void set_param_ca_failure_mode(int value); - void set_param_com_act_fail_act(int value); - - void enable_actuator_output_status(); - void ensure_motors_stopped(uint32_t stopped_mask, unsigned num_motors); - - void inject_failure(mavsdk::Failure::FailureUnit failure_unit, mavsdk::Failure::FailureType failure_type, int instance, - mavsdk::Failure::Result expected_result); - void connect(const std::string uri); - -private: - std::unique_ptr _failure{}; -}; diff --git a/test/mavsdk_tests/autopilot_tester_figure_eight.cpp b/test/mavsdk_tests/autopilot_tester_figure_eight.cpp deleted file mode 100644 index b855cc3ceb7..00000000000 --- a/test/mavsdk_tests/autopilot_tester_figure_eight.cpp +++ /dev/null @@ -1,177 +0,0 @@ - -/**************************************************************************** - * - * Copyright (c) 2023-2025 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_figure_eight.h" - -#include -#include -#include -#include - - -#include - - -using namespace mavsdk::geometry; - -void AutopilotTesterFigureEight::execute_figure_eight() -{ - - MavlinkPassthrough::CommandInt figure_eight_command; - - auto ct = get_coordinate_transformation(); - const auto global_center = ct.global_from_local(_figure_eight.center); - - figure_eight_command.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - figure_eight_command.target_compid = getMavlinkPassthrough()->get_target_compid(); - figure_eight_command.command = 35; // Figure eight command - figure_eight_command.frame = MAV_FRAME_GLOBAL_INT; - figure_eight_command.param1 = _figure_eight.major_axis; - figure_eight_command.param2 = _figure_eight.minor_axis; - figure_eight_command.param3 = NAN; - figure_eight_command.param4 = _figure_eight.orientation; - figure_eight_command.x = static_cast(global_center.latitude_deg * 1E7); - figure_eight_command.y = static_cast(global_center.longitude_deg * 1E7); - figure_eight_command.z = _figure_eight.alt; - - send_custom_mavlink_command(figure_eight_command); -} - -void AutopilotTesterFigureEight::set_figure_eight(const double major_axis, const double minor_axis, - const double orientation, const double home_offset_N, const double home_offset_E, const double rel_alt) -{ - _figure_eight.major_axis = major_axis; - _figure_eight.minor_axis = minor_axis; - _figure_eight.orientation = orientation; - _figure_eight.alt = getHome().absolute_altitude_m + rel_alt; - _figure_eight.center = {home_offset_N, home_offset_E}; -} - -void AutopilotTesterFigureEight::check_tracks_figure_eight(std::chrono::seconds timeout, double corridor_radius_m) -{ - auto prom = std::promise {}; - auto fut = prom.get_future(); - - const double cos_or = cos(_figure_eight.orientation); - const double sin_or = sin(_figure_eight.orientation); - - std::vector figure_eight_point_of_interest; - figure_eight_point_of_interest.push_back(_figure_eight.center); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (abs(_figure_eight.major_axis) - _figure_eight.minor_axis) - sin_or * (- _figure_eight.minor_axis), _figure_eight.center.east_m + sin_or * (abs(_figure_eight.major_axis) - _figure_eight.minor_axis) + cos_or * (- _figure_eight.minor_axis)}); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (abs(_figure_eight.major_axis)) - sin_or * 0., _figure_eight.center.east_m + sin_or * (abs(_figure_eight.major_axis)) + cos_or * 0.}); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (abs(_figure_eight.major_axis) - _figure_eight.minor_axis) - sin_or * (_figure_eight.minor_axis), _figure_eight.center.east_m + sin_or * (abs(_figure_eight.major_axis) - _figure_eight.minor_axis) + cos_or * (_figure_eight.minor_axis)}); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (-abs(_figure_eight.major_axis) + _figure_eight.minor_axis) - sin_or * (- _figure_eight.minor_axis), _figure_eight.center.east_m + sin_or * (-abs(_figure_eight.major_axis) + _figure_eight.minor_axis) + cos_or * (- _figure_eight.minor_axis)}); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (-abs(_figure_eight.major_axis)) - sin_or * 0., _figure_eight.center.east_m + sin_or * (-abs(_figure_eight.major_axis)) + cos_or * (0.)}); - figure_eight_point_of_interest.push_back({_figure_eight.center.north_m + cos_or * (-abs(_figure_eight.major_axis) + _figure_eight.minor_axis) - sin_or * (+ _figure_eight.minor_axis), _figure_eight.center.east_m + sin_or * (-abs(_figure_eight.major_axis) + _figure_eight.minor_axis) + cos_or * (_figure_eight.minor_axis)}); - - std::vector order_to_fly; - - if (_figure_eight.major_axis > 0) { - order_to_fly = std::vector {0, 1, 2, 3, 0, 4, 5, 6, 0}; - - } else { - order_to_fly = std::vector {0, 3, 2, 1, 0, 6, 5, 4, 0}; - } - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [&figure_eight_point_of_interest, &prom, &handle, corridor_radius_m, - &order_to_fly, this](Telemetry::PositionVelocityNed position_velocity_ned) { - static size_t index{0}; - int32_t close_index{-1}; - - for (size_t interest_point_index{0}; interest_point_index < figure_eight_point_of_interest.size(); - interest_point_index++) { - if ((abs(position_velocity_ned.position.north_m - figure_eight_point_of_interest[interest_point_index].north_m) < - corridor_radius_m) && - (abs(position_velocity_ned.position.east_m - figure_eight_point_of_interest[interest_point_index].east_m) < - corridor_radius_m)) { - close_index = static_cast(interest_point_index); - break; - } - } - - if (close_index >= 0) { - if (close_index == order_to_fly[index]) { // Still at the same point already found - // Do nothing - - } else if (close_index == order_to_fly[index + 1]) { // reached the next expected point - index++; - - } else { // reached an out of order point - - if (index > 0U) { // only set to false if we already hve passed the first center point - getTelemetry()->unsubscribe_position_velocity_ned(handle); - prom.set_value(false); - } - } - } - - if (index + 1 == order_to_fly.size()) { - getTelemetry()->unsubscribe_position_velocity_ned(handle); - prom.set_value(true); - } - }); - - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); - CHECK(fut.get() == true); -} - -void AutopilotTesterFigureEight::check_receive_execution_status(std::chrono::seconds timeout) -{ - auto prom = std::promise {}; - auto fut = prom.get_future(); - - auto ct = get_coordinate_transformation(); - const auto global_center = ct.global_from_local(_figure_eight.center); - - add_mavlink_message_callback(MAVLINK_MSG_ID_FIGURE_EIGHT_EXECUTION_STATUS, [&prom, global_center, - this](const mavlink_message_t &message) { - add_mavlink_message_callback(MAVLINK_MSG_ID_FIGURE_EIGHT_EXECUTION_STATUS, nullptr); - mavlink_figure_eight_execution_status_t status_message; - - mavlink_msg_figure_eight_execution_status_decode(&message, &status_message); - CHECK(abs(status_message.major_radius - _figure_eight.major_axis) < 1E-4); - CHECK(abs(status_message.minor_radius - _figure_eight.minor_axis) < 1E-4); - CHECK(abs(status_message.orientation - _figure_eight.orientation) < 1E-7); - CHECK(status_message.x == static_cast(global_center.latitude_deg * 1E7)); - CHECK(status_message.y == static_cast(global_center.longitude_deg * 1E7)); - CHECK(abs(status_message.z - _figure_eight.alt) < 1E-4); - - prom.set_value(); - - return true; - }); - - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); -} diff --git a/test/mavsdk_tests/autopilot_tester_figure_eight.h b/test/mavsdk_tests/autopilot_tester_figure_eight.h deleted file mode 100644 index 17761d8d2bc..00000000000 --- a/test/mavsdk_tests/autopilot_tester_figure_eight.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2023 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" - -#include -#include -#include - -class AutopilotTesterFigureEight : public AutopilotTester -{ -public: - AutopilotTesterFigureEight() = default; - ~AutopilotTesterFigureEight() = default; - - void set_figure_eight(double major_axis, double minor_axis, double orientation, double home_offset_N, - double home_offset_E, double rel_alt); - - void execute_figure_eight(); - void check_tracks_figure_eight(std::chrono::seconds timeout, double corridor_radius_m = 5.f); - void check_receive_execution_status(std::chrono::seconds timeout); - -private: - - struct { - double major_axis; - double minor_axis; - double orientation; - CoordinateTransformation::LocalCoordinate center; - double alt; - } _figure_eight; -}; diff --git a/test/mavsdk_tests/autopilot_tester_follow_me.cpp b/test/mavsdk_tests/autopilot_tester_follow_me.cpp deleted file mode 100644 index 10fa713030c..00000000000 --- a/test/mavsdk_tests/autopilot_tester_follow_me.cpp +++ /dev/null @@ -1,477 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2022 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_follow_me.h" - -// #include - -#include "math_helpers.h" - -#include -#include -#include -#include -#include -#include - - -FollowTargetSimulator::FollowTargetSimulator(std::array initial_position_ned, - mavsdk::Telemetry::GroundTruth home) : - _position_ned(initial_position_ned), _home(home) -{ - _velocity_ned[0] = 0.0f; - _velocity_ned[1] = 0.0f; - _velocity_ned[2] = 0.0f; -} - -FollowTargetSimulator::~FollowTargetSimulator() -{ - -} - -void FollowTargetSimulator::update(float delta_t_s) -{ - const float velocity_m_s = 2.0; - - _velocity_ned[0] = velocity_m_s; - _velocity_ned[1] = 0.0; - - _position_ned[0] += _velocity_ned[0] * delta_t_s; - _position_ned[1] += _velocity_ned[1] * delta_t_s; - _position_ned[2] += _velocity_ned[2] * delta_t_s; - - _udpate_count++; -} - -std::array FollowTargetSimulator::get_position_global(bool add_noise) -{ - std::array pos_ned = _position_ned; - - if (add_noise) { - unsigned seed = _udpate_count; - std::default_random_engine generator(seed); - std::normal_distribution distribution(0.0, 1.0); - pos_ned[0] += distribution(generator); - pos_ned[1] += distribution(generator); - pos_ned[2] += distribution(generator); - } - - CHECK(std::isfinite(_home.latitude_deg)); - CHECK(std::isfinite(_home.longitude_deg)); - const auto ct = CoordinateTransformation({_home.latitude_deg, _home.longitude_deg}); - - mavsdk::geometry::CoordinateTransformation::LocalCoordinate local_coordinate{pos_ned[0], pos_ned[1]}; - mavsdk::geometry::CoordinateTransformation::GlobalCoordinate global_coordinate = ct.global_from_local(local_coordinate); - std::array global_pos{global_coordinate.latitude_deg, global_coordinate.longitude_deg, pos_ned[2] + _home.absolute_altitude_m}; - return global_pos; -} - -std::array FollowTargetSimulator::get_position_ned(bool add_noise) -{ - - std::array pos_ned = _position_ned; - - if (add_noise) { - unsigned seed = _udpate_count; - std::default_random_engine generator(seed); - std::normal_distribution distribution(0.0, pos_noise_std); - pos_ned[0] += distribution(generator); - pos_ned[1] += distribution(generator); - pos_ned[2] += distribution(generator); - } - - return pos_ned; -} - -std::array FollowTargetSimulator::get_velocity_ned_noisy() -{ - return get_velocity_ned(true); -} - -std::array FollowTargetSimulator::get_velocity_ned_ground_truth() -{ - return get_velocity_ned(false); -} - -std::array FollowTargetSimulator::get_velocity_ned(bool add_noise) -{ - std::array vel_ned = _velocity_ned; - - if (add_noise) { - unsigned seed = _udpate_count; - std::default_random_engine generator(seed); - std::normal_distribution distribution(0.0, vel_noise_std); - - vel_ned[0] += distribution(generator); - vel_ned[1] += distribution(generator); - vel_ned[2] += distribution(generator); - } - - return vel_ned; -} - -std::array FollowTargetSimulator::get_position_ned_noisy() -{ - return get_position_ned(true); -} - -std::array FollowTargetSimulator::get_position_ground_truth_ned() -{ - return get_position_ned(false); -} - -std::array FollowTargetSimulator::get_position_global_noisy() -{ - return get_position_global(true); -} - -std::array FollowTargetSimulator::get_position_global_ground_truth() -{ - return get_position_global(false); -} - -void FollowTargetSimulator::check_follow_angle(FollowMe::Config config, std::array drone_pos_ned, - std::array target_pos_ned, float tolerance) -{ - // This check assumes that the target is travelling straight on the x-axis - const float target_to_drone_offset_x = drone_pos_ned[0] - target_pos_ned[0]; - const float target_to_drone_offset_y = drone_pos_ned[1] - target_pos_ned[1]; - - // Follow Angle is measured relative from the target's course (direction it is moving towards) - const float target_to_drone_angle_expected_rad = config.follow_angle_deg * (M_PI / 180.0f); - const float target_to_drone_offset_x_expected = config.follow_distance_m * cos(target_to_drone_angle_expected_rad); - const float target_to_drone_offset_y_expected = config.follow_distance_m * sin(target_to_drone_angle_expected_rad); - - // Check that drone is following at an expected position within the tolerance error - CHECK(fabsf(target_to_drone_offset_x - target_to_drone_offset_x_expected) < tolerance); - CHECK(fabsf(target_to_drone_offset_y - target_to_drone_offset_y_expected) < tolerance); -} - -void AutopilotTesterFollowMe::connect(const std::string uri) -{ - AutopilotTester::connect(uri); - - auto system = get_system(); - _follow_me.reset(new FollowMe(system)); -} - - -void AutopilotTesterFollowMe::straight_line_test(const bool stream_velocity) -{ - // CONFIGURATION for the test - const unsigned location_update_rate = 1; // [Hz] How often the GPS location update samples are generated - const float position_error_tolerance = 11.0f; // [m] Position error tolerance in both X and Y direction - const float follow_me_height_setting = 10.0f; // [m] Height above home position where the Drone will follow from - - // Start with simulated target on the same plane as drone's home position - std::array start_location_ned = get_current_position_ned(); - FollowTargetSimulator target_simulator(start_location_ned, getHome()); - - // Configure the Follow Me parameters - FollowMe::Config config; - config.follow_height_m = follow_me_height_setting; - config.follow_distance_m = 8.0f; - config.follow_angle_deg = 0.0f; - // Ensure that tangential velocity control generates fast enough trajectory to be responsive - config.max_tangential_vel_m_s = 15.0f; - - // Allow some time for mode switch - sleep_for(std::chrono::milliseconds(1000)); - - // Start Follow Me - CHECK(FollowMe::Result::Success == _follow_me->start()); - - // Allow some time for mode switch - sleep_for(std::chrono::milliseconds(1000)); - - // task loop - bool target_moving = false; - bool perform_checks = false; - - // Simulate generating 75 different target location updates - for (unsigned location_update_idx = 0; location_update_idx < 75 * location_update_rate; ++location_update_idx) { - std::array target_pos_ned_ground_truth = target_simulator.get_position_ground_truth_ned(); - std::array position_ned = get_current_position_ned(); - const float distance_to_target = norm(diff(target_pos_ned_ground_truth, position_ned)); - - // poor-man's state machine - if (location_update_idx < 5) { - // Stream target location without moving - - } else if (location_update_idx == 5) { - // Change config to Follow from 'Behind' - perform_checks = false; - config.follow_angle_deg = 180.0f; - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - } else if (location_update_idx < 15) { - // Move target for 10 samples and wait for steady state of drone - target_moving = true; - - } else if (location_update_idx < 20) { - // Perform positional checks in steady state for 5 samples - perform_checks = true; - - } else if (location_update_idx == 20) { - // Change config to follow from 'Front' - perform_checks = false; - config.follow_angle_deg = 0.0f; - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - } else if (location_update_idx < 30) { - // Move target for 10 samples and wait for steady state of drone - - } else if (location_update_idx < 35) { - // Perform positional checks in steady state for 5 samples - perform_checks = true; - - } else if (location_update_idx == 35) { - // Change config to follow from 'Front right' - perform_checks = false; - config.follow_angle_deg = 45.0f; - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - } else if (location_update_idx < 45) { - // Move target for 10 samples and wait for steady state of drone - - } else if (location_update_idx < 55) { - // Perform positional checks in steady state for 5 samples - perform_checks = true; - - } else if (location_update_idx == 55) { - // Change config to follow from 'Front Left' - perform_checks = false; - config.follow_angle_deg = -45.0f; - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - } else if (location_update_idx < 65) { - // Move target for 10 samples and wait for steady state of drone - - } else if (location_update_idx < 75) { - // Perform positional checks in steady state for 10 samples - perform_checks = true; - } - - if (target_moving) { - target_simulator.update(1.0f / location_update_rate); - } - - if (perform_checks) { - check_current_altitude(follow_me_height_setting); - CHECK(distance_to_target <= config.follow_distance_m + position_error_tolerance); - CHECK(distance_to_target >= config.follow_distance_m - position_error_tolerance); - target_simulator.check_follow_angle(config, position_ned, target_pos_ned_ground_truth, position_error_tolerance); - } - - // Construct follow-me message - std::array global_coordinate = target_simulator.get_position_global_noisy(); - - FollowMe::TargetLocation target_location{}; - target_location.latitude_deg = global_coordinate[0]; - target_location.longitude_deg = global_coordinate[1]; - target_location.absolute_altitude_m = global_coordinate[2]; - - if (stream_velocity) { - std::array target_vel_ned = target_simulator.get_velocity_ned_noisy(); - target_location.velocity_x_m_s = target_vel_ned[0]; - target_location.velocity_y_m_s = target_vel_ned[1]; - target_location.velocity_z_m_s = target_vel_ned[2]; - - } else { - target_location.velocity_x_m_s = NAN; - target_location.velocity_y_m_s = NAN; - target_location.velocity_z_m_s = NAN; - } - - - // Send message and check result - CHECK(FollowMe::Result::Success == _follow_me->set_target_location(target_location)); - - sleep_for(std::chrono::milliseconds(1000 / location_update_rate)); - } - - CHECK(FollowMe::Result::Success == _follow_me->stop()); -} - -void AutopilotTesterFollowMe::stream_velocity_only() -{ - const unsigned loop_update_rate = 1; - const float position_tolerance = 4.0f; - - // Configure follow-me - FollowMe::Config config; - config.follow_angle_deg = 180.0f; // Follow from behind - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - // Allow some time for mode switch - sleep_for(std::chrono::milliseconds(1000)); - - // Start Follow Me - CHECK(FollowMe::Result::Success == _follow_me->start()); - - // Allow some time for mode switch - sleep_for(std::chrono::milliseconds(1000)); - - std::array drone_initial_pos = get_current_position_ned(); - - // Start streaming velocity only. The drone should not move. - for (unsigned i = 0; i < 15 * loop_update_rate; i++) { - FollowMe::TargetLocation target_location{}; - target_location.latitude_deg = NAN; - target_location.longitude_deg = NAN; - target_location.absolute_altitude_m = NAN; - target_location.velocity_x_m_s = 2.0f; - target_location.velocity_y_m_s = 1.0f; - target_location.velocity_z_m_s = 0.5f; - - // Send message and check result - CHECK(FollowMe::Result::Success == _follow_me->set_target_location(target_location)); - - sleep_for(std::chrono::milliseconds(1000 / loop_update_rate)); - } - - // Check that drone is still close to initial position and has not moved much - std::array drone_final_pos = get_current_position_ned(); - const float distance_travelled = norm(diff(drone_initial_pos, drone_final_pos)); - CHECK(distance_travelled < position_tolerance); -} - -void AutopilotTesterFollowMe::rc_adjustment_test() -{ - // CONFIGURATION - const unsigned loop_update_rate = 50; // [Hz] - const float follow_height_setting = 10.0f; // [m] - const float follow_angle_setting = 0.0f; // [deg] - const float follow_distance_setting = 10.0f; // [m] - - // The constants below are copied from the "FlightTaskAutoFollowTarget.hpp" to get a reference point for - // how much change a RC adjustment is expected to bring for each follow me parameters - - // [m/s] Speed with which the follow distance will be adjusted by when commanded with deflection via RC command - static constexpr float FOLLOW_DISTANCE_USER_ADJUST_SPEED = 2.0; - // [m/s] Speed with which the follow height will be adjusted by when commanded with deflection via RC command - static constexpr float FOLLOW_HEIGHT_USER_ADJUST_SPEED = 1.5; - // [rad/s] Angular rate with which the follow distance will be adjusted by when commanded with full deflection via RC command - static constexpr float FOLLOW_ANGLE_USER_ADJUST_SPEED = 1.5; - - // Start with simulated target on the same plane as drone's home position - std::array start_location_ned = get_current_position_ned(); - FollowTargetSimulator target_simulator(start_location_ned, getHome()); - - // Set Follow Me parameters - FollowMe::Config config; - config.follow_height_m = follow_height_setting; - config.follow_distance_m = follow_distance_setting; - config.follow_angle_deg = follow_angle_setting; - CHECK(FollowMe::Result::Success == _follow_me->set_config(config)); - - // [deg] Get a single sample of target's GPS coordinate - const std::array target_global_coordinate = target_simulator.get_position_global_ground_truth(); - - // Set TargetLocation as the sample to simulate a stationary target for a controlled RC adjustment test - const FollowMe::TargetLocation target_location{}; - target_location.latitude_deg = target_global_coordinate[0]; - target_location.longitude_deg = target_global_coordinate[1]; - target_location.absolute_altitude_m = target_global_coordinate[2]; - - // [m] Save the target's location in Local NED (in meters), assuming it is where drone is at in the beginning - const std::array target_pos = get_current_position_ned(); - - // Start Follow-me - CHECK(FollowMe::Result::Success == _follow_me->start()); - std::array drone_initial_pos; - - // task loop - for (unsigned i = 0; i <= 60 * loop_update_rate; ++i) { - _follow_me->set_target_location(target_location); - - std::array current_drone_pos = get_current_position_ned(); - - if (i < 5 * loop_update_rate) { - // For 5 seconds, give time for the drone to go to it's initial following position (front) - CHECK(getManualControl()->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i == 5 * loop_update_rate) { - // At 5 second mark, record the current drone position as initial position - drone_initial_pos = get_current_position_ned(); - - } else if (i < 8 * loop_update_rate) { - // FOLLOW HEIGHT ADJUSTMENT - // Command Throttle-up (Z = 1.0f) for 3 seconds - CHECK(getManualControl()->set_manual_control_input(0.f, 0.f, 1.0f, 0.f) == ManualControl::Result::Success); - - } else if (i < 10 * loop_update_rate) { - // Center the throttle for 2 seconds - CHECK(getManualControl()->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i == 10 * loop_update_rate) { - // Check if altitude has increased at least half of the expected adjustment (Z is directed downwards, so flip the sign) - CHECK(-(current_drone_pos[2] - drone_initial_pos[2]) > FOLLOW_HEIGHT_USER_ADJUST_SPEED * 3.0f * 0.5f); - - } else if (i < 13 * loop_update_rate) { - // FOLLOW HEIGHT ADJUSTMENT - // Command Pitch-down (= Forward) (X = 1.0f) for 3 seconds - CHECK(getManualControl()->set_manual_control_input(1.0f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i < 15 * loop_update_rate) { - // Center the Pitch for 2 seconds - CHECK(getManualControl()->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i == 15 * loop_update_rate) { - // Check if follow distance has increased at least half of the expected adjustment - const float target_to_drone_x_diff = current_drone_pos[0] - target_pos[0]; - const float target_to_drone_y_diff = current_drone_pos[1] - target_pos[1]; - const float current_follow_distance = sqrt(sq(target_to_drone_x_diff) + sq(target_to_drone_y_diff)); - CHECK(current_follow_distance > follow_distance_setting + FOLLOW_DISTANCE_USER_ADJUST_SPEED * 3.0f * 0.5f); - - } else if (i < 18 * loop_update_rate) { - // FOLLOW ANGLE ADJUSTMENT - // Command Roll-right (=Rightwards) (Y = 1.0f) for 3 seconds - CHECK(getManualControl()->set_manual_control_input(0.f, 1.0f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i < 20 * loop_update_rate) { - // Center the Roll for 2 seconds - CHECK(getManualControl()->set_manual_control_input(0.f, 0.f, 0.5f, 0.f) == ManualControl::Result::Success); - - } else if (i == 20 * loop_update_rate) { - // Check if follow angle has increased at least half of the expected adjustment - // Since Roll-right corresponds to the follow angle increasing in clockwise direction - const float target_to_drone_x_diff = current_drone_pos[0] - target_pos[0]; - const float target_to_drone_y_diff = current_drone_pos[1] - target_pos[1]; - const float current_follow_angle_rad = atan2f(target_to_drone_y_diff, target_to_drone_x_diff); - CHECK(current_follow_angle_rad > follow_angle_setting * M_PI / 180.0f + FOLLOW_ANGLE_USER_ADJUST_SPEED * 3.0f * 0.5f); - } - - sleep_for(std::chrono::milliseconds(1000 / loop_update_rate)); - } -} diff --git a/test/mavsdk_tests/autopilot_tester_follow_me.h b/test/mavsdk_tests/autopilot_tester_follow_me.h deleted file mode 100644 index f3d0ffa1cdc..00000000000 --- a/test/mavsdk_tests/autopilot_tester_follow_me.h +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2022 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" - -#include -#include -#include - - -// Simulate a target moving on a straight line in X+ direction -class FollowTargetSimulator -{ -public: - FollowTargetSimulator(std::array initial_position_ned, mavsdk::Telemetry::GroundTruth home); - ~FollowTargetSimulator(); - - // Integrate simulator by one time step - // This moves the target on a line - void update(float delta_t_s); - - // Retrieve noisy version of position state in NED coordinate frame - // The noise is deterministic and changes whenever the update() function is called - std::array get_position_ned_noisy(); - - // Retrieve ground truth of position state in NED coordinate frame - std::array get_position_ground_truth_ned(); - - // Retrieve noisy version of velocity state in NED coordinate frame - // The noise is deterministic and changes whenever the update() function is called - std::array get_velocity_ned_noisy(); - - // Retrieve ground truth of velocity state in NED coordinate frame - std::array get_velocity_ned_ground_truth(); - - // Retrieve noisy version of position state in global coordinate frame (lat, lon, alt) - // The noise is deterministic and changes whenever the update() function is called - std::array get_position_global_noisy(); - - // Retrieve ground truth of position state in global coordinate frame (lat, lon, alt) - std::array get_position_global_ground_truth(); - - // Run checks whether the drone has the correct angle towards the target, specified by the follow-me configuration - void check_follow_angle(FollowMe::Config config, std::array drone_pos_ned, - std::array target_pos_ned, float tolerance); - -private: - // Retrieve estimate with the option to add deterministic gaussian noise - // - // @param add_noise: Add gaussian noise to the state. Noise is deterministic and changes with each inokation of update() - std::array get_position_global(bool add_noise); - - // Retrieve estimate with the option to add deterministic gaussian noise - // - // @param add_noise: Add gaussian noise to the state. Noise is deterministic and changes with each inokation of update() - std::array get_position_ned(bool add_noise); - - // Retrieve estimate with the option to add deterministic gaussian noise - // - // @param add_noise: Add gaussian noise to the state. Noise is deterministic and changes with each inokation of update() - std::array get_velocity_ned(bool add_noise); - - std::array _position_ned; - std::array _velocity_ned; - mavsdk::Telemetry::GroundTruth _home; - size_t _udpate_count = 0; - - const double pos_noise_std = 0.3; - const double vel_noise_std = 0.1; - - std::unique_ptr _telemetry{}; -}; - -class AutopilotTesterFollowMe : public AutopilotTester -{ -public: - AutopilotTesterFollowMe() = default; - ~AutopilotTesterFollowMe() = default; - void connect(const std::string uri); - - /** - * @brief Moves the Target in X+ direction and check the behavior - * - * @param stream_velocity [bool] Whether Target's FollowMe message includes velocity info or not - */ - void straight_line_test(const bool stream_velocity); - - /** - * @brief Sends Target Velocity data only with invalid Position Data - * - * This case should be considered as an 'invalid' Target movement, and the vehicle - * therefore shouldn't move even when the target data is sent - */ - void stream_velocity_only(); - - /** - * @brief Test to check if RC adjustments work - * - * Simulates moving throttle up and down for Follow Height Control - * Simulates moving roll left and right for Follow Angle Control - * Simulates moving pitch up and down for Follow Distance Control - */ - void rc_adjustment_test(); - -private: - std::unique_ptr _follow_me{}; -}; diff --git a/test/mavsdk_tests/autopilot_tester_follow_me.py b/test/mavsdk_tests/autopilot_tester_follow_me.py new file mode 100644 index 00000000000..353ac548fe9 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_follow_me.py @@ -0,0 +1,290 @@ +"""AutopilotTester for follow-me (follow target) tests.""" + +import math +import random +from typing import Any, Optional + +from mavsdk.plugins.follow_me import Config, FollowMe, TargetLocation # type: ignore + +from autopilot_tester import AutopilotTester, log +from geometry import CoordinateTransformation, Vec3, diff, norm + + +def follow_me_config(follow_height_m: float = 8.0, follow_distance_m: float = 8.0, + follow_angle_deg: float = 180.0, + max_tangential_vel_m_s: float = 8.0) -> Any: + # All fields need to be set, the Python defaults are None. These are the C++ defaults. + return Config(follow_height_m=follow_height_m, follow_distance_m=follow_distance_m, + responsiveness=0.1, altitude_mode=Config.FollowAltitudeMode.CONSTANT, + max_tangential_vel_m_s=max_tangential_vel_m_s, + follow_angle_deg=follow_angle_deg) + + +def target_location(latitude_deg: float = math.nan, longitude_deg: float = math.nan, + absolute_altitude_m: float = math.nan, velocity: Vec3 = ( + math.nan, math.nan, math.nan)) -> Any: + return TargetLocation(latitude_deg=latitude_deg, longitude_deg=longitude_deg, + absolute_altitude_m=absolute_altitude_m, velocity_x_m_s=velocity[0], + velocity_y_m_s=velocity[1], velocity_z_m_s=velocity[2]) + + +class FollowTargetSimulator: + """A target moving north in a straight line at 2 m/s, with deterministic noise that changes + with every update().""" + + SPEED_M_S = 2.0 + POSITION_NOISE_STD_M = 1.0 + VELOCITY_NOISE_STD_M_S = 0.1 + + def __init__(self, initial_position_ned: Vec3, home_latitude_deg: float, + home_longitude_deg: float, home_altitude_m: float) -> None: + self._position_ned = list(initial_position_ned) + self._velocity_ned = [0.0, 0.0, 0.0] + self._ct = CoordinateTransformation(home_latitude_deg, home_longitude_deg) + self._home_altitude_m = home_altitude_m + self._update_count = 0 + + def update(self, dt_s: float) -> None: + self._velocity_ned = [self.SPEED_M_S, 0.0, 0.0] + for i in range(3): + self._position_ned[i] += self._velocity_ned[i] * dt_s + self._update_count += 1 + + def _noise(self, std: float) -> Vec3: + rng = random.Random(self._update_count) + return rng.gauss(0.0, std), rng.gauss(0.0, std), rng.gauss(0.0, std) + + def position_ned(self) -> Vec3: + return self._position_ned[0], self._position_ned[1], self._position_ned[2] + + def global_position(self, add_noise: bool) -> Vec3: + """(latitude_deg, longitude_deg, absolute_altitude_m)""" + north_m, east_m, down_m = self.position_ned() + if add_noise: + noise = self._noise(self.POSITION_NOISE_STD_M) + north_m, east_m, down_m = north_m + noise[0], east_m + noise[1], down_m + noise[2] + latitude_deg, longitude_deg = self._ct.global_from_local(north_m, east_m) + # Same as the C++ test: the down offset is added to the home altitude. + return latitude_deg, longitude_deg, down_m + self._home_altitude_m + + def velocity_ned_noisy(self) -> Vec3: + noise = self._noise(self.VELOCITY_NOISE_STD_M_S) + return (self._velocity_ned[0] + noise[0], self._velocity_ned[1] + noise[1], + self._velocity_ned[2] + noise[2]) + + +class AutopilotTesterFollowMe(AutopilotTester): + + def __init__(self, speed_factor: Optional[float] = None) -> None: + super().__init__(speed_factor) + self._follow_me: Any = None + + def connect(self, url: str) -> None: + super().connect(url) + self._follow_me = FollowMe(self._system) + + def _target_simulator(self) -> FollowTargetSimulator: + # Start the target on the drone's position. + return FollowTargetSimulator(self.get_current_position_ned(), *self._home_or_fail(), + self.home_absolute_altitude_m()) + + def _start_follow_me(self) -> None: + self._follow_me.start() + # Target locations are only accepted once MAVSDK sees the vehicle in follow-me mode. + assert self.poll_condition_with_timeout( + lambda: bool(self._follow_me.is_active()), 5), "Follow-me not active within 5 s" + + def _check(self, ok: bool, message: str) -> None: + # Record and continue, so one run shows everything that's off. + self.check_in_callback(ok, message) + + def _check_follow_position(self, config: Any, drone: Vec3, target: Vec3, + tolerance_m: float) -> None: + """Assumes that the target travels north. The follow angle is relative to the target's + course.""" + offset_north_m = drone[0] - target[0] + offset_east_m = drone[1] - target[1] + angle_rad = math.radians(config.follow_angle_deg) + expected_north_m = config.follow_distance_m * math.cos(angle_rad) + expected_east_m = config.follow_distance_m * math.sin(angle_rad) + self._check(abs(offset_north_m - expected_north_m) < tolerance_m and + abs(offset_east_m - expected_east_m) < tolerance_m, + "Follow angle {}: offset to target ({:.1f}, {:.1f}) m, expected " + "({:.1f}, {:.1f}) +- {} m".format( + config.follow_angle_deg, offset_north_m, offset_east_m, + expected_north_m, expected_east_m, tolerance_m)) + + def straight_line_test(self, stream_velocity: bool) -> None: + """Move the target north and check that the drone follows from behind, front, front + right and front left.""" + update_rate_hz = 1 + tolerance_m = 11.0 + follow_height_m = 10.0 + + target = self._target_simulator() + config = follow_me_config(follow_height_m=follow_height_m, follow_distance_m=8.0, + follow_angle_deg=0.0, + # Fast enough tangential velocity to be responsive. + max_tangential_vel_m_s=15.0) + + # Allow some time for the mode switch. + self.sleep_for(1) + self._start_follow_me() + + # (sample index, follow angle) at which the follow angle is changed. The drone then gets + # 10 samples to reach steady state, after which positions are checked until the next + # change. + # The target starts moving after the first change. + angle_changes = {5: 180.0, 20: 0.0, 35: 45.0, 55: -45.0} + first_change = min(angle_changes) + check_from = first_change + 10 + + for i in range(75 * update_rate_hz): + target_position = target.position_ned() + drone_position = self.get_current_position_ned() + + if i in angle_changes: + config.follow_angle_deg = angle_changes[i] + self._follow_me.set_config(config) + log("Follow angle {} deg".format(config.follow_angle_deg)) + check_from = i + 10 + + if i > first_change: + target.update(1.0 / update_rate_hz) + + if i >= check_from: + altitude_m = self._telemetry.position().relative_altitude_m + self._check(abs(altitude_m - follow_height_m) <= 1.5, + "Relative altitude {:.1f} m, expected {} m".format( + altitude_m, follow_height_m)) + distance_m = norm(diff(target_position, drone_position)) + self._check(abs(distance_m - config.follow_distance_m) <= tolerance_m, + "Distance to target {:.1f} m, expected {} +- {} m".format( + distance_m, config.follow_distance_m, tolerance_m)) + self._check_follow_position(config, drone_position, target_position, + tolerance_m) + + latitude_deg, longitude_deg, altitude_m = target.global_position(add_noise=True) + velocity = target.velocity_ned_noisy() if stream_velocity \ + else (math.nan, math.nan, math.nan) + self._follow_me.set_target_location( + target_location(latitude_deg, longitude_deg, altitude_m, velocity)) + + self.sleep_for(1.0 / update_rate_hz) + + self._follow_me.stop() + self._assert_no_callback_failures() + + def stream_velocity_only(self) -> None: + """Stream target velocity without a position. Follow-me needs at least one position to + integrate the velocity, so the drone must not move.""" + position_tolerance_m = 4.0 + + self._follow_me.set_config(follow_me_config(follow_angle_deg=180.0)) + self.sleep_for(1) + self._start_follow_me() + + initial_position = self.get_current_position_ned() + + for _ in range(15): + self._follow_me.set_target_location(target_location(velocity=(2.0, 1.0, 0.5))) + self.sleep_for(1) + + distance_m = norm(diff(initial_position, self.get_current_position_ned())) + assert distance_m < position_tolerance_m, \ + "Moved {:.1f} m with velocity only, expected < {} m".format( + distance_m, position_tolerance_m) + + def rc_adjustment_test(self) -> None: + """Adjust follow height (throttle), distance (pitch) and angle (roll) with RC sticks.""" + rate_hz = 50 + follow_height_m = 10.0 + follow_angle_deg = 0.0 + follow_distance_m = 10.0 + max_tangential_vel_m_s = 8.0 + + # Adjustment speeds at full deflection, from FlightTaskAutoFollowTarget.hpp. The angle + # adjustment is additionally limited to max_tangential_vel_m_s / follow distance. + follow_distance_adjust_speed_m_s = 2.0 + follow_height_adjust_speed_m_s = 1.5 + follow_angle_adjust_speed_rad_s = 1.5 + + target = self._target_simulator() + self._follow_me.set_config(follow_me_config( + follow_height_m=follow_height_m, follow_distance_m=follow_distance_m, + follow_angle_deg=follow_angle_deg, max_tangential_vel_m_s=max_tangential_vel_m_s)) + + # A stationary target where the drone is now. + stationary_target = target_location(*target.global_position(add_noise=False)) + target_position = self.get_current_position_ned() + + self._start_follow_me() + + def sticks(x: float, y: float, z: float) -> None: + self._manual_control.set_manual_control_input(x, y, z, 0.0) + + # Each check compares against the state right before its stick input, since the drone + # does not necessarily sit exactly at the configured setting. + height_before_m = 0.0 + distance_before_m = 0.0 + angle_before_rad = 0.0 + + for i in range(60 * rate_hz + 1): + self._follow_me.set_target_location(stationary_target) + drone = self.get_current_position_ned() + t_s = i / rate_hz + height_m = -drone[2] + distance_m = math.hypot(drone[0] - target_position[0], drone[1] - target_position[1]) + angle_rad = math.atan2(drone[1] - target_position[1], drone[0] - target_position[0]) + + if t_s < 5: + # Give the drone time to reach its initial follow position (in front). + sticks(0.0, 0.0, 0.5) + elif i == 5 * rate_hz: + height_before_m = height_m + log("Adjusting follow height") + elif t_s < 8: + sticks(0.0, 0.0, 1.0) # throttle up + elif t_s < 10: + sticks(0.0, 0.0, 0.5) + elif i == 10 * rate_hz: + # At least half of the expected adjustment. + expected_m = follow_height_adjust_speed_m_s * 3.0 * 0.5 + self._check(height_m - height_before_m > expected_m, + "Follow height went up {:.1f} m, expected > {:.1f} m".format( + height_m - height_before_m, expected_m)) + distance_before_m = distance_m + log("Adjusting follow distance") + elif t_s < 13: + sticks(1.0, 0.0, 0.5) # pitch forward + elif t_s < 15: + sticks(0.0, 0.0, 0.5) + elif i == 15 * rate_hz: + # PX4 only grows the distance setpoint while the drone is within 1 m of it, and the + # position controller closes 1 m at ~0.75 m/s. So the distance only changes at + # about 40% of the nominal speed: expect a quarter of the nominal change. + expected_m = follow_distance_adjust_speed_m_s * 3.0 * 0.25 + self._check(distance_m - distance_before_m > expected_m, + "Follow distance went up {:.1f} m to {:.1f} m, expected > {:.1f} m" + .format(distance_m - distance_before_m, distance_m, expected_m)) + angle_before_rad = angle_rad + log("Adjusting follow angle") + elif t_s < 18: + sticks(0.0, 1.0, 0.5) # roll right, follow angle increases clockwise + elif t_s < 20: + sticks(0.0, 0.0, 0.5) + elif i == 20 * rate_hz: + angle_change_rad = math.remainder(angle_rad - angle_before_rad, 2 * math.pi) + angle_speed_rad_s = min(follow_angle_adjust_speed_rad_s, + max_tangential_vel_m_s / distance_m) + expected_rad = angle_speed_rad_s * 3.0 * 0.5 + self._check(angle_change_rad > expected_rad, + "Follow angle went up {:.2f} rad, expected > {:.2f} rad".format( + angle_change_rad, expected_rad)) + else: + # Keep manual control alive, otherwise PX4 fails safe after COM_RC_LOSS_T. + sticks(0.0, 0.0, 0.5) + + self.sleep_for(1.0 / rate_hz) + + self._assert_no_callback_failures() diff --git a/test/mavsdk_tests/autopilot_tester_loiter.cpp b/test/mavsdk_tests/autopilot_tester_loiter.cpp deleted file mode 100644 index eff2123a760..00000000000 --- a/test/mavsdk_tests/autopilot_tester_loiter.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2025 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_loiter.h" - -#include -#include -#include -#include -#include - -#include - -using namespace mavsdk; -using namespace mavsdk::geometry; - -namespace -{ - -// MAVLink command IDs (kept as literals to match the style of the figure-eight tester and avoid -// pulling extra mavlink enum headers). -constexpr uint16_t CMD_DO_ORBIT = 34; -constexpr uint16_t CMD_DO_FIGURE_EIGHT = 35; -constexpr uint16_t CMD_DO_REPOSITION = 192; - -// MAV_DO_REPOSITION_FLAGS_CHANGE_MODE: request a switch into Hold if not already there. -constexpr float REPOSITION_FLAG_CHANGE_MODE = 1.f; - -// Sample rate for the trajectory monitors. -constexpr double POSITION_RATE_HZ = 10.0; - -using Sample = Telemetry::PositionVelocityNed; - -} // namespace - -double AutopilotTesterLoiter::horizontal_distance(const Sample &sample, const LocalCoordinate &c) -{ - return std::hypot(sample.position.north_m - c.north_m, sample.position.east_m - c.east_m); -} - -void AutopilotTesterLoiter::enter_hold_and_wait(std::chrono::seconds timeout) -{ - REQUIRE(getAction()->hold() == Action::Result::Success); - - const auto start = std::chrono::steady_clock::now(); - - while (getTelemetry()->flight_mode() != Telemetry::FlightMode::Hold) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - REQUIRE(std::chrono::steady_clock::now() - start < timeout); - } -} - -void AutopilotTesterLoiter::command_orbit(LocalCoordinate center, float radius_m, float rel_alt_m) -{ - const auto global = get_coordinate_transformation().global_from_local(center); - - MavlinkPassthrough::CommandInt cmd{}; - cmd.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - cmd.target_compid = getMavlinkPassthrough()->get_target_compid(); - cmd.command = CMD_DO_ORBIT; - cmd.frame = MAV_FRAME_GLOBAL_INT; - cmd.param1 = radius_m; // radius, sign encodes direction (positive == clockwise) - cmd.param2 = NAN; // tangential velocity: use default - cmd.param3 = NAN; - cmd.param4 = NAN; - cmd.x = static_cast(global.latitude_deg * 1e7); - cmd.y = static_cast(global.longitude_deg * 1e7); - cmd.z = getHome().absolute_altitude_m + rel_alt_m; - - send_custom_mavlink_command(cmd); -} - -void AutopilotTesterLoiter::command_figure_eight(LocalCoordinate center, float major_axis_m, float minor_axis_m, - float rel_alt_m) -{ - const auto global = get_coordinate_transformation().global_from_local(center); - - MavlinkPassthrough::CommandInt cmd{}; - cmd.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - cmd.target_compid = getMavlinkPassthrough()->get_target_compid(); - cmd.command = CMD_DO_FIGURE_EIGHT; - cmd.frame = MAV_FRAME_GLOBAL_INT; - cmd.param1 = major_axis_m; // major radius, sign encodes direction - cmd.param2 = minor_axis_m; // minor radius - cmd.param3 = NAN; - cmd.param4 = 0.f; // orientation - cmd.x = static_cast(global.latitude_deg * 1e7); - cmd.y = static_cast(global.longitude_deg * 1e7); - cmd.z = getHome().absolute_altitude_m + rel_alt_m; - - send_custom_mavlink_command(cmd); -} - -void AutopilotTesterLoiter::command_reposition(LocalCoordinate target, float rel_alt_m) -{ - const auto global = get_coordinate_transformation().global_from_local(target); - - MavlinkPassthrough::CommandInt cmd{}; - cmd.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - cmd.target_compid = getMavlinkPassthrough()->get_target_compid(); - cmd.command = CMD_DO_REPOSITION; - cmd.frame = MAV_FRAME_GLOBAL_INT; - cmd.param1 = -1.f; // ground speed: use default - cmd.param2 = REPOSITION_FLAG_CHANGE_MODE; - cmd.param3 = 0.f; - cmd.param4 = NAN; // yaw: unchanged - cmd.x = static_cast(global.latitude_deg * 1e7); - cmd.y = static_cast(global.longitude_deg * 1e7); - cmd.z = getHome().absolute_altitude_m + rel_alt_m; - - send_custom_mavlink_command(cmd); -} - -void AutopilotTesterLoiter::command_hold_here() -{ - MavlinkPassthrough::CommandInt cmd{}; - cmd.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - cmd.target_compid = getMavlinkPassthrough()->get_target_compid(); - cmd.command = CMD_DO_REPOSITION; - cmd.frame = MAV_FRAME_GLOBAL_INT; - cmd.param1 = -1.f; // ground speed: use default - cmd.param2 = REPOSITION_FLAG_CHANGE_MODE; - cmd.param3 = 0.f; - cmd.param4 = NAN; // yaw: unchanged - cmd.x = INT32_MAX; // latitude ignored -> NaN - cmd.y = INT32_MAX; // longitude ignored -> NaN - cmd.z = NAN; // altitude ignored -> keep current - send_custom_mavlink_command(cmd); -} - -void AutopilotTesterLoiter::command_reposition_altitude(float rel_alt_m) -{ - MavlinkPassthrough::CommandInt cmd{}; - cmd.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - cmd.target_compid = getMavlinkPassthrough()->get_target_compid(); - cmd.command = CMD_DO_REPOSITION; - cmd.frame = MAV_FRAME_GLOBAL_INT; - cmd.param1 = -1.f; // ground speed: use default - cmd.param2 = REPOSITION_FLAG_CHANGE_MODE; - cmd.param3 = 0.f; - cmd.param4 = NAN; // yaw: unchanged - cmd.x = INT32_MAX; // latitude ignored -> NaN (position unchanged) - cmd.y = INT32_MAX; // longitude ignored -> NaN (position unchanged) - cmd.z = getHome().absolute_altitude_m + rel_alt_m; // only altitude changes - send_custom_mavlink_command(cmd); -} - -void AutopilotTesterLoiter::wait_until_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - std::chrono::seconds settle, std::chrono::seconds timeout) -{ - // Flying out to the loiter circle only crosses the radial band once and then stays on it, so the - // first band entry marks establishment; `settle` (measured in simulator time) then lets the loiter - // stabilize before the caller asserts on it. - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - // Shared with the callback: with MAVSDK 3.x, a queued callback can still run after unsubscribe. - auto prom = std::make_shared>(); - auto fut = prom->get_future(); - auto reported = std::make_shared>(false); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [prom, reported, center, radius_m, radius_tol_m](Sample sample) { - const double d = horizontal_distance(sample, center); - - if (d >= (radius_m - radius_tol_m) && d <= (radius_m + radius_tol_m) && !reported->exchange(true)) { - prom->set_value(); - } - }); - - // wait_for is only an upper bound (wall-clock); the future resolves as soon as the loiter is - // reached, which happens quickly under a high simulation speed factor. - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); - getTelemetry()->unsubscribe_position_velocity_ned(handle); - - sleep_for(settle); - std::cout << time_str() << "Established on loiter" << std::endl; -} - -void AutopilotTesterLoiter::wait_until_relative_altitude_above(float threshold_m, std::chrono::seconds timeout) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - // Shared with the callback: with MAVSDK 3.x, a queued callback can still run after unsubscribe. - auto prom = std::make_shared>(); - auto fut = prom->get_future(); - auto reported = std::make_shared>(false); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [prom, reported, threshold_m](Sample sample) { - const float rel_alt = -sample.position.down_m; // home-relative, up-positive - - if (rel_alt >= threshold_m && !reported->exchange(true)) { - prom->set_value(); - } - }); - - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); - getTelemetry()->unsubscribe_position_velocity_ned(handle); -} - -void AutopilotTesterLoiter::check_stays_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - std::chrono::seconds duration) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [center, radius_m, radius_tol_m](Sample sample) { - const double d = horizontal_distance(sample, center); - CHECK(d >= (radius_m - radius_tol_m)); - CHECK(d <= (radius_m + radius_tol_m)); - }); - - sleep_for(duration); - getTelemetry()->unsubscribe_position_velocity_ned(handle); -} - -void AutopilotTesterLoiter::check_stays_within(LocalCoordinate center, float max_radius_m, - std::chrono::seconds duration) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [center, max_radius_m](Sample sample) { - CHECK(horizontal_distance(sample, center) <= max_radius_m); - }); - - sleep_for(duration); - getTelemetry()->unsubscribe_position_velocity_ned(handle); -} - -void AutopilotTesterLoiter::check_never_reaches(LocalCoordinate point, float min_dist_m, - std::chrono::seconds duration) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [point, min_dist_m](Sample sample) { - CHECK(horizontal_distance(sample, point) >= min_dist_m); - }); - - sleep_for(duration); - getTelemetry()->unsubscribe_position_velocity_ned(handle); -} - -void AutopilotTesterLoiter::check_holds_altitude(float rel_alt_m, float tol_m, std::chrono::seconds duration) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [rel_alt_m, tol_m](Sample sample) { - const float rel_alt = -sample.position.down_m; // home-relative, up-positive - CHECK(std::abs(rel_alt - rel_alt_m) <= tol_m); - }); - - sleep_for(duration); - getTelemetry()->unsubscribe_position_velocity_ned(handle); -} - -void AutopilotTesterLoiter::check_climbs_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - float target_rel_alt_m, float alt_tol_m, std::chrono::seconds timeout) -{ - getTelemetry()->set_rate_position_velocity_ned(POSITION_RATE_HZ); - - // Shared with the callback: with MAVSDK 3.x, a queued callback can still run after unsubscribe. - auto prom = std::make_shared>(); - auto fut = prom->get_future(); - auto reported = std::make_shared>(false); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [prom, reported, center, radius_m, radius_tol_m, target_rel_alt_m, alt_tol_m](Sample sample) { - // Invariant: never leave the radial band around the loiter center while climbing. - const double d = horizontal_distance(sample, center); - CHECK(d >= (radius_m - radius_tol_m)); - CHECK(d <= (radius_m + radius_tol_m)); - - const float rel_alt = -sample.position.down_m; - - if (std::abs(rel_alt - target_rel_alt_m) <= alt_tol_m && !reported->exchange(true)) { - prom->set_value(); - } - }); - - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); - getTelemetry()->unsubscribe_position_velocity_ned(handle); - std::cout << time_str() << "Climbed to target altitude while staying on loiter" << std::endl; -} - -float AutopilotTesterLoiter::current_relative_altitude() -{ - // Use NED down (up-positive) to match the altitude source used by the trajectory monitors. - return -getTelemetry()->position_velocity_ned().position.down_m; -} - -AutopilotTesterLoiter::LocalCoordinate AutopilotTesterLoiter::current_local_position() -{ - const auto pos = getTelemetry()->position_velocity_ned().position; - return LocalCoordinate{pos.north_m, pos.east_m}; -} - -float AutopilotTesterLoiter::default_loiter_radius() -{ - const auto result = getParams()->get_param_float("NAV_LOITER_RAD"); - CHECK(result.first == Param::Result::Success); - return result.second; -} - -float AutopilotTesterLoiter::fw_altitude_acceptance_radius() -{ - const auto result = getParams()->get_param_float("NAV_FW_ALT_RAD"); - CHECK(result.first == Param::Result::Success); - return result.second; -} diff --git a/test/mavsdk_tests/autopilot_tester_loiter.h b/test/mavsdk_tests/autopilot_tester_loiter.h deleted file mode 100644 index 68de264bb8f..00000000000 --- a/test/mavsdk_tests/autopilot_tester_loiter.h +++ /dev/null @@ -1,121 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2025 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" - -#include - -#include - -// Test helper for fixed-wing loiter / reposition / Hold behaviour. -// -// All positions are expressed as home-relative NED local coordinates and -// converted to global setpoints internally. Loiter geometry can only be -// observed indirectly (there is no MAVLink message that exposes the internal -// position setpoint), so the checks are trajectory based: they assert where the -// vehicle actually flies over a time window. -class AutopilotTesterLoiter : public AutopilotTester -{ -public: - using LocalCoordinate = mavsdk::geometry::CoordinateTransformation::LocalCoordinate; - - AutopilotTesterLoiter() = default; - ~AutopilotTesterLoiter() = default; - - // Switch to Hold (AUTO_LOITER) and wait until the flight mode is reported. - void enter_hold_and_wait(std::chrono::seconds timeout = std::chrono::seconds(10)); - - // Command a fixed-wing orbit (MAV_CMD_DO_ORBIT) around a home-relative center - // with the given radius. Must be in Hold for the setpoint to be picked up. - void command_orbit(LocalCoordinate center, float radius_m, float rel_alt_m); - - // Command a figure-eight (MAV_CMD_DO_FIGURE_EIGHT) around a home-relative center. - void command_figure_eight(LocalCoordinate center, float major_axis_m, float minor_axis_m, float rel_alt_m); - - // Command a plain reposition to a home-relative target (fly straight toward it). - void command_reposition(LocalCoordinate target, float rel_alt_m); - - // Send a pause/Hold reposition: lat/lon/alt all NaN, CHANGE_MODE flag set. - void command_hold_here(); - - // Send a reposition that only changes altitude: lat/lon NaN, alt finite. - void command_reposition_altitude(float rel_alt_m); - - // Wait until the vehicle is circling `center` at ~radius (within tol) and has - // stayed in that radial band continuously for `settle`. - void wait_until_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - std::chrono::seconds settle, std::chrono::seconds timeout); - - // Wait until the relative (to home) altitude climbs above `threshold_m`. Uses a monotonic - // threshold (not a band) so it cannot be skipped between samples at a high speed factor. - void wait_until_relative_altitude_above(float threshold_m, std::chrono::seconds timeout); - - // Assert that for the whole `duration` the vehicle stays in the radial band - // [radius - tol, radius + tol] around `center`, i.e. keeps circling that loiter. - void check_stays_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - std::chrono::seconds duration); - - // Assert that for the whole `duration` the vehicle stays within `max_radius_m` - // of `center` (loose "circles near here" check for a freshly created loiter). - void check_stays_within(LocalCoordinate center, float max_radius_m, std::chrono::seconds duration); - - // Assert the horizontal distance to `point` never drops below `min_dist_m` - // during `duration` (the vehicle must not reach the given point). - void check_never_reaches(LocalCoordinate point, float min_dist_m, std::chrono::seconds duration); - - // Assert relative altitude stays within `tol_m` of `rel_alt_m` for `duration`. - void check_holds_altitude(float rel_alt_m, float tol_m, std::chrono::seconds duration); - - // Assert the vehicle climbs to `target_rel_alt_m` (within tol) while never - // leaving the radial band around `center`. - void check_climbs_on_loiter(LocalCoordinate center, float radius_m, float radius_tol_m, - float target_rel_alt_m, float alt_tol_m, std::chrono::seconds timeout); - - // Current relative (to home) altitude in meters. - float current_relative_altitude(); - - // Current horizontal position as a home-relative NED coordinate. - LocalCoordinate current_local_position(); - - // NAV_LOITER_RAD default loiter radius in meters. - float default_loiter_radius(); - - // NAV_FW_ALT_RAD fixed-wing altitude acceptance radius in meters. - float fw_altitude_acceptance_radius(); - -private: - // Horizontal distance in meters between a NED sample and a local coordinate. - static double horizontal_distance(const mavsdk::Telemetry::PositionVelocityNed &sample, const LocalCoordinate &c); -}; diff --git a/test/mavsdk_tests/autopilot_tester_loiter.py b/test/mavsdk_tests/autopilot_tester_loiter.py new file mode 100644 index 00000000000..955dd91314f --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_loiter.py @@ -0,0 +1,231 @@ +"""AutopilotTester for fixed-wing loiter, reposition, Hold and figure-eight behaviour. + +Positions are home-relative local (north, east) coordinates, converted to global setpoints +internally. The loiter geometry can only be observed indirectly (no MAVLink message exposes the +internal position setpoint), so the checks are trajectory based: they assert where the vehicle +actually flies over a time window. +""" + +import math +from typing import Any, List, Optional, Tuple + +from mavsdk.plugins.telemetry import FlightMode # type: ignore + +from autopilot_tester import AutopilotTester, log + +MAV_CMD_DO_ORBIT = 34 +MAV_CMD_DO_FIGURE_EIGHT = 35 +MAV_CMD_DO_REPOSITION = 192 + +# MAV_DO_REPOSITION_FLAGS_CHANGE_MODE: switch into Hold if not already there. +REPOSITION_FLAG_CHANGE_MODE = 1.0 + +# INT32_MAX in x/y of COMMAND_INT means "not set", i.e. keep the current position. +COORDINATE_NOT_SET = 2**31 - 1 + +Local2 = Tuple[float, float] + + +def horizontal_distance(sample: Any, point: Local2) -> float: + return math.hypot(sample.position.north_m - point[0], sample.position.east_m - point[1]) + + +def relative_altitude(sample: Any) -> float: + return float(-sample.position.down_m) + + +class AutopilotTesterLoiter(AutopilotTester): + + # ------------------------------------------------------------------ + # Commands + # ------------------------------------------------------------------ + + def enter_hold_and_wait(self, timeout_s: float = 10) -> None: + self.hold() + self.wait_for_flight_mode(FlightMode.HOLD, timeout_s) + + def _global_int(self, point: Local2) -> Tuple[int, int]: + latitude_deg, longitude_deg = self.get_coordinate_transformation().global_from_local( + *point) + return int(latitude_deg * 1e7), int(longitude_deg * 1e7) + + def command_orbit(self, center: Local2, radius_m: float, rel_alt_m: float) -> None: + """Fixed-wing orbit around center. The radius sign is the direction (positive is + clockwise). Needs Hold for the setpoint to be picked up.""" + x, y = self._global_int(center) + nan = float("nan") + self.send_command_int(MAV_CMD_DO_ORBIT, param1=radius_m, param2=nan, param3=nan, + param4=nan, x=x, y=y, + z=self.home_absolute_altitude_m() + rel_alt_m) + + def command_figure_eight(self, center: Local2, major_axis_m: float, minor_axis_m: float, + rel_alt_m: float, orientation_rad: float = 0.0) -> None: + """Figure eight around center. The major axis sign is the direction.""" + x, y = self._global_int(center) + self.send_command_int(MAV_CMD_DO_FIGURE_EIGHT, param1=major_axis_m, param2=minor_axis_m, + param3=float("nan"), param4=orientation_rad, x=x, y=y, + z=self.home_absolute_altitude_m() + rel_alt_m) + + def _reposition(self, x: int, y: int, z: float) -> None: + # Default ground speed, switch to Hold, yaw unchanged. + self.send_command_int(MAV_CMD_DO_REPOSITION, param1=-1.0, + param2=REPOSITION_FLAG_CHANGE_MODE, param3=0.0, + param4=float("nan"), x=x, y=y, z=z) + + def command_reposition(self, target: Local2, rel_alt_m: float) -> None: + """Plain reposition: fly straight toward target.""" + x, y = self._global_int(target) + self._reposition(x, y, self.home_absolute_altitude_m() + rel_alt_m) + + def command_hold_here(self) -> None: + """Pause/Hold reposition: position and altitude not set.""" + self._reposition(COORDINATE_NOT_SET, COORDINATE_NOT_SET, float("nan")) + + def command_reposition_altitude(self, rel_alt_m: float) -> None: + """Reposition that only changes the altitude.""" + self._reposition(COORDINATE_NOT_SET, COORDINATE_NOT_SET, + self.home_absolute_altitude_m() + rel_alt_m) + + # ------------------------------------------------------------------ + # Waits + # ------------------------------------------------------------------ + + def wait_until_on_loiter(self, center: Local2, radius_m: float, radius_tol_m: float, + settle_s: float, timeout_s: float) -> None: + """Wait until the vehicle reaches the radial band around center, then settle_s more. + + Flying out to the circle only crosses the band once and then stays on it, so the first + entry marks establishment. + """ + self.wait_for_position_ned( + lambda s: abs(horizontal_distance(s, center) - radius_m) <= radius_tol_m, timeout_s) + self.sleep_for(settle_s) + log("Established on loiter") + + def wait_until_relative_altitude_above(self, threshold_m: float, timeout_s: float) -> None: + # A threshold rather than a band, so it cannot be skipped between samples at a high + # speed factor. + self.wait_for_position_ned(lambda s: relative_altitude(s) >= threshold_m, timeout_s) + + # ------------------------------------------------------------------ + # Trajectory checks + # ------------------------------------------------------------------ + + def check_stays_on_loiter(self, center: Local2, radius_m: float, radius_tol_m: float, + duration_s: float) -> None: + def check(sample: Any) -> Optional[str]: + distance_m = horizontal_distance(sample, center) + if abs(distance_m - radius_m) > radius_tol_m: + return "Distance to loiter center {:.1f} m, expected {} +- {} m".format( + distance_m, radius_m, radius_tol_m) + return None + + self.check_position_ned_for(check, duration_s) + + def check_stays_within(self, center: Local2, max_radius_m: float, duration_s: float) -> None: + def check(sample: Any) -> Optional[str]: + distance_m = horizontal_distance(sample, center) + if distance_m > max_radius_m: + return "Distance to {} is {:.1f} m, expected <= {} m".format( + center, distance_m, max_radius_m) + return None + + self.check_position_ned_for(check, duration_s) + + def check_never_reaches(self, point: Local2, min_distance_m: float, + duration_s: float) -> None: + def check(sample: Any) -> Optional[str]: + distance_m = horizontal_distance(sample, point) + if distance_m < min_distance_m: + return "Distance to {} is {:.1f} m, expected >= {} m".format( + point, distance_m, min_distance_m) + return None + + self.check_position_ned_for(check, duration_s) + + def check_holds_altitude(self, rel_alt_m: float, tol_m: float, duration_s: float) -> None: + def check(sample: Any) -> Optional[str]: + altitude_m = relative_altitude(sample) + if abs(altitude_m - rel_alt_m) > tol_m: + return "Relative altitude {:.1f} m, expected {:.1f} +- {} m".format( + altitude_m, rel_alt_m, tol_m) + return None + + self.check_position_ned_for(check, duration_s) + + def check_climbs_on_loiter(self, center: Local2, radius_m: float, radius_tol_m: float, + target_rel_alt_m: float, alt_tol_m: float, + timeout_s: float) -> None: + """Check that the vehicle climbs to the target altitude without ever leaving the radial + band around center.""" + def done(sample: Any) -> bool: + distance_m = horizontal_distance(sample, center) + self.check_in_callback( + abs(distance_m - radius_m) <= radius_tol_m, + "Left the loiter while climbing: distance to center {:.1f} m, " + "expected {} +- {} m".format(distance_m, radius_m, radius_tol_m)) + return abs(relative_altitude(sample) - target_rel_alt_m) <= alt_tol_m + + self.wait_for_position_ned(done, timeout_s) + self._assert_no_callback_failures() + log("Climbed to target altitude while staying on loiter") + + def check_tracks_figure_eight(self, center: Local2, major_axis_m: float, + minor_axis_m: float, orientation_rad: float, + corridor_radius_m: float, timeout_s: float) -> None: + """Check that the vehicle passes the points of interest of the figure eight in order: + center, one lobe, center, other lobe, center.""" + cos_o = math.cos(orientation_rad) + sin_o = math.sin(orientation_rad) + major = abs(major_axis_m) + minor = minor_axis_m + + def point(along: float, across: float) -> Local2: + return (center[0] + cos_o * along - sin_o * across, + center[1] + sin_o * along + cos_o * across) + + points: List[Local2] = [ + center, + point(major - minor, -minor), point(major, 0.0), point(major - minor, minor), + point(-major + minor, -minor), point(-major, 0.0), point(-major + minor, minor), + ] + order = [0, 1, 2, 3, 0, 4, 5, 6, 0] if major_axis_m > 0 else [0, 3, 2, 1, 0, 6, 5, 4, 0] + + index = 0 + out_of_order: List[int] = [] + + def done(sample: Any) -> bool: + nonlocal index + close = next((i for i, p in enumerate(points) + if abs(sample.position.north_m - p[0]) < corridor_radius_m + and abs(sample.position.east_m - p[1]) < corridor_radius_m), None) + if close is not None and close != order[index]: + if close == order[index + 1]: + index += 1 + elif index > 0: + # Out of order, but only once past the first center point. + out_of_order.append(close) + return True + return index + 1 == len(order) + + self.wait_for_position_ned(done, timeout_s) + assert not out_of_order, "Reached figure eight point {} out of order".format( + out_of_order[0]) + + # ------------------------------------------------------------------ + # Accessors + # ------------------------------------------------------------------ + + def current_relative_altitude(self) -> float: + # NED down, to match the altitude used by the trajectory checks. + return relative_altitude(self._telemetry.position_velocity_ned()) + + def current_local_position(self) -> Local2: + position = self._telemetry.position_velocity_ned().position + return float(position.north_m), float(position.east_m) + + def default_loiter_radius(self) -> float: + return self.get_param_float("NAV_LOITER_RAD") + + def fw_altitude_acceptance_radius(self) -> float: + return self.get_param_float("NAV_FW_ALT_RAD") diff --git a/test/mavsdk_tests/autopilot_tester_rtl.cpp b/test/mavsdk_tests/autopilot_tester_rtl.cpp deleted file mode 100644 index 1065577f4f9..00000000000 --- a/test/mavsdk_tests/autopilot_tester_rtl.cpp +++ /dev/null @@ -1,451 +0,0 @@ - -/**************************************************************************** - * - * Copyright (c) 2023 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_rtl.h" - -#include "math_helpers.h" -#include -#include -#include -#include -#include - -#include - - -void AutopilotTesterRtl::connect(const std::string uri) -{ - AutopilotTester::connect(uri); -} - -void AutopilotTesterRtl::set_rtl_type(int rtl_type) -{ - CHECK(getParams()->set_param_int("RTL_TYPE", rtl_type) == Param::Result::Success); -} - -void AutopilotTesterRtl::set_rtl_appr_force(int rtl_appr_force) -{ - CHECK(getParams()->set_param_int("RTL_APPR_FORCE", rtl_appr_force) == Param::Result::Success); -} - -void AutopilotTesterRtl::set_takeoff_land_requirements(int req) -{ - CHECK(getParams()->set_param_int("MIS_TKO_LAND_REQ", req) == Param::Result::Success); -} - -void AutopilotTesterRtl::upload_rally_points() -{ - REQUIRE(getMissionRaw()->upload_rally_points(_rally_points) == MissionRaw::Result::Success); -} - -void AutopilotTesterRtl::add_home_to_rally_point() -{ - add_local_rally_point({0., 0.}); -} - -void AutopilotTesterRtl::add_home_with_approaches_to_rally_point() -{ - add_local_rally_point({0., 0.}); - add_approaches_to_point({0., 0.}); -} - -void AutopilotTesterRtl::add_local_rally_point(mavsdk::geometry::CoordinateTransformation::LocalCoordinate - local_coordinate) -{ - _local_rally_points.push_back(local_coordinate); - - mavsdk::geometry::CoordinateTransformation ct(get_coordinate_transformation()); - mavsdk::geometry::CoordinateTransformation::GlobalCoordinate pos(ct.global_from_local(local_coordinate)); - - // Set rally point - mavsdk::MissionRaw::MissionItem tmp_mission_item; - tmp_mission_item.param1 = 0.f; - tmp_mission_item.param2 = 0.f; - tmp_mission_item.param3 = 0.f; - tmp_mission_item.param4 = 0.f; - tmp_mission_item.x = static_cast(pos.latitude_deg * 1E7); - tmp_mission_item.y = static_cast(pos.longitude_deg * 1E7); - tmp_mission_item.z = 0.f; - tmp_mission_item.seq = static_cast(_rally_points.size()); - tmp_mission_item.command = MAV_CMD_NAV_RALLY_POINT; - tmp_mission_item.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; - // FIXME: this is currently required with MAVSDK even though it doesn't make much sense for rally points - tmp_mission_item.current = _rally_points.empty() ? 1 : 0; - tmp_mission_item.autocontinue = 0; - tmp_mission_item.mission_type = MAV_MISSION_TYPE_RALLY; - - _rally_points.push_back(tmp_mission_item); -} - -void AutopilotTesterRtl::add_local_rally_with_approaches_point( - mavsdk::geometry::CoordinateTransformation::LocalCoordinate local_coordinate) -{ - add_local_rally_point(local_coordinate); - add_approaches_to_point(local_coordinate); -} - -void AutopilotTesterRtl::add_approaches_to_point(mavsdk::geometry::CoordinateTransformation::LocalCoordinate - local_coordinate) -{ - - mavsdk::geometry::CoordinateTransformation ct(get_coordinate_transformation()); - - // Set north loiter to alt - mavsdk::geometry::CoordinateTransformation::LocalCoordinate tmp_coordinate{local_coordinate}; - tmp_coordinate.north_m += 200.; - mavsdk::geometry::CoordinateTransformation::GlobalCoordinate pos(ct.global_from_local(tmp_coordinate)); - mavsdk::MissionRaw::MissionItem tmp_mission_item; - tmp_mission_item.param1 = 0.f; - tmp_mission_item.param2 = 80.f; - tmp_mission_item.param3 = 0.f; - tmp_mission_item.param4 = 0.f; - tmp_mission_item.x = static_cast(pos.latitude_deg * 1E7); - tmp_mission_item.y = static_cast(pos.longitude_deg * 1E7); - tmp_mission_item.z = 15.f; - tmp_mission_item.seq = static_cast(_rally_points.size()); - tmp_mission_item.command = MAV_CMD_NAV_LOITER_TO_ALT; - tmp_mission_item.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; - // FIXME: this is currently required with MAVSDK even though it doesn't make much sense for rally points - tmp_mission_item.current = _rally_points.empty() ? 1 : 0; - tmp_mission_item.autocontinue = 0; - tmp_mission_item.mission_type = MAV_MISSION_TYPE_RALLY; - - _rally_points.push_back(tmp_mission_item); - - // Set east loiter to alt - tmp_coordinate = local_coordinate; - tmp_coordinate.east_m += 200.; - pos = ct.global_from_local(tmp_coordinate); - tmp_mission_item.x = static_cast(pos.latitude_deg * 1E7); - tmp_mission_item.y = static_cast(pos.longitude_deg * 1E7); - tmp_mission_item.seq = static_cast(_rally_points.size()); - - _rally_points.push_back(tmp_mission_item); -} - -void AutopilotTesterRtl::check_rally_point_within(float acceptance_radius_m) -{ - auto old_home(getHome()); - mavsdk::geometry::CoordinateTransformation ct({old_home.latitude_deg, old_home.longitude_deg}); - Telemetry::GroundTruth land_coord{}; - mavsdk::geometry::CoordinateTransformation::GlobalCoordinate pos; - bool within_rally_point{false}; - - for (const auto &rally_point : _local_rally_points) { - pos = ct.global_from_local(rally_point); - land_coord.latitude_deg = pos.latitude_deg; - land_coord.longitude_deg = pos.longitude_deg; - within_rally_point |= ground_truth_horizontal_position_close_to(land_coord, acceptance_radius_m); - } - - CHECK(within_rally_point); -} - -void AutopilotTesterRtl::wait_until_disarmed_while_in_multicopter_mode(std::chrono::seconds timeout) -{ - const uint64_t start_time_us = getTelemetry()->attitude_quaternion().timestamp_us; - const uint64_t timeout_us = std::chrono::duration_cast(timeout).count(); - bool remained_in_multicopter_mode = true; - - while (getTelemetry()->armed() && remained_in_multicopter_mode - && getTelemetry()->attitude_quaternion().timestamp_us - start_time_us < timeout_us) { - remained_in_multicopter_mode &= getTelemetry()->vtol_state() == Telemetry::VtolState::Mc; - sleep_for(std::chrono::milliseconds(100)); - } - - REQUIRE(remained_in_multicopter_mode); - REQUIRE_FALSE(getTelemetry()->armed()); -} - -void AutopilotTesterRtl::load_qgc_mission_and_geofence_here(const std::string &plan_file) -{ - auto import_result = getMissionRaw()->import_qgroundcontrol_mission(plan_file); - REQUIRE(import_result.first == mavsdk::MissionRaw::Result::Success); - - auto &data = import_result.second; - REQUIRE(!data.mission_items.empty()); - - // Same offset semantics as move_mission_raw_here, but applied to mission and geofence - // together so the fences keep their plan-relative positions. - const auto pos = getTelemetry()->position(); - REQUIRE(std::isfinite(pos.latitude_deg)); - REQUIRE(std::isfinite(pos.longitude_deg)); - - const int32_t offset_x = data.mission_items[0].x - static_cast(1e7 * pos.latitude_deg); - const int32_t offset_y = data.mission_items[0].y - static_cast(1e7 * pos.longitude_deg); - - // Only items in a global position frame carry lat/lon in x/y. For MAV_FRAME_MISSION - // items (e.g. Return, DO_* commands) x/y are generic params p5/p6, so offsetting them - // corrupts the params and the item is rejected by the mission-param validation. - auto is_global_position_frame = [](uint32_t frame) { - switch (frame) { - case MAV_FRAME_GLOBAL: - case MAV_FRAME_GLOBAL_INT: - case MAV_FRAME_GLOBAL_RELATIVE_ALT: - case MAV_FRAME_GLOBAL_RELATIVE_ALT_INT: - case MAV_FRAME_GLOBAL_TERRAIN_ALT: - case MAV_FRAME_GLOBAL_TERRAIN_ALT_INT: - return true; - - default: - return false; - } - }; - - auto apply_offset = [&](std::vector &items) { - for (auto &item : items) { - if (!is_global_position_frame(item.frame)) { - continue; - } - - item.x -= offset_x; - item.y -= offset_y; - } - }; - - apply_offset(data.mission_items); - apply_offset(data.geofence_items); - - REQUIRE(getMissionRaw()->upload_mission(data.mission_items) == mavsdk::MissionRaw::Result::Success); - - _geofence_shapes.clear(); - - if (!data.geofence_items.empty()) { - REQUIRE(getMissionRaw()->upload_geofence(data.geofence_items) == mavsdk::MissionRaw::Result::Success); - - // Parse MAVLink fence items into shape records in local NED. - // Polygon vertex items (5001/5002) are emitted as a run with param1 = vertex count; - // circle items (5003/5004) are one-shot with param1 = radius_m. - constexpr uint16_t kCmdPolygonInclusion = 5001; - constexpr uint16_t kCmdPolygonExclusion = 5002; - constexpr uint16_t kCmdCircleInclusion = 5003; - constexpr uint16_t kCmdCircleExclusion = 5004; - - const auto ct = get_coordinate_transformation(); - - auto flush_open_polygon = [this](GeofenceShape & open) { - if (!open.vertices.empty()) { - _geofence_shapes.push_back(std::move(open)); - } - - open = GeofenceShape{}; - }; - - GeofenceShape open{}; - size_t vertex_target = 0; - - for (const auto &item : data.geofence_items) { - const double lat = static_cast(item.x) / 1e7; - const double lon = static_cast(item.y) / 1e7; - const auto local = ct.local_from_global({lat, lon}); - - if (item.command == kCmdPolygonInclusion || item.command == kCmdPolygonExclusion) { - const auto kind = (item.command == kCmdPolygonInclusion) - ? GeofenceShape::Kind::PolygonInclusion - : GeofenceShape::Kind::PolygonExclusion; - - // Start a new polygon when kind changes or the previous one is full. - if (open.vertices.empty() || open.kind != kind - || open.vertices.size() >= vertex_target) { - flush_open_polygon(open); - open.kind = kind; - vertex_target = static_cast(item.param1); - } - - open.vertices.push_back(local); - - } else if (item.command == kCmdCircleInclusion || item.command == kCmdCircleExclusion) { - flush_open_polygon(open); - GeofenceShape circle{}; - circle.kind = (item.command == kCmdCircleInclusion) - ? GeofenceShape::Kind::CircleInclusion - : GeofenceShape::Kind::CircleExclusion; - circle.center = local; - circle.radius_m = static_cast(item.param1); - _geofence_shapes.push_back(std::move(circle)); - } - } - - flush_open_polygon(open); - } - - sleep_for(std::chrono::seconds(1)); -} - -void AutopilotTesterRtl::start_monitoring_geofence_breach() -{ - REQUIRE(!_geofence_shapes.empty()); // load_qgc_mission_and_geofence_here() must run first - REQUIRE(!_geofence_monitor_active); - - auto ct = get_coordinate_transformation(); - _geofence_breached.store(false); - _geofence_monitor_active.store(true); - - _geofence_monitor_handle = getTelemetry()->subscribe_ground_truth( - [this, ct](Telemetry::GroundTruth gt) { - if (!_geofence_monitor_active.load()) { - return; - } - - if (std::isnan(gt.latitude_deg) || std::isnan(gt.longitude_deg)) { - return; - } - - const auto local = ct.local_from_global({gt.latitude_deg, gt.longitude_deg}); - - for (size_t i = 0; i < _geofence_shapes.size(); ++i) { - if (point_breaches_shape(local.north_m, local.east_m, _geofence_shapes[i])) { - if (!_geofence_breached.exchange(true)) { - std::cout << time_str() << "GEOFENCE BREACH (shape #" << i - << ") at NED (" << local.north_m << ", " - << local.east_m << ")\n"; - } - - break; - } - } - }); -} - -void AutopilotTesterRtl::check_no_geofence_breach() -{ - if (_geofence_monitor_active.exchange(false)) { - getTelemetry()->unsubscribe_ground_truth(_geofence_monitor_handle); - } - - CHECK(!_geofence_breached.load()); -} - -bool AutopilotTesterRtl::point_in_polygon_local( - double north_m, double east_m, - const std::vector &poly) -{ - bool inside = false; - const size_t n = poly.size(); - - for (size_t i = 0, j = n - 1; i < n; j = i++) { - const double ni = poly[i].north_m; - const double ei = poly[i].east_m; - const double nj = poly[j].north_m; - const double ej = poly[j].east_m; - - const bool crosses = ((ei > east_m) != (ej > east_m)) - && (north_m < (nj - ni) * (east_m - ei) / (ej - ei) + ni); - - if (crosses) { - inside = !inside; - } - } - - return inside; -} - -bool AutopilotTesterRtl::point_breaches_shape(double north_m, double east_m, const GeofenceShape &shape) -{ - switch (shape.kind) { - case GeofenceShape::Kind::PolygonExclusion: - return shape.vertices.size() >= 3 - && point_in_polygon_local(north_m, east_m, shape.vertices); - - case GeofenceShape::Kind::PolygonInclusion: - return shape.vertices.size() >= 3 - && !point_in_polygon_local(north_m, east_m, shape.vertices); - - case GeofenceShape::Kind::CircleExclusion: { - const double dn = north_m - shape.center.north_m; - const double de = east_m - shape.center.east_m; - return std::sqrt(dn * dn + de * de) < shape.radius_m; - } - - case GeofenceShape::Kind::CircleInclusion: { - const double dn = north_m - shape.center.north_m; - const double de = east_m - shape.center.east_m; - return std::sqrt(dn * dn + de * de) > shape.radius_m; - } - } - - return false; -} - -void AutopilotTesterRtl::check_rtl_approaches(float acceptance_radius_m, std::chrono::seconds timeout) -{ - auto prom = std::promise {}; - auto fut = prom.get_future(); - auto ct = get_coordinate_transformation(); - auto return_rtl_alt = getParams()->get_param_float("RTL_RETURN_ALT"); - auto descend_rtl_alt = getParams()->get_param_float("RTL_DESCEND_ALT"); - REQUIRE(return_rtl_alt.first == Param::Result::Success); - REQUIRE(descend_rtl_alt.first == Param::Result::Success); - - Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( - [&prom, &handle, acceptance_radius_m, return_rtl_alt, descend_rtl_alt, ct, - this](Telemetry::PositionVelocityNed position_velocity_ned) { - - if ((-position_velocity_ned.position.down_m < return_rtl_alt.second - 3.) - && (position_velocity_ned.velocity.down_m_s > 0.05)) { - // We started to loiter down so we should be on the approach loiter - bool on_approach_loiter(false); - - for (const auto mission_item : _rally_points) { - if (mission_item.command == MAV_CMD_NAV_LOITER_TO_ALT) { - mavsdk::geometry::CoordinateTransformation::LocalCoordinate pos(ct.local_from_global({static_cast(mission_item.x) / 1E7, static_cast(mission_item.y) / 1E7})); - double rel_distance_to_center = sqrt(sq(position_velocity_ned.position.north_m - pos.north_m) + sq( - position_velocity_ned.position.east_m - pos.east_m)); - - if ((rel_distance_to_center > (mission_item.param2 - acceptance_radius_m)) - && (rel_distance_to_center > (mission_item.param2 + acceptance_radius_m))) { - on_approach_loiter |= true; - - if (-position_velocity_ned.position.down_m < descend_rtl_alt.second + 3.) { - // We reached the altitude - getTelemetry()->unsubscribe_position_velocity_ned(handle); - prom.set_value(true); - return; - - } - } - } - } - - if (!on_approach_loiter) { - getTelemetry()->unsubscribe_position_velocity_ned(handle); - prom.set_value(false); - - } - } - }); - - REQUIRE(fut.wait_for(timeout) == std::future_status::ready); - REQUIRE(fut.get()); -} diff --git a/test/mavsdk_tests/autopilot_tester_rtl.h b/test/mavsdk_tests/autopilot_tester_rtl.h deleted file mode 100644 index 449c33ac87b..00000000000 --- a/test/mavsdk_tests/autopilot_tester_rtl.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2023 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" - -#include -#include - -#include -#include -#include -#include - - -class AutopilotTesterRtl : public AutopilotTester -{ -public: - AutopilotTesterRtl() = default; - ~AutopilotTesterRtl() = default; - - void set_rtl_type(int rtl_type); - void set_rtl_appr_force(int rtl_appr_force); - void set_takeoff_land_requirements(int req); - void add_home_to_rally_point(); - void add_home_with_approaches_to_rally_point(); - void add_local_rally_point(mavsdk::geometry::CoordinateTransformation::LocalCoordinate local_coordinate); - void add_local_rally_with_approaches_point(mavsdk::geometry::CoordinateTransformation::LocalCoordinate - local_coordinate); - void connect(const std::string uri); - void check_rally_point_within(float acceptance_radius_m); - void check_rtl_approaches(float acceptance_radius_m, std::chrono::seconds timeout); - void wait_until_disarmed_while_in_multicopter_mode(std::chrono::seconds timeout); - void upload_rally_points(); - - // Import a QGC .plan and upload both the mission and any geofence polygons/circles it - // contains. Mission and geofence are shifted by the same offset so the fences stay in - // their plan-relative positions (same semantics as load_qgc_mission_raw_and_move_here). - // All fence shapes (inclusion/exclusion, polygon/circle) are cached in local NED for the - // breach monitor. - void load_qgc_mission_and_geofence_here(const std::string &plan_file); - - // Subscribe to ground-truth position and assert (latched) that the vehicle never breaches - // any of the cached fence shapes. A breach is entering an exclusion shape or leaving an - // inclusion shape. Call after load_qgc_mission_and_geofence_here(). - void start_monitoring_geofence_breach(); - - // Unsubscribe and CHECK() that no breach was observed. - void check_no_geofence_breach(); - -private: - struct GeofenceShape { - enum class Kind { PolygonInclusion, PolygonExclusion, CircleInclusion, CircleExclusion }; - Kind kind; - std::vector vertices{}; // polygons only - mavsdk::geometry::CoordinateTransformation::LocalCoordinate center{}; // circles only - double radius_m{0.0}; // circles only - }; - - void add_approaches_to_point(mavsdk::geometry::CoordinateTransformation::LocalCoordinate local_coordinate); - - static bool point_in_polygon_local( - double north_m, double east_m, - const std::vector &poly); - - static bool point_breaches_shape(double north_m, double east_m, const GeofenceShape &shape); - - std::unique_ptr _failure{}; - std::vector _rally_points{}; - std::vector _local_rally_points{}; - - std::vector _geofence_shapes{}; - mavsdk::Telemetry::GroundTruthHandle _geofence_monitor_handle{}; - std::atomic _geofence_breached{false}; - std::atomic _geofence_monitor_active{false}; -}; diff --git a/test/mavsdk_tests/autopilot_tester_rtl.py b/test/mavsdk_tests/autopilot_tester_rtl.py new file mode 100644 index 00000000000..6176479a0a5 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_rtl.py @@ -0,0 +1,273 @@ +"""AutopilotTester with rally points and geofences for the return tests.""" + +import math +import threading +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, List, Optional, Tuple + +from mavsdk.plugins.telemetry import VtolState # type: ignore + +from autopilot_tester import ( + MAV_FRAME_GLOBAL_RELATIVE_ALT, MAV_GLOBAL_FRAMES, AutopilotTester, log, raw_mission_item, + raw_item_local) +from geometry import CoordinateTransformation + +MAV_CMD_NAV_LOITER_TO_ALT = 31 +MAV_CMD_NAV_RALLY_POINT = 5100 +MAV_MISSION_TYPE_RALLY = 2 + +MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION = 5001 +MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION = 5002 +MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION = 5003 +MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION = 5004 + +Local2 = Tuple[float, float] + + +class FenceKind(Enum): + POLYGON_INCLUSION = 0 + POLYGON_EXCLUSION = 1 + CIRCLE_INCLUSION = 2 + CIRCLE_EXCLUSION = 3 + + +@dataclass +class FenceShape: + kind: FenceKind + vertices: List[Local2] = field(default_factory=list) # polygons only + center: Local2 = (0.0, 0.0) # circles only + radius_m: float = 0.0 # circles only + + def is_breached_by(self, north_m: float, east_m: float) -> bool: + """A breach is being inside an exclusion or outside an inclusion shape.""" + if self.kind in (FenceKind.POLYGON_INCLUSION, FenceKind.POLYGON_EXCLUSION): + if len(self.vertices) < 3: + return False + inside = point_in_polygon(north_m, east_m, self.vertices) + return inside == (self.kind == FenceKind.POLYGON_EXCLUSION) + + distance_m = math.hypot(north_m - self.center[0], east_m - self.center[1]) + if self.kind == FenceKind.CIRCLE_EXCLUSION: + return distance_m < self.radius_m + return distance_m > self.radius_m + + +def point_in_polygon(north_m: float, east_m: float, polygon: List[Local2]) -> bool: + inside = False + j = len(polygon) - 1 + for i in range(len(polygon)): + ni, ei = polygon[i] + nj, ej = polygon[j] + if (ei > east_m) != (ej > east_m) and north_m < (nj - ni) * (east_m - ei) / (ej - ei) + ni: + inside = not inside + j = i + return inside + + +class AutopilotTesterRtl(AutopilotTester): + + def __init__(self, speed_factor: Optional[float] = None) -> None: + super().__init__(speed_factor) + self._rally_points: List[Any] = [] + self._local_rally_points: List[Local2] = [] + self._fence_shapes: List[FenceShape] = [] + self._fence_monitor_handle: Any = None + self._fence_breached = threading.Event() + + def set_rtl_type(self, rtl_type: int) -> None: + self.set_param_int("RTL_TYPE", rtl_type) + + def set_rtl_appr_force(self, rtl_appr_force: int) -> None: + self.set_param_int("RTL_APPR_FORCE", rtl_appr_force) + + def set_takeoff_land_requirements(self, requirements: int) -> None: + self.set_param_int("MIS_TKO_LAND_REQ", requirements) + + # ------------------------------------------------------------------ + # Rally points + # ------------------------------------------------------------------ + + def _add_rally_item(self, command: int, north_m: float, east_m: float, z: float, + param2: float = 0.0) -> None: + ct = self.get_coordinate_transformation() + latitude_deg, longitude_deg = ct.global_from_local(north_m, east_m) + self._rally_points.append(raw_mission_item( + len(self._rally_points), command, MAV_FRAME_GLOBAL_RELATIVE_ALT, + x=int(latitude_deg * 1e7), y=int(longitude_deg * 1e7), z=z, param2=param2, + # MAVSDK requires a current item, even though it makes little sense for rally points. + current=1 if not self._rally_points else 0, + autocontinue=0, mission_type=MAV_MISSION_TYPE_RALLY)) + + def add_local_rally_point(self, north_m: float, east_m: float) -> None: + self._local_rally_points.append((north_m, east_m)) + self._add_rally_item(MAV_CMD_NAV_RALLY_POINT, north_m, east_m, 0.0) + + def add_local_rally_with_approaches_point(self, north_m: float, east_m: float) -> None: + self.add_local_rally_point(north_m, east_m) + self._add_approaches_to_point(north_m, east_m) + + def add_home_to_rally_point(self) -> None: + self.add_local_rally_point(0.0, 0.0) + + def add_home_with_approaches_to_rally_point(self) -> None: + self.add_local_rally_with_approaches_point(0.0, 0.0) + + def _add_approaches_to_point(self, north_m: float, east_m: float) -> None: + # Loiter-to-altitude approaches 200 m north and east, with an 80 m radius. + self._add_rally_item(MAV_CMD_NAV_LOITER_TO_ALT, north_m + 200.0, east_m, 15.0, 80.0) + self._add_rally_item(MAV_CMD_NAV_LOITER_TO_ALT, north_m, east_m + 200.0, 15.0, 80.0) + + def upload_rally_points(self) -> None: + self._mission_raw.upload_rally_points(self._rally_points) + + def check_rally_point_within(self, acceptance_radius_m: float) -> None: + ct = CoordinateTransformation(*self._home_or_fail()) + distances_m = [ + self._ground_truth_horizontal_distance_to(*ct.global_from_local(north_m, east_m)) + for north_m, east_m in self._local_rally_points] + assert any(d < acceptance_radius_m for d in distances_m), \ + "Not within {} m of any rally point, distances: {}".format( + acceptance_radius_m, ["{:.1f}".format(d) for d in distances_m]) + + def check_rtl_approaches(self, acceptance_radius_m: float, timeout_s: float) -> None: + """Check that the vehicle descends on one of the rally point approach loiters, down to + RTL_DESCEND_ALT.""" + ct = self.get_coordinate_transformation() + return_alt_m = self.get_param_float("RTL_RETURN_ALT") + descend_alt_m = self.get_param_float("RTL_DESCEND_ALT") + approaches = [(raw_item_local(item, ct), float(item.param2)) for item in self._rally_points + if item.command == MAV_CMD_NAV_LOITER_TO_ALT] + results: List[bool] = [] + + def done(sample: Any) -> bool: + altitude_m = -sample.position.down_m + # Started to loiter down, so it should be on an approach loiter. + if not (altitude_m < return_alt_m - 3.0 and sample.velocity.down_m_s > 0.05): + return False + + for center, radius_m in approaches: + distance_m = math.hypot(sample.position.north_m - center[0], + sample.position.east_m - center[1]) + # Ported as is from the C++ test, and it can't fail: with both bounds ">", any + # sample is outside the loiter of at least one of the two approaches, which are + # far apart. So this only waits for the descent. TODO: check that the vehicle is + # on the loiter of the approach it took. + if distance_m > radius_m - acceptance_radius_m \ + and distance_m > radius_m + acceptance_radius_m: + if altitude_m < descend_alt_m + 3.0: + results.append(True) + return True + return False + + results.append(False) + return True + + self.wait_for_position_ned(done, timeout_s, rate_hz=50.0) + assert results and results[0], "Vehicle descended without being on an approach loiter" + + def wait_until_disarmed_while_in_multicopter_mode(self, timeout_s: float) -> None: + start_us = self._autopilot_time_us() + while self._telemetry.armed(): + assert self._telemetry.vtol_state() == VtolState.MC, "Left multicopter mode" + assert (self._autopilot_time_us() - start_us) / 1e6 < timeout_s, \ + "Not disarmed within {} s".format(timeout_s) + self.sleep_for(0.1) + + # ------------------------------------------------------------------ + # Geofence + # ------------------------------------------------------------------ + + def load_qgc_mission_and_geofence_here(self, plan_file: str) -> None: + """Upload the mission and geofence of a QGC .plan, both shifted by the same offset so + that the mission starts at the current position and the fences keep their positions + relative to it. The fence shapes are kept in local NED for the breach monitor.""" + data = self._mission_raw.import_qgroundcontrol_mission(plan_file) + assert data.mission_items, "No mission items in {}".format(plan_file) + + position = self._telemetry.position() + assert math.isfinite(position.latitude_deg) and math.isfinite(position.longitude_deg), \ + "No global position" + offset_x = data.mission_items[0].x - int(1e7 * position.latitude_deg) + offset_y = data.mission_items[0].y - int(1e7 * position.longitude_deg) + + # Only items in a global frame carry lat/lon in x/y. For MAV_FRAME_MISSION items + # (e.g. Return, DO_* commands) x/y are generic params, so shifting them would make + # the mission validation reject the item. + for item in list(data.mission_items) + list(data.geofence_items): + if item.frame in MAV_GLOBAL_FRAMES: + item.x -= offset_x + item.y -= offset_y + + self._mission_raw.upload_mission(data.mission_items) + + self._fence_shapes = [] + if data.geofence_items: + self._mission_raw.upload_geofence(data.geofence_items) + self._fence_shapes = self._parse_fence_shapes(data.geofence_items) + + self.sleep_for(1) + + def _parse_fence_shapes(self, items: List[Any]) -> List[FenceShape]: + # Polygon vertices come as a run of items with param1 = vertex count; circles are one + # item each with param1 = radius. + ct = self.get_coordinate_transformation() + shapes: List[FenceShape] = [] + polygon: Optional[FenceShape] = None + vertex_count = 0 + + for item in items: + local = ct.local_from_global(item.x / 1e7, item.y / 1e7) + + if item.command in (MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION, + MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION): + kind = (FenceKind.POLYGON_INCLUSION + if item.command == MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION + else FenceKind.POLYGON_EXCLUSION) + # Start a new polygon when the kind changes or the previous one is full. + if polygon is None or polygon.kind != kind or len(polygon.vertices) >= vertex_count: + polygon = FenceShape(kind) + shapes.append(polygon) + vertex_count = int(item.param1) + polygon.vertices.append(local) + + elif item.command in (MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION, + MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION): + polygon = None + kind = (FenceKind.CIRCLE_INCLUSION + if item.command == MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION + else FenceKind.CIRCLE_EXCLUSION) + shapes.append(FenceShape(kind, center=local, radius_m=float(item.param1))) + + return shapes + + def start_monitoring_geofence_breach(self) -> None: + """Watch the ground truth position and latch any geofence breach until + check_no_geofence_breach().""" + assert self._fence_shapes, "Call load_qgc_mission_and_geofence_here() first" + assert self._fence_monitor_handle is None, "Already monitoring" + + ct = self.get_coordinate_transformation() + self._fence_breached.clear() + + def check(ground_truth: Any, _user_data: Any) -> None: + if math.isnan(ground_truth.latitude_deg) or math.isnan(ground_truth.longitude_deg): + return + north_m, east_m = ct.local_from_global(ground_truth.latitude_deg, + ground_truth.longitude_deg) + for i, shape in enumerate(self._fence_shapes): + if shape.is_breached_by(north_m, east_m): + if not self._fence_breached.is_set(): + self._fence_breached.set() + log("GEOFENCE BREACH (shape #{}) at NED ({:.1f}, {:.1f})".format( + i, north_m, east_m)) + return + + self._fence_monitor_handle = self._telemetry.subscribe_ground_truth(check) + + def check_no_geofence_breach(self) -> None: + if self._fence_monitor_handle is not None: + self.unsubscribe(self._telemetry, self._telemetry.unsubscribe_ground_truth, + self._fence_monitor_handle) + self._fence_monitor_handle = None + assert not self._fence_breached.is_set(), "Geofence was breached" diff --git a/test/mavsdk_tests/autopilot_tester_vision_target.cpp b/test/mavsdk_tests/autopilot_tester_vision_target.cpp deleted file mode 100644 index 13306d12d55..00000000000 --- a/test/mavsdk_tests/autopilot_tester_vision_target.cpp +++ /dev/null @@ -1,406 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2026 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#include "autopilot_tester_vision_target.h" - -#include -#include -#include -#include -#include -#include - -using namespace std::chrono_literals; -using Clock = std::chrono::steady_clock; -using Vector3d = std::array; - -namespace -{ -constexpr double mission_offset_north_m = -3.0; -constexpr double target_yaw_deg = 120.0; -constexpr auto telemetry_timeout = 2s; -constexpr auto observation_poll_interval = 1ms; -} - -void AutopilotTesterVisionTarget::connect(const std::string uri) -{ - AutopilotTester::connect(uri); - _direct = std::make_unique(get_system()); - - // TODO: Change development.xml to common.xml when TARGET_* are promoted. - std::ifstream xml(std::string(PX4_MAVLINK_XML_DIR) + "/development.xml"); - REQUIRE(xml.good()); - const std::string content{std::istreambuf_iterator(xml), std::istreambuf_iterator()}; - REQUIRE(_direct->load_custom_xml(content) == MavlinkDirect::Result::Success); - - // Without VTE, TARGET_RELATIVE can bypass the estimator and feed precland directly. - const auto enabled = getParams()->get_param_int("VTE_EN"); - REQUIRE(enabled.first == Param::Result::Success); - REQUIRE(enabled.second == 1); -} - -void AutopilotTesterVisionTarget::set_landing_target( - const CoordinateTransformation::LocalCoordinate &offset_from_home_m) -{ - store_home(); - _target = getHome(); - REQUIRE(std::isfinite(_target.absolute_altitude_m)); - CoordinateTransformation home_frame({_target.latitude_deg, _target.longitude_deg}); - const auto target = home_frame.global_from_local(offset_from_home_m); - _target.latitude_deg = target.latitude_deg; - _target.longitude_deg = target.longitude_deg; -} - -void AutopilotTesterVisionTarget::start_landing_mission() -{ - // An approximate mission location: vision must correct the landing to the true pad. - CoordinateTransformation target_frame({_target.latitude_deg, _target.longitude_deg}); - const auto coarse_pad = target_frame.global_from_local({mission_offset_north_m, 0.0}); - MissionRaw::MissionItem waypoint{}; - waypoint.current = 1; - waypoint.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; - waypoint.command = MAV_CMD_NAV_WAYPOINT; - waypoint.autocontinue = 1; - waypoint.mission_type = MAV_MISSION_TYPE_MISSION; - waypoint.param2 = 1.f; // Waypoint acceptance radius in metres. - waypoint.param4 = NAN; - waypoint.x = std::llround(coarse_pad.latitude_deg * 1e7); - waypoint.y = std::llround(coarse_pad.longitude_deg * 1e7); - waypoint.z = getTelemetry()->position().relative_altitude_m; - auto land = waypoint; - land.seq = 1; - land.current = 0; - land.command = MAV_CMD_NAV_LAND; - land.param2 = 2.f; // Required precision landing. - land.param3 = NAN; - land.z = 0.f; - REQUIRE(getMissionRaw()->upload_mission({waypoint, land}) == MissionRaw::Result::Success); - sleep_for(1s); // Allow PX4 to publish mission availability, as in the other mission helpers. - REQUIRE(getMissionRaw()->start_mission() == MissionRaw::Result::Success); -} - -void AutopilotTesterVisionTarget::precision_land(Scenario scenario, std::chrono::seconds timeout) -{ - // VTE_AID_MASK: target GNSS position (bit 0), vehicle GNSS velocity (bit 1), - // vision (bit 2), mission position (bit 3). Home aiding is always disabled. - int aid_mask = 7; - - switch (scenario) { - case Scenario::Vision: aid_mask = 4; break; - - case Scenario::Gnss: aid_mask = 3; break; - - case Scenario::Mission: aid_mask = 14; break; - - default: break; - } - - REQUIRE(getParams()->set_param_int("VTE_AID_MASK", aid_mask) == Param::Result::Success); - REQUIRE(getTelemetry()->set_rate_attitude_euler(15) == Telemetry::Result::Success); - - // PX4 streams the VTE output as LANDING_TARGET, with the relative position in x, y, z. - struct TargetEstimate { - std::mutex mutex; - mavlink_landing_target_t message{}; - }; - const auto estimate = std::make_shared(); - add_mavlink_message_callback(MAVLINK_MSG_ID_LANDING_TARGET, [estimate](const mavlink_message_t &message) { - std::lock_guard lock(estimate->mutex); - mavlink_msg_landing_target_decode(&message, &estimate->message); - }); - MavlinkPassthrough::CommandLong interval{}; - interval.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - interval.target_compid = getMavlinkPassthrough()->get_target_compid(); - interval.command = MAV_CMD_SET_MESSAGE_INTERVAL; - interval.param1 = static_cast(MAVLINK_MSG_ID_LANDING_TARGET); - interval.param2 = 50000.f; // 20 Hz - REQUIRE(getMavlinkPassthrough()->send_command_long(interval) == MavlinkPassthrough::Result::Success); - - if (scenario == Scenario::Mission) { - start_landing_mission(); - - } else { - MavlinkPassthrough::CommandLong command{}; - command.target_sysid = getMavlinkPassthrough()->get_target_sysid(); - command.target_compid = getMavlinkPassthrough()->get_target_compid(); - command.command = MAV_CMD_DO_SET_MODE; - command.param1 = MAV_MODE_FLAG_CUSTOM_MODE_ENABLED; - command.param2 = 4; // PX4_CUSTOM_MAIN_MODE_AUTO - command.param3 = 9; // PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND (required precision landing) - REQUIRE(getMavlinkPassthrough()->send_command_long(command) == MavlinkPassthrough::Result::Success); - } - - // Use simulator time for flight deadlines so speedup does not change the scenario. - const auto start_us = getTelemetry()->ground_truth().timestamp_us; - REQUIRE(start_us != 0); - const auto timeout_us = std::chrono::duration_cast(timeout).count(); - auto last_sample_received = Clock::now(); - uint64_t last_sample = start_us; - uint64_t vision_loss_us = 0; - unsigned spoofed_samples = 0; - bool vision_enabled = scenario != Scenario::Mission; - bool mission_correction_checked = false; - bool yaw_checked = false; - constexpr float minimum_disturbance_height_m = 3.f; - constexpr double acquisition_radius_m = 0.75; - constexpr double corrected_radius_m = 0.5; - CoordinateTransformation target_frame({_target.latitude_deg, _target.longitude_deg}); - - while (getTelemetry()->armed() && last_sample - start_us < static_cast(timeout_us)) { - const auto vehicle = getTelemetry()->ground_truth(); - - if (vehicle.timestamp_us != last_sample) { - REQUIRE(std::isfinite(vehicle.latitude_deg)); - REQUIRE(std::isfinite(vehicle.longitude_deg)); - REQUIRE(std::isfinite(vehicle.absolute_altitude_m)); - const auto relative = target_frame.local_from_global({vehicle.latitude_deg, vehicle.longitude_deg}); - const double distance_m = std::hypot(relative.north_m, relative.east_m); - const float height_m = vehicle.absolute_altitude_m - _target.absolute_altitude_m; - - if (scenario == Scenario::Mission) { - // Below PLD_SRCH_ALT (pinned in sih-sitl.json), so searching alone cannot expose vision. - constexpr float mission_vision_height_m = 9.f; - - if (!vision_enabled && height_m < mission_vision_height_m) { - // Verify the aircraft is over the mission position before exposing the true pad. - const double mission_error_m = std::hypot(relative.north_m - mission_offset_north_m, relative.east_m); - CAPTURE(mission_error_m, distance_m); - REQUIRE(mission_error_m < acquisition_radius_m); - REQUIRE(distance_m > std::abs(mission_offset_north_m) - acquisition_radius_m); - vision_enabled = true; - } - - constexpr float correction_check_height_m = 4.f; - - if (vision_enabled && height_m < correction_check_height_m) { - // Allow the controller time to complete the 3 m correction before checking alignment. - CAPTURE(distance_m); - REQUIRE(distance_m < corrected_radius_m); - mission_correction_checked = true; - } - } - - constexpr float vision_loss_height_m = 8.f; - constexpr auto minimum_bias_overlap = 4s; - - if (scenario == Scenario::VisionLoss && vision_enabled - && height_m < vision_loss_height_m && height_m > minimum_disturbance_height_m - && distance_m < corrected_radius_m - && std::chrono::microseconds(vehicle.timestamp_us - start_us) >= minimum_bias_overlap) { - // Verify yaw acquisition before vision disappears and the orientation estimate expires. - check_target_yaw(); - yaw_checked = true; - vision_enabled = false; - vision_loss_us = vehicle.timestamp_us; - } - - // Spoof only after acquisition, while descending with time left to react. - constexpr float spoof_start_height_m = 8.f; - const bool start_spoof = scenario == Scenario::GnssJump && distance_m < acquisition_radius_m - && height_m < spoof_start_height_m && height_m > minimum_disturbance_height_m; - const bool spoof_gnss = start_spoof || spoofed_samples > 0; - constexpr double gnss_bias_east_m = 2.0; - double gnss_offset_east_m = scenario == Scenario::VisionLoss ? gnss_bias_east_m : 0.0; - - if (spoof_gnss) { - constexpr double gnss_jump_east_m = 200.0; - gnss_offset_east_m = gnss_jump_east_m; - } - - send_target_observations(scenario, vehicle, vision_enabled, gnss_offset_east_m); - constexpr float yaw_check_height_m = 4.f; - - if (scenario != Scenario::Gnss && vision_enabled && height_m < yaw_check_height_m) { - check_target_yaw(); - yaw_checked = true; - } - - if (spoof_gnss) { - ++spoofed_samples; - CAPTURE(distance_m); - // Catch a transient excursion even if vision subsequently recovers the landing. - constexpr double spoof_max_distance_m = 2.0; - REQUIRE(distance_m < spoof_max_distance_m); - } - - if (vision_loss_us != 0) { - CAPTURE(distance_m); - REQUIRE(distance_m < corrected_radius_m); - } - - constexpr float estimate_check_min_height_m = 1.f; - constexpr float estimate_check_max_height_m = 4.f; - - if (height_m > estimate_check_min_height_m && height_m < estimate_check_max_height_m) { - // VTE must keep a live estimate that matches the pad in 3D, including the height. - mavlink_landing_target_t target; - { - std::lock_guard lock(estimate->mutex); - target = estimate->message; - } - const double estimate_age_s = (static_cast(vehicle.timestamp_us) - target.time_usec) * 1e-6; - const double estimate_error_m = std::hypot(target.x + relative.north_m, target.y + relative.east_m, - target.z - height_m); - CAPTURE(estimate_age_s, estimate_error_m, target.z, height_m); - REQUIRE(target.position_valid); - constexpr double maximum_estimate_age_s = 0.25; - REQUIRE(std::abs(estimate_age_s) < maximum_estimate_age_s); - constexpr double estimate_acceptance_m = 0.5; - REQUIRE(estimate_error_m < estimate_acceptance_m); - } - - last_sample = vehicle.timestamp_us; - last_sample_received = Clock::now(); - } - - // Do not keep publishing a stale observation if ground-truth telemetry stops. - if (Clock::now() - last_sample_received >= telemetry_timeout) { - FAIL("Ground-truth telemetry stopped during precision landing"); - } - - std::this_thread::sleep_for(observation_poll_interval); - } - - REQUIRE_FALSE(getTelemetry()->armed()); - - if (scenario != Scenario::Gnss) { - REQUIRE(yaw_checked); - } - - if (scenario == Scenario::Mission) { - REQUIRE(mission_correction_checked); - } - - if (scenario == Scenario::GnssJump) { - constexpr unsigned minimum_spoofed_samples = 10; - REQUIRE(spoofed_samples >= minimum_spoofed_samples); - } - - if (scenario == Scenario::VisionLoss) { - constexpr auto minimum_vision_outage = 8s; - REQUIRE(vision_loss_us != 0); - REQUIRE(std::chrono::microseconds(last_sample - vision_loss_us) >= minimum_vision_outage); - } -} - -void AutopilotTesterVisionTarget::send_target_observations(Scenario scenario, const Telemetry::GroundTruth &vehicle, - bool vision_enabled, double gnss_offset_east_m) -{ - if (scenario != Scenario::Gnss && vision_enabled) { - CoordinateTransformation target_frame({_target.latitude_deg, _target.longitude_deg}); - const auto vehicle_ne = target_frame.local_from_global({vehicle.latitude_deg, vehicle.longitude_deg}); - const Vector3d target_ned_m{-vehicle_ne.north_m, -vehicle_ne.east_m, - vehicle.absolute_altitude_m - _target.absolute_altitude_m}; - // Fixed virtual camera looking down (yaw 90, then pitch -90 deg): sensor (x,y,z) = (down,-north,-east). - // Independent of the estimated attitude; the pitch stops q_sensor commuting with q_target. - const Vector3d target_sensor_m{target_ned_m[2], -target_ned_m[0], -target_ned_m[1]}; - constexpr int frame_other = 3; // TARGET_OBS_FRAME_OTHER - constexpr Vector3d position_std_m{0.1, 0.1, 0.1}; - constexpr double yaw_std_rad = 0.1; - // q_target = conj(q_sensor) * yaw(target_yaw_deg): the pad lies flat, so q_sensor * q_target is a pure yaw. - const double cos_half_yaw = std::cos(target_yaw_deg * M_PI / 360.0); - const double sin_half_yaw = std::sin(target_yaw_deg * M_PI / 360.0); - const double q_target_wy = 0.5 * (cos_half_yaw + sin_half_yaw); - const double q_target_xz = 0.5 * (sin_half_yaw - cos_half_yaw); - std::ostringstream fields; - fields << std::setprecision(10) << "\"frame\":" << frame_other - << ",\"type\":" << LANDING_TARGET_TYPE_VISION_FIDUCIAL - << ",\"x\":" << target_sensor_m[0] << ",\"y\":" << target_sensor_m[1] << ",\"z\":" << target_sensor_m[2] - << ",\"pos_std\":[" << position_std_m[0] << ',' << position_std_m[1] << ',' << position_std_m[2] << ']' - << R"(,"q_sensor":[0.5,0.5,-0.5,0.5])" - << ",\"q_target\":[" << q_target_wy << ',' << q_target_xz << ',' << q_target_wy << ',' << q_target_xz << ']' - << ",\"yaw_std\":" << yaw_std_rad; - send_message("TARGET_RELATIVE", fields.str()); - } - - if (scenario != Scenario::Vision && scenario != Scenario::Mission) { - constexpr int position_capability = 1; // TARGET_ABSOLUTE_SENSOR_CAPABILITY_POSITION - constexpr double degrees_to_mavlink = 1e7; - CoordinateTransformation target_frame({_target.latitude_deg, _target.longitude_deg}); - const auto reported_target = target_frame.global_from_local({0.0, gnss_offset_east_m}); - std::ostringstream fields; - fields << std::setprecision(10) - << "\"sensor_capabilities\":" << position_capability - << ",\"lat\":" << std::llround(reported_target.latitude_deg * degrees_to_mavlink) - << ",\"lon\":" << std::llround(reported_target.longitude_deg * degrees_to_mavlink) - << ",\"alt\":" << _target.absolute_altitude_m << R"(,"position_std":[0.1,0.1])"; - send_message("TARGET_ABSOLUTE", fields.str()); - } -} - -void AutopilotTesterVisionTarget::send_message(const std::string &name, const std::string &fields) -{ - // Generate observations immediately, with UNIX timestamps as required by TARGET_*. - // No TIMESYNC: these flight tests use PX4's unsynchronized arrival-time fallback. - const auto timestamp_us = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); - MavlinkDirect::MavlinkMessage message{}; - message.message_name = name; - message.fields_json = "{\"timestamp\":" + std::to_string(timestamp_us) + "," + fields + "}"; - REQUIRE(_direct->send_message(message) == MavlinkDirect::Result::Success); -} - -void AutopilotTesterVisionTarget::check_target_yaw() -{ - const auto attitude = getTelemetry()->attitude_euler(); - const double sample_age_us = std::abs(static_cast(getTelemetry()->ground_truth().timestamp_us) - - attitude.timestamp_us); - constexpr double maximum_attitude_age_us = 1e6; - CAPTURE(sample_age_us); - REQUIRE(sample_age_us < maximum_attitude_age_us); - const double yaw_error_deg = std::abs(std::remainder(attitude.yaw_deg - target_yaw_deg, 360.0)); - constexpr double yaw_acceptance_deg = 5.0; - CAPTURE(attitude.yaw_deg, yaw_error_deg); - REQUIRE(yaw_error_deg < yaw_acceptance_deg); -} - -void AutopilotTesterVisionTarget::check_landed_at_target(float acceptance_radius_m) -{ - CHECK(getTelemetry()->landed_state() == Telemetry::LandedState::OnGround); - // Wait for a fresh simulator position after disarming before checking touchdown. - const auto previous_sample = getTelemetry()->ground_truth().timestamp_us; - const auto deadline = Clock::now() + telemetry_timeout; - - while (getTelemetry()->ground_truth().timestamp_us <= previous_sample && Clock::now() < deadline) { - std::this_thread::sleep_for(observation_poll_interval); - } - - REQUIRE(getTelemetry()->ground_truth().timestamp_us > previous_sample); - CoordinateTransformation target_frame({_target.latitude_deg, _target.longitude_deg}); - const auto vehicle = getTelemetry()->ground_truth(); - const auto relative = target_frame.local_from_global({vehicle.latitude_deg, vehicle.longitude_deg}); - const double landing_error_m = std::hypot(relative.north_m, relative.east_m); - std::cout << "Landing error: " << landing_error_m << " m" << std::endl; - CAPTURE(landing_error_m, acceptance_radius_m); - CHECK(landing_error_m < acceptance_radius_m); -} diff --git a/test/mavsdk_tests/autopilot_tester_vision_target.h b/test/mavsdk_tests/autopilot_tester_vision_target.h deleted file mode 100644 index 942a424d1ff..00000000000 --- a/test/mavsdk_tests/autopilot_tester_vision_target.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** - * - * Copyright (c) 2026 PX4 Development Team. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. Neither the name PX4 nor the names of its contributors may be - * used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************/ - -#pragma once - -#include "autopilot_tester.h" -#include - -class AutopilotTesterVisionTarget : public AutopilotTester -{ -public: - enum class Scenario { Vision, Gnss, VisionAndGnss, Mission, GnssJump, VisionLoss }; - - void connect(const std::string uri); - void set_landing_target(const CoordinateTransformation::LocalCoordinate &offset_from_home_m); - void precision_land(Scenario scenario, std::chrono::seconds timeout); - void check_landed_at_target(float acceptance_radius_m); - -private: - void start_landing_mission(); - void check_target_yaw(); - void send_target_observations(Scenario scenario, const Telemetry::GroundTruth &vehicle, - bool vision_enabled, double gnss_offset_east_m); - void send_message(const std::string &name, const std::string &fields); - - std::unique_ptr _direct; - Telemetry::GroundTruth _target{}; -}; diff --git a/test/mavsdk_tests/autopilot_tester_vision_target.py b/test/mavsdk_tests/autopilot_tester_vision_target.py new file mode 100644 index 00000000000..1ad159e0644 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_vision_target.py @@ -0,0 +1,368 @@ +"""AutopilotTester for precision landing on a target estimated by the vision target estimator. + +The landing pad is fixed on the ground next to home. The tester simulates the target sensors +from ground truth: TARGET_RELATIVE for a downward looking camera, and TARGET_ABSOLUTE for a GNSS +receiver on the pad. PX4 streams its estimate back as LANDING_TARGET. +""" + +import json +import math +import os +import threading +import time +from enum import Enum +from typing import Any, Dict, Optional + +from mavsdk.plugins.telemetry import LandedState # type: ignore + +from autopilot_tester import ( + MAV_CMD_NAV_LAND, MAV_CMD_NAV_WAYPOINT, MAV_FRAME_GLOBAL_RELATIVE_ALT, + TEST_DIR, AutopilotTester, log, raw_mission_item) +from geometry import CoordinateTransformation + +# TODO: Change development.xml to common.xml when TARGET_* are promoted. +MAVLINK_XML = os.path.join(TEST_DIR, "..", "..", "src", "modules", "mavlink", "mavlink", + "message_definitions", "v1.0", "development.xml") + +MAV_CMD_DO_SET_MODE = 176 +MAV_CMD_SET_MESSAGE_INTERVAL = 511 +MAV_MODE_FLAG_CUSTOM_MODE_ENABLED = 1 +PX4_CUSTOM_MAIN_MODE_AUTO = 4 +PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND = 9 +MAVLINK_MSG_ID_LANDING_TARGET = 149 +LANDING_TARGET_TYPE_VISION_FIDUCIAL = 2 +TARGET_OBS_FRAME_OTHER = 3 +TARGET_ABSOLUTE_SENSOR_CAPABILITY_POSITION = 1 + +MISSION_OFFSET_NORTH_M = -3.0 +TARGET_YAW_DEG = 120.0 +# Host time: detects telemetry that stopped, independent of the simulation. +TELEMETRY_TIMEOUT_S = 2.0 +OBSERVATION_POLL_INTERVAL_S = 0.001 + +MINIMUM_DISTURBANCE_HEIGHT_M = 3.0 +ACQUISITION_RADIUS_M = 0.75 +CORRECTED_RADIUS_M = 0.5 + + +class Scenario(Enum): + VISION = "vision" + GNSS = "gnss" + VISION_AND_GNSS = "vision_and_gnss" + MISSION = "mission" + GNSS_JUMP = "gnss_jump" + VISION_LOSS = "vision_loss" + + +# VTE_AID_MASK: target GNSS position (bit 0), vehicle GNSS velocity (bit 1), vision (bit 2), +# mission position (bit 3). Home aiding is always disabled. +AID_MASKS = { + Scenario.VISION: 4, + Scenario.GNSS: 3, + Scenario.MISSION: 14, +} +DEFAULT_AID_MASK = 7 + + +class AutopilotTesterVisionTarget(AutopilotTester): + + def __init__(self, speed_factor: Optional[float] = None) -> None: + super().__init__(speed_factor) + self._target_latitude_deg = math.nan + self._target_longitude_deg = math.nan + self._target_altitude_m = math.nan + self._estimate_lock = threading.Lock() + self._estimate: Optional[Dict[str, Any]] = None + + def connect(self, url: str) -> None: + super().connect(url) + + with open(MAVLINK_XML) as xml: + self._mavlink_direct.load_custom_xml(xml.read()) + + # Without VTE, TARGET_RELATIVE can bypass the estimator and feed precland directly. + assert self._param.get_param_int("VTE_EN") == 1, "VTE_EN needs to be set" + + def set_landing_target(self, north_m: float, east_m: float) -> None: + """Place the pad at an offset from home.""" + self.store_home() + home_latitude_deg, home_longitude_deg = self._home_or_fail() + self._target_altitude_m = self.home_absolute_altitude_m() + assert math.isfinite(self._target_altitude_m) + self._target_latitude_deg, self._target_longitude_deg = CoordinateTransformation( + home_latitude_deg, home_longitude_deg).global_from_local(north_m, east_m) + + def _target_frame(self) -> CoordinateTransformation: + return CoordinateTransformation(self._target_latitude_deg, self._target_longitude_deg) + + def _start_landing_mission(self) -> None: + # An approximate mission location: vision must correct the landing to the true pad. + latitude_deg, longitude_deg = self._target_frame().global_from_local( + MISSION_OFFSET_NORTH_M, 0.0) + x = round(latitude_deg * 1e7) + y = round(longitude_deg * 1e7) + waypoint = raw_mission_item( + 0, MAV_CMD_NAV_WAYPOINT, MAV_FRAME_GLOBAL_RELATIVE_ALT, x=x, y=y, + z=self._telemetry.position().relative_altitude_m, + param2=1.0, # Waypoint acceptance radius in metres. + current=1) + waypoint.param4 = math.nan + land = raw_mission_item( + 1, MAV_CMD_NAV_LAND, MAV_FRAME_GLOBAL_RELATIVE_ALT, x=x, y=y, z=0.0, + param2=2.0) # Required precision landing. + land.param3 = math.nan + land.param4 = math.nan + self.upload_mission_raw([waypoint, land]) + self._mission_raw.start_mission() + + def _on_landing_target(self, message: Any, _user_data: Any) -> None: + fields = json.loads(message.fields_json) + with self._estimate_lock: + self._estimate = fields + + def precision_land(self, scenario: Scenario, timeout_s: float) -> None: + self.set_param_int("VTE_AID_MASK", AID_MASKS.get(scenario, DEFAULT_AID_MASK)) + self._telemetry.set_rate_attitude_euler(15) + + # PX4 streams the VTE output as LANDING_TARGET, with the relative position in x, y, z. + self._mavlink_direct.subscribe_message("LANDING_TARGET", self._on_landing_target) + self.send_command_long(MAV_CMD_SET_MESSAGE_INTERVAL, + param1=MAVLINK_MSG_ID_LANDING_TARGET, + param2=50000) # 20 Hz + + if scenario == Scenario.MISSION: + self._start_landing_mission() + else: + self.send_command_long(MAV_CMD_DO_SET_MODE, + param1=MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, + param2=PX4_CUSTOM_MAIN_MODE_AUTO, + param3=PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND) + + # Use simulator time for flight deadlines so speedup does not change the scenario. + start_us = int(self._telemetry.ground_truth().timestamp_us) + assert start_us != 0, "No ground truth timestamp" + last_sample_received = time.monotonic() + last_sample_us = start_us + vision_loss_us = 0 + spoofed_samples = 0 + vision_enabled = scenario != Scenario.MISSION + mission_correction_checked = False + yaw_checked = False + target_frame = self._target_frame() + + while (self._telemetry.armed() + and (last_sample_us - start_us) / 1e6 < timeout_s): + vehicle = self._telemetry.ground_truth() + + if vehicle.timestamp_us != last_sample_us: + assert math.isfinite(vehicle.latitude_deg) + assert math.isfinite(vehicle.longitude_deg) + assert math.isfinite(vehicle.absolute_altitude_m) + north_m, east_m = target_frame.local_from_global( + vehicle.latitude_deg, vehicle.longitude_deg) + distance_m = math.hypot(north_m, east_m) + height_m = vehicle.absolute_altitude_m - self._target_altitude_m + + if scenario == Scenario.MISSION: + # Below PLD_SRCH_ALT (pinned in sih-sitl.json), so searching alone cannot + # expose vision. + mission_vision_height_m = 9.0 + + if not vision_enabled and height_m < mission_vision_height_m: + # Verify the aircraft is over the mission position before exposing the + # true pad. + mission_error_m = math.hypot(north_m - MISSION_OFFSET_NORTH_M, east_m) + assert mission_error_m < ACQUISITION_RADIUS_M, \ + "Not over the mission position: error {:.2f} m".format( + mission_error_m) + assert distance_m > abs(MISSION_OFFSET_NORTH_M) - ACQUISITION_RADIUS_M, \ + "Already over the pad before vision: {:.2f} m".format(distance_m) + vision_enabled = True + + correction_check_height_m = 4.0 + + if vision_enabled and height_m < correction_check_height_m: + # Allow the controller time to complete the 3 m correction before + # checking alignment. + assert distance_m < CORRECTED_RADIUS_M, \ + "Not corrected to the pad: {:.2f} m".format(distance_m) + mission_correction_checked = True + + vision_loss_height_m = 8.0 + minimum_bias_overlap_s = 4.0 + + if (scenario == Scenario.VISION_LOSS and vision_enabled + and MINIMUM_DISTURBANCE_HEIGHT_M < height_m < vision_loss_height_m + and distance_m < CORRECTED_RADIUS_M + and (vehicle.timestamp_us - start_us) / 1e6 >= minimum_bias_overlap_s): + # Verify yaw acquisition before vision disappears and the orientation + # estimate expires. + self._check_target_yaw() + yaw_checked = True + vision_enabled = False + vision_loss_us = vehicle.timestamp_us + log("Vision lost at {:.1f} m".format(height_m)) + + # Spoof only after acquisition, while descending with time left to react. + spoof_start_height_m = 8.0 + start_spoof = (scenario == Scenario.GNSS_JUMP + and distance_m < ACQUISITION_RADIUS_M + and MINIMUM_DISTURBANCE_HEIGHT_M < height_m < spoof_start_height_m) + spoof_gnss = start_spoof or spoofed_samples > 0 + gnss_bias_east_m = 2.0 + gnss_offset_east_m = gnss_bias_east_m if scenario == Scenario.VISION_LOSS else 0.0 + + if spoof_gnss: + gnss_jump_east_m = 200.0 + gnss_offset_east_m = gnss_jump_east_m + + self._send_target_observations(scenario, vehicle, vision_enabled, + gnss_offset_east_m) + yaw_check_height_m = 4.0 + + if (scenario != Scenario.GNSS and vision_enabled + and height_m < yaw_check_height_m): + self._check_target_yaw() + yaw_checked = True + + if spoof_gnss: + spoofed_samples += 1 + # Catch a transient excursion even if vision subsequently recovers the + # landing. + spoof_max_distance_m = 2.0 + assert distance_m < spoof_max_distance_m, \ + "Followed the GNSS jump: {:.2f} m from the pad".format(distance_m) + + if vision_loss_us != 0: + assert distance_m < CORRECTED_RADIUS_M, \ + "Drifted after vision loss: {:.2f} m from the pad".format(distance_m) + + if 1.0 < height_m < 4.0: + self._check_estimate(vehicle.timestamp_us, north_m, east_m, height_m) + + last_sample_us = vehicle.timestamp_us + last_sample_received = time.monotonic() + + # Do not keep publishing a stale observation if ground-truth telemetry stops. + assert time.monotonic() - last_sample_received < TELEMETRY_TIMEOUT_S, \ + "Ground-truth telemetry stopped during precision landing" + + time.sleep(OBSERVATION_POLL_INTERVAL_S) + + assert not self._telemetry.armed(), \ + "Still armed after {} s of precision landing".format(timeout_s) + + if scenario != Scenario.GNSS: + assert yaw_checked, "Target yaw was never checked" + + if scenario == Scenario.MISSION: + assert mission_correction_checked, "Mission correction was never checked" + + if scenario == Scenario.GNSS_JUMP: + minimum_spoofed_samples = 10 + assert spoofed_samples >= minimum_spoofed_samples, \ + "Only {} spoofed samples".format(spoofed_samples) + + if scenario == Scenario.VISION_LOSS: + minimum_vision_outage_s = 8.0 + assert vision_loss_us != 0, "Vision was never lost" + outage_s = (last_sample_us - vision_loss_us) / 1e6 + assert outage_s >= minimum_vision_outage_s, \ + "Vision outage only {:.1f} s".format(outage_s) + + def _check_estimate(self, timestamp_us: int, north_m: float, east_m: float, + height_m: float) -> None: + """VTE must keep a live estimate that matches the pad in 3D, including the height.""" + with self._estimate_lock: + estimate = self._estimate + assert estimate is not None, "No LANDING_TARGET received" + estimate_age_s = (timestamp_us - estimate["time_usec"]) * 1e-6 + estimate_error_m = math.hypot(estimate["x"] + north_m, estimate["y"] + east_m, + estimate["z"] - height_m) + details = "age {:.3f} s, error {:.2f} m, z {:.2f} m, height {:.2f} m".format( + estimate_age_s, estimate_error_m, estimate["z"], height_m) + assert estimate["position_valid"], "Target estimate not valid: " + details + maximum_estimate_age_s = 0.25 + assert abs(estimate_age_s) < maximum_estimate_age_s, \ + "Target estimate too old: " + details + estimate_acceptance_m = 0.5 + assert estimate_error_m < estimate_acceptance_m, \ + "Target estimate off: " + details + + def _send_target_observations(self, scenario: Scenario, vehicle: Any, vision_enabled: bool, + gnss_offset_east_m: float) -> None: + target_frame = self._target_frame() + + if scenario != Scenario.GNSS and vision_enabled: + vehicle_north_m, vehicle_east_m = target_frame.local_from_global( + vehicle.latitude_deg, vehicle.longitude_deg) + target_ned_m = (-vehicle_north_m, -vehicle_east_m, + vehicle.absolute_altitude_m - self._target_altitude_m) + # Fixed virtual camera looking down (yaw 90, then pitch -90 deg): + # sensor (x, y, z) = (down, -north, -east). Independent of the estimated attitude; + # the pitch stops q_sensor commuting with q_target. + target_sensor_m = (target_ned_m[2], -target_ned_m[0], -target_ned_m[1]) + # q_target = conj(q_sensor) * yaw(TARGET_YAW_DEG): the pad lies flat, so + # q_sensor * q_target is a pure yaw. + cos_half_yaw = math.cos(math.radians(TARGET_YAW_DEG) / 2) + sin_half_yaw = math.sin(math.radians(TARGET_YAW_DEG) / 2) + q_target_wy = 0.5 * (cos_half_yaw + sin_half_yaw) + q_target_xz = 0.5 * (sin_half_yaw - cos_half_yaw) + self._send_target_message("TARGET_RELATIVE", { + "frame": TARGET_OBS_FRAME_OTHER, + "type": LANDING_TARGET_TYPE_VISION_FIDUCIAL, + "x": target_sensor_m[0], "y": target_sensor_m[1], "z": target_sensor_m[2], + "pos_std": [0.1, 0.1, 0.1], + "q_sensor": [0.5, 0.5, -0.5, 0.5], + "q_target": [q_target_wy, q_target_xz, q_target_wy, q_target_xz], + "yaw_std": 0.1, + }) + + if scenario not in (Scenario.VISION, Scenario.MISSION): + latitude_deg, longitude_deg = target_frame.global_from_local( + 0.0, gnss_offset_east_m) + self._send_target_message("TARGET_ABSOLUTE", { + "sensor_capabilities": TARGET_ABSOLUTE_SENSOR_CAPABILITY_POSITION, + "lat": round(latitude_deg * 1e7), + "lon": round(longitude_deg * 1e7), + "alt": self._target_altitude_m, + "position_std": [0.1, 0.1], + }) + + def _send_target_message(self, name: str, fields: Dict[str, Any]) -> None: + # Generate observations immediately, with UNIX timestamps as required by TARGET_*. + # No TIMESYNC: these flight tests use PX4's unsynchronized arrival-time fallback. + self.send_mavlink_message(name, {"timestamp": int(time.time() * 1e6), **fields}) + + def _check_target_yaw(self) -> None: + attitude = self._telemetry.attitude_euler() + sample_age_us = abs(self._telemetry.ground_truth().timestamp_us - attitude.timestamp_us) + maximum_attitude_age_us = 1e6 + assert sample_age_us < maximum_attitude_age_us, \ + "Attitude too old: {} us".format(sample_age_us) + yaw_error_deg = abs(math.remainder(attitude.yaw_deg - TARGET_YAW_DEG, 360.0)) + yaw_acceptance_deg = 5.0 + assert yaw_error_deg < yaw_acceptance_deg, \ + "Yaw {:.1f} deg, error to target yaw {:.1f} deg".format( + attitude.yaw_deg, yaw_error_deg) + + def check_landed_at_target(self, acceptance_radius_m: float) -> None: + assert self._telemetry.landed_state() == LandedState.ON_GROUND, \ + "Landed state is {}".format(self._telemetry.landed_state()) + + # Wait for a fresh simulator position after disarming before checking touchdown. + previous_sample_us = self._telemetry.ground_truth().timestamp_us + deadline = time.monotonic() + TELEMETRY_TIMEOUT_S + while (self._telemetry.ground_truth().timestamp_us <= previous_sample_us + and time.monotonic() < deadline): + time.sleep(OBSERVATION_POLL_INTERVAL_S) + + vehicle = self._telemetry.ground_truth() + assert vehicle.timestamp_us > previous_sample_us, "No fresh ground truth after landing" + north_m, east_m = self._target_frame().local_from_global( + vehicle.latitude_deg, vehicle.longitude_deg) + landing_error_m = math.hypot(north_m, east_m) + log("Landing error: {:.2f} m".format(landing_error_m)) + assert landing_error_m < acceptance_radius_m, \ + "Landed {:.2f} m from the pad, expected < {} m".format( + landing_error_m, acceptance_radius_m) diff --git a/test/mavsdk_tests/catch2/catch.hpp b/test/mavsdk_tests/catch2/catch.hpp deleted file mode 100644 index 71c863abeeb..00000000000 --- a/test/mavsdk_tests/catch2/catch.hpp +++ /dev/null @@ -1,17965 +0,0 @@ -/* - * Catch v2.13.8 - * Generated: 2022-01-03 21:20:09.589503 - * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -// start catch.hpp - - -#define CATCH_VERSION_MAJOR 2 -#define CATCH_VERSION_MINOR 13 -#define CATCH_VERSION_PATCH 8 - -#ifdef __clang__ -# pragma clang system_header -#elif defined __GNUC__ -# pragma GCC system_header -#endif - -// start catch_suppress_warnings.h - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wswitch-enum" -# pragma clang diagnostic ignored "-Wcovered-switch-default" -# endif -#elif defined __GNUC__ - // Because REQUIREs trigger GCC's -Wparentheses, and because still - // supported version of g++ have only buggy support for _Pragmas, - // Wparentheses have to be suppressed globally. -# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details - -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic ignored "-Wpadded" -#endif -// end catch_suppress_warnings.h -#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -# define CATCH_CONFIG_ALL_PARTS -#endif - -// In the impl file, we want to have access to all parts of the headers -// Can also be used to sanely support PCHs -#if defined(CATCH_CONFIG_ALL_PARTS) -# define CATCH_CONFIG_EXTERNAL_INTERFACES -# if defined(CATCH_CONFIG_DISABLE_MATCHERS) -# undef CATCH_CONFIG_DISABLE_MATCHERS -# endif -# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) -# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER -# endif -#endif - -#if !defined(CATCH_CONFIG_IMPL_ONLY) -// start catch_platform.h - -// See e.g.: -// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html -#ifdef __APPLE__ -# include -# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ - (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) -# define CATCH_PLATFORM_MAC -# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) -# define CATCH_PLATFORM_IPHONE -# endif - -#elif defined(linux) || defined(__linux) || defined(__linux__) -# define CATCH_PLATFORM_LINUX - -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) -# define CATCH_PLATFORM_WINDOWS -#endif - -// end catch_platform.h - -#ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif -#endif - -// start catch_user_interfaces.h - -namespace Catch { - unsigned int rngSeed(); -} - -// end catch_user_interfaces.h -// start catch_tag_alias_autoregistrar.h - -// start catch_common.h - -// start catch_compiler_capabilities.h - -// Detect a number of compiler features - by compiler -// The following features are defined: -// -// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? -// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? -// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? -// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? -// **************** -// Note to maintainers: if new toggles are added please document them -// in configuration.md, too -// **************** - -// In general each macro has a _NO_ form -// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -#ifdef __cplusplus - -# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) -# define CATCH_CPP14_OR_GREATER -# endif - -# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -# define CATCH_CPP17_OR_GREATER -# endif - -#endif - -// Only GCC compiler should be used in this block, so other compilers trying to -// mask themselves as GCC should be ignored. -#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) - -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) - -#endif - -#if defined(__clang__) - -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) - -// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug -// which results in calls to destructors being emitted for each temporary, -// without a matching initialization. In practice, this can result in something -// like `std::string::~string` being called on an uninitialized value. -// -// For example, this code will likely segfault under IBM XL: -// ``` -// REQUIRE(std::string("12") + "34" == "1234") -// ``` -// -// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. -# if !defined(__ibmxl__) && !defined(__CUDACC__) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ -# endif - -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ - _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") - -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) - -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) - -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) - -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// Assume that non-Windows platforms support posix signals by default -#if !defined(CATCH_PLATFORM_WINDOWS) - #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS -#endif - -//////////////////////////////////////////////////////////////////////////////// -// We know some environments not to support full POSIX signals -#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) - #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -#endif - -#ifdef __OS400__ -# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -# define CATCH_CONFIG_COLOUR_NONE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Android somehow still does not support std::to_string -#if defined(__ANDROID__) -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING -# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Not all Windows environments support SEH properly -#if defined(__MINGW32__) -# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH -#endif - -//////////////////////////////////////////////////////////////////////////////// -// PS4 -#if defined(__ORBIS__) -# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Cygwin -#ifdef __CYGWIN__ - -// Required for some versions of Cygwin to declare gettimeofday -// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin -# define _BSD_SOURCE -// some versions of cygwin (most) do not support std::to_string. Use the libstd check. -// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 -# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ - && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) - -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING - -# endif -#endif // __CYGWIN__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#if defined(_MSC_VER) - -// Universal Windows platform does not support SEH -// Or console colours (or console at all...) -# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) -# define CATCH_CONFIG_COLOUR_NONE -# else -# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH -# endif - -# if !defined(__clang__) // Handle Clang masquerading for msvc - -// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ -// _MSVC_TRADITIONAL == 0 means new conformant preprocessor -// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor -# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) -# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -# endif // MSVC_TRADITIONAL - -// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop` -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) -# endif // __clang__ - -#endif // _MSC_VER - -#if defined(_REENTRANT) || defined(_MSC_VER) -// Enable async processing, as -pthread is specified or no additional linking is required -# define CATCH_INTERNAL_CONFIG_USE_ASYNC -#endif // _MSC_VER - -//////////////////////////////////////////////////////////////////////////////// -// Check if we are compiled with -fno-exceptions or equivalent -#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) -# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED -#endif - -//////////////////////////////////////////////////////////////////////////////// -// DJGPP -#ifdef __DJGPP__ -# define CATCH_INTERNAL_CONFIG_NO_WCHAR -#endif // __DJGPP__ - -//////////////////////////////////////////////////////////////////////////////// -// Embarcadero C++Build -#if defined(__BORLANDC__) - #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN -#endif - -//////////////////////////////////////////////////////////////////////////////// - -// Use of __COUNTER__ is suppressed during code analysis in -// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly -// handled by it. -// Otherwise all supported compilers support COUNTER macro, -// but user still might want to turn it off -#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) - #define CATCH_INTERNAL_CONFIG_COUNTER -#endif - -//////////////////////////////////////////////////////////////////////////////// - -// RTX is a special version of Windows that is real time. -// This means that it is detected as Windows, but does not provide -// the same set of capabilities as real Windows does. -#if defined(UNDER_RTSS) || defined(RTX64_BUILD) - #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH - #define CATCH_INTERNAL_CONFIG_NO_ASYNC - #define CATCH_CONFIG_COLOUR_NONE -#endif - -#if !defined(_GLIBCXX_USE_C99_MATH_TR1) -#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER -#endif - -// Various stdlib support checks that require __has_include -#if defined(__has_include) - // Check if string_view is available and usable - #if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW - #endif - - // Check if optional is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) - - // Check if byte is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # include - # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) - # define CATCH_INTERNAL_CONFIG_CPP17_BYTE - # endif - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) - - // Check if variant is available and usable - # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # if defined(__clang__) && (__clang_major__ < 8) - // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 - // fix should be in clang 8, workaround in libstdc++ 8.2 - # include - # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # define CATCH_CONFIG_NO_CPP17_VARIANT - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__clang__) && (__clang_major__ < 8) - # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) -#endif // defined(__has_include) - -#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) -# define CATCH_CONFIG_COUNTER -#endif -#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) -# define CATCH_CONFIG_WINDOWS_SEH -#endif -// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. -#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) -# define CATCH_CONFIG_POSIX_SIGNALS -#endif -// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. -#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) -# define CATCH_CONFIG_WCHAR -#endif - -#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) -# define CATCH_CONFIG_CPP11_TO_STRING -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) -# define CATCH_CONFIG_CPP17_OPTIONAL -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) -# define CATCH_CONFIG_CPP17_STRING_VIEW -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) -# define CATCH_CONFIG_CPP17_VARIANT -#endif - -#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) -# define CATCH_CONFIG_CPP17_BYTE -#endif - -#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) -# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE -#endif - -#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) -# define CATCH_CONFIG_NEW_CAPTURE -#endif - -#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) -# define CATCH_CONFIG_DISABLE_EXCEPTIONS -#endif - -#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) -# define CATCH_CONFIG_POLYFILL_ISNAN -#endif - -#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) -# define CATCH_CONFIG_USE_ASYNC -#endif - -#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) -# define CATCH_CONFIG_ANDROID_LOGWRITE -#endif - -#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) -# define CATCH_CONFIG_GLOBAL_NEXTAFTER -#endif - -// Even if we do not think the compiler has that warning, we still have -// to provide a macro that can be used by the code. -#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION -#endif -#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS -#endif - -// The goal of this macro is to avoid evaluation of the arguments, but -// still have the compiler warn on problems inside... -#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) -#endif - -#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#elif defined(__clang__) && (__clang_major__ < 5) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#endif - -#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS -#endif - -#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) -#define CATCH_TRY if ((true)) -#define CATCH_CATCH_ALL if ((false)) -#define CATCH_CATCH_ANON(type) if ((false)) -#else -#define CATCH_TRY try -#define CATCH_CATCH_ALL catch (...) -#define CATCH_CATCH_ANON(type) catch (type) -#endif - -#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) -#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#endif - -// end catch_compiler_capabilities.h -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) -#ifdef CATCH_CONFIG_COUNTER -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) -#else -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) -#endif - -#include -#include -#include - -// We need a dummy global operator<< so we can bring it into Catch namespace later -struct Catch_global_namespace_dummy {}; -std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); - -namespace Catch { - - struct CaseSensitive { enum Choice { - Yes, - No - }; }; - - class NonCopyable { - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; - - protected: - NonCopyable(); - virtual ~NonCopyable(); - }; - - struct SourceLineInfo { - - SourceLineInfo() = delete; - SourceLineInfo( char const* _file, std::size_t _line ) noexcept - : file( _file ), - line( _line ) - {} - - SourceLineInfo( SourceLineInfo const& other ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo( SourceLineInfo&& ) noexcept = default; - SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; - - bool empty() const noexcept { return file[0] == '\0'; } - bool operator == ( SourceLineInfo const& other ) const noexcept; - bool operator < ( SourceLineInfo const& other ) const noexcept; - - char const* file; - std::size_t line; - }; - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); - - // Bring in operator<< from global namespace into Catch namespace - // This is necessary because the overload of operator<< above makes - // lookup stop at namespace Catch - using ::operator<<; - - // Use this in variadic streaming macros to allow - // >> +StreamEndStop - // as well as - // >> stuff +StreamEndStop - struct StreamEndStop { - std::string operator+() const; - }; - template - T const& operator + ( T const& value, StreamEndStop ) { - return value; - } -} - -#define CATCH_INTERNAL_LINEINFO \ - ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) - -// end catch_common.h -namespace Catch { - - struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - }; - -} // end namespace Catch - -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION - -// end catch_tag_alias_autoregistrar.h -// start catch_test_registry.h - -// start catch_interfaces_testcase.h - -#include - -namespace Catch { - - class TestSpec; - - struct ITestInvoker { - virtual void invoke () const = 0; - virtual ~ITestInvoker(); - }; - - class TestCase; - struct IConfig; - - struct ITestCaseRegistry { - virtual ~ITestCaseRegistry(); - virtual std::vector const& getAllTests() const = 0; - virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; - }; - - bool isThrowSafe( TestCase const& testCase, IConfig const& config ); - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); - std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); - std::vector const& getAllTestCasesSorted( IConfig const& config ); - -} - -// end catch_interfaces_testcase.h -// start catch_stringref.h - -#include -#include -#include -#include - -namespace Catch { - - /// A non-owning string class (similar to the forthcoming std::string_view) - /// Note that, because a StringRef may be a substring of another string, - /// it may not be null terminated. - class StringRef { - public: - using size_type = std::size_t; - using const_iterator = const char*; - - private: - static constexpr char const* const s_empty = ""; - - char const* m_start = s_empty; - size_type m_size = 0; - - public: // construction - constexpr StringRef() noexcept = default; - - StringRef( char const* rawChars ) noexcept; - - constexpr StringRef( char const* rawChars, size_type size ) noexcept - : m_start( rawChars ), - m_size( size ) - {} - - StringRef( std::string const& stdString ) noexcept - : m_start( stdString.c_str() ), - m_size( stdString.size() ) - {} - - explicit operator std::string() const { - return std::string(m_start, m_size); - } - - public: // operators - auto operator == ( StringRef const& other ) const noexcept -> bool; - auto operator != (StringRef const& other) const noexcept -> bool { - return !(*this == other); - } - - auto operator[] ( size_type index ) const noexcept -> char { - assert(index < m_size); - return m_start[index]; - } - - public: // named queries - constexpr auto empty() const noexcept -> bool { - return m_size == 0; - } - constexpr auto size() const noexcept -> size_type { - return m_size; - } - - // Returns the current start pointer. If the StringRef is not - // null-terminated, throws std::domain_exception - auto c_str() const -> char const*; - - public: // substrings and searches - // Returns a substring of [start, start + length). - // If start + length > size(), then the substring is [start, size()). - // If start > size(), then the substring is empty. - auto substr( size_type start, size_type length ) const noexcept -> StringRef; - - // Returns the current start pointer. May not be null-terminated. - auto data() const noexcept -> char const*; - - constexpr auto isNullTerminated() const noexcept -> bool { - return m_start[m_size] == '\0'; - } - - public: // iterators - constexpr const_iterator begin() const { return m_start; } - constexpr const_iterator end() const { return m_start + m_size; } - }; - - auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; - auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; - - constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { - return StringRef( rawChars, size ); - } -} // namespace Catch - -constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { - return Catch::StringRef( rawChars, size ); -} - -// end catch_stringref.h -// start catch_preprocessor.hpp - - -#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ -#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) - -#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ -// MSVC needs more evaluations -#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) -#else -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) -#endif - -#define CATCH_REC_END(...) -#define CATCH_REC_OUT - -#define CATCH_EMPTY() -#define CATCH_DEFER(id) id CATCH_EMPTY() - -#define CATCH_REC_GET_END2() 0, CATCH_REC_END -#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 -#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 -#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT -#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) -#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) - -#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) - -#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) - -// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, -// and passes userdata as the first parameter to each invocation, -// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) -#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) - -#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) - -#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) -#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ -#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ -#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF -#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) -#else -// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF -#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) -#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) -#endif - -#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ -#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) - -#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) - -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) -#else -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) -#endif - -#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ - CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) - -#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) -#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) -#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) -#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) -#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) -#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) -#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) -#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) -#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) -#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) -#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) - -#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N - -#define INTERNAL_CATCH_TYPE_GEN\ - template struct TypeList {};\ - template\ - constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ - template class...> struct TemplateTypeList{};\ - template class...Cs>\ - constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ - template\ - struct append;\ - template\ - struct rewrap;\ - template class, typename...>\ - struct create;\ - template class, typename>\ - struct convert;\ - \ - template \ - struct append { using type = T; };\ - template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ - struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ - template< template class L1, typename...E1, typename...Rest>\ - struct append, TypeList, Rest...> { using type = L1; };\ - \ - template< template class Container, template class List, typename...elems>\ - struct rewrap, List> { using type = TypeList>; };\ - template< template class Container, template class List, class...Elems, typename...Elements>\ - struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ - \ - template