From c4e66ad3031b1d13bc66cec74f26fbb7fe6a16e6 Mon Sep 17 00:00:00 2001 From: Anil Kircaliali Date: Tue, 24 Nov 2026 16:15:26 +0100 Subject: [PATCH] feat(navigator): RTL type 6 takes the quickest rally point instead of the closest --- docs/en/config/safety.md | 2 +- docs/en/flight_modes/return.md | 17 +- docs/en/releases/main.md | 6 +- src/modules/navigator/rtl.cpp | 237 ++++++++++++++++-------- src/modules/navigator/rtl.h | 31 +++- src/modules/navigator/rtl_direct.cpp | 23 ++- src/modules/navigator/rtl_direct.h | 6 +- src/modules/navigator/rtl_params.yaml | 2 +- src/modules/navigator/test/test_RTL.cpp | 150 ++++++++++++++- 9 files changed, 363 insertions(+), 111 deletions(-) diff --git a/docs/en/config/safety.md b/docs/en/config/safety.md index e20961d6d0b..62eae961009 100644 --- a/docs/en/config/safety.md +++ b/docs/en/config/safety.md @@ -125,7 +125,7 @@ PX4 compares: - The time needed to return, estimated along the current Return mode path (including climb, descent and landing), with the safety margin set by [RTL_TIME_FACTOR](../advanced_config/parameter_reference.md#RTL_TIME_FACTOR) and [RTL_TIME_MARGIN](../advanced_config/parameter_reference.md#RTL_TIME_MARGIN). - The remaining flight time of the battery with the least time left, if more than one is connected. -With the [battery-aware home priority return type](../flight_modes/return.md#rtl_type_6) (`RTL_TYPE=6`) the return destination itself depends on the battery, so the time needed to return is the lower of the estimates to home and to the rally point that replaces it. The failsafe then engages once neither is within reach, not when home drops out of reach. +With the [battery-aware home priority return type](../flight_modes/return.md#rtl_type_6) (`RTL_TYPE=6`) the return destination itself depends on the battery, so the time needed to return is the lowest of the estimates to home and to the rally points. The failsafe then engages once none of them is within reach, not when home drops out of reach. Once Return mode has been triggered, it is not cancelled if the estimate improves again on the way back. diff --git a/docs/en/flight_modes/return.md b/docs/en/flight_modes/return.md index a7ed3130f5f..ff498a9a449 100644 --- a/docs/en/flight_modes/return.md +++ b/docs/en/flight_modes/return.md @@ -58,8 +58,8 @@ At high level these are: Rally points are not considered. - [Rally point return](#rtl_type_5) (`RTL_TYPE=5`): Return directly to the closest rally point, ignoring home and mission landing. If no rally point is defined, land at the current position (a fixed-wing vehicle circles there instead). -- [Battery-aware home priority return](#rtl_type_6) (`RTL_TYPE=6`): Return to home if the estimated flight time is within the remaining battery time, otherwise return to the closest rally point if it is closer than home. - Falls back to the closest safe point (home or rally) if the remaining battery time is unknown/unavailable. +- [Battery-aware home priority return](#rtl_type_6) (`RTL_TYPE=6`): Return to home if the estimated flight time is within the remaining battery time, otherwise return to the rally point with the lowest estimated flight time if it is quicker to reach than home. + Takes the quickest of home and the rally points if the remaining battery time is unknown/unavailable. More detailed explanations for each of the types are provided in the following sections. @@ -200,14 +200,13 @@ The vehicle: - Computes the estimated time to fly home, including a safety factor and margin ([RTL_TIME_FACTOR](#RTL_TIME_FACTOR) and [RTL_TIME_MARGIN](#RTL_TIME_MARGIN)). - If the estimated flight time to home is less than the remaining battery time (`time_remaining_s`): returns to home via a direct path. -- If home is not within battery reach: returns to the closest rally point via a direct path. -- If no rally point is closer than home, or no rally points are defined, falls back to home. -- If the battery time remaining estimate is unavailable (e.g. no current sensor, battery capacity not - configured): falls back to returning to the closest safe point — whichever of home or the defined rally - points is nearest. +- If home is not within battery reach: returns to the rally point with the lowest estimated flight time via a direct path. + The estimate of each rally point includes its own path around geofences and, for fixed-wing flight, the wind. +- If no rally point is quicker to reach than home, or no rally points are defined, falls back to home. +- If the battery time remaining estimate is unavailable (e.g. no current sensor, battery capacity not configured): returns to the quickest of home and the defined rally points. The [distance-aware return failsafe](../config/safety.md#distance-aware-return-failsafe) does not engage Return mode when home drops out of battery reach. -It waits until the rally point that replaces home is no longer within reach either. +It waits until no rally point is within reach either. ## Geofence Awareness {#geofence_awareness} @@ -343,7 +342,7 @@ The Return parameters are listed in [Parameter Reference > Return Mode](../advan | Parameter | Description | | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [RTL_TYPE](../advanced_config/parameter_reference.md#RTL_TYPE) | Return mechanism (path and destination).
`0`: Return to a rally point or home (whichever is closest) via direct path.
`1`: Return to a rally point or the mission landing pattern start point (whichever is closest), via direct path. If neither mission landing or rally points are defined return home via a direct path. If the destination is a mission landing pattern, follow the pattern to land.
`2`: Use the mission path to landing while skipping DO_JUMP and other non-position mission items if a landing pattern is defined, otherwise fast-reverse to home with the same traversal rules. Ignore rally points. Fly direct to home if no mission plan is defined.
`3`: Return via direct path to closest destination: home, start of mission landing pattern or safe point. If the destination is a mission landing pattern, follow the pattern to land.
`4`: Like type 2, but selects between mission landing (fast-forward) and reverse mission path based on which requires fewer waypoints from the current position. Rally points not considered. Fly direct to home if no mission is defined.
`5`: Return via direct path to closest rally point. If no rally points are defined, land at current position (a fixed-wing vehicle circles there).
`6`: Return to home if estimated flight time to home is less than remaining battery time, otherwise return to closest rally point if it is closer than home. Falls back to closest safe point (home or rally) if battery time remaining is unavailable. | +| [RTL_TYPE](../advanced_config/parameter_reference.md#RTL_TYPE) | Return mechanism (path and destination).
`0`: Return to a rally point or home (whichever is closest) via direct path.
`1`: Return to a rally point or the mission landing pattern start point (whichever is closest), via direct path. If neither mission landing or rally points are defined return home via a direct path. If the destination is a mission landing pattern, follow the pattern to land.
`2`: Use the mission path to landing while skipping DO_JUMP and other non-position mission items if a landing pattern is defined, otherwise fast-reverse to home with the same traversal rules. Ignore rally points. Fly direct to home if no mission plan is defined.
`3`: Return via direct path to closest destination: home, start of mission landing pattern or safe point. If the destination is a mission landing pattern, follow the pattern to land.
`4`: Like type 2, but selects between mission landing (fast-forward) and reverse mission path based on which requires fewer waypoints from the current position. Rally points not considered. Fly direct to home if no mission is defined.
`5`: Return via direct path to closest rally point. If no rally points are defined, land at current position (a fixed-wing vehicle circles there).
`6`: Return to home if estimated flight time to home is less than remaining battery time, otherwise return to the rally point with the lowest time estimate if it is quicker to reach than home. Takes the quickest of home and the rally points if battery time remaining is unavailable. | | [RTL_RETURN_ALT](../advanced_config/parameter_reference.md#RTL_RETURN_ALT) | Return altitude in meters (default: 60m) when [RTL_CONE_ANG](../advanced_config/parameter_reference.md#RTL_CONE_ANG) is 0. If already above this value the vehicle will return at its current altitude. | | [RTL_DESCEND_ALT](../advanced_config/parameter_reference.md#RTL_DESCEND_ALT) | Altitude above the destination used for the final descent before landing or loitering (default: 30m). | | [RTL_LAND_DELAY](../advanced_config/parameter_reference.md#RTL_LAND_DELAY) | Time to wait at `RTL_DESCEND_ALT` before landing (default: 0 s, -1 on fixed-wing airframes). If set to -1 the system will loiter at `RTL_DESCEND_ALT` rather than landing. The delay is provided to allow you to configure time for landing gear to be deployed (triggered automatically). | diff --git a/docs/en/releases/main.md b/docs/en/releases/main.md index 4f5deb1102f..b09234b58af 100644 --- a/docs/en/releases/main.md +++ b/docs/en/releases/main.md @@ -164,9 +164,9 @@ Please continue reading for [upgrade instructions](#upgrade-guide). - [Motor failure recovery](../config/motor_failure_recovery.md) for hexarotors: on a single motor failure the control allocator removes the failed motor and additionally stops ([CA_FAILURE_MODE](../advanced_config/parameter_reference.md#CA_FAILURE_MODE) = `1`) or reverses (`2`) the motor opposite it to recover the lost yaw authority. Mode `2` requires a reverse-capable ESC and models the reverse thrust of a forward propeller with the new [CA_REV_THR_FRAC](../advanced_config/parameter_reference.md#CA_REV_THR_FRAC) (default `0.4`). Reversible motor outputs on DroneCAN are now sent as signed `RawCommand` values (negative is reverse). ([PX4-Autopilot#28078](https://github.com/PX4/PX4-Autopilot/pull/28078)) - [Distance-aware return failsafe](../config/safety.md#distance-aware-return-failsafe) (also known as "bingo fuel"): engaging Return mode when the remaining flight time is only just enough to return is now part of [COM_LOW_BAT_ACT](../advanced_config/parameter_reference.md#COM_LOW_BAT_ACT) `3` and `4` (the new options `5` and `6` opt out), instead of with the separate `COM_FLTT_LOW_ACT`. See the [Upgrade Guide](#upgrade-guide). ([PX4-Autopilot#26955](https://github.com/PX4/PX4-Autopilot/pull/26955)) - Added `RTL_TYPE=6` for battery-aware home priority return ([PX4-Autopilot#26968](https://github.com/PX4/PX4-Autopilot/pull/26968)). - Returns to home if the estimated flight time to home is within the remaining battery time; otherwise returns to the closest rally point if it is closer than home. - Falls back to the closest safe point (home or rally) if battery time remaining is unavailable. - The [distance-aware return failsafe](../config/safety.md#distance-aware-return-failsafe) engages once neither home nor that rally point is within reach. + Returns to home if the estimated flight time to home is within the remaining battery time; otherwise returns to the rally point with the lowest estimated flight time if it is quicker to reach than home. + Takes the quickest of home and the rally points if battery time remaining is unavailable. + The [distance-aware return failsafe](../config/safety.md#distance-aware-return-failsafe) engages once neither home nor any rally point is within reach. - [Secure boot](../advanced_config/bootloader_secure_boot.md#multi-part-signed-images) now supports applications that can boot securely from SD card or eMMC. ([PX4-Autopilot#28228](https://github.com/PX4/PX4-Autopilot/pull/28228)) - [Motor failure detection](../config/motor_failure_detection.md) now compares a low-pass filtered current residual against a separate trip band and trigger time for the undercurrent and overcurrent directions, instead of one symmetric band on the instantaneous current, and the current model gains an offset term. See [Upgrading from PX4 v1.18](../config/motor_failure_detection.md#upgrading-from-px4-v1-18). ([PX4-Autopilot#27711](https://github.com/PX4/PX4-Autopilot/pull/27711), [PX4-Autopilot#27917](https://github.com/PX4/PX4-Autopilot/pull/27917)) - For MC, arming check can detect [stuck motors](../config/safety.md#motor-not-spinning-after-arming) and disarm before takeoff. ([PX4-Autopilot#29436](https://github.com/PX4/PX4-Autopilot/pull/29436)) diff --git a/src/modules/navigator/rtl.cpp b/src/modules/navigator/rtl.cpp index 2d2a5c512e6..ed88a141789 100644 --- a/src/modules/navigator/rtl.cpp +++ b/src/modules/navigator/rtl.cpp @@ -54,6 +54,7 @@ using namespace time_literals; using namespace math; static constexpr float MIN_DIST_THRESHOLD = 2.f; +static constexpr float MIN_TIME_THRESHOLD_S = 1.f; // Named constants for RTL_TYPE parameter values (must match value tags in rtl_params.yaml). static constexpr int RTL_TYPE_CLOSEST_HOME_OR_SAFE_POINT = 0; @@ -300,13 +301,13 @@ void RTL::selectHomeIfReachable(ReturnSelection &selection) && PX4_ISFINITE(worst_battery_time_s) && (time_to_home.safe_time_estimate < worst_battery_time_s); - // A rally point replaces Home only if it is closer - const float home_dist = get_distance_to_next_waypoint(_global_pos_sub.get().lat, _global_pos_sub.get().lon, - home.lat, home.lon); + // A rally point replaces Home only if it is quicker to reach uint8_t rally_point_index{RTL_STATUS_NO_SAFE_POINT}; bool rally_point_has_land_approach{false}; - const PositionYawSetpoint rally_point = findClosestSafePoint(home_dist, /*skip_near_home=*/false, - rally_point_index, rally_point_has_land_approach); + rtl_time_estimate_s time_to_rally_point{}; + const PositionYawSetpoint rally_point = findQuickestSafePoint( + time_to_home.valid ? time_to_home.safe_time_estimate : FLT_MAX, + rally_point_index, rally_point_has_land_approach, time_to_rally_point); const bool has_rally_point = rally_point_index != RTL_STATUS_NO_SAFE_POINT; if (!home_within_reach) { @@ -319,14 +320,8 @@ void RTL::selectHomeIfReachable(ReturnSelection &selection) selection.safe_point_index = rally_point_index; } - // If no rally points are closer (or none are defined), fall back to home (already set as the destination) } else if (has_rally_point) { - // Only a quicker rally point can extend the available return time. - const rtl_time_estimate_s fallback = estimateDirectReturn(rally_point); - - if (fallback.valid && fallback.safe_time_estimate < time_to_home.safe_time_estimate) { - selection.fallback_safe_time_estimate = fallback.safe_time_estimate; - } + selection.fallback_safe_time_estimate = time_to_rally_point.safe_time_estimate; } } @@ -347,9 +342,36 @@ loiter_point_s RTL::landingLoiter(const PositionYawSetpoint &destination) const return landing_loiter; } -rtl_time_estimate_s RTL::estimateDirectReturn(const PositionYawSetpoint &destination) +rtl_time_estimate_s RTL::estimateDirectReturn(const PositionYawSetpoint &destination, bool use_avoidance_path) { - return _rtl_direct.estimateReturnTo({destination, landingLoiter(destination), computeReturnAltitude(destination)}); + const loiter_point_s landing_loiter = landingLoiter(destination); + + if (use_avoidance_path) { + planAvoidancePath(matrix::Vector2d{landing_loiter.lat, landing_loiter.lon}); + } + + return _rtl_direct.estimateReturnTo({destination, landing_loiter, computeReturnAltitude(destination)}, + use_avoidance_path); +} + +void RTL::planAvoidancePath(const matrix::Vector2d &destination) +{ +#if CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE + GeofenceAvoidancePlanner &planner = _navigator->get_geofence_avoidance_planner(); + + if (destination.isAllFinite()) { + planner.updateDestination(destination); + } + + const vehicle_global_position_s &gpos = _global_pos_sub.get(); + + const bool gpos_recent = gpos.timestamp > 0 && hrt_elapsed_time(&gpos.timestamp) < 10_s; + + if (gpos_recent) { + planner.updateStartAndFillPath(matrix::Vector2d(gpos.lat, gpos.lon)); + } + +#endif // CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE } void RTL::applyReturn(const ReturnSelection &selection) @@ -414,17 +436,17 @@ void RTL::applyReturn(const ReturnSelection &selection) planner_destination = _rtl_mission_type_handle->getRtlPlannerDestination(); } - if (planner_destination.isAllFinite()) { - planner.updateDestination(planner_destination); + planAvoidancePath(planner_destination); + + // RTL_TYPE 6 plans to other destinations for its estimates, so the planner reports + // an unchanged destination that breaches the geofence at every evaluation: warn once + if (_param_rtl_type.get() == RTL_TYPE_HOME_OR_SAFE_POINT_DIRECT + && planner.status() == GeofenceAvoidancePlanner::Status::DestinationBreachesGeofence + && (planner_destination - _planned_destination).norm() < DBL_EPSILON) { + planner.resetStatus(); } - const vehicle_global_position_s &gpos = _global_pos_sub.get(); - - const bool gpos_recent = gpos.timestamp > 0 && hrt_elapsed_time(&gpos.timestamp) < 10_s; - - if (gpos_recent) { - planner.updateStartAndFillPath(matrix::Vector2d(_global_pos_sub.get().lat, _global_pos_sub.get().lon)); - } + _planned_destination = planner_destination; #endif // CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE @@ -468,10 +490,6 @@ float RTL::worstBatteryTimeRemaining() PositionYawSetpoint RTL::findClosestSafePoint(float min_dist, bool skip_near_home, uint8_t &safe_point_index, bool &has_land_approach) const { -#if defined(CONFIG_MODULES_VTOL_ATT_CONTROL) && CONFIG_MODULES_VTOL_ATT_CONTROL - const bool vtol_in_fw_mode = _vehicle_status_sub.get().is_vtol - && (_vehicle_status_sub.get().vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING); -#endif const MissionRouteCache &mission_route_cache = _navigator->get_mission_route_cache(); PositionYawSetpoint closest_safe_point{static_cast(NAN), static_cast(NAN), NAN, NAN}; @@ -482,63 +500,136 @@ PositionYawSetpoint RTL::findClosestSafePoint(float min_dist, bool skip_near_hom } for (int current_seq = 0; current_seq < mission_route_cache.safePointCount(); ++current_seq) { - mission_item_s mission_safe_point; + PositionYawSetpoint candidate_setpoint; - if (!mission_route_cache.loadSafePointItem(current_seq, mission_safe_point)) { - PX4_ERR("dm_read failed"); + if (!loadRallyPoint(current_seq, skip_near_home, candidate_setpoint, has_land_approach)) { continue; } - // Only look at rally points - if (mission_safe_point.nav_cmd != NAV_CMD_RALLY_POINT) { - continue; - } + const float dist{get_distance_to_next_waypoint(_global_pos_sub.get().lat, _global_pos_sub.get().lon, + candidate_setpoint.lat, candidate_setpoint.lon)}; - mission_route::Position candidate_position{}; - - if (!mission_route::extractSafePointPosition(mission_safe_point, _home_pos_sub.get().alt, candidate_position)) { - continue; - } - - const PositionYawSetpoint candidate_setpoint{ - candidate_position.lat, - candidate_position.lon, - candidate_position.alt, - NAN - }; - - // Ignore safepoints which are too close to the homepoint (only if home is an option to return to) - const bool far_from_home = get_distance_to_next_waypoint(_home_pos_sub.get().lat, _home_pos_sub.get().lon, - candidate_setpoint.lat, candidate_setpoint.lon) > mission_route::kLandApproachAssociationDistanceM; - - if (far_from_home || !skip_near_home) { - const float dist{get_distance_to_next_waypoint(_global_pos_sub.get().lat, _global_pos_sub.get().lon, - candidate_setpoint.lat, candidate_setpoint.lon)}; - -#if defined(CONFIG_MODULES_VTOL_ATT_CONTROL) && CONFIG_MODULES_VTOL_ATT_CONTROL - const bool current_safe_point_has_approaches { - mission_route::hasVtolLandApproachesAtSafePointIndex(mission_route_cache, current_seq, - _home_pos_sub.get().alt) - }; - - has_land_approach |= current_safe_point_has_approaches; - const bool approach_requirement_satisfied = !vtol_in_fw_mode || (_param_rtl_appr_force.get() == 0) - || current_safe_point_has_approaches; -#else - constexpr bool approach_requirement_satisfied = true; -#endif - - if (((dist + MIN_DIST_THRESHOLD) < min_dist) && approach_requirement_satisfied) { - min_dist = dist; - closest_safe_point = candidate_setpoint; - safe_point_index = static_cast(current_seq); - } + if ((dist + MIN_DIST_THRESHOLD) < min_dist) { + min_dist = dist; + closest_safe_point = candidate_setpoint; + safe_point_index = static_cast(current_seq); } } return closest_safe_point; } +bool RTL::loadRallyPoint(int index, bool skip_near_home, PositionYawSetpoint &rally_point, bool &has_land_approach) const +{ + const MissionRouteCache &mission_route_cache = _navigator->get_mission_route_cache(); + mission_item_s mission_safe_point; + + if (!mission_route_cache.loadSafePointItem(index, mission_safe_point)) { + PX4_ERR("dm_read failed"); + return false; + } + + // Only look at rally points + if (mission_safe_point.nav_cmd != NAV_CMD_RALLY_POINT) { + return false; + } + + mission_route::Position position{}; + + if (!mission_route::extractSafePointPosition(mission_safe_point, _home_pos_sub.get().alt, position)) { + return false; + } + + rally_point = PositionYawSetpoint{position.lat, position.lon, position.alt, NAN}; + + // Ignore safepoints which are too close to the homepoint (only if home is an option to return to) + const bool far_from_home = get_distance_to_next_waypoint(_home_pos_sub.get().lat, _home_pos_sub.get().lon, + rally_point.lat, rally_point.lon) > mission_route::kLandApproachAssociationDistanceM; + + if (skip_near_home && !far_from_home) { + return false; + } + +#if defined(CONFIG_MODULES_VTOL_ATT_CONTROL) && CONFIG_MODULES_VTOL_ATT_CONTROL + const bool vtol_in_fw_mode = _vehicle_status_sub.get().is_vtol + && (_vehicle_status_sub.get().vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING); + const bool rally_point_has_approaches = mission_route::hasVtolLandApproachesAtSafePointIndex(mission_route_cache, index, + _home_pos_sub.get().alt); + + has_land_approach |= rally_point_has_approaches; + return !vtol_in_fw_mode || (_param_rtl_appr_force.get() == 0) || rally_point_has_approaches; +#else + return true; +#endif +} + +PositionYawSetpoint RTL::findQuickestSafePoint(float max_safe_time_s, uint8_t &safe_point_index, bool &has_land_approach, + rtl_time_estimate_s &estimate) +{ + const MissionRouteCache &mission_route_cache = _navigator->get_mission_route_cache(); + + PositionYawSetpoint quickest_safe_point{static_cast(NAN), static_cast(NAN), NAN, NAN}; + has_land_approach = false; + + if (!mission_route_cache.safePointsReady()) { + return quickest_safe_point; + } + + const int count = min(static_cast(mission_route_cache.safePointCount()), static_cast(DM_KEY_SAFE_POINTS_MAX)); + + // The straight line is never slower than the avoidance path: estimate it for every rally point first + float straight_safe_time_s[DM_KEY_SAFE_POINTS_MAX]; + + for (int seq = 0; seq < count; ++seq) { + PositionYawSetpoint candidate; + straight_safe_time_s[seq] = NAN; + + if (loadRallyPoint(seq, /*skip_near_home=*/false, candidate, has_land_approach)) { + const rtl_time_estimate_s straight = estimateDirectReturn(candidate, /*use_avoidance_path=*/false); + + if (straight.valid) { + straight_safe_time_s[seq] = straight.safe_time_estimate; + } + } + } + + // Then plan the avoidance path only for those that can still be the quickest, most promising first. + // Each one replans: if all of them need a long way around the geofence this scales with the + // number of rally points and the size of the geofence, and may need a limit per evaluation. + while (true) { + int next = -1; + + for (int seq = 0; seq < count; ++seq) { + if (PX4_ISFINITE(straight_safe_time_s[seq]) && ((next < 0) || (straight_safe_time_s[seq] < straight_safe_time_s[next]))) { + next = seq; + } + } + + if ((next < 0) || ((straight_safe_time_s[next] + MIN_TIME_THRESHOLD_S) >= max_safe_time_s)) { + break; + } + + straight_safe_time_s[next] = NAN; + PositionYawSetpoint candidate; + bool unused{false}; + + if (!loadRallyPoint(next, /*skip_near_home=*/false, candidate, unused)) { + continue; + } + + const rtl_time_estimate_s candidate_estimate = estimateDirectReturn(candidate); + + if (candidate_estimate.valid && ((candidate_estimate.safe_time_estimate + MIN_TIME_THRESHOLD_S) < max_safe_time_s)) { + max_safe_time_s = candidate_estimate.safe_time_estimate; + quickest_safe_point = candidate; + safe_point_index = static_cast(next); + estimate = candidate_estimate; + } + } + + return quickest_safe_point; +} + void RTL::selectClosest(int32_t rtl_type, ReturnSelection &selection) { const bool vtol_in_rw_mode = _vehicle_status_sub.get().is_vtol diff --git a/src/modules/navigator/rtl.h b/src/modules/navigator/rtl.h index 62dff013f97..a8f416efcd9 100644 --- a/src/modules/navigator/rtl.h +++ b/src/modules/navigator/rtl.h @@ -143,7 +143,7 @@ private: void selectMissionPath(int32_t rtl_type, ReturnSelection &selection) const; /** RTL_TYPE 5: the closest rally point, or the current position. */ void selectSafePoint(ReturnSelection &selection) const; - /** RTL_TYPE 6: Home if the battery reaches it, else the closest rally point. */ + /** RTL_TYPE 6: Home if the battery reaches it, else the quickest of Home and the rally points. */ void selectHomeIfReachable(ReturnSelection &selection); /** Creates and configures the executor, updates the avoidance planner and publishes rtl_status. */ @@ -151,8 +151,11 @@ private: PositionYawSetpoint homeDestination() const; - /** Configures RtlDirect for the destination to estimate it; applyReturn() then configures the selected one. */ - rtl_time_estimate_s estimateDirectReturn(const PositionYawSetpoint &destination); + /** Estimate a direct Return to the destination, optionally planning its avoidance path. */ + rtl_time_estimate_s estimateDirectReturn(const PositionYawSetpoint &destination, bool use_avoidance_path = true); + + /** Plan the geofence avoidance path from the vehicle to the destination. */ + void planAvoidancePath(const matrix::Vector2d &destination); /** The VTOL land approach of the destination, or the destination itself. */ loiter_point_s landingLoiter(const PositionYawSetpoint &destination) const; @@ -160,7 +163,7 @@ private: /** * @brief Publish the remaining time estimate to go to the Return landing point. * - * While inactive, RTL_TYPE 6 also reports the lower estimate of Home and its rally point. + * While inactive, RTL_TYPE 6 also reports the lowest estimate of Home and the rally points. */ void publishRemainingTimeEstimate(float fallback_safe_time_estimate); @@ -173,6 +176,24 @@ private: PositionYawSetpoint findClosestSafePoint(float min_dist, bool skip_near_home, uint8_t &safe_point_index, bool &has_land_approach) const; + /** + * @brief Find the rally point with the lowest time estimate below max_safe_time_s + * + * @param[out] has_land_approach a rally point looked at has a VTOL land approach + * @param[out] estimate the estimate to the rally point found + */ + PositionYawSetpoint findQuickestSafePoint(float max_safe_time_s, uint8_t &safe_point_index, bool &has_land_approach, + rtl_time_estimate_s &estimate); + + /** + * @brief Load a rally point Return may go to + * + * @param[in] skip_near_home ignore rally points within 10 m of Home + * @param[out] has_land_approach set if the rally point has a VTOL land approach + * @return false if there is none at this index or RTL_APPR_FORCE excludes it + */ + bool loadRallyPoint(int index, bool skip_near_home, PositionYawSetpoint &rally_point, bool &has_land_approach) const; + /** * @brief Smallest remaining time [s] of the connected batteries, NAN if none reports one. */ @@ -227,6 +248,8 @@ private: RtlDirect _rtl_direct; + matrix::Vector2d _planned_destination{(double)NAN, (double)NAN}; ///< of the avoidance path applied last + bool _enforce_rtl_alt{false}; DEFINE_PARAMETERS( diff --git a/src/modules/navigator/rtl_direct.cpp b/src/modules/navigator/rtl_direct.cpp index 8dcdbba5420..3d321ad5810 100644 --- a/src/modules/navigator/rtl_direct.cpp +++ b/src/modules/navigator/rtl_direct.cpp @@ -542,17 +542,18 @@ rtl_time_estimate_s RtlDirect::calc_rtl_time_estimate() { _global_pos_sub.update(); const Target configured{_destination, _land_approach, _rtl_alt, _destination_is_current_position}; - return estimateReturnFromState(configured, isActive() ? _rtl_state : getActivationState(_rtl_alt)); + return estimateReturnFromState(configured, isActive() ? _rtl_state : getActivationState(_rtl_alt), true); } -rtl_time_estimate_s RtlDirect::estimateReturnTo(const Target &target) +rtl_time_estimate_s RtlDirect::estimateReturnTo(const Target &target, bool use_avoidance_path) { parameters_update(); _global_pos_sub.update(); - return estimateReturnFromState(target, getActivationState(target.return_alt)); + return estimateReturnFromState(target, getActivationState(target.return_alt), use_avoidance_path); } -rtl_time_estimate_s RtlDirect::estimateReturnFromState(const Target &target, const RTLState start_state_for_estimate) +rtl_time_estimate_s RtlDirect::estimateReturnFromState(const Target &target, const RTLState start_state_for_estimate, + bool use_avoidance_path) { _rtl_time_estimator.update(); _rtl_time_estimator.setVehicleType(_vehicle_status_sub.get().vehicle_type); @@ -585,11 +586,15 @@ rtl_time_estimate_s RtlDirect::estimateReturnFromState(const Target &target, con // FALLTHROUGH case RTLState::AVOID_GEOFENCE: { #if CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE - pos_before_loiter = add_geofence_avoidance_path_distance( - _rtl_time_estimator, - _navigator->get_geofence_avoidance_planner(), - matrix::Vector2d(_global_pos_sub.get().lat, _global_pos_sub.get().lon) - ); + + if (use_avoidance_path) { + pos_before_loiter = add_geofence_avoidance_path_distance( + _rtl_time_estimator, + _navigator->get_geofence_avoidance_planner(), + matrix::Vector2d(_global_pos_sub.get().lat, _global_pos_sub.get().lon) + ); + } + #endif // CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE } diff --git a/src/modules/navigator/rtl_direct.h b/src/modules/navigator/rtl_direct.h index 2f83603d4e7..eeed36847dd 100644 --- a/src/modules/navigator/rtl_direct.h +++ b/src/modules/navigator/rtl_direct.h @@ -117,9 +117,9 @@ public: /** * Time a direct Return to target would take if it started now, without configuring RtlDirect. - * Like calc_rtl_time_estimate(), it adds the geofence avoidance path the planner holds. + * Set use_avoidance_path to false for a straight-line estimate. */ - rtl_time_estimate_s estimateReturnTo(const Target &target); + rtl_time_estimate_s estimateReturnTo(const Target &target, bool use_avoidance_path = true); void setReturnAltMin(bool min) { _enforce_rtl_alt = min; } void setRtlAlt(float alt) {_rtl_alt = alt;}; @@ -180,7 +180,7 @@ private: RTLState getActivationState(const float return_alt); /** Time of a direct Return to target that starts in start_state_for_estimate. */ - rtl_time_estimate_s estimateReturnFromState(const Target &target, const RTLState start_state_for_estimate); + rtl_time_estimate_s estimateReturnFromState(const Target &target, const RTLState start_state_for_estimate, bool use_avoidance_path); /** * @brief Whether the geofence-avoidance planner currently has a path to fly. diff --git a/src/modules/navigator/rtl_params.yaml b/src/modules/navigator/rtl_params.yaml index c7b4bdce814..7879d40d36b 100644 --- a/src/modules/navigator/rtl_params.yaml +++ b/src/modules/navigator/rtl_params.yaml @@ -66,7 +66,7 @@ parameters: - 5 (Direct to rally point only): Return directly to safe landing point (do not consider mission landing and Home). - - 6 (Home if battery allows, else rally point): Return to home if time estimate to home is less than battery remaining estimate. Otherwise, or if battery remaining estimate is not available, return to the closest safe point (home or rally point). + - 6 (Home if battery allows, else rally point): Return to home if time estimate to home is less than battery remaining estimate. Otherwise, or if battery remaining estimate is not available, return to the safe point (home or rally point) with the lowest time estimate. type: enum values: 0: Direct to home or rally point diff --git a/src/modules/navigator/test/test_RTL.cpp b/src/modules/navigator/test/test_RTL.cpp index 878dd10cb36..07405d4130e 100644 --- a/src/modules/navigator/test/test_RTL.cpp +++ b/src/modules/navigator/test/test_RTL.cpp @@ -263,6 +263,8 @@ public: _mission_sub.update(); _home_pos_sub.update(); _wind_sub.update(); + + _rtl_direct.run(false); const ReturnSelection selection = selectReturn(); applyReturn(selection); return selection.fallback_safe_time_estimate; @@ -3480,10 +3482,9 @@ TEST_F(RTLTest, RallyPointReturnWithoutRallyPointEstimatesNoFixedWingLanding) EXPECT_FLOAT_EQ(no_delay.time_estimate, hold.time_estimate); } -// WHY: Return compares destinations only by straight-line distance, -// so it has no reason to prefer a rally point that is farther away than Home. +// WHY: a rally point that takes longer to reach than Home is even less within reach. // WHAT: RTL_TYPE 6 keeps Home while the battery reaches it. When the battery does not reach Home, -// it takes a rally point only if it is closer than Home. +// it takes a rally point only if it is quicker to reach than Home. TEST_F(RTLTest, Type6BeyondBatteryTakesOnlyCloserRallyPoint) { // GIVEN: Home 300 m away @@ -3616,11 +3617,12 @@ TEST_F(RTLLowestEstimateTest, CloserButSlowerRallyDoesNotProvideFallbackTime) EXPECT_FLOAT_EQ(home.min_safe_time_estimate, home.safe_time_estimate); publishBatteryTimeRemaining(1.f); - const float selected_rally_fallback = _rtl.evaluateReturnTypeForTest(6); - ASSERT_TRUE(selectsRallyPoint()); - const rtl_time_estimate_s selected_rally = publishedEstimate(selected_rally_fallback); - EXPECT_GT(selected_rally.safe_time_estimate, home.safe_time_estimate); - EXPECT_FLOAT_EQ(selected_rally.min_safe_time_estimate, selected_rally.safe_time_estimate); + const float low_battery_fallback = _rtl.evaluateReturnTypeForTest(6); + ASSERT_FALSE(selectsRallyPoint()); + EXPECT_TRUE(std::isnan(low_battery_fallback)); + const rtl_time_estimate_s low_battery = publishedEstimate(low_battery_fallback); + EXPECT_FLOAT_EQ(low_battery.safe_time_estimate, home.safe_time_estimate); + EXPECT_FLOAT_EQ(low_battery.min_safe_time_estimate, low_battery.safe_time_estimate); } // WHY: only RTL_TYPE 6 chooses between two destinations by the battery. @@ -3673,3 +3675,135 @@ TEST_F(RTLLowestEstimateTest, Type6LowestEstimateFollowsTheActiveReturn) EXPECT_FLOAT_EQ(active.min_safe_time_estimate, active.safe_time_estimate); EXPECT_FLOAT_EQ(active.safe_time_estimate, inactive.safe_time_estimate); } + + +// A multicopter 100 m above the scene whose battery does not reach Home. +class RTLQuickestRallyPointTest : public RTLLowestEstimateTest +{ +protected: + void SetUp() override + { + RTLLowestEstimateTest::SetUp(); + publishBatteryTimeRemaining(1.f); + } + + void TearDown() override + { + mission_stats_entry_s no_fence{}; + EXPECT_TRUE(_dataman_client.clearSync(DM_KEY_FENCE_POINTS_0)); + EXPECT_TRUE(_dataman_client.writeSync(DM_KEY_FENCE_POINTS_STATE, 0, reinterpret_cast(&no_fence), + sizeof(no_fence))); + RTLLowestEstimateTest::TearDown(); + } + + void setHomeAndRallyPoints(float home_north_m, const std::vector &rally_points) + { + publishHomePosition(makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, home_north_m, 0.f, kAlt)); + primeNavigatorState(); + std::vector items; + + for (const PositionYawSetpoint &rally_point : rally_points) { + items.push_back(makeSafePointItem(rally_point.lat, rally_point.lon, rally_point.alt, NAV_FRAME_GLOBAL)); + } + + loadSafePointsIntoRouteCache(items); + } + + // an exclusion zone, as corners in meters north and east of the vehicle, with the avoidance graph Navigator builds + void loadExclusionZone(const std::vector &corners) + { + for (size_t i = 0; i < corners.size(); ++i) { + const PositionYawSetpoint corner = makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, corners[i](0), + corners[i](1), kAlt); + mission_fence_point_s point{}; + point.nav_cmd = NAV_CMD_FENCE_POLYGON_VERTEX_EXCLUSION; + point.frame = NAV_FRAME_GLOBAL; + point.lat = corner.lat; + point.lon = corner.lon; + point.vertex_count = static_cast(corners.size()); + ASSERT_TRUE(_dataman_client.writeSync(DM_KEY_FENCE_POINTS_0, static_cast(i), + reinterpret_cast(&point), sizeof(point))); + } + + mission_stats_entry_s stats{}; + stats.num_items = static_cast(corners.size()); + stats.opaque_id = 77; + stats.dataman_id = DM_KEY_FENCE_POINTS_0; + ASSERT_TRUE(_dataman_client.writeSync(DM_KEY_FENCE_POINTS_STATE, 0, reinterpret_cast(&stats), + sizeof(stats))); + + Geofence &fence = _navigator.get_geofence(); + fence.updateFence(); + const hrt_abstime start = hrt_absolute_time(); + + while (!fence.isReadyForPathChecks() && hrt_elapsed_time(&start) < 1_s) { + fence.run(); + px4_usleep(1000); + } + + ASSERT_TRUE(fence.isReadyForPathChecks()); + GeofenceAvoidancePlanner &planner = _navigator.get_geofence_avoidance_planner(); + planner.updateGraphFromGeofence(fence, 10.f); + ASSERT_EQ(planner.status(), GeofenceAvoidancePlanner::Status::Success); + } + + rtl_time_estimate_s evaluateAndPublish(uint8_t expected_safe_point) + { + const float fallback = _rtl.evaluateReturnTypeForTest(6); + EXPECT_TRUE(_rtl_status_sub.update()); + EXPECT_EQ(_rtl_status_sub.get().safe_point_index, expected_safe_point); + return publishedEstimate(fallback); + } +}; + +// WHY: the closest destination is not the quickest one when it needs more climb or descent, a way around a +// geofence, or a headwind leg. +// WHAT: beyond the battery, RTL_TYPE 6 takes the rally point with the lowest time estimate, not the closest one, +// and reports its estimate as the lowest. +TEST_F(RTLQuickestRallyPointTest, Type6TakesTheQuickestRallyPoint) +{ + // GIVEN: Home 600 m away, a rally point 100 m away but 400 m further down, and one 300 m away + setHomeAndRallyPoints(-600.f, { + makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, 100.f, 0.f, kAlt - 400.f), + makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, 300.f, 0.f, kAlt), + }); + + // THEN: it takes the second one + const rtl_time_estimate_s beyond_battery = evaluateAndPublish(1); + EXPECT_FLOAT_EQ(beyond_battery.min_safe_time_estimate, beyond_battery.safe_time_estimate); + + // WHEN: the battery reaches Home + publishBatteryTimeRemaining(3600.f); + + // THEN: it goes Home, and the lowest estimate is still the one to that rally point + EXPECT_FLOAT_EQ(evaluateAndPublish(UINT8_MAX).min_safe_time_estimate, beyond_battery.safe_time_estimate); +} + +// WHAT: beyond the battery, RTL_TYPE 6 keeps Home if it is quicker to reach than a closer rally point. +TEST_F(RTLQuickestRallyPointTest, Type6KeepsHomeIfQuickerThanCloserRallyPoint) +{ + // GIVEN: Home 300 m away and a rally point 100 m away but 400 m further down + setHomeAndRallyPoints(-300.f, {makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, 100.f, 0.f, kAlt - 400.f)}); + + const rtl_time_estimate_s estimate = evaluateAndPublish(UINT8_MAX); + EXPECT_FLOAT_EQ(estimate.min_safe_time_estimate, estimate.safe_time_estimate); +} + +#if CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE +// WHY: each destination has its own way around the geofence. +// WHAT: RTL_TYPE 6 takes a rally point that is closer than Home only while the way to it is not longer. +TEST_F(RTLQuickestRallyPointTest, Type6CountsTheWayAroundTheGeofence) +{ + // GIVEN: Home 400 m south and a rally point 200 m north + setHomeAndRallyPoints(-400.f, {makePositionYawSetpointFromOffset(kBaseLat, kBaseLon, 200.f, 0.f, kAlt)}); + const rtl_time_estimate_s straight = evaluateAndPublish(0); + + // WHEN: an exclusion zone 400 m wide lies between the vehicle and the rally point + loadExclusionZone({{50.f, -200.f}, {150.f, -200.f}, {150.f, 200.f}, {50.f, 200.f}}); + + // THEN: Home is quicker to reach + const rtl_time_estimate_s around = evaluateAndPublish(UINT8_MAX); + EXPECT_FLOAT_EQ(around.min_safe_time_estimate, around.safe_time_estimate); + EXPECT_GT(around.safe_time_estimate, straight.safe_time_estimate); +} +#endif // CONFIG_NAVIGATOR_GEOFENCE_AVOIDANCE