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, TunedLoop};
7use crate::stabilizers::plane::{PlaneLoop, 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's `Standard::fill_actuator_outputs`). A side that starts flying is
80/// primed, so it starts without the integrals of its last flight (PX4 resets the idle side's
81/// rate integrators, `FixedwingRateControl::Run`); 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        let sides = Sides::of(setpoint);
153        self.prime_entering(sides, state);
154        // A probe flies only while its side flies alone: a blend is a transition, which no
155        // probe should disturb.
156        if sides != Sides::Hover {
157            self.hover.interrupt_stage();
158        }
159        if sides != Sides::Plane {
160            self.plane.interrupt_stage();
161        }
162        match setpoint {
163            Setpoint::Plane(_) | Setpoint::PlaneRate(_) => {
164                let cruise = self.plane.stabilize(dt, setpoint, state);
165                ControlOutput {
166                    cruise: Some(CruiseOutput {
167                        thrust: cruise.thrust,
168                        moments: cruise.moments,
169                    }),
170                    ..ControlOutput::default()
171                }
172            }
173            Setpoint::Blend(blend) => {
174                // NaN: the lift rotors carry it all.
175                let share = if blend.lift_share.is_nan() {
176                    1.0
177                } else {
178                    blend.lift_share.clamp(0.0, 1.0)
179                };
180                let lift = self
181                    .hover
182                    .stabilize(dt, &Setpoint::Attitude(blend.hover), state);
183                let cruise = self
184                    .plane
185                    .stabilize(dt, &Setpoint::Plane(blend.plane), state);
186                ControlOutput {
187                    thrust: lift.thrust * share,
188                    moments: lift.moments * share,
189                    cruise: Some(CruiseOutput {
190                        thrust: cruise.thrust,
191                        moments: cruise.moments,
192                    }),
193                }
194            }
195            _ => ControlOutput {
196                cruise: Some(CruiseOutput {
197                    thrust: 0.0,
198                    moments: Vec3::zeros(),
199                }),
200                ..self.hover.stabilize(dt, setpoint, state)
201            },
202        }
203    }
204
205    /// Primes both sides; the hover side flies next.
206    fn prime(&mut self, state: &VehicleState) {
207        self.hover.prime(state);
208        self.plane.prime(state);
209        self.sides = Sides::Hover;
210    }
211
212    /// The sides that flew the last tick, merged in a blend.
213    fn saturation(&self) -> Saturation {
214        match self.sides {
215            Sides::Hover => self.hover.saturation(),
216            Sides::Plane => self.plane.saturation(),
217            Sides::Both => self.hover.saturation().merge(self.plane.saturation()),
218        }
219    }
220}
221
222impl Configurable for QuadPlaneStabilizer {
223    type Config = QuadPlaneStabilizerConfig;
224
225    fn config(&self) -> &QuadPlaneStabilizerConfig {
226        &self.config
227    }
228
229    /// Validates the whole config first, then hands each part its own.
230    fn set_config(&mut self, config: QuadPlaneStabilizerConfig) -> Result<(), InvalidConfig> {
231        config.validate()?;
232        self.hover.set_config(config.hover)?;
233        self.plane.set_config(config.plane)?;
234        self.config = config;
235        Ok(())
236    }
237}
238
239/// The parts' params, chained: hover (`STAB_*`), plane (`PSTAB_*`).
240impl Params for QuadPlaneStabilizer {
241    fn param_count(&self) -> usize {
242        self.hover.param_count() + self.plane.param_count()
243    }
244
245    fn param_name(&self, index: usize) -> Option<&'static str> {
246        match locate(&[&self.hover, &self.plane], index)? {
247            (0, i) => self.hover.param_name(i),
248            (_, i) => self.plane.param_name(i),
249        }
250    }
251
252    fn param_at(&self, index: usize) -> Option<f32> {
253        match locate(&[&self.hover, &self.plane], index)? {
254            (0, i) => self.hover.param_at(i),
255            (_, i) => self.plane.param_at(i),
256        }
257    }
258
259    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
260        let result = match locate(&[&self.hover, &self.plane], index).ok_or(ParamError::Unknown)? {
261            (0, i) => self.hover.set_param_at(i, value),
262            (_, i) => self.plane.set_param_at(i, value),
263        };
264        self.sync_config();
265        result
266    }
267}
268
269/// Hover probes, on the lift rotors: they fly only while the hover side flies alone.
270impl Tunable<TunedLoop> for QuadPlaneStabilizer {
271    fn start_probe(&mut self, target: TunedLoop, config: ProbeConfig) {
272        self.hover.start_probe(target, config);
273    }
274
275    fn probe(&self) -> Option<(TunedLoop, ProbeStatus)> {
276        self.hover.probe()
277    }
278
279    fn stop_probe(&mut self) -> Option<(TunedLoop, ProbeStatus)> {
280        self.hover.stop_probe()
281    }
282}
283
284/// Plane probes, on the surfaces: they fly only while the plane side flies alone.
285impl Tunable<PlaneLoop> for QuadPlaneStabilizer {
286    fn start_probe(&mut self, target: PlaneLoop, config: ProbeConfig) {
287        self.plane.start_probe(target, config);
288    }
289
290    fn probe(&self) -> Option<(PlaneLoop, ProbeStatus)> {
291        self.plane.probe()
292    }
293
294    fn stop_probe(&mut self) -> Option<(PlaneLoop, ProbeStatus)> {
295        self.plane.stop_probe()
296    }
297}