diff --git a/src/modules/navigator/course.cpp b/src/modules/navigator/course.cpp index 18c4c8e1800..c2fb30b2f96 100644 --- a/src/modules/navigator/course.cpp +++ b/src/modules/navigator/course.cpp @@ -49,6 +49,9 @@ Course::Course(Navigator *navigator) : void Course::on_activation() { + // reset triplets, modes should be explicit about which fields they want to set + _navigator->reset_triplets(); + const vehicle_local_position_s *lpos = _navigator->get_local_position(); _altitude = _navigator->get_global_position()->alt; diff --git a/src/modules/navigator/land.cpp b/src/modules/navigator/land.cpp index 15b8cd4459a..281bad0ee75 100644 --- a/src/modules/navigator/land.cpp +++ b/src/modules/navigator/land.cpp @@ -49,6 +49,9 @@ Land::Land(Navigator *navigator) : void Land::on_activation() { + // reset triplets, modes should be explicit about which fields they want to set + _navigator->reset_triplets(); + /* set current mission item to Land */ set_land_item(&_mission_item); _navigator->get_mission_result()->finished = false; diff --git a/src/modules/navigator/loiter.cpp b/src/modules/navigator/loiter.cpp index f8c4482ac63..57461719206 100644 --- a/src/modules/navigator/loiter.cpp +++ b/src/modules/navigator/loiter.cpp @@ -53,13 +53,18 @@ Loiter::Loiter(Navigator *navigator) : void Loiter::on_activation() { + // Snapshot the setpoint the previous mode left before resetting the triplet, so we can continue + // an already-established loiter (used by set_loiter_position()). + const position_setpoint_s previous_setpoint = _navigator->get_position_setpoint_triplet()->current; + _navigator->reset_triplets(); + if (_navigator->get_reposition_triplet()->current.valid && hrt_elapsed_time(&_navigator->get_reposition_triplet()->current.timestamp) < 500_ms) { reposition(); } else { // this is executed when the flight mode is switched to Hold manually, not through a reposition - set_loiter_position(); + set_loiter_position(previous_setpoint); } // reset cruising speed to default @@ -76,7 +81,8 @@ Loiter::on_active() if (_param_nav_ltr_last_dl.get() && _navigator->get_vstatus()->failsafe && _navigator->get_vstatus()->gcs_connection_lost) { if (!_loiter_at_last_link_position_executed) { - set_loiter_position(); // if we already were in hold (e.g. GoTo), we need to reset the position setpoint + // if we already were in hold (e.g. GoTo), we need to reset the position setpoint + set_loiter_position(_navigator->get_position_setpoint_triplet()->current); _loiter_at_last_link_position_executed = true; } @@ -92,7 +98,7 @@ Loiter::on_inactive() } void -Loiter::set_loiter_position() +Loiter::set_loiter_position(const position_setpoint_s &reference_setpoint) { if (_navigator->get_vstatus()->arming_state != vehicle_status_s::ARMING_STATE_ARMED && _navigator->get_land_detected()->landed) { @@ -114,11 +120,11 @@ Loiter::set_loiter_position() // Check if we already loiter on a circle and are on the loiter pattern. bool on_loiter{false}; - if (pos_sp_triplet->current.valid && pos_sp_triplet->current.type == position_setpoint_s::SETPOINT_TYPE_LOITER - && pos_sp_triplet->current.loiter_pattern == position_setpoint_s::LOITER_TYPE_ORBIT) { - const float d_current = get_distance_to_next_waypoint(pos_sp_triplet->current.lat, pos_sp_triplet->current.lon, + if (reference_setpoint.valid && reference_setpoint.type == position_setpoint_s::SETPOINT_TYPE_LOITER + && reference_setpoint.loiter_pattern == position_setpoint_s::LOITER_TYPE_ORBIT) { + const float d_current = get_distance_to_next_waypoint(reference_setpoint.lat, reference_setpoint.lon, _navigator->get_global_position()->lat, _navigator->get_global_position()->lon); - on_loiter = d_current <= (_navigator->get_acceptance_radius() + pos_sp_triplet->current.loiter_radius); + on_loiter = d_current <= (_navigator->get_acceptance_radius() + reference_setpoint.loiter_radius); } if (_navigator->get_vstatus()->failsafe && _navigator->get_vstatus()->gcs_connection_lost && _param_nav_ltr_last_dl.get()) { @@ -126,13 +132,13 @@ Loiter::set_loiter_position() setLoiterFromLastLink(&_mission_item); } else if (on_loiter) { - setLoiterItemFromCurrentPositionSetpoint(&_mission_item); + setLoiterItemFromCurrentPositionSetpoint(_mission_item, reference_setpoint); } else if (_navigator->get_vstatus()->vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING) { setLoiterItemFromCurrentPositionWithBraking(&_mission_item); } else { - setLoiterItemFromCurrentPosition(&_mission_item); + setLoiterItemFromCurrentPosition(_mission_item); } } diff --git a/src/modules/navigator/loiter.h b/src/modules/navigator/loiter.h index 47441cb45ca..36df5390ef1 100644 --- a/src/modules/navigator/loiter.h +++ b/src/modules/navigator/loiter.h @@ -65,7 +65,7 @@ private: /** * Set the position to hold based on the current local position */ - void set_loiter_position(); + void set_loiter_position(const position_setpoint_s &reference_setpoint); bool _loiter_at_last_link_position_executed{false}; diff --git a/src/modules/navigator/mission_base.cpp b/src/modules/navigator/mission_base.cpp index 8228bc3d9ae..0f378a64084 100644 --- a/src/modules/navigator/mission_base.cpp +++ b/src/modules/navigator/mission_base.cpp @@ -204,6 +204,9 @@ MissionBase::on_inactivation() void MissionBase::on_activation() { + // reset triplets, modes should be explicit about which fields they want to set + _navigator->reset_triplets(); + /* reset the current mission to the start sequence if needed.*/ checkMissionRestart(); @@ -561,10 +564,10 @@ void MissionBase::setEndOfMissionItems() if (pos_sp_triplet->current.valid && (pos_sp_triplet->current.type == position_setpoint_s::SETPOINT_TYPE_LOITER || pos_sp_triplet->current.type == position_setpoint_s::SETPOINT_TYPE_POSITION)) { - setLoiterItemFromCurrentPositionSetpoint(&_mission_item); + setLoiterItemFromCurrentPositionSetpoint(_mission_item, pos_sp_triplet->current); } else { - setLoiterItemFromCurrentPosition(&_mission_item); + setLoiterItemFromCurrentPosition(_mission_item); } } diff --git a/src/modules/navigator/mission_block.cpp b/src/modules/navigator/mission_block.cpp index caf14603011..414a06ff70f 100644 --- a/src/modules/navigator/mission_block.cpp +++ b/src/modules/navigator/mission_block.cpp @@ -698,27 +698,26 @@ MissionBlock::mission_item_to_position_setpoint(const mission_item_s &item, posi } void -MissionBlock::setLoiterItemFromCurrentPositionSetpoint(struct mission_item_s *item) +MissionBlock::setLoiterItemFromCurrentPositionSetpoint(struct mission_item_s &item, + const position_setpoint_s &reference_setpoint) { - setLoiterItemCommonFields(item); + setLoiterItemCommonFields(&item); - const position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); - - item->lat = pos_sp_triplet->current.lat; - item->lon = pos_sp_triplet->current.lon; - item->altitude = pos_sp_triplet->current.alt; - item->loiter_radius = pos_sp_triplet->current.loiter_direction_counter_clockwise ? - -pos_sp_triplet->current.loiter_radius : pos_sp_triplet->current.loiter_radius; - item->yaw = pos_sp_triplet->current.yaw; + item.lat = reference_setpoint.lat; + item.lon = reference_setpoint.lon; + item.altitude = reference_setpoint.alt; + item.loiter_radius = reference_setpoint.loiter_direction_counter_clockwise ? + -reference_setpoint.loiter_radius : reference_setpoint.loiter_radius; + item.yaw = reference_setpoint.yaw; } void -MissionBlock::setLoiterItemFromCurrentPosition(struct mission_item_s *item) +MissionBlock::setLoiterItemFromCurrentPosition(struct mission_item_s &item) { - setLoiterItemCommonFields(item); + setLoiterItemCommonFields(&item); - item->lat = _navigator->get_global_position()->lat; - item->lon = _navigator->get_global_position()->lon; + item.lat = _navigator->get_global_position()->lat; + item.lon = _navigator->get_global_position()->lon; // check if minimum loiter altitude is specified, and enforce it if so float loiter_altitude_amsl = _navigator->get_global_position()->alt; @@ -728,9 +727,9 @@ MissionBlock::setLoiterItemFromCurrentPosition(struct mission_item_s *item) _navigator->get_home_position()->alt + _navigator->get_loiter_min_alt()); } - item->altitude = loiter_altitude_amsl; - item->loiter_radius = _navigator->get_default_loiter_rad(); - item->yaw = NAN; + item.altitude = loiter_altitude_amsl; + item.loiter_radius = _navigator->get_default_loiter_rad(); + item.yaw = NAN; } void @@ -1065,7 +1064,7 @@ void MissionBlock::updateMaxHaglFailsafe() _navigator->trigger_hagl_failsafe(getNavigatorStateId()); // While waiting for a failsafe action from commander, keep the curren position - setLoiterItemFromCurrentPosition(&_mission_item); + setLoiterItemFromCurrentPosition(_mission_item); mission_item_to_position_setpoint(_mission_item, &_navigator->get_position_setpoint_triplet()->current); diff --git a/src/modules/navigator/mission_block.h b/src/modules/navigator/mission_block.h index 0177533a3c4..826206a2b4e 100644 --- a/src/modules/navigator/mission_block.h +++ b/src/modules/navigator/mission_block.h @@ -154,9 +154,9 @@ protected: */ bool mission_item_to_position_setpoint(const mission_item_s &item, position_setpoint_s *sp); - void setLoiterItemFromCurrentPositionSetpoint(struct mission_item_s *item); + void setLoiterItemFromCurrentPositionSetpoint(struct mission_item_s &item, const position_setpoint_s &reference_setpoint); - void setLoiterItemFromCurrentPosition(struct mission_item_s *item); + void setLoiterItemFromCurrentPosition(struct mission_item_s &item); void setLoiterItemFromCurrentPositionWithBraking(struct mission_item_s *item); void setLoiterFromLastLink(struct mission_item_s *item); diff --git a/src/modules/navigator/navigator.h b/src/modules/navigator/navigator.h index 35f0023f098..8e207220803 100644 --- a/src/modules/navigator/navigator.h +++ b/src/modules/navigator/navigator.h @@ -225,7 +225,21 @@ public: * * @return the distance at which the next waypoint should be used */ - float get_acceptance_radius(); + float get_acceptance_radius() const; + + /** + * Check whether the vehicle is currently established on a circular loiter (orbit) + * defined by the given setpoint. + * + * True only if the setpoint is a valid ORBIT-pattern loiter and the vehicle is within + * one acceptance radius of the loiter circle. Used to decide whether a Hold/pause, + * geofence loiter or RTL climb should continue the existing orbit instead of + * re-centering it on the current position. + * + * @param sp the loiter setpoint to test against + * @return true if the vehicle is established on the orbit described by sp + */ + bool is_established_on_loiter(const position_setpoint_s &sp) const; /** * Get the altitude acceptance radius diff --git a/src/modules/navigator/navigator_main.cpp b/src/modules/navigator/navigator_main.cpp index b246c269f19..9218c452f75 100644 --- a/src/modules/navigator/navigator_main.cpp +++ b/src/modules/navigator/navigator_main.cpp @@ -436,13 +436,27 @@ void Navigator::run() // All three set to NaN - pause vehicle rep->current.alt = get_global_position()->alt; - if (_vstatus.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING - && (get_position_setpoint_triplet()->current.type != position_setpoint_s::SETPOINT_TYPE_TAKEOFF)) { + // If the vehicle is already established on a circular loiter (orbit), keep that + // loiter's center and shape instead of re-centering the circle on the current + // position. This lets a Hold/pause continue the existing orbit. Non-circular + // patterns (e.g. figure-eight) are not continued: a Hold reverts to a plain + // loiter circle so we never mix patterns. + if (is_established_on_loiter(curr->current)) { + rep->current.lat = curr->current.lat; + rep->current.lon = curr->current.lon; + rep->current.loiter_radius = curr->current.loiter_radius; + rep->current.loiter_pattern = curr->current.loiter_pattern; + rep->current.loiter_direction_counter_clockwise = curr->current.loiter_direction_counter_clockwise; + } else if (_vstatus.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING + && (get_position_setpoint_triplet()->current.type != position_setpoint_s::SETPOINT_TYPE_TAKEOFF)) { + + rep->current.loiter_pattern = position_setpoint_s::LOITER_TYPE_ORBIT; preproject_stop_point(rep->current.lat, rep->current.lon); } else { // For fixedwings we can use the current vehicle's position to define the loiter point + rep->current.loiter_pattern = position_setpoint_s::LOITER_TYPE_ORBIT; rep->current.lat = get_global_position()->lat; rep->current.lon = get_global_position()->lon; } @@ -990,31 +1004,6 @@ void Navigator::run() navigation_mode_new = nullptr; } - /* we have a new navigation mode: reset triplet */ - if (_navigation_mode != navigation_mode_new) { - // We don't reset the triplet in the following two cases: - // 1) if we just did an auto-takeoff and are now - // going to loiter. Otherwise, we lose the takeoff altitude and end up lower - // than where we wanted to go. - // 2) We switch to loiter and the current position setpoint already has a valid loiter point. - // In that case we can assume that the vehicle has already established a loiter and we don't need to set a new - // loiter position. - // - // FIXME: a better solution would be to add reset where they are needed and remove - // this general reset here. - - const bool current_mode_is_takeoff = _navigation_mode == &_takeoff; - const bool new_mode_is_loiter = navigation_mode_new == &_loiter; - const bool valid_loiter_setpoint = (_pos_sp_triplet.current.valid - && _pos_sp_triplet.current.type == position_setpoint_s::SETPOINT_TYPE_LOITER); - - const bool did_not_switch_takeoff_to_loiter = !(current_mode_is_takeoff && new_mode_is_loiter); - const bool did_not_switch_to_loiter_with_valid_loiter_setpoint = !(new_mode_is_loiter && valid_loiter_setpoint); - - if (did_not_switch_takeoff_to_loiter && did_not_switch_to_loiter_with_valid_loiter_setpoint) { - reset_triplets(); - } - } // VTOL: transition to hover in Descend mode if force_vtol() is true if (_vstatus.nav_state == vehicle_status_s::NAVIGATION_STATE_DESCEND && @@ -1147,17 +1136,23 @@ void Navigator::geofence_breach_check() double current_latitude = _global_pos.lat; double current_longitude = _global_pos.lon; float current_altitude = _global_pos.alt; - bool position_valid = _global_pos.timestamp > 0; + bool global_position_valid = _global_pos.timestamp > 0 + && hrt_elapsed_time(&_global_pos.timestamp) < 1_s; + bool have_valid_position_for_breach_check = global_position_valid; + + // relying on raw gps is questionable already, but at least check the basics + const bool raw_gps_valid = + hrt_elapsed_time(&_gps_pos.timestamp) < 2_s && _gps_pos.fix_type >= 2; if (_geofence.getSource() == Geofence::GF_SOURCE_GPS) { current_latitude = _gps_pos.latitude_deg; current_longitude = _gps_pos.longitude_deg; current_altitude = _gps_pos.altitude_msl_m; - position_valid = _global_pos.timestamp > 0; + + have_valid_position_for_breach_check = raw_gps_valid; } - if (!position_valid) { - // we don't have a valid position yet, so we can't check for geofence violations + if (!have_valid_position_for_breach_check) { return; } @@ -1190,16 +1185,26 @@ void Navigator::geofence_breach_check() || _geofence_result.geofence_custom_fence_triggered; if (breach) { - if (!_geofence_reposition_sent && _vstatus.arming_state == vehicle_status_s::ARMING_STATE_ARMED + if (!_geofence_reposition_sent && global_position_valid && _vstatus.arming_state == vehicle_status_s::ARMING_STATE_ARMED && _geofence.getGeofenceAction() == geofence_result_s::GF_ACTION_LOITER) { + const position_setpoint_s current = get_position_setpoint_triplet()->current; + double loiter_center_lat = _global_pos.lat; + double loiter_center_lon = _global_pos.lon; + + // if we are established on a loiter, continue loitering + if (is_established_on_loiter(current)) { + loiter_center_lat = current.lat; + loiter_center_lon = current.lon; + } + // loiter at the current position; we no longer predict ahead of the vehicle position_setpoint_triplet_s *rep = get_reposition_triplet(); rep->current.timestamp = now; rep->current.yaw = NAN; - rep->current.lat = current_latitude; - rep->current.lon = current_longitude; - rep->current.alt = current_altitude; + rep->current.lat = loiter_center_lat; + rep->current.lon = loiter_center_lon; + rep->current.alt = _global_pos.alt; rep->current.valid = true; rep->current.loiter_radius = get_default_loiter_rad(); rep->current.type = position_setpoint_s::SETPOINT_TYPE_LOITER; @@ -1348,7 +1353,7 @@ float Navigator::get_cruising_throttle() } } -float Navigator::get_acceptance_radius() +float Navigator::get_acceptance_radius() const { float acceptance_radius = get_default_acceptance_radius(); // the value specified in the parameter NAV_ACC_RAD @@ -1373,6 +1378,19 @@ float Navigator::get_acceptance_radius() return acceptance_radius; } +bool Navigator::is_established_on_loiter(const position_setpoint_s &sp) const +{ + if (!sp.valid + || sp.type != position_setpoint_s::SETPOINT_TYPE_LOITER + || sp.loiter_pattern != position_setpoint_s::LOITER_TYPE_ORBIT) { + return false; + } + + const float dist_to_center = get_distance_to_next_waypoint(sp.lat, sp.lon, _global_pos.lat, _global_pos.lon); + + return dist_to_center <= (get_acceptance_radius() + fabsf(sp.loiter_radius)); +} + bool Navigator::get_yaw_to_be_accepted(float mission_item_yaw) { float yaw = mission_item_yaw; diff --git a/src/modules/navigator/precland.cpp b/src/modules/navigator/precland.cpp index 848c5e3415e..0cd0fca094e 100644 --- a/src/modules/navigator/precland.cpp +++ b/src/modules/navigator/precland.cpp @@ -98,11 +98,15 @@ PrecLand::on_activation() position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); - pos_sp_triplet->next.valid = false; - pos_sp_triplet->previous.valid = false; + // Snapshot the setpoint the previous mode left, then reset the triplet. If it was a valid landing + // target we continue to it, otherwise we land at the current position. + const position_setpoint_s previous_setpoint = pos_sp_triplet->current; + _navigator->reset_triplets(); - // Check that the current position setpoint is valid, otherwise land at current position - if (!pos_sp_triplet->current.valid) { + if (previous_setpoint.valid) { + pos_sp_triplet->current = previous_setpoint; + + } else { PX4_WARN("Reset"); pos_sp_triplet->current.lat = _navigator->get_global_position()->lat; pos_sp_triplet->current.lon = _navigator->get_global_position()->lon; diff --git a/src/modules/navigator/rtl_direct.cpp b/src/modules/navigator/rtl_direct.cpp index 59e173b5878..c519e9ef16c 100644 --- a/src/modules/navigator/rtl_direct.cpp +++ b/src/modules/navigator/rtl_direct.cpp @@ -81,6 +81,11 @@ void RtlDirect::on_activation() _rtl_state = getActivationState(); + // save the setpoint the previous mode left before resetting the triplet, so the climb can + // continue an already-established loiter (used in set_rtl_item(), CLIMBING state) + _setpoint_on_activation = _navigator->get_position_setpoint_triplet()->current; + _navigator->reset_triplets(); + // reset cruising speed and throttle to default for RTL _navigator->reset_cruising_speed(); _navigator->set_cruising_throttle(); @@ -251,13 +256,29 @@ void RtlDirect::set_rtl_item() switch (_rtl_state) { case RTLState::CLIMBING: { + // By default climb on a loiter centered at the current position. + double loiter_center_lat = _global_pos_sub.get().lat; + double loiter_center_lon = _global_pos_sub.get().lon; + float loiter_radius = _navigator->get_default_loiter_rad(); + + // If the vehicle was already established on a loiter when RTL was engaged (e.g. from Hold), + // keep that loiter's center and radius while climbing instead of re-centering the circle on + // the current position. + if (_navigator->is_established_on_loiter(_setpoint_on_activation)) { + loiter_center_lat = _setpoint_on_activation.lat; + loiter_center_lon = _setpoint_on_activation.lon; + // loiter_radius sign encodes direction (negative == counter-clockwise). + loiter_radius = _setpoint_on_activation.loiter_direction_counter_clockwise ? + -_setpoint_on_activation.loiter_radius : _setpoint_on_activation.loiter_radius; + } + PositionYawSetpoint pos_yaw_sp { - .lat = _global_pos_sub.get().lat, - .lon = _global_pos_sub.get().lon, + .lat = loiter_center_lat, + .lon = loiter_center_lon, .alt = _rtl_alt, .yaw = _param_wv_en.get() ? NAN : _navigator->get_local_position()->heading, }; - setLoiterToAltMissionItem(_mission_item, pos_yaw_sp, _navigator->get_default_loiter_rad()); + setLoiterToAltMissionItem(_mission_item, pos_yaw_sp, loiter_radius); break; } diff --git a/src/modules/navigator/rtl_direct.h b/src/modules/navigator/rtl_direct.h index 159838c86b0..2dce97b4086 100644 --- a/src/modules/navigator/rtl_direct.h +++ b/src/modules/navigator/rtl_direct.h @@ -174,6 +174,7 @@ private: bool _enforce_rtl_alt{false}; bool _force_heading{false}; + position_setpoint_s _setpoint_on_activation{}; ///< snapshot of the current setpoint taken before reset on activation, used to continue an established loiter through the climb RtlTimeEstimator _rtl_time_estimator; PositionYawSetpoint _destination{(double)NAN, (double)NAN, NAN, NAN}; ///< the RTL position to fly to diff --git a/src/modules/navigator/rtl_direct_mission_land.cpp b/src/modules/navigator/rtl_direct_mission_land.cpp index f1d6e19473c..80620580226 100644 --- a/src/modules/navigator/rtl_direct_mission_land.cpp +++ b/src/modules/navigator/rtl_direct_mission_land.cpp @@ -114,6 +114,10 @@ void RtlDirectMissionLand::on_activation() _is_current_planned_mission_item_valid = false; } + // Snapshot the setpoint the previous mode left before MissionBase::on_activation() resets the + // triplet, so the climb can continue an already-established loiter (used in setActiveMissionItems()). + _setpoint_on_activation = _navigator->get_position_setpoint_triplet()->current; + MissionBase::on_activation(); } @@ -146,8 +150,30 @@ void RtlDirectMissionLand::setActiveMissionItems() _mission_item.nav_cmd = NAV_CMD_LOITER_TO_ALT; } + // By default climb centered on the current position with the default loiter radius. _mission_item.lat = _global_pos_sub.get().lat; _mission_item.lon = _global_pos_sub.get().lon; + _mission_item.loiter_radius = _navigator->get_default_loiter_rad(); + + // If the vehicle was already established on a loiter when RTL was engaged (e.g. from Hold), + // keep that loiter's center and radius while climbing instead of re-centering the circle on + // the current position. The setpoint was snapshotted on activation before the triplet reset. + if (_setpoint_on_activation.valid + && _setpoint_on_activation.type == position_setpoint_s::SETPOINT_TYPE_LOITER + && _setpoint_on_activation.loiter_pattern == position_setpoint_s::LOITER_TYPE_ORBIT) { + const float dist_to_center = get_distance_to_next_waypoint( + _setpoint_on_activation.lat, _setpoint_on_activation.lon, + _global_pos_sub.get().lat, _global_pos_sub.get().lon); + + if (dist_to_center <= (_navigator->get_acceptance_radius() + fabsf(_setpoint_on_activation.loiter_radius))) { + _mission_item.lat = _setpoint_on_activation.lat; + _mission_item.lon = _setpoint_on_activation.lon; + // loiter_radius sign encodes direction (negative == counter-clockwise). + _mission_item.loiter_radius = _setpoint_on_activation.loiter_direction_counter_clockwise ? + -_setpoint_on_activation.loiter_radius : _setpoint_on_activation.loiter_radius; + } + } + _mission_item.altitude = _rtl_alt; _mission_item.altitude_is_relative = false; @@ -155,7 +181,6 @@ void RtlDirectMissionLand::setActiveMissionItems() _mission_item.time_inside = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; - _mission_item.loiter_radius = _navigator->get_default_loiter_rad(); mavlink_log_info(_navigator->get_mavlink_log_pub(), "RTL Mission land: climb to %d m\t", (int)ceilf(_rtl_alt)); diff --git a/src/modules/navigator/rtl_direct_mission_land.h b/src/modules/navigator/rtl_direct_mission_land.h index a68a9a5b3ed..8db3289adad 100644 --- a/src/modules/navigator/rtl_direct_mission_land.h +++ b/src/modules/navigator/rtl_direct_mission_land.h @@ -83,6 +83,7 @@ private: bool _needs_climbing{false}; //< Flag if climbing is required at the start bool _enforce_rtl_alt{false}; float _rtl_alt{0.0f}; ///< AMSL altitude at which the vehicle should return to the land position + position_setpoint_s _setpoint_on_activation{}; ///< snapshot of the current setpoint taken before reset on activation, used to continue an established loiter through the climb RtlTimeEstimator _rtl_time_estimator; }; diff --git a/src/modules/navigator/takeoff.cpp b/src/modules/navigator/takeoff.cpp index b8994b3676a..30079e576a6 100644 --- a/src/modules/navigator/takeoff.cpp +++ b/src/modules/navigator/takeoff.cpp @@ -50,6 +50,9 @@ Takeoff::Takeoff(Navigator *navigator) : void Takeoff::on_activation() { + // reset triplets, modes should be explicit about which fields they want to set + _navigator->reset_triplets(); + set_takeoff_position(); // reset cruising speed to default @@ -167,7 +170,7 @@ Takeoff::on_active() } else { if (pos_sp_triplet->current.valid && _navigator->get_vstatus()->vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING) { - setLoiterItemFromCurrentPositionSetpoint(&_mission_item); + setLoiterItemFromCurrentPositionSetpoint(_mission_item, pos_sp_triplet->current); } } diff --git a/src/modules/navigator/vtol_takeoff.cpp b/src/modules/navigator/vtol_takeoff.cpp index fde7702d318..052e8a56b18 100644 --- a/src/modules/navigator/vtol_takeoff.cpp +++ b/src/modules/navigator/vtol_takeoff.cpp @@ -51,6 +51,9 @@ VtolTakeoff::VtolTakeoff(Navigator *navigator) : void VtolTakeoff::on_activation() { + // reset triplets, modes should be explicit about which fields they want to set + _navigator->reset_triplets(); + if (hrt_elapsed_time(&_navigator->get_global_position()->timestamp) < 1_s) { set_takeoff_position(); _takeoff_state = vtol_takeoff_state::TAKEOFF_HOVER; @@ -111,10 +114,10 @@ VtolTakeoff::on_active() position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); if (pos_sp_triplet->current.valid && pos_sp_triplet->current.type == position_setpoint_s::SETPOINT_TYPE_LOITER) { - setLoiterItemFromCurrentPositionSetpoint(&_mission_item); + setLoiterItemFromCurrentPositionSetpoint(_mission_item, pos_sp_triplet->current); } else { - setLoiterItemFromCurrentPosition(&_mission_item); + setLoiterItemFromCurrentPosition(_mission_item); } _mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT; diff --git a/test/mavsdk_tests/CMakeLists.txt b/test/mavsdk_tests/CMakeLists.txt index c740a9d104a..3976b8fa7e6 100644 --- a/test/mavsdk_tests/CMakeLists.txt +++ b/test/mavsdk_tests/CMakeLists.txt @@ -19,6 +19,7 @@ if(MAVSDK_FOUND) autopilot_tester_failure.cpp autopilot_tester_rtl.cpp autopilot_tester_figure_eight.cpp + autopilot_tester_loiter.cpp # follow-me needs a MAVSDK update: # https://github.com/mavlink/MAVSDK/pull/1770 # autopilot_tester_follow_me.cpp @@ -32,6 +33,7 @@ if(MAVSDK_FOUND) test_multicopter_rtl_with_geofence.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 diff --git a/test/mavsdk_tests/autopilot_tester.h b/test/mavsdk_tests/autopilot_tester.h index b0ac078d5dc..f58a2cd35d2 100644 --- a/test/mavsdk_tests/autopilot_tester.h +++ b/test/mavsdk_tests/autopilot_tester.h @@ -190,6 +190,7 @@ public: } 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();} diff --git a/test/mavsdk_tests/autopilot_tester_loiter.cpp b/test/mavsdk_tests/autopilot_tester_loiter.cpp new file mode 100644 index 00000000000..48d88a6f823 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_loiter.cpp @@ -0,0 +1,331 @@ +/**************************************************************************** + * + * 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 + +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); + + auto prom = std::promise {}; + auto fut = prom.get_future(); + std::atomic reported{false}; + + Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( + [&](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); + + auto prom = std::promise {}; + auto fut = prom.get_future(); + std::atomic reported{false}; + + Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( + [&](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( + [&](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( + [&](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( + [&](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( + [&](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); + + auto prom = std::promise {}; + auto fut = prom.get_future(); + std::atomic reported{false}; + + Telemetry::PositionVelocityNedHandle handle = getTelemetry()->subscribe_position_velocity_ned( + [&](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; +} diff --git a/test/mavsdk_tests/autopilot_tester_loiter.h b/test/mavsdk_tests/autopilot_tester_loiter.h new file mode 100644 index 00000000000..65621fed414 --- /dev/null +++ b/test/mavsdk_tests/autopilot_tester_loiter.h @@ -0,0 +1,118 @@ +/**************************************************************************** + * + * 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(); + +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/configs/sitl.json b/test/mavsdk_tests/configs/sitl.json index a281c2fe2a2..9d32862402d 100644 --- a/test/mavsdk_tests/configs/sitl.json +++ b/test/mavsdk_tests/configs/sitl.json @@ -23,7 +23,7 @@ { "model": "standard_vtol", "vehicle": "standard_vtol", - "test_filter": "[vtol], [vtol_wind], [vtol_airspeed_fail]", + "test_filter": "[vtol], [vtol_wind], [vtol_airspeed_fail], [loiter]", "timeout_min": 10 }, { diff --git a/test/mavsdk_tests/test_vtol_loiter_reposition.cpp b/test/mavsdk_tests/test_vtol_loiter_reposition.cpp new file mode 100644 index 00000000000..41b1eece08e --- /dev/null +++ b/test/mavsdk_tests/test_vtol_loiter_reposition.cpp @@ -0,0 +1,191 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ + +// Integration tests for fixed-wing loiter / reposition / Hold interaction. +// +// These exercise how a Hold (MAV_CMD_DO_REPOSITION pause) and RTL interact with an already +// established loiter: +// 1. RTL while established on a non-default-radius loiter climbs on that same loiter. +// 2. A Hold (all-NaN reposition) while established keeps the loiter but holds the current altitude. +// 3. A Hold while still transiting toward a loiter creates a fresh loiter at the current position. +// 4. A Hold while flying a figure-eight reverts to a plain circular loiter (patterns are not mixed). +// 5. An altitude-only reposition keeps the loiter center and radius and only changes altitude. + +#include "autopilot_tester_loiter.h" + +#include + +using namespace std::chrono_literals; + +namespace +{ + +// Home-relative center used for the "work" loiter. Placed well away from home so that RTL climbs to +// the full return altitude (close to home the RTL cone would cap the climb). +const AutopilotTesterLoiter::LocalCoordinate kWorkCenter{250.0, 0.0}; + +constexpr float kTakeoffAltitude = 40.f; +constexpr float kLoiterAltitude = 40.f; + +// Clearly different from the default NAV_LOITER_RAD (80 m) so a default-radius circle would fall +// outside the tolerance band. +constexpr float kNonDefaultRadius = 120.f; +constexpr float kRadiusTolerance = 30.f; +constexpr float kAltitudeTolerance = 8.f; + +void arm_takeoff_transition_hold(AutopilotTesterLoiter &tester) +{ + tester.connect(connection_url); + tester.wait_until_ready(); + tester.store_home(); + tester.set_takeoff_altitude(kTakeoffAltitude); + tester.sleep_for(3s); + tester.arm(); + tester.takeoff(); + tester.wait_until_hovering(); + tester.wait_until_altitude(kTakeoffAltitude, 30s); + tester.transition_to_fixedwing(); + tester.wait_until_fixedwing(5s); + tester.sleep_for(1s); + tester.enter_hold_and_wait(); +} + +void establish_work_orbit(AutopilotTesterLoiter &tester) +{ + tester.command_orbit(kWorkCenter, kNonDefaultRadius, kLoiterAltitude); + tester.wait_until_on_loiter(kWorkCenter, kNonDefaultRadius, kRadiusTolerance, 12s, 180s); +} + +} // namespace + +TEST_CASE("Loiter: RTL climbs on an established non-default-radius loiter", "[loiter]") +{ + AutopilotTesterLoiter tester; + arm_takeoff_transition_hold(tester); + establish_work_orbit(tester); + + // Climb clearly above the loiter altitude when RTL is engaged. + const float rtl_altitude = 80.f; + tester.set_rtl_altitude(rtl_altitude); + tester.execute_rtl(); + + // RTL must climb to the return altitude while continuing to circle the very same loiter + // (same center and non-default radius), not re-center a new circle. + tester.check_climbs_on_loiter(kWorkCenter, kNonDefaultRadius, kRadiusTolerance, rtl_altitude, + kAltitudeTolerance, 180s); +} + +TEST_CASE("Loiter: Hold during an altitude change keeps the loiter and locks the current altitude", "[loiter]") +{ + AutopilotTesterLoiter tester; + arm_takeoff_transition_hold(tester); + establish_work_orbit(tester); // established at kLoiterAltitude + + // Command the very same loiter (same center and radius) but at a higher altitude, so the vehicle + // starts climbing while staying on the loiter. + const float climb_target = 200.f; + tester.command_orbit(kWorkCenter, kNonDefaultRadius, climb_target); + + // Catch the vehicle part way through the climb and issue an all-NaN Hold reposition. + const float intercept_altitude = 60.f; // between kLoiterAltitude and climb_target + tester.wait_until_relative_altitude_above(intercept_altitude, 120s); + tester.command_hold_here(); + tester.sleep_for(2s); // let the Hold take effect and the climb arrest + + const float locked_altitude = tester.current_relative_altitude(); + + // The Hold must arrest the climb well before reaching the commanded target altitude ... + CHECK(locked_altitude < climb_target - kAltitudeTolerance); + // ... lock the altitude the vehicle had reached (no further climb) ... + tester.check_holds_altitude(locked_altitude, kAltitudeTolerance, 40s); + // ... and keep circling the same loiter (same center and radius). + tester.check_stays_on_loiter(kWorkCenter, kNonDefaultRadius, kRadiusTolerance, 40s); +} + +TEST_CASE("Loiter: Hold while transiting creates a new loiter at the current position", "[loiter]") +{ + AutopilotTesterLoiter tester; + arm_takeoff_transition_hold(tester); + + // Command a loiter far away and Hold before getting anywhere near it. + const AutopilotTesterLoiter::LocalCoordinate far_center{600.0, 0.0}; + tester.command_reposition(far_center, kLoiterAltitude); + tester.sleep_for(6s); // fly toward it, but nowhere near established + + const auto hold_position = tester.current_local_position(); + tester.command_hold_here(); + tester.sleep_for(10s); // let the fresh loiter circle be captured before asserting on it + + const float default_radius = tester.default_loiter_radius(); + + // A fresh loiter must be created around where Hold was pressed: once captured the vehicle stays + // within one loiter radius (plus the usual tracking band) of that point ... + tester.check_stays_within(hold_position, default_radius + kRadiusTolerance, 40s); + // ... and the vehicle must not keep flying toward the previously commanded far loiter. + tester.check_never_reaches(far_center, 150.f, 40s); +} + +TEST_CASE("Loiter: Hold on a figure-eight reverts to a plain circular loiter", "[loiter]") +{ + AutopilotTesterLoiter tester; + arm_takeoff_transition_hold(tester); + + // Get onto a figure-eight (major 150 m, minor 50 m) around the work center. + tester.command_figure_eight(kWorkCenter, 150.f, 50.f, kLoiterAltitude); + tester.sleep_for(35s); // give it time to actually track the pattern + + const auto hold_position = tester.current_local_position(); + tester.command_hold_here(); + tester.sleep_for(2s); + + const float default_radius = tester.default_loiter_radius(); + + // After Hold the vehicle must settle into a single circular loiter around the Hold position. + // If it kept flying the figure-eight it would repeatedly swing out to the ~150 m lobes and + // leave this bound; a plain circle stays close to its single center. + tester.check_stays_within(hold_position, default_radius + 70.f, 40s); +} + +TEST_CASE("Loiter: altitude-only reposition keeps the loiter and only changes altitude", "[loiter]") +{ + AutopilotTesterLoiter tester; + arm_takeoff_transition_hold(tester); + establish_work_orbit(tester); + + // Request only an altitude change (lat/lon NaN). The loiter center and non-default radius must + // be preserved while the vehicle climbs to the new altitude. + const float new_altitude = 70.f; + tester.command_reposition_altitude(new_altitude); + tester.check_climbs_on_loiter(kWorkCenter, kNonDefaultRadius, kRadiusTolerance, new_altitude, + kAltitudeTolerance, 120s); +}