Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/ArduCopter/mode.cpp
Views: 1798
#include "Copter.h"12/*3* High level calls to set and update flight modes logic for individual4* flight modes is in control_acro.cpp, control_stabilize.cpp, etc5*/67/*8constructor for Mode object9*/10Mode::Mode(void) :11g(copter.g),12g2(copter.g2),13wp_nav(copter.wp_nav),14loiter_nav(copter.loiter_nav),15pos_control(copter.pos_control),16inertial_nav(copter.inertial_nav),17ahrs(copter.ahrs),18attitude_control(copter.attitude_control),19motors(copter.motors),20channel_roll(copter.channel_roll),21channel_pitch(copter.channel_pitch),22channel_throttle(copter.channel_throttle),23channel_yaw(copter.channel_yaw),24G_Dt(copter.G_Dt)25{ };2627#if AC_PAYLOAD_PLACE_ENABLED28PayloadPlace Mode::payload_place;29#endif3031// return the static controller object corresponding to supplied mode32Mode *Copter::mode_from_mode_num(const Mode::Number mode)33{3435switch (mode) {36#if MODE_ACRO_ENABLED37case Mode::Number::ACRO:38return &mode_acro;39#endif4041case Mode::Number::STABILIZE:42return &mode_stabilize;4344case Mode::Number::ALT_HOLD:45return &mode_althold;4647#if MODE_AUTO_ENABLED48case Mode::Number::AUTO:49return &mode_auto;50#endif5152#if MODE_CIRCLE_ENABLED53case Mode::Number::CIRCLE:54return &mode_circle;55#endif5657#if MODE_LOITER_ENABLED58case Mode::Number::LOITER:59return &mode_loiter;60#endif6162#if MODE_GUIDED_ENABLED63case Mode::Number::GUIDED:64return &mode_guided;65#endif6667case Mode::Number::LAND:68return &mode_land;6970#if MODE_RTL_ENABLED71case Mode::Number::RTL:72return &mode_rtl;73#endif7475#if MODE_DRIFT_ENABLED76case Mode::Number::DRIFT:77return &mode_drift;78#endif7980#if MODE_SPORT_ENABLED81case Mode::Number::SPORT:82return &mode_sport;83#endif8485#if MODE_FLIP_ENABLED86case Mode::Number::FLIP:87return &mode_flip;88#endif8990#if AUTOTUNE_ENABLED91case Mode::Number::AUTOTUNE:92return &mode_autotune;93#endif9495#if MODE_POSHOLD_ENABLED96case Mode::Number::POSHOLD:97return &mode_poshold;98#endif99100#if MODE_BRAKE_ENABLED101case Mode::Number::BRAKE:102return &mode_brake;103#endif104105#if MODE_THROW_ENABLED106case Mode::Number::THROW:107return &mode_throw;108#endif109110#if HAL_ADSB_ENABLED111case Mode::Number::AVOID_ADSB:112return &mode_avoid_adsb;113#endif114115#if MODE_GUIDED_NOGPS_ENABLED116case Mode::Number::GUIDED_NOGPS:117return &mode_guided_nogps;118#endif119120#if MODE_SMARTRTL_ENABLED121case Mode::Number::SMART_RTL:122return &mode_smartrtl;123#endif124125#if MODE_FLOWHOLD_ENABLED126case Mode::Number::FLOWHOLD:127return (Mode *)g2.mode_flowhold_ptr;128#endif129130#if MODE_FOLLOW_ENABLED131case Mode::Number::FOLLOW:132return &mode_follow;133#endif134135#if MODE_ZIGZAG_ENABLED136case Mode::Number::ZIGZAG:137return &mode_zigzag;138#endif139140#if MODE_SYSTEMID_ENABLED141case Mode::Number::SYSTEMID:142return (Mode *)g2.mode_systemid_ptr;143#endif144145#if MODE_AUTOROTATE_ENABLED146case Mode::Number::AUTOROTATE:147return &mode_autorotate;148#endif149150#if MODE_TURTLE_ENABLED151case Mode::Number::TURTLE:152return &mode_turtle;153#endif154155default:156break;157}158159#if MODE_GUIDED_ENABLED && AP_SCRIPTING_ENABLED160// Check registered custom modes161for (uint8_t i = 0; i < ARRAY_SIZE(mode_guided_custom); i++) {162if ((mode_guided_custom[i] != nullptr) && (mode_guided_custom[i]->mode_number() == mode)) {163return mode_guided_custom[i];164}165}166#endif167168return nullptr;169}170171172// called when an attempt to change into a mode is unsuccessful:173void Copter::mode_change_failed(const Mode *mode, const char *reason)174{175gcs().send_text(MAV_SEVERITY_WARNING, "Mode change to %s failed: %s", mode->name(), reason);176LOGGER_WRITE_ERROR(LogErrorSubsystem::FLIGHT_MODE, LogErrorCode(mode->mode_number()));177// make sad noise178if (copter.ap.initialised) {179AP_Notify::events.user_mode_change_failed = 1;180}181}182183// Check if this mode can be entered from the GCS184bool Copter::gcs_mode_enabled(const Mode::Number mode_num)185{186// List of modes that can be blocked, index is bit number in parameter bitmask187static const uint8_t mode_list [] {188(uint8_t)Mode::Number::STABILIZE,189(uint8_t)Mode::Number::ACRO,190(uint8_t)Mode::Number::ALT_HOLD,191(uint8_t)Mode::Number::AUTO,192(uint8_t)Mode::Number::GUIDED,193(uint8_t)Mode::Number::LOITER,194(uint8_t)Mode::Number::CIRCLE,195(uint8_t)Mode::Number::DRIFT,196(uint8_t)Mode::Number::SPORT,197(uint8_t)Mode::Number::FLIP,198(uint8_t)Mode::Number::AUTOTUNE,199(uint8_t)Mode::Number::POSHOLD,200(uint8_t)Mode::Number::BRAKE,201(uint8_t)Mode::Number::THROW,202(uint8_t)Mode::Number::AVOID_ADSB,203(uint8_t)Mode::Number::GUIDED_NOGPS,204(uint8_t)Mode::Number::SMART_RTL,205(uint8_t)Mode::Number::FLOWHOLD,206(uint8_t)Mode::Number::FOLLOW,207(uint8_t)Mode::Number::ZIGZAG,208(uint8_t)Mode::Number::SYSTEMID,209(uint8_t)Mode::Number::AUTOROTATE,210(uint8_t)Mode::Number::AUTO_RTL,211(uint8_t)Mode::Number::TURTLE212};213214if (!block_GCS_mode_change((uint8_t)mode_num, mode_list, ARRAY_SIZE(mode_list))) {215return true;216}217218// Mode disabled, try and grab a mode name to give a better warning.219Mode *new_flightmode = mode_from_mode_num(mode_num);220if (new_flightmode != nullptr) {221mode_change_failed(new_flightmode, "GCS entry disabled (FLTMODE_GCSBLOCK)");222} else {223notify_no_such_mode((uint8_t)mode_num);224}225226return false;227}228229// set_mode - change flight mode and perform any necessary initialisation230// optional force parameter used to force the flight mode change (used only first time mode is set)231// returns true if mode was successfully set232// ACRO, STABILIZE, ALTHOLD, LAND, DRIFT and SPORT can always be set successfully but the return state of other flight modes should be checked and the caller should deal with failures appropriately233bool Copter::set_mode(Mode::Number mode, ModeReason reason)234{235// update last reason236const ModeReason last_reason = _last_reason;237_last_reason = reason;238239// return immediately if we are already in the desired mode240if (mode == flightmode->mode_number()) {241control_mode_reason = reason;242// set yaw rate time constant during autopilot startup243if (reason == ModeReason::INITIALISED && mode == Mode::Number::STABILIZE) {244attitude_control->set_yaw_rate_tc(g2.command_model_pilot.get_rate_tc());245}246// make happy noise247if (copter.ap.initialised && (reason != last_reason)) {248AP_Notify::events.user_mode_change = 1;249}250return true;251}252253// Check if GCS mode change is disabled via parameter254if ((reason == ModeReason::GCS_COMMAND) && !gcs_mode_enabled(mode)) {255return false;256}257258#if MODE_AUTO_ENABLED259if (mode == Mode::Number::AUTO_RTL) {260// Special case for AUTO RTL, not a true mode, just AUTO in disguise261// Attempt to join return path, fallback to do-land-start262return mode_auto.return_path_or_jump_to_landing_sequence_auto_RTL(reason);263}264#endif265266Mode *new_flightmode = mode_from_mode_num(mode);267if (new_flightmode == nullptr) {268notify_no_such_mode((uint8_t)mode);269return false;270}271272bool ignore_checks = !motors->armed(); // allow switching to any mode if disarmed. We rely on the arming check to perform273274#if FRAME_CONFIG == HELI_FRAME275// do not allow helis to enter a non-manual throttle mode if the276// rotor runup is not complete277if (!ignore_checks && !new_flightmode->has_manual_throttle() && !motors->rotor_runup_complete()) {278mode_change_failed(new_flightmode, "runup not complete");279return false;280}281#endif282283#if FRAME_CONFIG != HELI_FRAME284// ensure vehicle doesn't leap off the ground if a user switches285// into a manual throttle mode from a non-manual-throttle mode286// (e.g. user arms in guided, raises throttle to 1300 (not enough to287// trigger auto takeoff), then switches into manual):288bool user_throttle = new_flightmode->has_manual_throttle();289#if MODE_DRIFT_ENABLED290if (new_flightmode == &mode_drift) {291user_throttle = true;292}293#endif294if (!ignore_checks &&295ap.land_complete &&296user_throttle &&297!copter.flightmode->has_manual_throttle() &&298new_flightmode->get_pilot_desired_throttle() > copter.get_non_takeoff_throttle()) {299mode_change_failed(new_flightmode, "throttle too high");300return false;301}302#endif303304if (!ignore_checks &&305new_flightmode->requires_GPS() &&306!copter.position_ok()) {307mode_change_failed(new_flightmode, "requires position");308return false;309}310311// check for valid altitude if old mode did not require it but new one does312// we only want to stop changing modes if it could make things worse313if (!ignore_checks &&314!copter.ekf_alt_ok() &&315flightmode->has_manual_throttle() &&316!new_flightmode->has_manual_throttle()) {317mode_change_failed(new_flightmode, "need alt estimate");318return false;319}320321#if AP_FENCE_ENABLED322// may not be allowed to change mode if recovering from fence breach323if (!ignore_checks &&324fence.enabled() &&325fence.option_enabled(AC_Fence::OPTIONS::DISABLE_MODE_CHANGE) &&326fence.get_breaches() &&327motors->armed() &&328get_control_mode_reason() == ModeReason::FENCE_BREACHED &&329!ap.land_complete) {330mode_change_failed(new_flightmode, "in fence recovery");331return false;332}333#endif334335if (!new_flightmode->init(ignore_checks)) {336mode_change_failed(new_flightmode, "init failed");337return false;338}339340// perform any cleanup required by previous flight mode341exit_mode(flightmode, new_flightmode);342343// update flight mode344flightmode = new_flightmode;345control_mode_reason = reason;346#if HAL_LOGGING_ENABLED347logger.Write_Mode((uint8_t)flightmode->mode_number(), reason);348#endif349gcs().send_message(MSG_HEARTBEAT);350351#if HAL_ADSB_ENABLED352adsb.set_is_auto_mode((mode == Mode::Number::AUTO) || (mode == Mode::Number::RTL) || (mode == Mode::Number::GUIDED));353#endif354355#if AP_FENCE_ENABLED356if (fence.get_action() != AC_FENCE_ACTION_REPORT_ONLY) {357// pilot requested flight mode change during a fence breach indicates pilot is attempting to manually recover358// this flight mode change could be automatic (i.e. fence, battery, GPS or GCS failsafe)359// but it should be harmless to disable the fence temporarily in these situations as well360fence.manual_recovery_start();361}362#endif363364#if AP_CAMERA_ENABLED365camera.set_is_auto_mode(flightmode->mode_number() == Mode::Number::AUTO);366#endif367368// set rate shaping time constants369#if MODE_ACRO_ENABLED || MODE_SPORT_ENABLED370attitude_control->set_roll_pitch_rate_tc(g2.command_model_acro_rp.get_rate_tc());371#endif372attitude_control->set_yaw_rate_tc(g2.command_model_pilot.get_rate_tc());373#if MODE_ACRO_ENABLED || MODE_DRIFT_ENABLED374if (mode== Mode::Number::ACRO || mode== Mode::Number::DRIFT) {375attitude_control->set_yaw_rate_tc(g2.command_model_acro_y.get_rate_tc());376}377#endif378379// update notify object380notify_flight_mode();381382// make happy noise383if (copter.ap.initialised) {384AP_Notify::events.user_mode_change = 1;385}386387// return success388return true;389}390391bool Copter::set_mode(const uint8_t new_mode, const ModeReason reason)392{393static_assert(sizeof(Mode::Number) == sizeof(new_mode), "The new mode can't be mapped to the vehicles mode number");394#ifdef DISALLOW_GCS_MODE_CHANGE_DURING_RC_FAILSAFE395if (reason == ModeReason::GCS_COMMAND && copter.failsafe.radio) {396// don't allow mode changes while in radio failsafe397return false;398}399#endif400return copter.set_mode(static_cast<Mode::Number>(new_mode), reason);401}402403// update_flight_mode - calls the appropriate attitude controllers based on flight mode404// called at 100hz or more405void Copter::update_flight_mode()406{407#if AP_RANGEFINDER_ENABLED408surface_tracking.invalidate_for_logging(); // invalidate surface tracking alt, flight mode will set to true if used409#endif410attitude_control->landed_gain_reduction(copter.ap.land_complete); // Adjust gains when landed to attenuate ground oscillation411412flightmode->run();413}414415// exit_mode - high level call to organise cleanup as a flight mode is exited416void Copter::exit_mode(Mode *&old_flightmode,417Mode *&new_flightmode)418{419// smooth throttle transition when switching from manual to automatic flight modes420if (old_flightmode->has_manual_throttle() && !new_flightmode->has_manual_throttle() && motors->armed() && !ap.land_complete) {421// this assumes all manual flight modes use get_pilot_desired_throttle to translate pilot input to output throttle422set_accel_throttle_I_from_pilot_throttle();423}424425// cancel any takeoffs in progress426old_flightmode->takeoff_stop();427428// perform cleanup required for each flight mode429old_flightmode->exit();430431#if FRAME_CONFIG == HELI_FRAME432// firmly reset the flybar passthrough to false when exiting acro mode.433if (old_flightmode == &mode_acro) {434attitude_control->use_flybar_passthrough(false, false);435motors->set_acro_tail(false);436}437438// if we are changing from a mode that did not use manual throttle,439// stab col ramp value should be pre-loaded to the correct value to avoid a twitch440// heli_stab_col_ramp should really only be active switching between Stabilize and Acro modes441if (!old_flightmode->has_manual_throttle()){442if (new_flightmode == &mode_stabilize){443input_manager.set_stab_col_ramp(1.0);444} else if (new_flightmode == &mode_acro){445input_manager.set_stab_col_ramp(0.0);446}447}448449// Make sure inverted flight is disabled if not supported in the new mode450if (!new_flightmode->allows_inverted()) {451attitude_control->set_inverted_flight(false);452}453#endif //HELI_FRAME454}455456// notify_flight_mode - sets notify object based on current flight mode. Only used for OreoLED notify device457void Copter::notify_flight_mode() {458AP_Notify::flags.autopilot_mode = flightmode->is_autopilot();459AP_Notify::flags.flight_mode = (uint8_t)flightmode->mode_number();460notify.set_flight_mode_str(flightmode->name4());461}462463// get_pilot_desired_angle - transform pilot's roll or pitch input into a desired lean angle464// returns desired angle in centi-degrees465void Mode::get_pilot_desired_lean_angles(float &roll_out_cd, float &pitch_out_cd, float angle_max_cd, float angle_limit_cd) const466{467// throttle failsafe check468if (copter.failsafe.radio || !rc().has_ever_seen_rc_input()) {469roll_out_cd = 0.0;470pitch_out_cd = 0.0;471return;472}473474//transform pilot's normalised roll or pitch stick input into a roll and pitch euler angle command475float roll_out_deg;476float pitch_out_deg;477rc_input_to_roll_pitch(channel_roll->get_control_in()*(1.0/ROLL_PITCH_YAW_INPUT_MAX), channel_pitch->get_control_in()*(1.0/ROLL_PITCH_YAW_INPUT_MAX), angle_max_cd * 0.01, angle_limit_cd * 0.01, roll_out_deg, pitch_out_deg);478479// Convert to centi-degrees480roll_out_cd = roll_out_deg * 100.0;481pitch_out_cd = pitch_out_deg * 100.0;482}483484// transform pilot's roll or pitch input into a desired velocity485Vector2f Mode::get_pilot_desired_velocity(float vel_max) const486{487Vector2f vel;488489// throttle failsafe check490if (copter.failsafe.radio || !rc().has_ever_seen_rc_input()) {491return vel;492}493// fetch roll and pitch inputs494float roll_out = channel_roll->get_control_in();495float pitch_out = channel_pitch->get_control_in();496497// convert roll and pitch inputs to -1 to +1 range498float scaler = 1.0 / (float)ROLL_PITCH_YAW_INPUT_MAX;499roll_out *= scaler;500pitch_out *= scaler;501502// convert roll and pitch inputs into velocity in NE frame503vel = Vector2f(-pitch_out, roll_out);504if (vel.is_zero()) {505return vel;506}507copter.rotate_body_frame_to_NE(vel.x, vel.y);508509// Transform square input range to circular output510// vel_scaler is the vector to the edge of the +- 1.0 square in the direction of the current input511Vector2f vel_scaler = vel / MAX(fabsf(vel.x), fabsf(vel.y));512// We scale the output by the ratio of the distance to the square to the unit circle and multiply by vel_max513vel *= vel_max / vel_scaler.length();514return vel;515}516517bool Mode::_TakeOff::triggered(const float target_climb_rate) const518{519if (!copter.ap.land_complete) {520// can't take off if we're already flying521return false;522}523if (target_climb_rate <= 0.0f) {524// can't takeoff unless we want to go up...525return false;526}527528if (copter.motors->get_spool_state() != AP_Motors::SpoolState::THROTTLE_UNLIMITED) {529// hold aircraft on the ground until rotor speed runup has finished530return false;531}532533return true;534}535536bool Mode::is_disarmed_or_landed() const537{538if (!motors->armed() || !copter.ap.auto_armed || copter.ap.land_complete) {539return true;540}541return false;542}543544void Mode::zero_throttle_and_relax_ac(bool spool_up)545{546if (spool_up) {547motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);548} else {549motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);550}551attitude_control->input_euler_angle_roll_pitch_euler_rate_yaw(0.0f, 0.0f, 0.0f);552attitude_control->set_throttle_out(0.0f, false, copter.g.throttle_filt);553}554555void Mode::zero_throttle_and_hold_attitude()556{557// run attitude controller558attitude_control->input_rate_bf_roll_pitch_yaw(0.0f, 0.0f, 0.0f);559attitude_control->set_throttle_out(0.0f, false, copter.g.throttle_filt);560}561562// handle situations where the vehicle is on the ground waiting for takeoff563// force_throttle_unlimited should be true in cases where we want to keep the motors spooled up564// (instead of spooling down to ground idle). This is required for tradheli's in Guided and Auto565// where we always want the motor spooled up in Guided or Auto mode. Tradheli's main rotor stops566// when spooled down to ground idle.567// ultimately it forces the motor interlock to be obeyed in auto and guided modes when on the ground.568void Mode::make_safe_ground_handling(bool force_throttle_unlimited)569{570if (force_throttle_unlimited) {571// keep rotors turning572motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);573} else {574// spool down to ground idle575motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);576}577578// aircraft is landed, integrator terms must be reset regardless of spool state579attitude_control->reset_rate_controller_I_terms_smoothly();580581switch (motors->get_spool_state()) {582case AP_Motors::SpoolState::SHUT_DOWN:583case AP_Motors::SpoolState::GROUND_IDLE:584// reset yaw targets and rates during idle states585attitude_control->reset_yaw_target_and_rate();586break;587case AP_Motors::SpoolState::SPOOLING_UP:588case AP_Motors::SpoolState::THROTTLE_UNLIMITED:589case AP_Motors::SpoolState::SPOOLING_DOWN:590// while transitioning though active states continue to operate normally591break;592}593594pos_control->relax_velocity_controller_xy();595pos_control->update_xy_controller();596pos_control->relax_z_controller(0.0f); // forces throttle output to decay to zero597pos_control->update_z_controller();598// we may need to move this out599attitude_control->input_euler_angle_roll_pitch_euler_rate_yaw(0.0f, 0.0f, 0.0f);600}601602/*603get a height above ground estimate for landing604*/605int32_t Mode::get_alt_above_ground_cm(void)606{607int32_t alt_above_ground_cm;608if (copter.get_rangefinder_height_interpolated_cm(alt_above_ground_cm)) {609return alt_above_ground_cm;610}611if (!pos_control->is_active_xy()) {612return copter.current_loc.alt;613}614if (copter.current_loc.get_alt_cm(Location::AltFrame::ABOVE_TERRAIN, alt_above_ground_cm)) {615return alt_above_ground_cm;616}617618// Assume the Earth is flat:619return copter.current_loc.alt;620}621622void Mode::land_run_vertical_control(bool pause_descent)623{624float cmb_rate = 0;625bool ignore_descent_limit = false;626if (!pause_descent) {627628// do not ignore limits until we have slowed down for landing629ignore_descent_limit = (MAX(g2.land_alt_low,100) > get_alt_above_ground_cm()) || copter.ap.land_complete_maybe;630631float max_land_descent_velocity;632if (g.land_speed_high > 0) {633max_land_descent_velocity = -g.land_speed_high;634} else {635max_land_descent_velocity = pos_control->get_max_speed_down_cms();636}637638// Don't speed up for landing.639max_land_descent_velocity = MIN(max_land_descent_velocity, -abs(g.land_speed));640641// Compute a vertical velocity demand such that the vehicle approaches g2.land_alt_low. Without the below constraint, this would cause the vehicle to hover at g2.land_alt_low.642cmb_rate = sqrt_controller(MAX(g2.land_alt_low,100)-get_alt_above_ground_cm(), pos_control->get_pos_z_p().kP(), pos_control->get_max_accel_z_cmss(), G_Dt);643644// Constrain the demanded vertical velocity so that it is between the configured maximum descent speed and the configured minimum descent speed.645cmb_rate = constrain_float(cmb_rate, max_land_descent_velocity, -abs(g.land_speed));646647#if AC_PRECLAND_ENABLED648const bool navigating = pos_control->is_active_xy();649bool doing_precision_landing = !copter.ap.land_repo_active && copter.precland.target_acquired() && navigating;650651if (doing_precision_landing) {652// prec landing is active653Vector2f target_pos;654float target_error_cm = 0.0f;655if (copter.precland.get_target_position_cm(target_pos)) {656const Vector2f current_pos = inertial_nav.get_position_xy_cm();657// target is this many cm away from the vehicle658target_error_cm = (target_pos - current_pos).length();659}660// check if we should descend or not661const float max_horiz_pos_error_cm = copter.precland.get_max_xy_error_before_descending_cm();662Vector3f target_pos_meas;663copter.precland.get_target_position_measurement_cm(target_pos_meas);664if (target_error_cm > max_horiz_pos_error_cm && !is_zero(max_horiz_pos_error_cm)) {665// doing precland but too far away from the obstacle666// do not descend667cmb_rate = 0.0f;668} else if (target_pos_meas.z > 35.0f && target_pos_meas.z < 200.0f && !copter.precland.do_fast_descend()) {669// very close to the ground and doing prec land, lets slow down to make sure we land on target670// compute desired descent velocity671const float precland_acceptable_error_cm = 15.0f;672const float precland_min_descent_speed_cms = 10.0f;673const float max_descent_speed_cms = abs(g.land_speed)*0.5f;674const float land_slowdown = MAX(0.0f, target_error_cm*(max_descent_speed_cms/precland_acceptable_error_cm));675cmb_rate = MIN(-precland_min_descent_speed_cms, -max_descent_speed_cms+land_slowdown);676}677}678#endif679}680681// update altitude target and call position controller682pos_control->land_at_climb_rate_cm(cmb_rate, ignore_descent_limit);683pos_control->update_z_controller();684}685686void Mode::land_run_horizontal_control()687{688Vector2f vel_correction;689690// relax loiter target if we might be landed691if (copter.ap.land_complete_maybe) {692pos_control->soften_for_landing_xy();693}694695// process pilot inputs696if (!copter.failsafe.radio) {697if ((g.throttle_behavior & THR_BEHAVE_HIGH_THROTTLE_CANCELS_LAND) != 0 && copter.rc_throttle_control_in_filter.get() > LAND_CANCEL_TRIGGER_THR){698LOGGER_WRITE_EVENT(LogEvent::LAND_CANCELLED_BY_PILOT);699// exit land if throttle is high700if (!set_mode(Mode::Number::LOITER, ModeReason::THROTTLE_LAND_ESCAPE)) {701set_mode(Mode::Number::ALT_HOLD, ModeReason::THROTTLE_LAND_ESCAPE);702}703}704705if (g.land_repositioning) {706// apply SIMPLE mode transform to pilot inputs707update_simple_mode();708709// convert pilot input to reposition velocity710// use half maximum acceleration as the maximum velocity to ensure aircraft will711// stop from full reposition speed in less than 1 second.712const float max_pilot_vel = wp_nav->get_wp_acceleration() * 0.5;713vel_correction = get_pilot_desired_velocity(max_pilot_vel);714715// record if pilot has overridden roll or pitch716if (!vel_correction.is_zero()) {717if (!copter.ap.land_repo_active) {718LOGGER_WRITE_EVENT(LogEvent::LAND_REPO_ACTIVE);719}720copter.ap.land_repo_active = true;721#if AC_PRECLAND_ENABLED722} else {723// no override right now, check if we should allow precland724if (copter.precland.allow_precland_after_reposition()) {725copter.ap.land_repo_active = false;726}727#endif728}729}730}731732// this variable will be updated if prec land target is in sight and pilot isn't trying to reposition the vehicle733copter.ap.prec_land_active = false;734#if AC_PRECLAND_ENABLED735copter.ap.prec_land_active = !copter.ap.land_repo_active && copter.precland.target_acquired();736// run precision landing737if (copter.ap.prec_land_active) {738Vector2f target_pos, target_vel;739if (!copter.precland.get_target_position_cm(target_pos)) {740target_pos = inertial_nav.get_position_xy_cm();741}742// get the velocity of the target743copter.precland.get_target_velocity_cms(inertial_nav.get_velocity_xy_cms(), target_vel);744745Vector2f zero;746Vector2p landing_pos = target_pos.topostype();747// target vel will remain zero if landing target is stationary748pos_control->input_pos_vel_accel_xy(landing_pos, target_vel, zero);749}750#endif751752if (!copter.ap.prec_land_active) {753Vector2f accel;754pos_control->input_vel_accel_xy(vel_correction, accel);755}756757// run pos controller758pos_control->update_xy_controller();759Vector3f thrust_vector = pos_control->get_thrust_vector();760761if (g2.wp_navalt_min > 0) {762// user has requested an altitude below which navigation763// attitude is limited. This is used to prevent commanded roll764// over on landing, which particularly affects helicopters if765// there is any position estimate drift after touchdown. We766// limit attitude to 7 degrees below this limit and linearly767// interpolate for 1m above that768const float attitude_limit_cd = linear_interpolate(700, copter.aparm.angle_max, get_alt_above_ground_cm(),769g2.wp_navalt_min*100U, (g2.wp_navalt_min+1)*100U);770const float thrust_vector_max = sinf(radians(attitude_limit_cd * 0.01f)) * GRAVITY_MSS * 100.0f;771const float thrust_vector_mag = thrust_vector.xy().length();772if (thrust_vector_mag > thrust_vector_max) {773float ratio = thrust_vector_max / thrust_vector_mag;774thrust_vector.x *= ratio;775thrust_vector.y *= ratio;776777// tell position controller we are applying an external limit778pos_control->set_externally_limited_xy();779}780}781782// call attitude controller783attitude_control->input_thrust_vector_heading(thrust_vector, auto_yaw.get_heading());784785}786787// run normal or precision landing (if enabled)788// pause_descent is true if vehicle should not descend789void Mode::land_run_normal_or_precland(bool pause_descent)790{791#if AC_PRECLAND_ENABLED792if (pause_descent || !copter.precland.enabled()) {793// we don't want to start descending immediately or prec land is disabled794// in both cases just run simple land controllers795land_run_horiz_and_vert_control(pause_descent);796} else {797// prec land is enabled and we have not paused descent798// the state machine takes care of the entire prec landing procedure799precland_run();800}801#else802land_run_horiz_and_vert_control(pause_descent);803#endif804}805806#if AC_PRECLAND_ENABLED807// Go towards a position commanded by prec land state machine in order to retry landing808// The passed in location is expected to be NED and in m809void Mode::precland_retry_position(const Vector3f &retry_pos)810{811if (!copter.failsafe.radio) {812if ((g.throttle_behavior & THR_BEHAVE_HIGH_THROTTLE_CANCELS_LAND) != 0 && copter.rc_throttle_control_in_filter.get() > LAND_CANCEL_TRIGGER_THR){813LOGGER_WRITE_EVENT(LogEvent::LAND_CANCELLED_BY_PILOT);814// exit land if throttle is high815if (!set_mode(Mode::Number::LOITER, ModeReason::THROTTLE_LAND_ESCAPE)) {816set_mode(Mode::Number::ALT_HOLD, ModeReason::THROTTLE_LAND_ESCAPE);817}818}819820// allow user to take control during repositioning. Note: copied from land_run_horizontal_control()821// To-Do: this code exists at several different places in slightly different forms and that should be fixed822if (g.land_repositioning) {823float target_roll = 0.0f;824float target_pitch = 0.0f;825// convert pilot input to lean angles826get_pilot_desired_lean_angles(target_roll, target_pitch, loiter_nav->get_angle_max_cd(), attitude_control->get_althold_lean_angle_max_cd());827828// record if pilot has overridden roll or pitch829if (!is_zero(target_roll) || !is_zero(target_pitch)) {830if (!copter.ap.land_repo_active) {831LOGGER_WRITE_EVENT(LogEvent::LAND_REPO_ACTIVE);832}833// this flag will be checked by prec land state machine later and any further landing retires will be cancelled834copter.ap.land_repo_active = true;835}836}837}838839Vector3p retry_pos_NEU{retry_pos.x, retry_pos.y, retry_pos.z * -1.0f};840// pos controller expects input in NEU cm's841retry_pos_NEU = retry_pos_NEU * 100.0f;842pos_control->input_pos_xyz(retry_pos_NEU, 0.0f, 1000.0f);843844// run position controllers845pos_control->update_xy_controller();846pos_control->update_z_controller();847848// call attitude controller849attitude_control->input_thrust_vector_heading(pos_control->get_thrust_vector(), auto_yaw.get_heading());850851}852853// Run precland statemachine. This function should be called from any mode that wants to do precision landing.854// This handles everything from prec landing, to prec landing failures, to retries and failsafe measures855void Mode::precland_run()856{857// if user is taking control, we will not run the statemachine, and simply land (may or may not be on target)858if (!copter.ap.land_repo_active) {859// This will get updated later to a retry pos if needed860Vector3f retry_pos;861862switch (copter.precland_statemachine.update(retry_pos)) {863case AC_PrecLand_StateMachine::Status::RETRYING:864// we want to retry landing by going to another position865precland_retry_position(retry_pos);866break;867868case AC_PrecLand_StateMachine::Status::FAILSAFE: {869// we have hit a failsafe. Failsafe can only mean two things, we either want to stop permanently till user takes over or land870switch (copter.precland_statemachine.get_failsafe_actions()) {871case AC_PrecLand_StateMachine::FailSafeAction::DESCEND:872// descend normally, prec land target is definitely not in sight873land_run_horiz_and_vert_control();874break;875case AC_PrecLand_StateMachine::FailSafeAction::HOLD_POS:876// sending "true" in this argument will stop the descend877land_run_horiz_and_vert_control(true);878break;879}880break;881}882case AC_PrecLand_StateMachine::Status::ERROR:883// should never happen, is certainly a bug. Report then descend884INTERNAL_ERROR(AP_InternalError::error_t::flow_of_control);885FALLTHROUGH;886case AC_PrecLand_StateMachine::Status::DESCEND:887// run land controller. This will descend towards the target if prec land target is in sight888// else it will just descend vertically889land_run_horiz_and_vert_control();890break;891}892} else {893// just land, since user has taken over controls, it does not make sense to run any retries or failsafe measures894land_run_horiz_and_vert_control();895}896}897#endif898899float Mode::throttle_hover() const900{901return motors->get_throttle_hover();902}903904// transform pilot's manual throttle input to make hover throttle mid stick905// used only for manual throttle modes906// thr_mid should be in the range 0 to 1907// returns throttle output 0 to 1908float Mode::get_pilot_desired_throttle() const909{910const float thr_mid = throttle_hover();911int16_t throttle_control = channel_throttle->get_control_in();912913int16_t mid_stick = copter.get_throttle_mid();914// protect against unlikely divide by zero915if (mid_stick <= 0) {916mid_stick = 500;917}918919// ensure reasonable throttle values920throttle_control = constrain_int16(throttle_control,0,1000);921922// calculate normalised throttle input923float throttle_in;924if (throttle_control < mid_stick) {925throttle_in = ((float)throttle_control)*0.5f/(float)mid_stick;926} else {927throttle_in = 0.5f + ((float)(throttle_control-mid_stick)) * 0.5f / (float)(1000-mid_stick);928}929930const float expo = constrain_float(-(thr_mid-0.5f)/0.375f, -0.5f, 1.0f);931// calculate the output throttle using the given expo function932float throttle_out = throttle_in*(1.0f-expo) + expo*throttle_in*throttle_in*throttle_in;933return throttle_out;934}935936float Mode::get_avoidance_adjusted_climbrate(float target_rate)937{938#if AP_AVOIDANCE_ENABLED939AP::ac_avoid()->adjust_velocity_z(pos_control->get_pos_z_p().kP(), pos_control->get_max_accel_z_cmss(), target_rate, G_Dt);940return target_rate;941#else942return target_rate;943#endif944}945946// send output to the motors, can be overridden by subclasses947void Mode::output_to_motors()948{949motors->output();950}951952Mode::AltHoldModeState Mode::get_alt_hold_state(float target_climb_rate_cms)953{954// Alt Hold State Machine Determination955if (!motors->armed()) {956// the aircraft should moved to a shut down state957motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::SHUT_DOWN);958959// transition through states as aircraft spools down960switch (motors->get_spool_state()) {961962case AP_Motors::SpoolState::SHUT_DOWN:963return AltHoldModeState::MotorStopped;964965case AP_Motors::SpoolState::GROUND_IDLE:966return AltHoldModeState::Landed_Ground_Idle;967968default:969return AltHoldModeState::Landed_Pre_Takeoff;970}971972} else if (takeoff.running() || takeoff.triggered(target_climb_rate_cms)) {973// the aircraft is currently landed or taking off, asking for a positive climb rate and in THROTTLE_UNLIMITED974// the aircraft should progress through the take off procedure975return AltHoldModeState::Takeoff;976977} else if (!copter.ap.auto_armed || copter.ap.land_complete) {978// the aircraft is armed and landed979if (target_climb_rate_cms < 0.0f && !copter.ap.using_interlock) {980// the aircraft should move to a ground idle state981motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::GROUND_IDLE);982983} else {984// the aircraft should prepare for imminent take off985motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);986}987988if (motors->get_spool_state() == AP_Motors::SpoolState::GROUND_IDLE) {989// the aircraft is waiting in ground idle990return AltHoldModeState::Landed_Ground_Idle;991992} else {993// the aircraft can leave the ground at any time994return AltHoldModeState::Landed_Pre_Takeoff;995}996997} else {998// the aircraft is in a flying state999motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED);1000return AltHoldModeState::Flying;1001}1002}10031004// transform pilot's yaw input into a desired yaw rate1005// returns desired yaw rate in centi-degrees per second1006float Mode::get_pilot_desired_yaw_rate() const1007{1008// throttle failsafe check1009if (copter.failsafe.radio || !rc().has_ever_seen_rc_input()) {1010return 0.0f;1011}10121013// Get yaw input1014const float yaw_in = channel_yaw->norm_input_dz();10151016// convert pilot input to the desired yaw rate1017return g2.command_model_pilot.get_rate() * 100.0 * input_expo(yaw_in, g2.command_model_pilot.get_expo());1018}10191020// pass-through functions to reduce code churn on conversion;1021// these are candidates for moving into the Mode base1022// class.1023float Mode::get_pilot_desired_climb_rate(float throttle_control)1024{1025return copter.get_pilot_desired_climb_rate(throttle_control);1026}10271028float Mode::get_non_takeoff_throttle()1029{1030return copter.get_non_takeoff_throttle();1031}10321033void Mode::update_simple_mode(void) {1034copter.update_simple_mode();1035}10361037bool Mode::set_mode(Mode::Number mode, ModeReason reason)1038{1039return copter.set_mode(mode, reason);1040}10411042void Mode::set_land_complete(bool b)1043{1044return copter.set_land_complete(b);1045}10461047GCS_Copter &Mode::gcs()1048{1049return copter.gcs();1050}10511052uint16_t Mode::get_pilot_speed_dn()1053{1054return copter.get_pilot_speed_dn();1055}10561057// Return stopping point as a location with above origin alt frame1058Location Mode::get_stopping_point() const1059{1060Vector3p stopping_point_NEU;1061copter.pos_control->get_stopping_point_xy_cm(stopping_point_NEU.xy());1062copter.pos_control->get_stopping_point_z_cm(stopping_point_NEU.z);1063return Location { stopping_point_NEU.tofloat(), Location::AltFrame::ABOVE_ORIGIN };1064}106510661067