Skip to main content

stable_flight/controllers/
mod.rs

1#![doc = include_str!("README.md")]
2
3use core::fmt;
4
5use crate::Vec3;
6
7pub mod altitude;
8pub mod attitude;
9mod biquad;
10pub mod body_rate;
11mod derivative;
12pub mod gyro;
13pub mod lateral;
14pub(crate) mod low_pass;
15pub mod notch;
16pub mod plane_rate;
17pub mod yaw;
18
19pub use altitude::{
20    AltitudeController, AltitudeControllerConfig, AltitudeEstimate, AltitudeTarget,
21    DEFAULT_HOVER_THRUST, DEFAULT_INTEGRATION_BAND_M,
22};
23pub use attitude::{AttitudeController, AttitudeControllerConfig};
24pub use body_rate::{BodyRateController, BodyRateControllerConfig, RATE_I_PER_P, YAW_RATE_I_PER_P};
25pub use gyro::GyroFilters;
26pub use lateral::{
27    DEFAULT_BRAKING_SHARE, LateralController, LateralControllerConfig, LateralEstimate,
28    LateralTarget,
29};
30pub use notch::NotchConfig;
31pub use plane_rate::{PlaneRateController, PlaneRateControllerConfig, RateGains};
32pub use yaw::{YawController, YawControllerConfig};
33
34#[cfg(test)]
35mod tests;
36
37/// A controller config value that [`validate`](BodyRateControllerConfig::validate) rejected.
38///
39/// Controllers assume a valid config: check it once at construction and on every live change.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct InvalidConfig {
43    /// The loop the field belongs to when a composite config (e.g.
44    /// [`CopterStabilizerConfig`](crate::stabilizers::copter::CopterStabilizerConfig))
45    /// reported it, e.g. `Some("body_rate")`; `None` from a controller config itself.
46    pub section: Option<&'static str>,
47    /// The offending field, e.g. `"max_integral"`.
48    pub field: &'static str,
49    /// What the field must satisfy, e.g. `"non-negative and finite"`.
50    pub requirement: &'static str,
51}
52
53impl InvalidConfig {
54    pub(crate) fn new(field: &'static str, requirement: &'static str) -> Self {
55        Self {
56            section: None,
57            field,
58            requirement,
59        }
60    }
61
62    /// The same error, attributed to `section` of a composite config.
63    pub(crate) fn in_section(self, section: &'static str) -> Self {
64        Self {
65            section: Some(section),
66            ..self
67        }
68    }
69}
70
71impl fmt::Display for InvalidConfig {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        if let Some(section) = self.section {
74            write!(f, "{section}.")?;
75        }
76        write!(f, "{} must be {}", self.field, self.requirement)
77    }
78}
79
80impl core::error::Error for InvalidConfig {}
81
82/// `Ok` when `value` is non-negative and finite, the rule for every controller limit.
83pub(crate) fn check_limit(field: &'static str, value: f32) -> Result<(), InvalidConfig> {
84    check(
85        field,
86        value >= 0.0 && value.is_finite(),
87        "non-negative and finite",
88    )
89}
90
91/// `Ok` when `value` is positive and finite.
92pub(crate) fn check_positive(field: &'static str, value: f32) -> Result<(), InvalidConfig> {
93    check(
94        field,
95        value > 0.0 && value.is_finite(),
96        "positive and finite",
97    )
98}
99
100/// `Ok` when `value` is in `(0, 1]` (a fraction of full scale that must not be zero).
101pub(crate) fn check_unit_interval(field: &'static str, value: f32) -> Result<(), InvalidConfig> {
102    check(field, value > 0.0 && value <= 1.0, "in (0, 1]")
103}
104
105/// `Ok` when `value` is a tilt angle strictly between level and vertical, `(0, π/2)` rad.
106pub(crate) fn check_tilt(field: &'static str, value: f32) -> Result<(), InvalidConfig> {
107    check(
108        field,
109        value > 0.0 && value < core::f32::consts::FRAC_PI_2,
110        "in (0, π/2) rad",
111    )
112}
113
114/// `Ok` when `ok`, otherwise an [`InvalidConfig`] naming `field` and its `requirement`.
115pub(crate) fn check(
116    field: &'static str,
117    ok: bool,
118    requirement: &'static str,
119) -> Result<(), InvalidConfig> {
120    if ok {
121        Ok(())
122    } else {
123        Err(InvalidConfig::new(field, requirement))
124    }
125}
126
127/// The integrated error that keeps the I term `i · integral` unchanged when the integral gain
128/// goes from `old_i` to `new_i`, so a retune doesn't bump the output (the policy in
129/// `docs/architecture/config.md#config-ownership`).
130///
131/// Unchanged when the gain is. Zero when either gain is zero (an integral accumulated under a
132/// zero gain was never applied, so carrying it in would bump) or the ratio isn't finite.
133pub(crate) fn rescale_integral(integral: f32, old_i: f32, new_i: f32) -> f32 {
134    if old_i == new_i {
135        return integral;
136    }
137    if old_i == 0.0 || new_i == 0.0 {
138        return 0.0;
139    }
140    let rescaled = integral * (old_i / new_i);
141    if rescaled.is_finite() { rescaled } else { 0.0 }
142}
143
144/// PID gains for a single control loop.
145#[derive(Default, Clone, Copy, Debug, PartialEq)]
146pub struct Gains {
147    pub p: f32,
148    pub i: f32,
149    pub d: f32,
150}
151
152// alpha 0.1 is a good starting point for most applications
153pub fn low_pass_filter_vec3(prev: Vec3, new: Vec3, alpha: f32) -> Vec3 {
154    Vec3::new(
155        alpha * new.x + (1.0 - alpha) * prev.x,
156        alpha * new.y + (1.0 - alpha) * prev.y,
157        alpha * new.z + (1.0 - alpha) * prev.z,
158    )
159}