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