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/ArduPlane/Plane.h
Views: 1798
/*1Lead developer: Andrew Tridgell & Tom Pittenger23Authors: Doug Weibel, Jose Julio, Jordi Munoz, Jason Short, Randy Mackay, Pat Hickey, John Arne Birkeland, Olivier Adler, Amilcar Lucas, Gregory Fletcher, Paul Riseborough, Brandon Jones, Jon Challinger4Thanks to: Chris Anderson, Michael Oborne, Paul Mather, Bill Premerlani, James Cohen, JB from rotorFX, Automatik, Fefenin, Peter Meister, Remzibi, Yury Smirnov, Sandro Benigno, Max Levine, Roberto Navoni, Lorenz Meier, Yury MonZon56Please contribute your ideas! See http://dev.ardupilot.com for details78This program is free software: you can redistribute it and/or modify9it under the terms of the GNU General Public License as published by10the Free Software Foundation, either version 3 of the License, or11(at your option) any later version.1213This program is distributed in the hope that it will be useful,14but WITHOUT ANY WARRANTY; without even the implied warranty of15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the16GNU General Public License for more details.1718You should have received a copy of the GNU General Public License19along with this program. If not, see <http://www.gnu.org/licenses/>.20*/21#pragma once2223////////////////////////////////////////////////////////////////////////////////24// Header includes25////////////////////////////////////////////////////////////////////////////////2627#include <cmath>28#include <stdarg.h>29#include <stdio.h>3031#include <AP_HAL/AP_HAL.h>32#include <AP_Common/AP_Common.h>33#include <AP_Airspeed/AP_Airspeed.h>34#include <AP_Param/AP_Param.h>35#include <StorageManager/StorageManager.h>36#include <AP_Math/AP_Math.h> // ArduPilot Mega Vector/Matrix math Library37#include <AP_InertialSensor/AP_InertialSensor.h> // Inertial Sensor Library38#include <AP_AccelCal/AP_AccelCal.h> // interface and maths for accelerometer calibration39#include <AP_AHRS/AP_AHRS.h> // ArduPilot Mega DCM Library40#include <SRV_Channel/SRV_Channel.h>41#include <AP_RangeFinder/AP_RangeFinder_config.h> // Range finder library42#include <Filter/Filter.h> // Filter library43#include <AP_Camera/AP_Camera.h> // Photo or video camera44#include <AP_Terrain/AP_Terrain.h>45#include <AP_RPM/AP_RPM.h>46#include <AP_Beacon/AP_Beacon.h>4748#include <AP_AdvancedFailsafe/AP_AdvancedFailsafe.h>49#include <APM_Control/APM_Control.h>50#include <APM_Control/AP_AutoTune.h>51#include <GCS_MAVLink/GCS_MAVLink.h> // MAVLink GCS definitions52#include <AP_Mount/AP_Mount.h> // Camera/Antenna mount53#include <AP_Declination/AP_Declination.h> // ArduPilot Mega Declination Helper Library54#include <AP_Logger/AP_Logger.h>55#include <AP_Scheduler/AP_Scheduler.h> // main loop scheduler56#include <AP_Scheduler/PerfInfo.h> // loop perf monitoring5758#include <AP_Navigation/AP_Navigation.h>59#include <AP_L1_Control/AP_L1_Control.h>60#include <AP_RCMapper/AP_RCMapper.h> // RC input mapping library6162#include <AP_Vehicle/AP_Vehicle.h>63#include <AP_TECS/AP_TECS.h>64#include <AP_NavEKF2/AP_NavEKF2.h>65#include <AP_NavEKF3/AP_NavEKF3.h>66#include <AP_Mission/AP_Mission.h> // Mission command library6768#include <AP_Soaring/AP_Soaring.h>69#include <AP_BattMonitor/AP_BattMonitor.h> // Battery monitor library7071#include <AP_Arming/AP_Arming.h>72#include <AP_Frsky_Telem/AP_Frsky_Telem.h>73#include <AP_OSD/AP_OSD.h>7475#include <AP_Rally/AP_Rally.h>7677#include <AP_OpticalFlow/AP_OpticalFlow.h> // Optical Flow library78#include <AP_Parachute/AP_Parachute.h>79#include <AP_ADSB/AP_ADSB.h>80#include <AP_ICEngine/AP_ICEngine.h>81#include <AP_Landing/AP_Landing.h>82#include <AP_LandingGear/AP_LandingGear.h> // Landing Gear library83#include <AP_Follow/AP_Follow.h>84#include <AP_ExternalControl/AP_ExternalControl_config.h>85#if AP_EXTERNAL_CONTROL_ENABLED86#include "AP_ExternalControl_Plane.h"87#endif8889#include <AC_PrecLand/AC_PrecLand_config.h>90#if AC_PRECLAND_ENABLED91# include <AC_PrecLand/AC_PrecLand.h>92#endif9394#include "GCS_MAVLink_Plane.h"95#include "GCS_Plane.h"96#include "quadplane.h"97#include <AP_Tuning/AP_Tuning_config.h>98#if AP_TUNING_ENABLED99#include "tuning.h"100#endif101102// Configuration103#include "config.h"104105#if AP_ADVANCEDFAILSAFE_ENABLED106#include "afs_plane.h"107#endif108109// Local modules110#include "defines.h"111#include "mode.h"112113#if AP_SCRIPTING_ENABLED114#include <AP_Scripting/AP_Scripting.h>115#endif116117#include "RC_Channel_Plane.h" // RC Channel Library118#include "Parameters.h"119#if HAL_ADSB_ENABLED120#include "avoidance_adsb.h"121#endif122#include "AP_Arming.h"123#include "pullup.h"124125/*126main APM:Plane class127*/128class Plane : public AP_Vehicle {129public:130friend class GCS_MAVLINK_Plane;131friend class Parameters;132friend class ParametersG2;133friend class AP_Arming_Plane;134friend class QuadPlane;135friend class QAutoTune;136friend class AP_Tuning_Plane;137friend class AP_AdvancedFailsafe_Plane;138friend class AP_Avoidance_Plane;139friend class GCS_Plane;140friend class RC_Channel_Plane;141friend class RC_Channels_Plane;142friend class Tailsitter;143friend class Tiltrotor;144friend class SLT_Transition;145friend class Tailsitter_Transition;146friend class VTOL_Assist;147148friend class Mode;149friend class ModeCircle;150friend class ModeStabilize;151friend class ModeTraining;152friend class ModeAcro;153friend class ModeFBWA;154friend class ModeFBWB;155friend class ModeCruise;156friend class ModeAutoTune;157friend class ModeAuto;158friend class ModeRTL;159friend class ModeLoiter;160friend class ModeAvoidADSB;161friend class ModeGuided;162friend class ModeInitializing;163friend class ModeManual;164friend class ModeQStabilize;165friend class ModeQHover;166friend class ModeQLoiter;167friend class ModeQLand;168friend class ModeQRTL;169friend class ModeQAcro;170friend class ModeQAutotune;171friend class ModeTakeoff;172friend class ModeThermal;173friend class ModeLoiterAltQLand;174#if MODE_AUTOLAND_ENABLED175friend class ModeAutoLand;176#endif177#if AP_EXTERNAL_CONTROL_ENABLED178friend class AP_ExternalControl_Plane;179#endif180#if AP_PLANE_GLIDER_PULLUP_ENABLED181friend class GliderPullup;182#endif183184Plane(void);185186private:187188// key aircraft parameters passed to multiple libraries189AP_FixedWing aparm;190191// Global parameters are all contained within the 'g' and 'g2' classes.192Parameters g;193ParametersG2 g2;194195// mapping between input channels196RCMapper rcmap;197198// primary input channels199RC_Channel *channel_roll;200RC_Channel *channel_pitch;201RC_Channel *channel_throttle;202RC_Channel *channel_rudder;203RC_Channel *channel_flap;204RC_Channel *channel_airbrake;205206// scaled roll limit based on pitch207int32_t roll_limit_cd;208float pitch_limit_min;209210// flight modes convenience array211AP_Int8 *flight_modes = &g.flight_mode1;212const uint8_t num_flight_modes = 6;213214#if AP_RANGEFINDER_ENABLED215AP_FixedWing::Rangefinder_State rangefinder_state;216217/*218orientation of rangefinder to use for landing219*/220Rotation rangefinder_orientation(void) const {221return Rotation(g2.rangefinder_land_orient.get());222}223#endif224225#if AP_MAVLINK_MAV_CMD_SET_HAGL_ENABLED226struct {227// allow for external height above ground estimate228float hagl;229uint32_t last_update_ms;230uint32_t timeout_ms;231} external_hagl;232bool get_external_HAGL(float &height_agl);233void handle_external_hagl(const mavlink_command_int_t &packet);234#endif // AP_MAVLINK_MAV_CMD_SET_HAGL_ENABLED235236float get_landing_height(bool &using_rangefinder);237238239#if AP_RPM_ENABLED240AP_RPM rpm_sensor;241#endif242243AP_TECS TECS_controller{ahrs, aparm, landing, MASK_LOG_TECS};244AP_L1_Control L1_controller{ahrs, &TECS_controller};245246// Attitude to servo controllers247AP_RollController rollController{aparm};248AP_PitchController pitchController{aparm};249AP_YawController yawController{aparm};250AP_SteerController steerController{};251252// Training mode253bool training_manual_roll; // user has manual roll control254bool training_manual_pitch; // user has manual pitch control255256// should throttle be pass-thru in guided?257bool guided_throttle_passthru;258259// are we doing calibration? This is used to allow heartbeat to260// external failsafe boards during baro and airspeed calibration261bool in_calibration;262263// are we currently in long failsafe but have postponed it in MODE TAKEOFF until min level alt is reached264bool long_failsafe_pending;265266// GCS selection267GCS_Plane _gcs; // avoid using this; use gcs()268GCS_Plane &gcs() { return _gcs; }269270// selected navigation controller271AP_Navigation *nav_controller = &L1_controller;272273// Camera274#if AP_CAMERA_ENABLED275AP_Camera camera{MASK_LOG_CAMERA};276#endif277278#if AP_OPTICALFLOW_ENABLED279// Optical flow sensor280AP_OpticalFlow optflow;281#endif282283#if HAL_RALLY_ENABLED284// Rally Points285AP_Rally rally;286#endif287288#if AC_PRECLAND_ENABLED289void precland_update(void);290#endif291292// returns a Location for a rally point or home; if293// HAL_RALLY_ENABLED is false, just home.294Location calc_best_rally_or_home_location(const Location ¤t_loc, float rtl_home_alt_amsl_cm) const;295296#if OSD_ENABLED || OSD_PARAM_ENABLED297AP_OSD osd;298#endif299300ModeCircle mode_circle;301ModeStabilize mode_stabilize;302ModeTraining mode_training;303ModeAcro mode_acro;304ModeFBWA mode_fbwa;305ModeFBWB mode_fbwb;306ModeCruise mode_cruise;307ModeAutoTune mode_autotune;308ModeAuto mode_auto;309ModeRTL mode_rtl;310ModeLoiter mode_loiter;311#if HAL_ADSB_ENABLED312ModeAvoidADSB mode_avoidADSB;313#endif314ModeGuided mode_guided;315ModeInitializing mode_initializing;316ModeManual mode_manual;317#if HAL_QUADPLANE_ENABLED318ModeQStabilize mode_qstabilize;319ModeQHover mode_qhover;320ModeQLoiter mode_qloiter;321ModeQLand mode_qland;322ModeQRTL mode_qrtl;323ModeQAcro mode_qacro;324ModeLoiterAltQLand mode_loiter_qland;325#if QAUTOTUNE_ENABLED326ModeQAutotune mode_qautotune;327#endif // QAUTOTUNE_ENABLED328#endif // HAL_QUADPLANE_ENABLED329ModeTakeoff mode_takeoff;330#if MODE_AUTOLAND_ENABLED331ModeAutoLand mode_autoland;332#endif333#if HAL_SOARING_ENABLED334ModeThermal mode_thermal;335#endif336337#if AP_QUICKTUNE_ENABLED338AP_Quicktune quicktune;339#endif340341// This is the state of the flight control system342// There are multiple states defined such as MANUAL, FBW-A, AUTO343Mode *control_mode = &mode_initializing;344Mode *previous_mode = &mode_initializing;345346// time of last mode change347uint32_t last_mode_change_ms;348349// Used to maintain the state of the previous control switch position350// This is set to 254 when we need to re-read the switch351uint8_t oldSwitchPosition = 254;352353// This is used to enable the inverted flight feature354bool inverted_flight;355356// last time we ran roll/pitch stabilization357uint32_t last_stabilize_ms;358359// Failsafe360struct {361// Used to track if the value on channel 3 (throttle) has fallen below the failsafe threshold362// RC receiver should be set up to output a low throttle value when signal is lost363bool rc_failsafe;364365// true if an adsb related failsafe has occurred366bool adsb;367368// saved flight mode369enum Mode::Number saved_mode_number;370371// A tracking variable for type of failsafe active372// Used for failsafe based on loss of RC signal or GCS signal373int16_t state;374375// number of low throttle values376uint8_t throttle_counter;377378// A timer used to track how long we have been in a "short failsafe" condition due to loss of RC signal379uint32_t short_timer_ms;380381uint32_t last_valid_rc_ms;382383//keeps track of the last valid rc as it relates to the AFS system384//Does not count rc inputs as valid if the standard failsafe is on385uint32_t AFS_last_valid_rc_ms;386} failsafe;387388#if HAL_QUADPLANE_ENABLED389// Landing390class VTOLApproach {391public:392enum class Stage {393RTL,394LOITER_TO_ALT,395ENSURE_RADIUS,396WAIT_FOR_BREAKOUT,397APPROACH_LINE,398VTOL_LANDING,399};400401Stage approach_stage;402float approach_direction_deg;403} vtol_approach_s;404#endif405406bool any_failsafe_triggered() {407return failsafe.state != FAILSAFE_NONE || battery.has_failsafed() || failsafe.adsb;408}409410// A counter used to count down valid gps fixes to allow the gps estimate to settle411// before recording our home position (and executing a ground start if we booted with an air start)412uint8_t ground_start_count = 5;413414// true if we have a position estimate from AHRS415bool have_position;416417// Airspeed418// The calculated airspeed to use in FBW-B. Also used in higher modes for insuring min ground speed is met.419// Also used for flap deployment criteria. Centimeters per second.420int32_t target_airspeed_cm;421int32_t new_airspeed_cm = -1; //temp variable for AUTO and GUIDED mode speed changes422423// The difference between current and desired airspeed. Used in the pitch controller. Meters per second.424float airspeed_error;425426// An amount that the airspeed should be increased in auto modes based on the user positioning the427// throttle stick in the top half of the range. Centimeters per second.428int16_t airspeed_nudge_cm;429430// Similar to airspeed_nudge, but used when no airspeed sensor.431// 0-(throttle_max - throttle_cruise) : throttle nudge in Auto mode using top 1/2 of throttle stick travel432int16_t throttle_nudge;433434// Ground speed435// The amount current ground speed is below min ground speed. Centimeters per second436int32_t groundspeed_undershoot;437bool groundspeed_undershoot_is_valid;438439// speed scaler for control surfaces, updated at 10Hz440float surface_speed_scaler = 1.0;441442// Battery Sensors443AP_BattMonitor battery{MASK_LOG_CURRENT,444FUNCTOR_BIND_MEMBER(&Plane::handle_battery_failsafe, void, const char*, const int8_t),445_failsafe_priorities};446447struct {448uint32_t last_tkoff_arm_time;449uint32_t last_check_ms;450uint32_t rudder_takeoff_warn_ms;451uint32_t last_report_ms;452bool launchTimerStarted;453uint8_t accel_event_counter;454uint32_t accel_event_ms;455uint32_t start_time_ms;456bool waiting_for_rudder_neutral;457float throttle_lim_max;458float throttle_lim_min;459uint32_t throttle_max_timer_ms;460uint32_t level_off_start_time_ms;461// Good candidate for keeping the initial time for TKOFF_THR_MAX_T.462#if MODE_AUTOLAND_ENABLED463struct {464float heading; // deg465bool initialized;466} initial_direction;467#endif468} takeoff_state;469470// ground steering controller state471struct {472// Direction held during phases of takeoff and landing centidegrees473// A value of -1 indicates the course has not been set/is not in use474// this is a 0..36000 value, or -1 for disabled475int32_t hold_course_cd = -1;476477// locked_course and locked_course_cd are used in stabilize mode478// when ground steering is active, and for steering in auto-takeoff479bool locked_course;480float locked_course_err;481uint32_t last_steer_ms;482} steer_state;483484// flight mode specific485struct {486// Altitude threshold to complete a takeoff command in autonomous487// modes. Centimeters above home488int32_t takeoff_altitude_rel_cm;489490// Begin leveling out the enforced takeoff pitch angle min at this height to reduce/eliminate overshoot491int32_t height_below_takeoff_to_level_off_cm;492493// the highest airspeed we have reached since entering AUTO. Used494// to control ground takeoff495float highest_airspeed;496497// turn angle for next leg of mission498float next_turn_angle {90};499500// filtered sink rate for landing501float sink_rate;502503// time when we first pass min GPS speed on takeoff504uint32_t takeoff_speed_time_ms;505506// distance to next waypoint507float wp_distance;508509// proportion to next waypoint510float wp_proportion;511512// last time is_flying() returned true in milliseconds513uint32_t last_flying_ms;514515// time stamp of when we start flying while in auto mode in milliseconds516uint32_t started_flying_in_auto_ms;517518// barometric altitude at start of takeoff519float baro_takeoff_alt;520521// initial pitch. Used to detect if nose is rising in a tail dragger522int16_t initial_pitch_cd;523524// Minimum pitch to hold during takeoff command execution. Hundredths of a degree525int16_t takeoff_pitch_cd;526527// Flag for using gps ground course instead of INS yaw. Set false when takeoff command in process.528bool takeoff_complete;529530// are we headed to the land approach waypoint? Works for any nav type531bool wp_is_land_approach;532533// should we fly inverted?534bool inverted_flight;535536// should we enable cross-tracking for the next waypoint?537bool next_wp_crosstrack;538539// should we use cross-tracking for this waypoint?540bool crosstrack;541542// in FBWA taildragger takeoff mode543bool fbwa_tdrag_takeoff_mode;544545// have we checked for an auto-land?546bool checked_for_autoland;547548// Altitude threshold to complete a takeoff command in autonomous modes. Centimeters549// are we in idle mode? used for balloon launch to stop servo550// movement until altitude is reached551bool idle_mode;552553// are we in VTOL mode in AUTO?554bool vtol_mode;555556// are we doing loiter mode as a VTOL?557bool vtol_loiter;558559// how much correction have we added for terrain data560float terrain_correction;561562// last home altitude for detecting changes563int32_t last_home_alt_cm;564} auto_state;565566#if AP_SCRIPTING_ENABLED567// support for scripting nav commands, with verify568struct {569bool enabled;570uint16_t id;571float roll_rate_dps;572float pitch_rate_dps;573float yaw_rate_dps;574float throttle_pct;575uint32_t start_ms;576uint32_t current_ms;577float rudder_offset_pct;578bool run_yaw_rate_controller;579} nav_scripting;580#endif581582struct {583// roll pitch yaw commanded from external controller in centidegrees584Vector3l forced_rpy_cd;585// last time we heard from the external controller586Vector3l last_forced_rpy_ms;587588// throttle commanded from external controller in percent589float forced_throttle;590uint32_t last_forced_throttle_ms;591592#if AP_PLANE_OFFBOARD_GUIDED_SLEW_ENABLED593// airspeed adjustments594float target_airspeed_cm = -1; // don't default to zero here, as zero is a valid speed.595float target_airspeed_accel;596uint32_t target_airspeed_time_ms;597598// altitude adjustments599Location target_location;600float target_alt_rate;601uint32_t target_alt_time_ms = 0;602uint8_t target_mav_frame = -1;603604// heading track605float target_heading = -4; // don't default to zero or -1 here, as both are valid headings in radians606float target_heading_accel_limit;607uint32_t target_heading_time_ms;608guided_heading_type_t target_heading_type;609bool target_heading_limit;610#endif // AP_PLANE_OFFBOARD_GUIDED_SLEW_ENABLED611} guided_state;612613#if AP_LANDINGGEAR_ENABLED614// landing gear state615struct {616AP_FixedWing::FlightStage last_flight_stage;617} gear;618#endif619620struct {621// on hard landings, only check once after directly a landing so you622// don't trigger a crash when picking up the aircraft623bool checkedHardLanding;624625// crash detection. True when we are crashed626bool is_crashed;627628// impact detection flag. Expires after a few seconds via impact_timer_ms629bool impact_detected;630631// debounce timer632uint32_t debounce_timer_ms;633634// delay time for debounce to count to635uint32_t debounce_time_total_ms;636637// length of time impact_detected has been true. Times out after a few seconds. Used to clip isFlyingProbability638uint32_t impact_timer_ms;639} crash_state;640641// this controls throttle suppression in auto modes642bool throttle_suppressed;643644#if AP_BATTERY_WATT_MAX_ENABLED645// reduce throttle to eliminate battery over-current646int8_t throttle_watt_limit_max;647int8_t throttle_watt_limit_min; // for reverse thrust648uint32_t throttle_watt_limit_timer_ms;649#endif650651AP_FixedWing::FlightStage flight_stage = AP_FixedWing::FlightStage::NORMAL;652653// probability of aircraft is currently in flight. range from 0 to654// 1 where 1 is 100% sure we're in flight655float isFlyingProbability;656657// previous value of is_flying()658bool previous_is_flying;659660// time since started flying in any mode in milliseconds661uint32_t started_flying_ms;662663// ground mode is true when disarmed and not flying664bool ground_mode;665666// Navigation control variables667// The instantaneous desired bank angle. Hundredths of a degree668int32_t nav_roll_cd;669670// The instantaneous desired pitch angle. Hundredths of a degree671int32_t nav_pitch_cd;672673// the aerodynamic load factor. This is calculated from the demanded674// roll before the roll is clipped, using 1/sqrt(cos(nav_roll))675float aerodynamic_load_factor = 1.0f;676677// a smoothed airspeed estimate, used for limiting roll angle678float smoothed_airspeed;679680// Mission library681AP_Mission mission{682FUNCTOR_BIND_MEMBER(&Plane::start_command_callback, bool, const AP_Mission::Mission_Command &),683FUNCTOR_BIND_MEMBER(&Plane::verify_command_callback, bool, const AP_Mission::Mission_Command &),684FUNCTOR_BIND_MEMBER(&Plane::exit_mission_callback, void)};685686687#if HAL_PARACHUTE_ENABLED688AP_Parachute parachute;689#endif690691// terrain handling692#if AP_TERRAIN_AVAILABLE693AP_Terrain terrain;694#endif695696AP_Landing landing{mission,ahrs,&TECS_controller,nav_controller,aparm,697FUNCTOR_BIND_MEMBER(&Plane::set_target_altitude_proportion, void, const Location&, float),698FUNCTOR_BIND_MEMBER(&Plane::constrain_target_altitude_location, void, const Location&, const Location&),699FUNCTOR_BIND_MEMBER(&Plane::adjusted_altitude_cm, int32_t),700FUNCTOR_BIND_MEMBER(&Plane::adjusted_relative_altitude_cm, int32_t),701FUNCTOR_BIND_MEMBER(&Plane::disarm_if_autoland_complete, void),702FUNCTOR_BIND_MEMBER(&Plane::update_flight_stage, void)};703#if HAL_ADSB_ENABLED704AP_ADSB adsb;705706// avoidance of adsb enabled vehicles (normally manned vehicles)707AP_Avoidance_Plane avoidance_adsb{adsb};708#endif709710// Outback Challenge Failsafe Support711#if AP_ADVANCEDFAILSAFE_ENABLED712AP_AdvancedFailsafe_Plane afs;713#endif714715/*716meta data to support counting the number of circles in a loiter717*/718struct {719// previous target bearing, used to update sum_cd720int32_t old_target_bearing_cd;721722// Total desired rotation in a loiter. Used for Loiter Turns commands.723int32_t total_cd;724725// total angle completed in the loiter so far726int32_t sum_cd;727728// Direction for loiter. 1 for clockwise, -1 for counter-clockwise729int8_t direction;730731// when loitering and an altitude is involved, this flag is true when it has been reached at least once732bool reached_target_alt;733734// check for scenarios where updrafts can keep you from loitering down indefinitely.735bool unable_to_acheive_target_alt;736737// start time of the loiter. Milliseconds.738uint32_t start_time_ms;739740// altitude at start of loiter loop lap. Used to detect delta alt of each lap.741// only valid when sum_cd > 36000742int32_t start_lap_alt_cm;743int32_t next_sum_lap_cd;744745// The amount of time we should stay in a loiter for the Loiter Time command. Milliseconds.746uint32_t time_max_ms;747748// current value of loiter radius in metres used by the controller749float radius;750} loiter;751752// Conditional command753// A value used in condition commands (eg delay, change alt, etc.)754// For example in a change altitude command, it is the altitude to change to.755int32_t condition_value;756757// A starting value used to check the status of a conditional command.758// For example in a delay command the condition_start records that start time for the delay759uint32_t condition_start;760// A value used in condition commands. For example the rate at which to change altitude.761int16_t condition_rate;762763// 3D Location vectors764// Location structure defined in AP_Common765const Location &home = ahrs.get_home();766767// The location of the previous waypoint. Used for track following and altitude ramp calculations768Location prev_WP_loc {};769770// The plane's current location771Location current_loc {};772773// The location of the current/active waypoint. Used for altitude ramp, track following and loiter calculations.774Location next_WP_loc {};775776// Altitude control777struct {778// target altitude above sea level in cm. Used for barometric779// altitude navigation780int32_t amsl_cm;781782// Altitude difference between previous and current waypoint in783// centimeters. Used for glide slope handling784int32_t offset_cm;785786#if AP_TERRAIN_AVAILABLE787// are we trying to follow terrain?788bool terrain_following;789790// are we waiting to load terrain data to init terrain following791bool terrain_following_pending;792793// target altitude above terrain in cm, valid if terrain_following794// is set795int32_t terrain_alt_cm;796797// lookahead value for height error reporting798float lookahead;799#endif800801// last input for FBWB/CRUISE height control802float last_elevator_input;803804// last time we checked for pilot control of height805uint32_t last_elev_check_us;806} target_altitude {};807808float relative_altitude;809810// loop performance monitoring:811AP::PerfInfo perf_info;812struct {813uint32_t last_trim_check;814uint32_t last_trim_save;815} auto_trim;816817struct {818bool done_climb;819} rtl;820821// last time home was updated while disarmed822uint32_t last_home_update_ms;823824// Camera/Antenna mount tracking and stabilisation stuff825#if HAL_MOUNT_ENABLED826AP_Mount camera_mount;827#endif828829// Arming/Disarming management class830AP_Arming_Plane arming;831832AP_Param param_loader {var_info};833834// external control library835#if AP_EXTERNAL_CONTROL_ENABLED836AP_ExternalControl_Plane external_control;837#endif838839static const AP_Scheduler::Task scheduler_tasks[];840static const AP_Param::Info var_info[];841842// time that rudder arming has been running843uint32_t rudder_arm_timer;844845// have we seen neutral rudder since arming with rudder?846bool seen_neutral_rudder;847848#if HAL_QUADPLANE_ENABLED849// support for quadcopter-plane850QuadPlane quadplane{ahrs};851#endif852853#if AP_TUNING_ENABLED854// support for transmitter tuning855AP_Tuning_Plane tuning;856#endif857858static const struct LogStructure log_structure[];859860// rudder mixing gain for differential thrust (0 - 1)861float rudder_dt;862863// soaring mode-change timer864uint32_t soaring_mode_timer_ms;865866// terrain disable for non AUTO modes, set with an RC Option switch867bool non_auto_terrain_disable;868bool terrain_disabled();869#if AP_TERRAIN_AVAILABLE870bool terrain_enabled_in_current_mode() const;871bool terrain_enabled_in_mode(Mode::Number num) const;872enum class terrain_bitmask {873ALL = 1U << 0,874FLY_BY_WIRE_B = 1U << 1,875CRUISE = 1U << 2,876AUTO = 1U << 3,877RTL = 1U << 4,878AVOID_ADSB = 1U << 5,879GUIDED = 1U << 6,880LOITER = 1U << 7,881CIRCLE = 1U << 8,882QRTL = 1U << 9,883QLAND = 1U << 10,884QLOITER = 1U << 11,885};886struct TerrainLookupTable{887Mode::Number mode_num;888terrain_bitmask bitmask;889};890static const TerrainLookupTable Terrain_lookup[];891#endif892893#if AP_QUICKTUNE_ENABLED894void update_quicktune(void);895#endif896897// Attitude.cpp898void adjust_nav_pitch_throttle(void);899void update_load_factor(void);900void adjust_altitude_target();901void setup_glide_slope(void);902int32_t get_RTL_altitude_cm() const;903float relative_ground_altitude(bool use_rangefinder_if_available);904float relative_ground_altitude(bool use_rangefinder_if_available, bool use_terrain_if_available);905void set_target_altitude_current(void);906void set_target_altitude_current_adjusted(void);907void set_target_altitude_location(const Location &loc);908int32_t relative_target_altitude_cm(void);909void change_target_altitude(int32_t change_cm);910void set_target_altitude_proportion(const Location &loc, float proportion);911void constrain_target_altitude_location(const Location &loc1, const Location &loc2);912int32_t calc_altitude_error_cm(void);913void check_fbwb_altitude(void);914void reset_offset_altitude(void);915void set_offset_altitude_location(const Location &start_loc, const Location &destination_loc);916bool above_location_current(const Location &loc);917void setup_terrain_target_alt(Location &loc);918int32_t adjusted_altitude_cm(void);919int32_t adjusted_relative_altitude_cm(void);920float mission_alt_offset(void);921float height_above_target(void);922float lookahead_adjustment(void);923#if AP_RANGEFINDER_ENABLED924float rangefinder_correction(void);925void rangefinder_height_update(void);926void rangefinder_terrain_correction(float &height);927#endif928void stabilize();929void calc_throttle();930void calc_nav_roll();931void calc_nav_pitch();932float calc_speed_scaler(void);933float get_speed_scaler(void) const { return surface_speed_scaler; }934bool stick_mixing_enabled(void);935void stabilize_roll();936float stabilize_roll_get_roll_out();937void stabilize_pitch();938float stabilize_pitch_get_pitch_out();939void stabilize_stick_mixing_fbw();940void stabilize_yaw();941int16_t calc_nav_yaw_coordinated();942int16_t calc_nav_yaw_course(void);943int16_t calc_nav_yaw_ground(void);944945#if HAL_LOGGING_ENABLED946947// methods for AP_Vehicle:948const AP_Int32 &get_log_bitmask() override { return g.log_bitmask; }949const struct LogStructure *get_log_structures() const override {950return log_structure;951}952uint8_t get_num_log_structures() const override;953954// Log.cpp955void Log_Write_FullRate(void);956void Log_Write_Attitude(void);957void Log_Write_Control_Tuning();958void Log_Write_OFG_Guided();959void Log_Write_Guided(void);960void Log_Write_Nav_Tuning();961void Log_Write_Status();962void Log_Write_RC(void);963void Log_Write_Vehicle_Startup_Messages();964void Log_Write_AETR();965#endif966967// Parameters.cpp968void load_parameters(void) override;969970// commands_logic.cpp971void set_next_WP(const Location &loc);972void do_RTL(int32_t alt);973bool verify_takeoff();974bool verify_loiter_unlim(const AP_Mission::Mission_Command &cmd);975bool verify_loiter_time();976bool verify_loiter_turns(const AP_Mission::Mission_Command &cmd);977bool verify_loiter_to_alt(const AP_Mission::Mission_Command &cmd);978bool verify_RTL();979bool verify_continue_and_change_alt();980bool verify_wait_delay();981bool verify_within_distance();982bool verify_altitude_wait(const AP_Mission::Mission_Command &cmd);983void do_loiter_at_location();984bool verify_loiter_heading(bool init);985void exit_mission_callback();986bool start_command(const AP_Mission::Mission_Command& cmd);987bool verify_command(const AP_Mission::Mission_Command& cmd);988void do_takeoff(const AP_Mission::Mission_Command& cmd);989void do_nav_wp(const AP_Mission::Mission_Command& cmd);990void do_land(const AP_Mission::Mission_Command& cmd);991#if HAL_QUADPLANE_ENABLED992void do_landing_vtol_approach(const AP_Mission::Mission_Command& cmd);993#endif994void loiter_set_direction_wp(const AP_Mission::Mission_Command& cmd);995void do_loiter_unlimited(const AP_Mission::Mission_Command& cmd);996void do_loiter_turns(const AP_Mission::Mission_Command& cmd);997void do_loiter_time(const AP_Mission::Mission_Command& cmd);998void do_continue_and_change_alt(const AP_Mission::Mission_Command& cmd);999void do_altitude_wait(const AP_Mission::Mission_Command& cmd);1000void do_loiter_to_alt(const AP_Mission::Mission_Command& cmd);1001void do_vtol_takeoff(const AP_Mission::Mission_Command& cmd);1002void do_vtol_land(const AP_Mission::Mission_Command& cmd);1003bool verify_nav_wp(const AP_Mission::Mission_Command& cmd);1004#if HAL_QUADPLANE_ENABLED1005bool verify_landing_vtol_approach(const AP_Mission::Mission_Command& cmd);1006#endif1007void do_wait_delay(const AP_Mission::Mission_Command& cmd);1008void do_within_distance(const AP_Mission::Mission_Command& cmd);1009bool do_change_speed(const AP_Mission::Mission_Command& cmd);1010void do_set_home(const AP_Mission::Mission_Command& cmd);1011bool start_command_callback(const AP_Mission::Mission_Command &cmd);1012bool verify_command_callback(const AP_Mission::Mission_Command& cmd);1013float get_wp_radius() const;10141015bool is_land_command(uint16_t cmd) const;10161017bool do_change_speed(uint8_t speedtype, float speed_target_ms, float rhtottle_pct);1018/*1019return true if in a specific AUTO mission command1020*/1021bool in_auto_mission_id(uint16_t command) const;10221023#if AP_SCRIPTING_ENABLED1024// nav scripting support1025void do_nav_script_time(const AP_Mission::Mission_Command& cmd);1026bool verify_nav_script_time(const AP_Mission::Mission_Command& cmd);1027#endif10281029// commands.cpp1030void set_guided_WP(const Location &loc);10311032// update home position. Return true if update done1033bool update_home();10341035// update current_loc1036void update_current_loc(void);10371038// set home location and store it persistently:1039bool set_home_persistently(const Location &loc) WARN_IF_UNUSED;1040bool set_home_to_current_location(bool lock) override WARN_IF_UNUSED;1041bool set_home(const Location& loc, bool lock) override WARN_IF_UNUSED;10421043// control_modes.cpp1044void read_control_switch();1045uint8_t readSwitch(void) const;1046void autotune_start(void);1047void autotune_restore(void);1048void autotune_enable(bool enable);1049bool fly_inverted(void);1050bool mode_allows_autotuning(void);1051uint8_t get_mode() const override { return (uint8_t)control_mode->mode_number(); }1052Mode *mode_from_mode_num(const enum Mode::Number num);1053bool current_mode_requires_mission() const override {1054return control_mode == &mode_auto;1055}10561057bool autotuning;10581059// events.cpp1060void failsafe_short_on_event(enum failsafe_state fstype, ModeReason reason);1061void failsafe_long_on_event(enum failsafe_state fstype, ModeReason reason);1062void failsafe_short_off_event(ModeReason reason);1063void failsafe_long_off_event(ModeReason reason);1064void handle_battery_failsafe(const char* type_str, const int8_t action);1065bool failsafe_in_landing_sequence() const; // returns true if the vehicle is in landing sequence. Intended only for use in failsafe code.10661067#if AP_FENCE_ENABLED1068// fence.cpp1069void fence_check();1070bool fence_stickmixing() const;1071bool in_fence_recovery() const;1072#endif10731074// Plane.cpp1075void disarm_if_autoland_complete();1076bool trigger_land_abort(const float climb_to_alt_m);1077void get_osd_roll_pitch_rad(float &roll, float &pitch) const override;1078float tecs_hgt_afe(void);1079void efi_update(void);1080void get_scheduler_tasks(const AP_Scheduler::Task *&tasks,1081uint8_t &task_count,1082uint32_t &log_bit) override;1083void ahrs_update();1084void update_speed_height(void);1085void update_GPS_50Hz(void);1086void update_GPS_10Hz(void);1087void update_compass(void);1088void update_alt(void);1089#if AP_ADVANCEDFAILSAFE_ENABLED1090void afs_fs_check(void);1091#endif1092void one_second_loop(void);1093void three_hz_loop(void);1094#if AP_AIRSPEED_AUTOCAL_ENABLE1095void airspeed_ratio_update(void);1096#endif1097void compass_save(void);1098void update_logging10(void);1099void update_logging25(void);1100void update_control_mode(void);1101void update_fly_forward(void);1102void update_flight_stage();1103void set_flight_stage(AP_FixedWing::FlightStage fs);1104bool flight_option_enabled(FlightOptions flight_option) const;11051106// navigation.cpp1107void loiter_angle_reset(void);1108void loiter_angle_update(void);1109void navigate();1110void check_home_alt_change(void);1111void calc_airspeed_errors();1112float mode_auto_target_airspeed_cm();1113void calc_gndspeed_undershoot();1114void update_loiter(uint16_t radius);1115void update_loiter_update_nav(uint16_t radius);1116void update_cruise();1117void update_fbwb_speed_height(void);1118void setup_turn_angle(void);1119bool reached_loiter_target(void);11201121// radio.cpp1122void set_control_channels(void) override;1123void init_rc_in();1124void init_rc_out_main();1125void init_rc_out_aux();1126void rudder_arm_disarm_check();1127void read_radio();1128int16_t rudder_input(void);1129void control_failsafe();1130void trim_radio();1131bool rc_throttle_value_ok(void) const;1132bool rc_failsafe_active(void) const;11331134#if AP_RANGEFINDER_ENABLED1135// sensors.cpp1136void read_rangefinder(void);1137#endif11381139// system.cpp1140void init_ardupilot() override;1141bool set_mode(Mode& new_mode, const ModeReason reason);1142bool set_mode(const uint8_t mode, const ModeReason reason) override;1143bool set_mode_by_number(const Mode::Number new_mode_number, const ModeReason reason);1144void check_long_failsafe();1145void check_short_failsafe();1146void startup_INS(void);1147bool should_log(uint32_t mask);1148int8_t throttle_percentage(void);1149void notify_mode(const Mode& mode);1150bool gcs_mode_enabled(const Mode::Number mode_num) const;11511152// takeoff.cpp1153bool auto_takeoff_check(void);1154void takeoff_calc_roll(void);1155void takeoff_calc_pitch(void);1156void takeoff_calc_throttle();1157int8_t takeoff_tail_hold(void);1158int16_t get_takeoff_pitch_min_cd(void);1159void landing_gear_update(void);1160bool check_takeoff_timeout(void);1161bool check_takeoff_timeout_level_off(void);11621163// avoidance_adsb.cpp1164void avoidance_adsb_update(void);11651166// servos.cpp1167void set_servos();1168float apply_throttle_limits(float throttle_in);1169void set_throttle(void);1170void set_takeoff_expected(void);1171void set_servos_old_elevons(void);1172void set_servos_flaps(void);1173void set_landing_gear(void);1174void dspoiler_update(void);1175void airbrake_update(void);1176void landing_neutral_control_surface_servos(void);1177void servos_output(void);1178void servos_auto_trim(void);1179void servos_twin_engine_mix();1180void force_flare();1181void throttle_watt_limiter(int8_t &min_throttle, int8_t &max_throttle);1182void throttle_slew_limit();1183bool suppress_throttle(void);1184void update_throttle_hover();1185void channel_function_mixer(SRV_Channel::Aux_servo_function_t func1_in, SRV_Channel::Aux_servo_function_t func2_in,1186SRV_Channel::Aux_servo_function_t func1_out, SRV_Channel::Aux_servo_function_t func2_out) const;1187void flaperon_update();1188void indicate_waiting_for_rud_neutral_to_takeoff(void);11891190// is_flying.cpp1191void update_is_flying_5Hz(void);1192void crash_detection_update(void);1193bool in_preLaunch_flight_stage(void);1194bool is_flying(void);11951196// parachute.cpp1197void parachute_check();1198#if HAL_PARACHUTE_ENABLED1199void do_parachute(const AP_Mission::Mission_Command& cmd);1200void parachute_release();1201bool parachute_manual_release();1202#endif12031204// soaring.cpp1205#if HAL_SOARING_ENABLED1206void update_soaring();1207#endif12081209// RC_Channel.cpp1210bool emergency_landing;12111212// vehicle specific waypoint info helpers1213bool get_wp_distance_m(float &distance) const override;1214bool get_wp_bearing_deg(float &bearing) const override;1215bool get_wp_crosstrack_error_m(float &xtrack_error) const override;12161217// reverse_thrust.cpp1218bool reversed_throttle;1219bool have_reverse_throttle_rc_option;1220bool allow_reverse_thrust(void) const;1221bool have_reverse_thrust(void) const;1222float get_throttle_input(bool no_deadzone=false) const;1223float get_adjusted_throttle_input(bool no_deadzone=false) const;12241225#if AP_SCRIPTING_ENABLED1226// support for NAV_SCRIPT_TIME mission command1227bool nav_scripting_active(void);1228bool nav_script_time(uint16_t &id, uint8_t &cmd, float &arg1, float &arg2, int16_t &arg3, int16_t &arg4) override;1229void nav_script_time_done(uint16_t id) override;12301231// command throttle percentage and roll, pitch, yaw target1232// rates. For use with scripting controllers1233void set_target_throttle_rate_rpy(float throttle_pct, float roll_rate_dps, float pitch_rate_dps, float yaw_rate_dps) override;1234void set_rudder_offset(float rudder_pct, bool run_yaw_rate_controller) override;1235bool nav_scripting_enable(uint8_t mode) override;1236#endif12371238enum Failsafe_Action {1239Failsafe_Action_None = 0,1240Failsafe_Action_RTL = 1,1241Failsafe_Action_Land = 2,1242Failsafe_Action_Terminate = 3,1243#if HAL_QUADPLANE_ENABLED1244Failsafe_Action_QLand = 4,1245#endif1246Failsafe_Action_Parachute = 5,1247#if HAL_QUADPLANE_ENABLED1248Failsafe_Action_Loiter_alt_QLand = 6,1249#endif1250};12511252// list of priorities, highest priority first1253static constexpr int8_t _failsafe_priorities[] = {1254Failsafe_Action_Terminate,1255Failsafe_Action_Parachute,1256#if HAL_QUADPLANE_ENABLED1257Failsafe_Action_QLand,1258#endif1259Failsafe_Action_Land,1260Failsafe_Action_RTL,1261Failsafe_Action_None,1262-1 // the priority list must end with a sentinel of -11263};1264static_assert(_failsafe_priorities[ARRAY_SIZE(_failsafe_priorities) - 1] == -1,1265"_failsafe_priorities is missing the sentinel");12661267// EKF checks for loss of navigation performed in ekf_check.cpp1268// These are specific to VTOL operation1269void ekf_check();1270bool ekf_over_threshold();1271void failsafe_ekf_event();1272void failsafe_ekf_off_event(void);12731274enum class CrowMode {1275NORMAL,1276PROGRESSIVE,1277CROW_DISABLED,1278};12791280enum class ThrFailsafe {1281Disabled = 0,1282Enabled = 1,1283EnabledNoFS = 21284};12851286CrowMode crow_mode = CrowMode::NORMAL;12871288enum class FlareMode {1289FLARE_DISABLED = 0,1290ENABLED_NO_PITCH_TARGET,1291ENABLED_PITCH_TARGET1292};12931294enum class AutoTuneAxis {1295ROLL = 1U <<0,1296PITCH = 1U <<1,1297YAW = 1U <<2,1298};12991300FlareMode flare_mode;1301bool throttle_at_zero(void) const;13021303// expo handling1304float roll_in_expo(bool use_dz) const;1305float pitch_in_expo(bool use_dz) const;1306float rudder_in_expo(bool use_dz) const;13071308// mode reason for entering previous mode1309ModeReason previous_mode_reason = ModeReason::UNKNOWN;13101311// last target alt we passed to tecs1312int32_t tecs_target_alt_cm;13131314public:1315void failsafe_check(void);1316bool is_landing() const override;1317bool is_taking_off() const override;1318#if AP_SCRIPTING_ENABLED || AP_EXTERNAL_CONTROL_ENABLED1319bool set_target_location(const Location& target_loc) override;1320#endif //AP_SCRIPTING_ENABLED || AP_EXTERNAL_CONTROL_ENABLED1321#if AP_SCRIPTING_ENABLED1322bool get_target_location(Location& target_loc) override;1323bool update_target_location(const Location &old_loc, const Location &new_loc) override;1324bool set_velocity_match(const Vector2f &velocity) override;13251326// allow for landing descent rate to be overridden by a script, may be -ve to climb1327bool set_land_descent_rate(float descent_rate) override;13281329// allow scripts to override mission/guided crosstrack behaviour1330// It's up to the Lua script to ensure the provided location makes sense1331bool set_crosstrack_start(const Location &new_start_location) override;13321333#endif // AP_SCRIPTING_ENABLED13341335};13361337extern Plane plane;13381339using AP_HAL::millis;1340using AP_HAL::micros;134113421343