Skip to main content

stable_flight/stabilizers/vtol/
quadplane.rs

1//! [`QuadPlaneStabilizer`]: a lift+cruise VTOL's lift rotors on the copter stabilizer, its
2//! surfaces and pusher on the plane stabilizer.
3
4use crate::controllers::InvalidConfig;
5use crate::params::{ParamError, Params, locate};
6use crate::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
7use crate::stabilizers::plane::{PlaneStabilizer, PlaneStabilizerConfig};
8use crate::tuning::{ProbeConfig, ProbeStatus, Tunable};
9use crate::{
10    Configurable, ControlOutput, CruiseOutput, Saturation, Setpoint, Stabilizer, Vec3, VehicleState,
11};
12
13#[cfg(test)]
14mod tests;
15
16/// [`QuadPlaneStabilizer`] settings: its two stabilizers'.
17#[derive(Clone, Copy, Debug, Default, PartialEq)]
18pub struct QuadPlaneStabilizerConfig {
19    /// Hover stabilizer, on the lift rotors.
20    pub hover: CopterStabilizerConfig,
21    /// Wing-borne stabilizer, on the surfaces and pusher.
22    pub plane: PlaneStabilizerConfig,
23}
24
25impl QuadPlaneStabilizerConfig {
26    /// `Ok` when both parts validate.
27    ///
28    /// # Errors
29    ///
30    /// The first part's [`InvalidConfig`], in its section (`hover`, `plane`).
31    pub fn validate(&self) -> Result<(), InvalidConfig> {
32        self.hover.validate().map_err(|e| e.in_section("hover"))?;
33        self.plane.validate().map_err(|e| e.in_section("plane"))
34    }
35}
36
37/// Which stabilizers flew a tick.
38#[derive(Clone, Copy, Debug, PartialEq)]
39enum Sides {
40    Hover,
41    Plane,
42    Both,
43}
44
45impl Sides {
46    /// The sides `setpoint` flies.
47    fn of(setpoint: &Setpoint) -> Self {
48        match setpoint {
49            Setpoint::Plane(_) | Setpoint::PlaneRate(_) => Sides::Plane,
50            Setpoint::Blend(_) => Sides::Both,
51            _ => Sides::Hover,
52        }
53    }
54
55    fn hover(self) -> bool {
56        self != Sides::Plane
57    }
58
59    fn plane(self) -> bool {
60        self != Sides::Hover
61    }
62}
63
64/// A lift+cruise VTOL's (quadplane's) stabilizer: a [`CopterStabilizer`] on the lift rotors
65/// ([`ControlOutput`]'s `thrust` and `moments`) and a [`PlaneStabilizer`] on the surfaces and
66/// pusher ([`cruise`](ControlOutput::cruise)). Pair it with a mixer that splits the two, such
67/// as [`TableMixer::quadplane`](crate::mixers::TableMixer::quadplane).
68///
69/// The setpoint picks the sides:
70///
71/// | Setpoint | Lift rotors | Surfaces and pusher |
72/// |---|---|---|
73/// | [`Attitude`](Setpoint::Attitude), [`Rate`](Setpoint::Rate), [`BodyRate`](Setpoint::BodyRate) | copter stabilizer | neutral, pusher stopped |
74/// | [`Plane`](Setpoint::Plane), [`PlaneRate`](Setpoint::PlaneRate) | stopped | plane stabilizer |
75/// | [`Blend`](Setpoint::Blend) | copter stabilizer on its `hover`, thrust and moments × `lift_share` | plane stabilizer on its `plane`, in full |
76///
77/// In a hover the surfaces are held neutral (PX4's `VT_ELEV_MC_LOCK`,
78/// `vtol_att_control_params.yaml`), and in a blend the lift rotors' output is weighted and the
79/// surfaces' isn't (PX4 `standard.cpp:294-368`). A side that starts flying is primed, so it
80/// starts without the integrals of its last flight (PX4 resets the idle side's rate
81/// integrators, `FixedwingRateControl.cpp:266-269`); a side that keeps flying from a blend
82/// keeps them.
83///
84/// Autotune probes go to the hover side. Params chain the parts' (`STAB_*`, `PSTAB_*`).
85///
86/// # Examples
87///
88/// ```
89/// use stable_flight::stabilizers::vtol::{QuadPlaneStabilizer, QuadPlaneStabilizerConfig};
90/// use stable_flight::{AttitudeSetpoint, BlendSetpoint, PlaneSetpoint, Setpoint, Stabilizer};
91/// use stable_flight::VehicleState;
92///
93/// let mut stabilizer = QuadPlaneStabilizer::new(QuadPlaneStabilizerConfig::default());
94/// let blend = Setpoint::Blend(BlendSetpoint {
95///     hover: AttitudeSetpoint { thrust: 0.8, ..Default::default() },
96///     plane: PlaneSetpoint { thrust: 1.0, ..Default::default() },
97///     lift_share: 0.5,
98/// });
99/// let output = stabilizer.stabilize(0.004, &blend, &VehicleState::default());
100/// assert!((output.thrust - 0.32).abs() < 1e-6); // 0.8 through the thrust curve, halved
101/// assert_eq!(output.cruise.unwrap().thrust, 1.0); // the pusher at full
102/// ```
103pub struct QuadPlaneStabilizer {
104    config: QuadPlaneStabilizerConfig,
105    hover: CopterStabilizer,
106    plane: PlaneStabilizer,
107    /// The sides the last tick flew.
108    sides: Sides,
109}
110
111impl QuadPlaneStabilizer {
112    /// A stabilizer with `config`, on the hover side.
113    ///
114    /// # Panics
115    ///
116    /// If `config` is invalid ([`QuadPlaneStabilizerConfig::validate`]).
117    pub fn new(config: QuadPlaneStabilizerConfig) -> Self {
118        if let Err(error) = config.validate() {
119            panic!("invalid QuadPlaneStabilizerConfig: {error}");
120        }
121        QuadPlaneStabilizer {
122            config,
123            hover: CopterStabilizer::new(config.hover),
124            plane: PlaneStabilizer::new(config.plane),
125            sides: Sides::Hover,
126        }
127    }
128
129    /// Primes the sides `sides` adds to the last tick's.
130    fn prime_entering(&mut self, sides: Sides, state: &VehicleState) {
131        if sides.hover() && !self.sides.hover() {
132            self.hover.prime(state);
133        }
134        if sides.plane() && !self.sides.plane() {
135            self.plane.prime(state);
136        }
137        self.sides = sides;
138    }
139
140    /// Copies the parts' configs back after a param write, so [`Configurable::config`] stays
141    /// the one view of them.
142    fn sync_config(&mut self) {
143        self.config = QuadPlaneStabilizerConfig {
144            hover: *self.hover.config(),
145            plane: *self.plane.config(),
146        };
147    }
148}
149
150impl Stabilizer for QuadPlaneStabilizer {
151    fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput {
152        self.prime_entering(Sides::of(setpoint), state);
153        match setpoint {
154            Setpoint::Plane(_) | Setpoint::PlaneRate(_) => {
155                let cruise = self.plane.stabilize(dt, setpoint, state);
156                ControlOutput {
157                    cruise: Some(CruiseOutput {
158                        thrust: cruise.thrust,
159                        moments: cruise.moments,
160                    }),
161                    ..ControlOutput::default()
162                }
163            }
164            Setpoint::Blend(blend) => {
165                // NaN: the lift rotors carry it all.
166                let share = if blend.lift_share.is_nan() {
167                    1.0
168                } else {
169                    blend.lift_share.clamp(0.0, 1.0)
170                };
171                let lift = self
172                    .hover
173                    .stabilize(dt, &Setpoint::Attitude(blend.hover), state);
174                let cruise = self
175                    .plane
176                    .stabilize(dt, &Setpoint::Plane(blend.plane), state);
177                ControlOutput {
178                    thrust: lift.thrust * share,
179                    moments: lift.moments * share,
180                    cruise: Some(CruiseOutput {
181                        thrust: cruise.thrust,
182                        moments: cruise.moments,
183                    }),
184                }
185            }
186            _ => ControlOutput {
187                cruise: Some(CruiseOutput {
188                    thrust: 0.0,
189                    moments: Vec3::zeros(),
190                }),
191                ..self.hover.stabilize(dt, setpoint, state)
192            },
193        }
194    }
195
196    /// Primes both sides; the hover side flies next.
197    fn prime(&mut self, state: &VehicleState) {
198        self.hover.prime(state);
199        self.plane.prime(state);
200        self.sides = Sides::Hover;
201    }
202
203    /// The sides that flew the last tick, merged in a blend.
204    fn saturation(&self) -> Saturation {
205        match self.sides {
206            Sides::Hover => self.hover.saturation(),
207            Sides::Plane => self.plane.saturation(),
208            Sides::Both => self.hover.saturation().merge(self.plane.saturation()),
209        }
210    }
211}
212
213impl Configurable for QuadPlaneStabilizer {
214    type Config = QuadPlaneStabilizerConfig;
215
216    fn config(&self) -> &QuadPlaneStabilizerConfig {
217        &self.config
218    }
219
220    /// Validates the whole config first, then hands each part its own.
221    fn set_config(&mut self, config: QuadPlaneStabilizerConfig) -> Result<(), InvalidConfig> {
222        config.validate()?;
223        self.hover.set_config(config.hover)?;
224        self.plane.set_config(config.plane)?;
225        self.config = config;
226        Ok(())
227    }
228}
229
230/// The parts' params, chained: hover (`STAB_*`), plane (`PSTAB_*`).
231impl Params for QuadPlaneStabilizer {
232    fn param_count(&self) -> usize {
233        self.hover.param_count() + self.plane.param_count()
234    }
235
236    fn param_name(&self, index: usize) -> Option<&'static str> {
237        match locate(&[&self.hover, &self.plane], index)? {
238            (0, i) => self.hover.param_name(i),
239            (_, i) => self.plane.param_name(i),
240        }
241    }
242
243    fn param_at(&self, index: usize) -> Option<f32> {
244        match locate(&[&self.hover, &self.plane], index)? {
245            (0, i) => self.hover.param_at(i),
246            (_, i) => self.plane.param_at(i),
247        }
248    }
249
250    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
251        let result = match locate(&[&self.hover, &self.plane], index).ok_or(ParamError::Unknown)? {
252            (0, i) => self.hover.set_param_at(i, value),
253            (_, i) => self.plane.set_param_at(i, value),
254        };
255        self.sync_config();
256        result
257    }
258}
259
260/// Autotune runs on the hover side.
261impl Tunable for QuadPlaneStabilizer {
262    type Target = <CopterStabilizer as Tunable>::Target;
263
264    fn start_probe(&mut self, target: Self::Target, config: ProbeConfig) {
265        self.hover.start_probe(target, config);
266    }
267
268    fn probe(&self) -> Option<(Self::Target, ProbeStatus)> {
269        self.hover.probe()
270    }
271
272    fn stop_probe(&mut self) -> Option<(Self::Target, ProbeStatus)> {
273        self.hover.stop_probe()
274    }
275}