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