Skip to main content

stable_flight/stabilizers/
vtol.rs

1//! VTOL stabilization: [`TailsitterStabilizer`] flies each setpoint on the side it belongs to,
2//! hover or plane; [`QuadPlaneStabilizer`] flies a lift+cruise VTOL's lift rotors and surfaces,
3//! both at once through a transition.
4
5use crate::controllers::InvalidConfig;
6use crate::params::{ParamError, Params, locate};
7use crate::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
8use crate::stabilizers::plane::{PlaneStabilizer, PlaneStabilizerConfig};
9use crate::tuning::{ProbeConfig, ProbeStatus, Tunable};
10use crate::{Configurable, ControlOutput, Saturation, Setpoint, Stabilizer, VehicleState, View};
11use nalgebra::UnitQuaternion;
12
13mod quadplane;
14#[cfg(test)]
15mod tests;
16
17pub use quadplane::{QuadPlaneStabilizer, QuadPlaneStabilizerConfig};
18
19/// [`TailsitterStabilizer`] settings: its two stabilizers'.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct TailsitterStabilizerConfig {
22    /// Hover stabilizer, flown in the tailsitter [`View`] (its gains in view axes).
23    pub hover: CopterStabilizerConfig,
24    /// Wing-borne stabilizer, in the airplane frame.
25    pub plane: PlaneStabilizerConfig,
26}
27
28impl TailsitterStabilizerConfig {
29    /// `Ok` when both parts validate.
30    ///
31    /// # Errors
32    ///
33    /// The first part's [`InvalidConfig`], in its section (`hover`, `plane`).
34    pub fn validate(&self) -> Result<(), InvalidConfig> {
35        self.hover.validate().map_err(|e| e.in_section("hover"))?;
36        self.plane.validate().map_err(|e| e.in_section("plane"))
37    }
38}
39
40/// A tailsitter's stabilizer: copter stabilization in the tailsitter [`View`] for
41/// [`Setpoint::Attitude`], [`Setpoint::Rate`], and [`Setpoint::BodyRate`], and a
42/// [`PlaneStabilizer`] for [`Setpoint::Plane`] and [`Setpoint::PlaneRate`]. The setpoint picks
43/// the side, so the guidance's mode reaches it without a copy: one side runs per tick, and when
44/// the side changes the incoming stabilizer is primed, so it starts without the integrals of
45/// the flight it last flew (PX4 resets the inactive side's rate integrators,
46/// `FixedwingRateControl.cpp`, `MulticopterRateControl.cpp`).
47///
48/// Autotune probes go to the hover side. Params chain the parts' (`STAB_*`, `PSTAB_*`).
49///
50/// # Examples
51///
52/// ```
53/// use stable_flight::stabilizers::vtol::{TailsitterStabilizer, TailsitterStabilizerConfig};
54/// use stable_flight::{PlaneSetpoint, Setpoint, Stabilizer, VehicleState};
55///
56/// let mut stabilizer = TailsitterStabilizer::new(TailsitterStabilizerConfig::default());
57/// let bank = Setpoint::Plane(PlaneSetpoint { roll_rad: 0.3, thrust: 0.6, ..Default::default() });
58/// let output = stabilizer.stabilize(0.004, &bank, &VehicleState::default());
59/// assert!(output.moments.x > 0.0); // the plane side rolls right
60/// ```
61pub struct TailsitterStabilizer {
62    config: TailsitterStabilizerConfig,
63    hover: View<CopterStabilizer>,
64    plane: PlaneStabilizer,
65    /// Whether the last tick flew the plane side.
66    on_plane: bool,
67}
68
69impl TailsitterStabilizer {
70    /// A stabilizer with `config`, on the hover side.
71    ///
72    /// # Panics
73    ///
74    /// If `config` is invalid ([`TailsitterStabilizerConfig::validate`]).
75    pub fn new(config: TailsitterStabilizerConfig) -> Self {
76        if let Err(error) = config.validate() {
77            panic!("invalid TailsitterStabilizerConfig: {error}");
78        }
79        TailsitterStabilizer {
80            config,
81            hover: View::tailsitter(CopterStabilizer::new(config.hover)),
82            plane: PlaneStabilizer::new(config.plane),
83            on_plane: false,
84        }
85    }
86
87    /// Copies the parts' configs back after a param write, so [`Configurable::config`] stays
88    /// the one view of them.
89    fn sync_config(&mut self) {
90        self.config = TailsitterStabilizerConfig {
91            hover: *self.hover.config(),
92            plane: *self.plane.config(),
93        };
94    }
95}
96
97impl Stabilizer for TailsitterStabilizer {
98    fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput {
99        let on_plane = matches!(setpoint, Setpoint::Plane(_) | Setpoint::PlaneRate(_));
100        if on_plane != self.on_plane {
101            if on_plane {
102                self.plane.prime(state);
103            } else {
104                self.hover.prime(state);
105            }
106            self.on_plane = on_plane;
107        }
108        if on_plane {
109            self.plane.stabilize(dt, setpoint, state)
110        } else {
111            self.hover.stabilize(dt, setpoint, state)
112        }
113    }
114
115    /// Primes both sides; the hover side flies next.
116    fn prime(&mut self, state: &VehicleState) {
117        self.hover.prime(state);
118        self.plane.prime(state);
119        self.on_plane = false;
120    }
121
122    /// The side that flew the last tick.
123    fn saturation(&self) -> Saturation {
124        if self.on_plane {
125            self.plane.saturation()
126        } else {
127            self.hover.saturation()
128        }
129    }
130}
131
132impl Configurable for TailsitterStabilizer {
133    type Config = TailsitterStabilizerConfig;
134
135    fn config(&self) -> &TailsitterStabilizerConfig {
136        &self.config
137    }
138
139    /// Validates the whole config first, then hands each part its own.
140    fn set_config(&mut self, config: TailsitterStabilizerConfig) -> Result<(), InvalidConfig> {
141        config.validate()?;
142        self.hover.set_config(config.hover)?;
143        self.plane.set_config(config.plane)?;
144        self.config = config;
145        Ok(())
146    }
147}
148
149/// The parts' params, chained: hover (`STAB_*`), plane (`PSTAB_*`).
150impl Params for TailsitterStabilizer {
151    fn param_count(&self) -> usize {
152        self.hover.param_count() + self.plane.param_count()
153    }
154
155    fn param_name(&self, index: usize) -> Option<&'static str> {
156        match locate(&[&self.hover, &self.plane], index)? {
157            (0, i) => self.hover.param_name(i),
158            (_, i) => self.plane.param_name(i),
159        }
160    }
161
162    fn param_at(&self, index: usize) -> Option<f32> {
163        match locate(&[&self.hover, &self.plane], index)? {
164            (0, i) => self.hover.param_at(i),
165            (_, i) => self.plane.param_at(i),
166        }
167    }
168
169    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
170        let result = match locate(&[&self.hover, &self.plane], index).ok_or(ParamError::Unknown)? {
171            (0, i) => self.hover.set_param_at(i, value),
172            (_, i) => self.plane.set_param_at(i, value),
173        };
174        self.sync_config();
175        result
176    }
177}
178
179/// Autotune runs on the hover side.
180impl Tunable for TailsitterStabilizer {
181    type Target = <View<CopterStabilizer> as Tunable>::Target;
182
183    fn start_probe(&mut self, target: Self::Target, config: ProbeConfig) {
184        self.hover.start_probe(target, config);
185    }
186
187    fn probe(&self) -> Option<(Self::Target, ProbeStatus)> {
188        self.hover.probe()
189    }
190
191    fn stop_probe(&mut self) -> Option<(Self::Target, ProbeStatus)> {
192        self.hover.stop_probe()
193    }
194
195    /// The hover view's: autotune judges the hover in its view axes.
196    fn probe_frame(&self) -> UnitQuaternion<f32> {
197        self.hover.probe_frame()
198    }
199}