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/Copter.h
Views: 1798
/*1This program is free software: you can redistribute it and/or modify2it under the terms of the GNU General Public License as published by3the Free Software Foundation, either version 3 of the License, or4(at your option) any later version.56This program is distributed in the hope that it will be useful,7but WITHOUT ANY WARRANTY; without even the implied warranty of8MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9GNU General Public License for more details.1011You should have received a copy of the GNU General Public License12along with this program. If not, see <http://www.gnu.org/licenses/>.13*/14#pragma once15/*16This is the main Copter class17*/1819////////////////////////////////////////////////////////////////////////////////20// Header includes21////////////////////////////////////////////////////////////////////////////////2223#include <cmath>24#include <stdio.h>25#include <stdarg.h>2627#include <AP_HAL/AP_HAL.h>2829// Common dependencies30#include <AP_Common/AP_Common.h> // Common definitions and utility routines for the ArduPilot libraries31#include <AP_Common/Location.h> // Library having the implementation of location class32#include <AP_Param/AP_Param.h> // A system for managing and storing variables that are of general interest to the system.33#include <StorageManager/StorageManager.h> // library for Management for hal.storage to allow for backwards compatible mapping of storage offsets to available storage3435// Application dependencies36#include <AP_Logger/AP_Logger.h> // ArduPilot Mega Flash Memory Library37#include <AP_Math/AP_Math.h> // ArduPilot Mega Vector/Matrix math Library38#include <AP_AccelCal/AP_AccelCal.h> // interface and maths for accelerometer calibration39#include <AP_InertialSensor/AP_InertialSensor.h> // ArduPilot Mega Inertial Sensor (accel & gyro) Library40#include <AP_AHRS/AP_AHRS.h> // AHRS (Attitude Heading Reference System) interface library for ArduPilot41#include <AP_Mission/AP_Mission.h> // Mission command library42#include <AP_Mission/AP_Mission_ChangeDetector.h> // Mission command change detection library43#include <AC_AttitudeControl/AC_AttitudeControl_Multi.h> // Attitude control library44#include <AC_AttitudeControl/AC_AttitudeControl_Multi_6DoF.h> // 6DoF Attitude control library45#include <AC_AttitudeControl/AC_AttitudeControl_Heli.h> // Attitude control library for traditional helicopter46#include <AC_AttitudeControl/AC_PosControl.h> // Position control library47#include <AC_AttitudeControl/AC_CommandModel.h> // Command model library48#include <AP_Motors/AP_Motors.h> // AP Motors library49#include <Filter/Filter.h> // Filter library50#include <AP_Vehicle/AP_Vehicle.h> // needed for AHRS build51#include <AP_InertialNav/AP_InertialNav.h> // inertial navigation library52#include <AC_WPNav/AC_WPNav.h> // ArduCopter waypoint navigation library53#include <AC_WPNav/AC_Loiter.h> // ArduCopter Loiter Mode Library54#include <AC_WPNav/AC_Circle.h> // circle navigation library55#include <AP_Declination/AP_Declination.h> // ArduPilot Mega Declination Helper Library56#include <AP_RCMapper/AP_RCMapper.h> // RC input mapping library57#include <AP_BattMonitor/AP_BattMonitor.h> // Battery monitor library58#include <AP_LandingGear/AP_LandingGear.h> // Landing Gear library59#include <AC_InputManager/AC_InputManager.h> // Pilot input handling library60#include <AC_InputManager/AC_InputManager_Heli.h> // Heli specific pilot input handling library61#include <AP_Arming/AP_Arming.h> // ArduPilot motor arming library62#include <AP_SmartRTL/AP_SmartRTL.h> // ArduPilot Smart Return To Launch Mode (SRTL) library63#include <AP_TempCalibration/AP_TempCalibration.h> // temperature calibration library64#include <AC_AutoTune/AC_AutoTune_Multi.h> // ArduCopter autotune library. support for autotune of multirotors.65#include <AC_AutoTune/AC_AutoTune_Heli.h> // ArduCopter autotune library. support for autotune of helicopters.66#include <AP_Parachute/AP_Parachute.h> // ArduPilot parachute release library67#include <AC_Sprayer/AC_Sprayer.h> // Crop sprayer library68#include <AP_ADSB/AP_ADSB.h> // ADS-B RF based collision avoidance module library69#include <AP_Proximity/AP_Proximity.h> // ArduPilot proximity sensor library70#include <AC_PrecLand/AC_PrecLand_config.h>71#include <AP_OpticalFlow/AP_OpticalFlow.h>72#include <AP_Winch/AP_Winch_config.h>73#include <AP_SurfaceDistance/AP_SurfaceDistance.h>7475// Configuration76#include "defines.h"77#include "config.h"7879#if FRAME_CONFIG == HELI_FRAME80#define MOTOR_CLASS AP_MotorsHeli81#else82#define MOTOR_CLASS AP_MotorsMulticopter83#endif8485#if MODE_AUTOROTATE_ENABLED86#include <AC_Autorotation/AC_Autorotation.h> // Autorotation controllers87#endif8889#include "RC_Channel_Copter.h" // RC Channel Library9091#include "GCS_MAVLink_Copter.h"92#include "GCS_Copter.h"93#include "AP_Rally.h" // Rally point library94#include "AP_Arming.h"9596#include <AP_ExternalControl/AP_ExternalControl_config.h>97#if AP_EXTERNAL_CONTROL_ENABLED98#include "AP_ExternalControl_Copter.h"99#endif100101#include <AP_Beacon/AP_Beacon_config.h>102#if AP_BEACON_ENABLED103#include <AP_Beacon/AP_Beacon.h>104#endif105106#if AP_AVOIDANCE_ENABLED107#include <AC_Avoidance/AC_Avoid.h>108#endif109#if AP_OAPATHPLANNER_ENABLED110#include <AC_WPNav/AC_WPNav_OA.h>111#include <AC_Avoidance/AP_OAPathPlanner.h>112#endif113#if AC_PRECLAND_ENABLED114# include <AC_PrecLand/AC_PrecLand.h>115# include <AC_PrecLand/AC_PrecLand_StateMachine.h>116#endif117#if MODE_FOLLOW_ENABLED118# include <AP_Follow/AP_Follow.h>119#endif120#if AP_TERRAIN_AVAILABLE121# include <AP_Terrain/AP_Terrain.h>122#endif123#if AP_RANGEFINDER_ENABLED124# include <AP_RangeFinder/AP_RangeFinder.h>125#endif126127#include <AP_Mount/AP_Mount.h>128129#include <AP_Camera/AP_Camera.h>130131#if HAL_BUTTON_ENABLED132# include <AP_Button/AP_Button.h>133#endif134135#if OSD_ENABLED || OSD_PARAM_ENABLED136#include <AP_OSD/AP_OSD.h>137#endif138139#if AP_COPTER_ADVANCED_FAILSAFE_ENABLED140# include "afs_copter.h"141#endif142#if TOY_MODE_ENABLED143# include "toy_mode.h"144#endif145#if AP_WINCH_ENABLED146# include <AP_Winch/AP_Winch.h>147#endif148#include <AP_RPM/AP_RPM.h>149150#if AP_SCRIPTING_ENABLED151#include <AP_Scripting/AP_Scripting.h>152#endif153154#if AC_CUSTOMCONTROL_MULTI_ENABLED155#include <AC_CustomControl/AC_CustomControl.h> // Custom control library156#endif157158#if AP_AVOIDANCE_ENABLED && !AP_FENCE_ENABLED159#error AC_Avoidance relies on AP_FENCE_ENABLED which is disabled160#endif161162#if AP_OAPATHPLANNER_ENABLED && !AP_FENCE_ENABLED163#error AP_OAPathPlanner relies on AP_FENCE_ENABLED which is disabled164#endif165166#if HAL_ADSB_ENABLED167#include "avoidance_adsb.h"168#endif169// Local modules170#include "Parameters.h"171#if USER_PARAMS_ENABLED172#include "UserParameters.h"173#endif174#include "mode.h"175176class Copter : public AP_Vehicle {177public:178friend class GCS_MAVLINK_Copter;179friend class GCS_Copter;180friend class AP_Rally_Copter;181friend class Parameters;182friend class ParametersG2;183friend class AP_Avoidance_Copter;184185#if AP_COPTER_ADVANCED_FAILSAFE_ENABLED186friend class AP_AdvancedFailsafe_Copter;187#endif188friend class AP_Arming_Copter;189#if AP_EXTERNAL_CONTROL_ENABLED190friend class AP_ExternalControl_Copter;191#endif192friend class ToyMode;193friend class RC_Channel_Copter;194friend class RC_Channels_Copter;195196friend class AutoTune;197198friend class Mode;199friend class ModeAcro;200friend class ModeAcro_Heli;201friend class ModeAltHold;202friend class ModeAuto;203friend class ModeAutoTune;204friend class ModeAvoidADSB;205friend class ModeBrake;206friend class ModeCircle;207friend class ModeDrift;208friend class ModeFlip;209friend class ModeFlowHold;210friend class ModeFollow;211friend class ModeGuided;212friend class ModeLand;213friend class ModeLoiter;214friend class ModePosHold;215friend class ModeRTL;216friend class ModeSmartRTL;217friend class ModeSport;218friend class ModeStabilize;219friend class ModeStabilize_Heli;220friend class ModeSystemId;221friend class ModeThrow;222friend class ModeZigZag;223friend class ModeAutorotate;224friend class ModeTurtle;225226friend class _AutoTakeoff;227228friend class PayloadPlace;229230Copter(void);231232private:233234// key aircraft parameters passed to multiple libraries235AP_MultiCopter aparm;236237// Global parameters are all contained within the 'g' class.238Parameters g;239ParametersG2 g2;240241// used to detect MAVLink acks from GCS to stop compassmot242uint8_t command_ack_counter;243244// primary input control channels245RC_Channel *channel_roll;246RC_Channel *channel_pitch;247RC_Channel *channel_throttle;248RC_Channel *channel_yaw;249250// flight modes convenience array251AP_Int8 *flight_modes;252const uint8_t num_flight_modes = 6;253254AP_SurfaceDistance rangefinder_state {ROTATION_PITCH_270, inertial_nav, 0U};255AP_SurfaceDistance rangefinder_up_state {ROTATION_PITCH_90, inertial_nav, 1U};256257// helper function to get inertially interpolated rangefinder height.258bool get_rangefinder_height_interpolated_cm(int32_t& ret) const;259260#if AP_RANGEFINDER_ENABLED261class SurfaceTracking {262public:263264// update_surface_offset - manages the vertical offset of the position controller to follow the265// measured ground or ceiling level measured using the range finder.266void update_surface_offset();267268// target has already been set by terrain following so do not initalise again269// this should be called by flight modes when switching from terrain following to surface tracking (e.g. ZigZag)270void external_init();271272// get target and actual distances (in m) for logging purposes273bool get_target_dist_for_logging(float &target_dist) const;274float get_dist_for_logging() const;275void invalidate_for_logging() { valid_for_logging = false; }276277// surface tracking surface278enum class Surface {279NONE = 0,280GROUND = 1,281CEILING = 2282};283// set surface to track284void set_surface(Surface new_surface);285// initialise surface tracking286void init(Surface surf) { surface = surf; }287288private:289Surface surface;290uint32_t last_update_ms; // system time of last update to target_alt_cm291uint32_t last_glitch_cleared_ms; // system time of last handle glitch recovery292bool valid_for_logging; // true if we have a desired target altitude293bool reset_target; // true if target should be reset because of change in surface being tracked294} surface_tracking;295#endif296297#if AP_RPM_ENABLED298AP_RPM rpm_sensor;299#endif300301// Inertial Navigation EKF - different viewpoint302AP_AHRS_View *ahrs_view;303304// Arming/Disarming management class305AP_Arming_Copter arming;306307// Optical flow sensor308#if AP_OPTICALFLOW_ENABLED309AP_OpticalFlow optflow;310#endif311312// external control library313#if AP_EXTERNAL_CONTROL_ENABLED314AP_ExternalControl_Copter external_control;315#endif316317318// system time in milliseconds of last recorded yaw reset from ekf319uint32_t ekfYawReset_ms;320int8_t ekf_primary_core;321322// vibration check323struct {324bool high_vibes; // true while high vibration are detected325uint32_t start_ms; // system time high vibration were last detected326uint32_t clear_ms; // system time high vibrations stopped327} vibration_check;328329// EKF variances are unfiltered and are designed to recover very quickly when possible330// thus failsafes should be triggered on filtered values in order to avoid transient errors331LowPassFilterFloat pos_variance_filt;332LowPassFilterFloat vel_variance_filt;333LowPassFilterFloat hgt_variance_filt;334bool variances_valid;335uint32_t last_ekf_check_us;336337// takeoff check338uint32_t takeoff_check_warning_ms; // system time user was last warned of takeoff check failure339340// GCS selection341GCS_Copter _gcs; // avoid using this; use gcs()342GCS_Copter &gcs() { return _gcs; }343344// User variables345#ifdef USERHOOK_VARIABLES346# include USERHOOK_VARIABLES347#endif348349// ap_value calculates a 32-bit bitmask representing various pieces of350// state about the Copter. It replaces a global variable which was351// used to track this state.352uint32_t ap_value() const;353354// These variables are essentially global variables. These should355// be removed over time. It is critical that the offsets of these356// variables remain unchanged - the logging is dependent on this357// ordering!358struct PACKED {359bool unused1; // 0360bool unused_was_simple_mode_byte1; // 1361bool unused_was_simple_mode_byte2; // 2362bool pre_arm_rc_check; // 3 true if rc input pre-arm checks have been completed successfully363bool pre_arm_check; // 4 true if all pre-arm checks (rc, accel calibration, gps lock) have been performed364bool auto_armed; // 5 stops auto missions from beginning until throttle is raised365bool unused_log_started; // 6366bool land_complete; // 7 true if we have detected a landing367bool new_radio_frame; // 8 Set true if we have new PWM data to act on from the Radio368bool unused_usb_connected; // 9369bool unused_receiver_present; // 10370bool compass_mot; // 11 true if we are currently performing compassmot calibration371bool motor_test; // 12 true if we are currently performing the motors test372bool initialised; // 13 true once the init_ardupilot function has completed. Extended status to GCS is not sent until this completes373bool land_complete_maybe; // 14 true if we may have landed (less strict version of land_complete)374bool throttle_zero; // 15 true if the throttle stick is at zero, debounced, determines if pilot intends shut-down when not using motor interlock375bool system_time_set_unused; // 16 true if the system time has been set from the GPS376bool gps_glitching; // 17 true if GPS glitching is affecting navigation accuracy377bool using_interlock; // 18 aux switch motor interlock function is in use378bool land_repo_active; // 19 true if the pilot is overriding the landing position379bool motor_interlock_switch; // 20 true if pilot is requesting motor interlock enable380bool in_arming_delay; // 21 true while we are armed but waiting to spin motors381bool initialised_params; // 22 true when the all parameters have been initialised. we cannot send parameters to the GCS until this is done382bool unused_compass_init_location; // 23383bool unused2_aux_switch_rc_override_allowed; // 24384bool armed_with_airmode_switch; // 25 we armed using a arming switch385bool prec_land_active; // 26 true if precland is active386} ap;387388AirMode air_mode; // air mode is 0 = not-configured ; 1 = disabled; 2 = enabled;389bool force_flying; // force flying is enabled when true;390391// This is the state of the flight control system392// There are multiple states defined such as STABILIZE, ACRO,393Mode *flightmode;394395RCMapper rcmap;396397// inertial nav alt when we armed398float arming_altitude_m;399400// Failsafe401struct {402uint32_t terrain_first_failure_ms; // the first time terrain data access failed - used to calculate the duration of the failure403uint32_t terrain_last_failure_ms; // the most recent time terrain data access failed404405int8_t radio_counter; // number of iterations with throttle below throttle_fs_value406407uint8_t radio : 1; // A status flag for the radio failsafe408uint8_t gcs : 1; // A status flag for the ground station failsafe409uint8_t ekf : 1; // true if ekf failsafe has occurred410uint8_t terrain : 1; // true if the missing terrain data failsafe has occurred411uint8_t adsb : 1; // true if an adsb related failsafe has occurred412uint8_t deadreckon : 1; // true if a dead reckoning failsafe has triggered413} failsafe;414415bool any_failsafe_triggered() const {416return failsafe.radio || battery.has_failsafed() || failsafe.gcs || failsafe.ekf || failsafe.terrain || failsafe.adsb || failsafe.deadreckon;417}418419// dead reckoning state420struct {421bool active; // true if dead reckoning (position estimate using estimated airspeed, no position or velocity source)422bool timeout; // true if dead reckoning has timedout and EKF's position and velocity estimate should no longer be trusted423uint32_t start_ms; // system time that EKF began deadreckoning424} dead_reckoning;425426// Motor Output427MOTOR_CLASS *motors;428const struct AP_Param::GroupInfo *motors_var_info;429430int32_t _home_bearing;431uint32_t _home_distance;432433// SIMPLE Mode434// Used to track the orientation of the vehicle for Simple mode. This value is reset at each arming435// or in SuperSimple mode when the vehicle leaves a 20m radius from home.436enum class SimpleMode {437NONE = 0,438SIMPLE = 1,439SUPERSIMPLE = 2,440} simple_mode;441442float simple_cos_yaw;443float simple_sin_yaw;444int32_t super_simple_last_bearing;445float super_simple_cos_yaw;446float super_simple_sin_yaw;447448// Stores initial bearing when armed - initial simple bearing is modified in super simple mode so not suitable449int32_t initial_armed_bearing;450451// Battery Sensors452AP_BattMonitor battery{MASK_LOG_CURRENT,453FUNCTOR_BIND_MEMBER(&Copter::handle_battery_failsafe, void, const char*, const int8_t),454_failsafe_priorities};455456#if OSD_ENABLED || OSD_PARAM_ENABLED457AP_OSD osd;458#endif459460// Altitude461int32_t baro_alt; // barometer altitude in cm above home462LowPassFilterVector3f land_accel_ef_filter; // accelerations for land and crash detector tests463464// filtered pilot's throttle input used to cancel landing if throttle held high465LowPassFilterFloat rc_throttle_control_in_filter;466467// 3D Location vectors468// Current location of the vehicle (altitude is relative to home)469Location current_loc;470471// Inertial Navigation472AP_InertialNav inertial_nav;473474// Attitude, Position and Waypoint navigation objects475// To-Do: move inertial nav up or other navigation variables down here476AC_AttitudeControl *attitude_control;477const struct AP_Param::GroupInfo *attitude_control_var_info;478AC_PosControl *pos_control;479AC_WPNav *wp_nav;480AC_Loiter *loiter_nav;481482#if AC_CUSTOMCONTROL_MULTI_ENABLED483AC_CustomControl custom_control{ahrs_view, attitude_control, motors, scheduler.get_loop_period_s()};484#endif485486#if MODE_CIRCLE_ENABLED487AC_Circle *circle_nav;488#endif489490// System Timers491// --------------492// arm_time_ms - Records when vehicle was armed. Will be Zero if we are disarmed.493uint32_t arm_time_ms;494495// Used to exit the roll and pitch auto trim function496uint8_t auto_trim_counter;497bool auto_trim_started = false;498499// Camera500#if AP_CAMERA_ENABLED501AP_Camera camera{MASK_LOG_CAMERA};502#endif503504// Camera/Antenna mount tracking and stabilisation stuff505#if HAL_MOUNT_ENABLED506AP_Mount camera_mount;507#endif508509#if AP_AVOIDANCE_ENABLED510AC_Avoid avoid;511#endif512513// Rally library514#if HAL_RALLY_ENABLED515AP_Rally_Copter rally;516#endif517518// Crop Sprayer519#if HAL_SPRAYER_ENABLED520AC_Sprayer sprayer;521#endif522523// Parachute release524#if HAL_PARACHUTE_ENABLED525AP_Parachute parachute;526#endif527528// Landing Gear Controller529#if AP_LANDINGGEAR_ENABLED530AP_LandingGear landinggear;531#endif532533// terrain handling534#if AP_TERRAIN_AVAILABLE535AP_Terrain terrain;536#endif537538// Precision Landing539#if AC_PRECLAND_ENABLED540AC_PrecLand precland;541AC_PrecLand_StateMachine precland_statemachine;542#endif543544// Pilot Input Management Library545// Only used for Helicopter for now546#if FRAME_CONFIG == HELI_FRAME547AC_InputManager_Heli input_manager;548#endif549550#if HAL_ADSB_ENABLED551AP_ADSB adsb;552553// avoidance of adsb enabled vehicles (normally manned vehicles)554AP_Avoidance_Copter avoidance_adsb{adsb};555#endif556557// last valid RC input time558uint32_t last_radio_update_ms;559560// last esc calibration notification update561uint32_t esc_calibration_notify_update_ms;562563// Top-level logic564// setup the var_info table565AP_Param param_loader;566567#if FRAME_CONFIG == HELI_FRAME568// Mode filter to reject RC Input glitches. Filter size is 5, and it draws the 4th element, so it can reject 3 low glitches,569// and 1 high glitch. This is because any "off" glitches can be highly problematic for a helicopter running an ESC570// governor. Even a single "off" frame can cause the rotor to slow dramatically and take a long time to restart.571ModeFilterInt16_Size5 rotor_speed_deglitch_filter {4};572573// Tradheli flags574typedef struct {575uint8_t dynamic_flight : 1; // 0 // true if we are moving at a significant speed (used to turn on/off leaky I terms)576bool coll_stk_low ; // 1 // true when collective stick is on lower limit577} heli_flags_t;578heli_flags_t heli_flags;579580int16_t hover_roll_trim_scalar_slew;581#endif582583// ground effect detector584struct {585bool takeoff_expected;586bool touchdown_expected;587uint32_t takeoff_time_ms;588float takeoff_alt_cm;589} gndeffect_state;590591bool standby_active;592593static const AP_Scheduler::Task scheduler_tasks[];594static const AP_Param::Info var_info[];595static const struct LogStructure log_structure[];596597// enum for ESC CALIBRATION598enum ESCCalibrationModes : uint8_t {599ESCCAL_NONE = 0,600ESCCAL_PASSTHROUGH_IF_THROTTLE_HIGH = 1,601ESCCAL_PASSTHROUGH_ALWAYS = 2,602ESCCAL_AUTO = 3,603ESCCAL_DISABLED = 9,604};605606enum class FailsafeAction : uint8_t {607NONE = 0,608LAND = 1,609RTL = 2,610SMARTRTL = 3,611SMARTRTL_LAND = 4,612TERMINATE = 5,613AUTO_DO_LAND_START = 6,614BRAKE_LAND = 7615};616617enum class FailsafeOption {618RC_CONTINUE_IF_AUTO = (1<<0), // 1619GCS_CONTINUE_IF_AUTO = (1<<1), // 2620RC_CONTINUE_IF_GUIDED = (1<<2), // 4621CONTINUE_IF_LANDING = (1<<3), // 8622GCS_CONTINUE_IF_PILOT_CONTROL = (1<<4), // 16623RELEASE_GRIPPER = (1<<5), // 32624};625626627enum class FlightOption : uint32_t {628DISABLE_THRUST_LOSS_CHECK = (1<<0), // 1629DISABLE_YAW_IMBALANCE_WARNING = (1<<1), // 2630RELEASE_GRIPPER_ON_THRUST_LOSS = (1<<2), // 4631REQUIRE_POSITION_FOR_ARMING = (1<<3), // 8632};633634// type of fast rate attitude controller in operation635enum class FastRateType : uint8_t {636FAST_RATE_DISABLED = 0,637FAST_RATE_DYNAMIC = 1,638FAST_RATE_FIXED_ARMED = 2,639FAST_RATE_FIXED = 3,640};641642FastRateType get_fast_rate_type() const { return FastRateType(g2.att_enable.get()); }643644// returns true if option is enabled for this vehicle645bool option_is_enabled(FlightOption option) const {646return (g2.flight_options & uint32_t(option)) != 0;647}648649static constexpr int8_t _failsafe_priorities[] = {650(int8_t)FailsafeAction::TERMINATE,651(int8_t)FailsafeAction::LAND,652(int8_t)FailsafeAction::RTL,653(int8_t)FailsafeAction::SMARTRTL_LAND,654(int8_t)FailsafeAction::SMARTRTL,655(int8_t)FailsafeAction::NONE,656-1 // the priority list must end with a sentinel of -1657};658659#define FAILSAFE_LAND_PRIORITY 1660static_assert(_failsafe_priorities[FAILSAFE_LAND_PRIORITY] == (int8_t)FailsafeAction::LAND,661"FAILSAFE_LAND_PRIORITY must match the entry in _failsafe_priorities");662static_assert(_failsafe_priorities[ARRAY_SIZE(_failsafe_priorities) - 1] == -1,663"_failsafe_priorities is missing the sentinel");664665666667// AP_State.cpp668void set_auto_armed(bool b);669void set_simple_mode(SimpleMode b);670void set_failsafe_radio(bool b);671void set_failsafe_gcs(bool b);672void update_using_interlock();673674// Copter.cpp675void get_scheduler_tasks(const AP_Scheduler::Task *&tasks,676uint8_t &task_count,677uint32_t &log_bit) override;678#if AP_SCRIPTING_ENABLED || AP_EXTERNAL_CONTROL_ENABLED679#if MODE_GUIDED_ENABLED680bool set_target_location(const Location& target_loc) override;681bool start_takeoff(const float alt) override;682#endif // MODE_GUIDED_ENABLED683#endif // AP_SCRIPTING_ENABLED || AP_EXTERNAL_CONTROL_ENABLED684685#if AP_SCRIPTING_ENABLED686#if MODE_GUIDED_ENABLED687bool get_target_location(Location& target_loc) override;688bool update_target_location(const Location &old_loc, const Location &new_loc) override;689bool set_target_pos_NED(const Vector3f& target_pos, bool use_yaw, float yaw_deg, bool use_yaw_rate, float yaw_rate_degs, bool yaw_relative, bool terrain_alt) override;690bool set_target_posvel_NED(const Vector3f& target_pos, const Vector3f& target_vel) override;691bool set_target_posvelaccel_NED(const Vector3f& target_pos, const Vector3f& target_vel, const Vector3f& target_accel, bool use_yaw, float yaw_deg, bool use_yaw_rate, float yaw_rate_degs, bool yaw_relative) override;692bool set_target_velocity_NED(const Vector3f& vel_ned) override;693bool set_target_velaccel_NED(const Vector3f& target_vel, const Vector3f& target_accel, bool use_yaw, float yaw_deg, bool use_yaw_rate, float yaw_rate_degs, bool relative_yaw) override;694bool set_target_angle_and_climbrate(float roll_deg, float pitch_deg, float yaw_deg, float climb_rate_ms, bool use_yaw_rate, float yaw_rate_degs) override;695bool set_target_rate_and_throttle(float roll_rate_dps, float pitch_rate_dps, float yaw_rate_dps, float throttle) override;696697// Register a custom mode with given number and names698AP_Vehicle::custom_mode_state* register_custom_mode(const uint8_t number, const char* full_name, const char* short_name) override;699#endif700#if MODE_CIRCLE_ENABLED701bool get_circle_radius(float &radius_m) override;702bool set_circle_rate(float rate_dps) override;703#endif704bool set_desired_speed(float speed) override;705#if MODE_AUTO_ENABLED706bool nav_scripting_enable(uint8_t mode) override;707bool nav_script_time(uint16_t &id, uint8_t &cmd, float &arg1, float &arg2, int16_t &arg3, int16_t &arg4) override;708void nav_script_time_done(uint16_t id) override;709#endif710// lua scripts use this to retrieve EKF failsafe state711// returns true if the EKF failsafe has triggered712bool has_ekf_failsafed() const override;713#endif // AP_SCRIPTING_ENABLED714bool is_landing() const override;715bool is_taking_off() const override;716void rc_loop();717void throttle_loop();718void update_batt_compass(void);719void loop_rate_logging();720void ten_hz_logging_loop();721void twentyfive_hz_logging();722void three_hz_loop();723void one_hz_loop();724void init_simple_bearing();725void update_simple_mode(void);726void update_super_simple_bearing(bool force_update);727void read_AHRS(void);728void update_altitude();729bool get_wp_distance_m(float &distance) const override;730bool get_wp_bearing_deg(float &bearing) const override;731bool get_wp_crosstrack_error_m(float &xtrack_error) const override;732bool get_rate_ef_targets(Vector3f& rate_ef_targets) const override;733734// Attitude.cpp735void update_throttle_hover();736float get_pilot_desired_climb_rate(float throttle_control);737float get_non_takeoff_throttle();738void set_accel_throttle_I_from_pilot_throttle();739void rotate_body_frame_to_NE(float &x, float &y);740uint16_t get_pilot_speed_dn() const;741void run_rate_controller_main();742743// if AP_INERTIALSENSOR_FAST_SAMPLE_WINDOW_ENABLED744struct RateControllerRates {745uint8_t fast_logging_rate;746uint8_t medium_logging_rate;747uint8_t filter_rate;748uint8_t main_loop_rate;749};750751uint8_t calc_gyro_decimation(uint8_t gyro_decimation, uint16_t rate_hz);752void rate_controller_thread();753void rate_controller_filter_update();754void rate_controller_log_update();755void rate_controller_set_rates(uint8_t rate_decimation, RateControllerRates& rates, bool warn_cpu_high);756void enable_fast_rate_loop(uint8_t rate_decimation, RateControllerRates& rates);757void disable_fast_rate_loop(RateControllerRates& rates);758void update_dynamic_notch_at_specified_rate_main();759// endif AP_INERTIALSENSOR_FAST_SAMPLE_WINDOW_ENABLED760761#if AC_CUSTOMCONTROL_MULTI_ENABLED762void run_custom_controller() { custom_control.update(); }763#endif764765// avoidance.cpp766void low_alt_avoidance();767768#if HAL_ADSB_ENABLED769// avoidance_adsb.cpp770void avoidance_adsb_update(void);771#endif772773// baro_ground_effect.cpp774void update_ground_effect_detector(void);775void update_ekf_terrain_height_stable();776777// commands.cpp778void update_home_from_EKF();779void set_home_to_current_location_inflight();780bool set_home_to_current_location(bool lock) override WARN_IF_UNUSED;781bool set_home(const Location& loc, bool lock) override WARN_IF_UNUSED;782783// compassmot.cpp784MAV_RESULT mavlink_compassmot(const GCS_MAVLINK &gcs_chan);785786// crash_check.cpp787void crash_check();788void thrust_loss_check();789void yaw_imbalance_check();790LowPassFilterFloat yaw_I_filt{0.05f};791uint32_t last_yaw_warn_ms;792void parachute_check();793void parachute_release();794void parachute_manual_release();795796// ekf_check.cpp797void ekf_check();798bool ekf_over_threshold();799void failsafe_ekf_event();800void failsafe_ekf_off_event(void);801void failsafe_ekf_recheck();802void check_ekf_reset();803void check_vibration();804805// esc_calibration.cpp806void esc_calibration_startup_check();807void esc_calibration_passthrough();808void esc_calibration_auto();809void esc_calibration_notify();810void esc_calibration_setup();811812// events.cpp813bool failsafe_option(FailsafeOption opt) const;814void failsafe_radio_on_event();815void failsafe_radio_off_event();816void handle_battery_failsafe(const char* type_str, const int8_t action);817void failsafe_gcs_check();818void failsafe_gcs_on_event(void);819void failsafe_gcs_off_event(void);820void failsafe_terrain_check();821void failsafe_terrain_set_status(bool data_ok);822void failsafe_terrain_on_event();823void gpsglitch_check();824void failsafe_deadreckon_check();825void set_mode_RTL_or_land_with_pause(ModeReason reason);826void set_mode_SmartRTL_or_RTL(ModeReason reason);827void set_mode_SmartRTL_or_land_with_pause(ModeReason reason);828void set_mode_auto_do_land_start_or_RTL(ModeReason reason);829void set_mode_brake_or_land_with_pause(ModeReason reason);830bool should_disarm_on_failsafe();831void do_failsafe_action(FailsafeAction action, ModeReason reason);832void announce_failsafe(const char *type, const char *action_undertaken=nullptr);833834// failsafe.cpp835void failsafe_enable();836void failsafe_disable();837#if AP_COPTER_ADVANCED_FAILSAFE_ENABLED838void afs_fs_check(void);839#endif840841// fence.cpp842#if AP_FENCE_ENABLED843void fence_check();844#endif845846// heli.cpp847void heli_init();848void check_dynamic_flight(void);849bool should_use_landing_swash() const;850void update_heli_control_dynamics(void);851void heli_update_landing_swash();852float get_pilot_desired_rotor_speed() const;853void heli_update_rotor_speed_targets();854void heli_update_autorotation();855void update_collective_low_flag(int16_t throttle_control);856857// inertia.cpp858void read_inertia();859860// landing_detector.cpp861void update_land_and_crash_detectors();862void update_land_detector();863void set_land_complete(bool b);864void set_land_complete_maybe(bool b);865void update_throttle_mix();866bool get_force_flying() const;867#if HAL_LOGGING_ENABLED868enum class LandDetectorLoggingFlag : uint16_t {869LANDED = 1U << 0,870LANDED_MAYBE = 1U << 1,871LANDING = 1U << 2,872STANDBY_ACTIVE = 1U << 3,873WOW = 1U << 4,874RANGEFINDER_BELOW_2M = 1U << 5,875DESCENT_RATE_LOW = 1U << 6,876ACCEL_STATIONARY = 1U << 7,877LARGE_ANGLE_ERROR = 1U << 8,878LARGE_ANGLE_REQUEST = 1U << 8,879MOTOR_AT_LOWER_LIMIT = 1U << 9,880THROTTLE_MIX_AT_MIN = 1U << 10,881};882struct {883uint32_t last_logged_ms;884uint32_t last_logged_count;885uint16_t last_logged_flags;886} land_detector;887void Log_LDET(uint16_t logging_flags, uint32_t land_detector_count);888#endif889890#if AP_LANDINGGEAR_ENABLED891// landing_gear.cpp892void landinggear_update();893#endif894895// standby.cpp896void standby_update();897898#if HAL_LOGGING_ENABLED899// methods for AP_Vehicle:900const AP_Int32 &get_log_bitmask() override { return g.log_bitmask; }901const struct LogStructure *get_log_structures() const override {902return log_structure;903}904uint8_t get_num_log_structures() const override;905906// Log.cpp907void Log_Write_Control_Tuning();908void Log_Write_Attitude();909void Log_Write_Rate();910void Log_Write_EKF_POS();911void Log_Write_PIDS();912void Log_Write_Data(LogDataID id, int32_t value);913void Log_Write_Data(LogDataID id, uint32_t value);914void Log_Write_Data(LogDataID id, int16_t value);915void Log_Write_Data(LogDataID id, uint16_t value);916void Log_Write_Data(LogDataID id, float value);917void Log_Write_Parameter_Tuning(uint8_t param, float tuning_val, float tune_min, float tune_max);918void Log_Video_Stabilisation();919void Log_Write_Guided_Position_Target(ModeGuided::SubMode submode, const Vector3f& pos_target, bool terrain_alt, const Vector3f& vel_target, const Vector3f& accel_target);920void Log_Write_Guided_Attitude_Target(ModeGuided::SubMode target_type, float roll, float pitch, float yaw, const Vector3f &ang_vel, float thrust, float climb_rate);921void Log_Write_SysID_Setup(uint8_t systemID_axis, float waveform_magnitude, float frequency_start, float frequency_stop, float time_fade_in, float time_const_freq, float time_record, float time_fade_out);922void Log_Write_SysID_Data(float waveform_time, float waveform_sample, float waveform_freq, float angle_x, float angle_y, float angle_z, float accel_x, float accel_y, float accel_z);923void Log_Write_Vehicle_Startup_Messages();924void Log_Write_Rate_Thread_Dt(float dt, float dtAvg, float dtMax, float dtMin);925#endif // HAL_LOGGING_ENABLED926927// mode.cpp928bool set_mode(Mode::Number mode, ModeReason reason);929bool set_mode(const uint8_t new_mode, const ModeReason reason) override;930ModeReason _last_reason;931// called when an attempt to change into a mode is unsuccessful:932void mode_change_failed(const Mode *mode, const char *reason);933uint8_t get_mode() const override { return (uint8_t)flightmode->mode_number(); }934bool current_mode_requires_mission() const override;935void update_flight_mode();936void notify_flight_mode();937938// Check if this mode can be entered from the GCS939bool gcs_mode_enabled(const Mode::Number mode_num);940941// mode_land.cpp942void set_mode_land_with_pause(ModeReason reason);943bool landing_with_GPS();944945// motor_test.cpp946void motor_test_output();947bool mavlink_motor_control_check(const GCS_MAVLINK &gcs_chan, bool check_rc, const char* mode);948MAV_RESULT mavlink_motor_test_start(const GCS_MAVLINK &gcs_chan, uint8_t motor_seq, uint8_t throttle_type, float throttle_value, float timeout_sec, uint8_t motor_count);949void motor_test_stop();950951// motors.cpp952void arm_motors_check();953void auto_disarm_check();954void motors_output(bool full_push = true);955void motors_output_main();956void lost_vehicle_check();957958// navigation.cpp959void run_nav_updates(void);960int32_t home_bearing();961uint32_t home_distance();962963// Parameters.cpp964void load_parameters(void) override;965void convert_pid_parameters(void);966#if HAL_PROXIMITY_ENABLED967void convert_prx_parameters();968#endif969void convert_lgr_parameters(void);970971// precision_landing.cpp972void init_precland();973void update_precland();974975// radio.cpp976void default_dead_zones();977void init_rc_in();978void init_rc_out();979void read_radio();980void set_throttle_and_failsafe(uint16_t throttle_pwm);981void set_throttle_zero_flag(int16_t throttle_control);982void radio_passthrough_to_motors();983int16_t get_throttle_mid(void);984985// sensors.cpp986void read_barometer(void);987void init_rangefinder(void);988void read_rangefinder(void);989bool rangefinder_alt_ok() const;990bool rangefinder_up_ok() const;991void update_rangefinder_terrain_offset();992void update_optical_flow(void);993994// takeoff_check.cpp995void takeoff_check();996997// RC_Channel.cpp998void save_trim();999void auto_trim();1000void auto_trim_cancel();10011002// system.cpp1003void init_ardupilot() override;1004void startup_INS_ground();1005bool position_ok() const;1006bool ekf_has_absolute_position() const;1007bool ekf_has_relative_position() const;1008bool ekf_alt_ok() const;1009void update_auto_armed();1010bool should_log(uint32_t mask);1011const char* get_frame_string() const;1012void allocate_motors(void);1013bool is_tradheli() const;10141015// terrain.cpp1016void terrain_update();1017void terrain_logging();10181019// tuning.cpp1020void tuning();10211022// UserCode.cpp1023void userhook_init();1024void userhook_FastLoop();1025void userhook_50Hz();1026void userhook_MediumLoop();1027void userhook_SlowLoop();1028void userhook_SuperSlowLoop();1029void userhook_auxSwitch1(const RC_Channel::AuxSwitchPos ch_flag);1030void userhook_auxSwitch2(const RC_Channel::AuxSwitchPos ch_flag);1031void userhook_auxSwitch3(const RC_Channel::AuxSwitchPos ch_flag);10321033#if MODE_ACRO_ENABLED1034#if FRAME_CONFIG == HELI_FRAME1035ModeAcro_Heli mode_acro;1036#else1037ModeAcro mode_acro;1038#endif1039#endif1040ModeAltHold mode_althold;1041#if MODE_AUTO_ENABLED1042ModeAuto mode_auto;1043#endif1044#if AUTOTUNE_ENABLED1045ModeAutoTune mode_autotune;1046#endif1047#if MODE_BRAKE_ENABLED1048ModeBrake mode_brake;1049#endif1050#if MODE_CIRCLE_ENABLED1051ModeCircle mode_circle;1052#endif1053#if MODE_DRIFT_ENABLED1054ModeDrift mode_drift;1055#endif1056#if MODE_FLIP_ENABLED1057ModeFlip mode_flip;1058#endif1059#if MODE_FOLLOW_ENABLED1060ModeFollow mode_follow;1061#endif1062#if MODE_GUIDED_ENABLED1063ModeGuided mode_guided;1064#if AP_SCRIPTING_ENABLED1065// Custom modes registered at runtime1066ModeGuidedCustom *mode_guided_custom[5];1067#endif1068#endif1069ModeLand mode_land;1070#if MODE_LOITER_ENABLED1071ModeLoiter mode_loiter;1072#endif1073#if MODE_POSHOLD_ENABLED1074ModePosHold mode_poshold;1075#endif1076#if MODE_RTL_ENABLED1077ModeRTL mode_rtl;1078#endif1079#if FRAME_CONFIG == HELI_FRAME1080ModeStabilize_Heli mode_stabilize;1081#else1082ModeStabilize mode_stabilize;1083#endif1084#if MODE_SPORT_ENABLED1085ModeSport mode_sport;1086#endif1087#if MODE_SYSTEMID_ENABLED1088ModeSystemId mode_systemid;1089#endif1090#if HAL_ADSB_ENABLED1091ModeAvoidADSB mode_avoid_adsb;1092#endif1093#if MODE_THROW_ENABLED1094ModeThrow mode_throw;1095#endif1096#if MODE_GUIDED_NOGPS_ENABLED1097ModeGuidedNoGPS mode_guided_nogps;1098#endif1099#if MODE_SMARTRTL_ENABLED1100ModeSmartRTL mode_smartrtl;1101#endif1102#if MODE_FLOWHOLD_ENABLED1103ModeFlowHold mode_flowhold;1104#endif1105#if MODE_ZIGZAG_ENABLED1106ModeZigZag mode_zigzag;1107#endif1108#if MODE_AUTOROTATE_ENABLED1109ModeAutorotate mode_autorotate;1110#endif1111#if MODE_TURTLE_ENABLED1112ModeTurtle mode_turtle;1113#endif11141115// mode.cpp1116Mode *mode_from_mode_num(const Mode::Number mode);1117void exit_mode(Mode *&old_flightmode, Mode *&new_flightmode);11181119bool started_rate_thread;1120bool using_rate_thread;11211122public:1123void failsafe_check(); // failsafe.cpp1124};11251126extern Copter copter;11271128using AP_HAL::millis;1129using AP_HAL::micros;113011311132