use crate::{Vec2, Vec3};
use crate::{
AttitudeSetpoint, Configurable, ControlOutput, Saturation, Setpoint, Stabilizer, VehicleState,
};
use crate::controllers::gyro::GyroFilter;
use crate::controllers::*;
use crate::controllers::{GyroFilters, NotchConfig};
use crate::controllers::{check_limit, check_positive};
use crate::math::{
assert_dt, attitude_error, pitch_limit_rad, saturate_rates, saturate_unit, thrust_curve,
};
mod params;
#[cfg(test)]
mod tests;
mod tuning;
pub use tuning::TunedLoop;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CopterStabilizerConfig {
pub body_rate: BodyRateControllerConfig,
pub attitude: AttitudeControllerConfig,
pub yaw: YawControllerConfig,
pub full_scale_rates_radps: Vec3,
pub thrust_curve_exponent: f32,
pub gyro_cutoff_hz: f32,
pub gyro_notch: NotchConfig,
}
pub const DEFAULT_GYRO_CUTOFF_HZ: f32 = 40.0;
impl Default for CopterStabilizerConfig {
fn default() -> Self {
CopterStabilizerConfig {
body_rate: BodyRateControllerConfig::default(),
attitude: AttitudeControllerConfig::default(),
yaw: YawControllerConfig::default(),
full_scale_rates_radps: Vec3::new(3.0, 3.0, 3.0),
thrust_curve_exponent: 2.0,
gyro_cutoff_hz: DEFAULT_GYRO_CUTOFF_HZ,
gyro_notch: NotchConfig::default(),
}
}
}
impl CopterStabilizerConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
self.body_rate
.validate()
.map_err(|e| e.in_section("body_rate"))?;
self.attitude
.validate()
.map_err(|e| e.in_section("attitude"))?;
self.yaw.validate().map_err(|e| e.in_section("yaw"))?;
let scales = &self.full_scale_rates_radps;
check_limit("full_scale_rates_radps.x", scales.x)?;
check_limit("full_scale_rates_radps.y", scales.y)?;
check_limit("full_scale_rates_radps.z", scales.z)?;
check_positive("thrust_curve_exponent", self.thrust_curve_exponent)?;
check_limit("gyro_cutoff_hz", self.gyro_cutoff_hz)?;
self.gyro_notch
.validate()
.map_err(|e| e.in_section("gyro_notch"))
}
pub fn gyro_filters_on(&self, axis: usize) -> GyroFilters {
let notch = if axis < 2 {
self.gyro_notch
} else {
NotchConfig::default()
};
GyroFilters {
cutoff_hz: self.gyro_cutoff_hz,
notch,
}
}
}
pub struct CopterStabilizer {
config: CopterStabilizerConfig,
body_rate: BodyRateController,
attitude: AttitudeController,
yaw: YawController,
saturation: Saturation,
stage: Option<tuning::Stage>,
clipped: Clipped,
last_moments: Vec3,
gyro_filters: [GyroFilter; 3],
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Clipped {
moments: [bool; 3],
rates: [bool; 3],
}
impl CopterStabilizer {
pub fn new(config: CopterStabilizerConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid CopterStabilizerConfig: {error}");
}
CopterStabilizer {
config,
body_rate: BodyRateController::default(),
attitude: AttitudeController::default(),
yaw: YawController::default(),
saturation: Saturation::default(),
stage: None,
clipped: Clipped::default(),
last_moments: Vec3::zeros(),
gyro_filters: Default::default(),
}
}
}
impl Configurable for CopterStabilizer {
type Config = CopterStabilizerConfig;
fn config(&self) -> &CopterStabilizerConfig {
&self.config
}
fn set_config(&mut self, config: CopterStabilizerConfig) -> Result<(), InvalidConfig> {
config.validate()?;
let old = &self.config;
self.attitude
.rescale_integral(&old.attitude, &config.attitude);
self.yaw.rescale_integral(&old.yaw, &config.yaw);
self.config = config;
Ok(())
}
}
impl Stabilizer for CopterStabilizer {
fn stabilize(
&mut self,
dt: f32,
setpoint: &Setpoint,
estimated_state: &VehicleState,
) -> ControlOutput {
assert_dt(dt);
self.saturation = Saturation::default();
let output = match setpoint {
Setpoint::Attitude(attitude) => self.track_attitude(dt, attitude, estimated_state),
Setpoint::Rate(rates) => {
let fractions = Vec3::new(
saturate_unit(rates.roll_rate),
saturate_unit(rates.pitch_rate),
saturate_unit(rates.yaw_rate),
);
let desired = fractions.component_mul(&self.config.full_scale_rates_radps);
self.track_rates(dt, desired, rates.thrust, estimated_state)
}
Setpoint::BodyRate(rates) => {
let desired = saturate_rates(
Vec3::new(rates.roll_radps, rates.pitch_radps, rates.yaw_radps),
self.config.full_scale_rates_radps,
);
self.track_rates(dt, desired, rates.thrust, estimated_state)
}
Setpoint::Plane(_) | Setpoint::PlaneRate(_) | Setpoint::Blend(_) => {
ControlOutput::default()
}
};
if setpoint.idle() {
self.body_rate.clear_integral();
self.attitude.clear_integral();
self.yaw.clear_integral();
}
self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
self.clipped.moments = self.saturation.moments;
self.last_moments = output.moments;
self.finish_stage();
output
}
fn prime(&mut self, _state: &VehicleState) {
self.stage = None;
self.clipped = Clipped::default();
self.last_moments = Vec3::zeros();
self.gyro_filters = Default::default();
self.body_rate = BodyRateController::default();
self.attitude = AttitudeController::default();
self.yaw = YawController::default();
self.saturation = Saturation::default();
}
fn saturation(&self) -> Saturation {
self.saturation
}
}
impl CopterStabilizer {
fn track_attitude(
&mut self,
dt: f32,
setpoint: &AttitudeSetpoint,
estimated_state: &VehicleState,
) -> ControlOutput {
let max_angles_rad = self.max_angles_rad(setpoint);
self.saturation.tilt = setpoint.roll_rad.abs() > max_angles_rad.x
|| setpoint.pitch_rad.abs() > max_angles_rad.y;
let attitude = &estimated_state.attitude;
let saturate_tilt = |roll_rad: f32, pitch_rad: f32, heading_rad: f32| {
let tilt = AttitudeController::saturate_setpoint(
max_angles_rad,
Vec2::new(roll_rad, pitch_rad),
);
Vec3::new(tilt.x, tilt.y, heading_rad)
};
let mut desired =
saturate_tilt(setpoint.roll_rad, setpoint.pitch_rad, setpoint.heading_rad);
let error_for = |angles: &Vec3| attitude_error(attitude, angles.x, angles.y, angles.z);
let mut error = error_for(&desired);
let probed = desired;
self.probe_attitude(
dt,
&mut desired,
&error,
&estimated_state.angular_velocity_radps,
);
if desired != probed {
desired = saturate_tilt(desired.x, desired.y, desired.z);
error = error_for(&desired);
}
let [hold_roll, hold_pitch, hold_heading] = self.held_integrals();
let config = &self.config;
let desired_rates =
self.attitude
.control_error(&config.attitude, dt, error.xy(), [hold_roll, hold_pitch]);
let desired_yaw_rate = self
.yaw
.control_error(&config.yaw, dt, error.z, hold_heading);
let max_rates = config.attitude.max_rate_radps;
self.clipped.rates = [
desired_rates.x.abs() >= max_rates.x,
desired_rates.y.abs() >= max_rates.y,
desired_yaw_rate.abs() >= config.yaw.max_rate_radps,
];
let desired_rates = Vec3::new(desired_rates.x, desired_rates.y, desired_yaw_rate);
let moments = self.track_body_rates(dt, desired_rates, estimated_state);
ControlOutput {
thrust: self.fit_to_thrust_curve(setpoint.thrust),
moments,
cruise: None,
}
}
fn max_angles_rad(&self, setpoint: &AttitudeSetpoint) -> Vec2 {
let limits_rad = self.config.attitude.max_angles_rad;
Vec2::new(
limits_rad.x,
pitch_limit_rad(limits_rad.y, setpoint.transition),
)
}
fn track_rates(
&mut self,
dt: f32,
desired_rates_radps: Vec3,
thrust: f32,
estimated_state: &VehicleState,
) -> ControlOutput {
self.interrupt_attitude_stage();
self.attitude = AttitudeController::default();
self.yaw = YawController::default();
self.clipped.rates = [false; 3];
let moments = self.track_body_rates(dt, desired_rates_radps, estimated_state);
ControlOutput {
thrust: self.fit_to_thrust_curve(thrust),
moments,
cruise: None,
}
}
fn track_body_rates(
&mut self,
dt: f32,
desired_rates_radps: Vec3,
estimated_state: &VehicleState,
) -> Vec3 {
let current_rates = self.filter_rates(dt, estimated_state.angular_velocity_radps);
let mut desired_rates_radps = desired_rates_radps;
self.probe_rates(
dt,
&mut desired_rates_radps,
¤t_rates,
&estimated_state.angular_velocity_radps,
);
self.body_rate.control(
&self.config.body_rate,
dt,
desired_rates_radps,
current_rates,
)
}
fn filter_rates(&mut self, dt: f32, rates_radps: Vec3) -> Vec3 {
let config = self.config;
Vec3::from_fn(|axis, _| {
let filters = config.gyro_filters_on(axis);
self.gyro_filters[axis].apply(rates_radps[axis], dt, &filters)
})
}
fn fit_to_thrust_curve(&mut self, linear_thrust: f32) -> f32 {
self.saturation.thrust = !(0.0..=1.0).contains(&linear_thrust) && !linear_thrust.is_nan();
thrust_curve(linear_thrust, self.config.thrust_curve_exponent)
}
}