Skip to main content

stable_flight/tuning/autotune/
plane.rs

1//! The plane side of the supervisor: a plane's roll and pitch loops ([`PlaneSide`]), tuned by
2//! a [`PlaneMethod`] within a [`PlaneEnvelope`], as a [`PlaneAutotune`].
3
4use super::procedure::{Action, PlaneProcedure, Verdict};
5use super::side::{Decide, Motion, RateFilters, Side, SideConfig, StageView, Waits, zero_if_nan};
6use super::{AutotuneAbort, DEFAULT_SETTLE_SPEED_MPS, Settle, StagePlan, StepTestPlan, Supervisor};
7use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
8use crate::math::DEG;
9use crate::stabilizers::plane::{PlaneAxisGains, PlaneLoop, PlaneStabilizerConfig};
10use crate::stabilizers::vtol::{QuadPlaneStabilizerConfig, TailsitterStabilizerConfig};
11use crate::tuning::{IdentifyConfig, ProbeConfig, StepConfig, WingDesignConfig};
12use crate::{Setpoint, Vec2, Vec3};
13
14/// The plane autotune: a [`Supervisor`] of a plane's roll and pitch loops ([`PlaneSide`]), on
15/// a [`PlaneStabilizer`](crate::stabilizers::plane::PlaneStabilizer) or a VTOL's plane side.
16///
17/// The probes ride on whatever the commander flies; a plane's need a steady attitude hold at
18/// cruise thrust, the airspeed trimmed between probes (as ArduPilot's AUTOTUNE flies in FBWA
19/// at the pilot's throttle), not a line held by the energy control, which answers a pitch step
20/// with its own pitch (#533).
21pub type PlaneAutotune = Supervisor<PlaneSide>;
22
23/// A plane's roll and pitch loops ([`PlaneLoop`]), each stage on its loop's axis gains
24/// ([`PlaneAxisGains`]), tuned by a [`PlaneMethod`] within a [`PlaneEnvelope`]: the
25/// [`PlaneAutotune`].
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct PlaneSide;
28
29/// How a plane stage tunes its loop.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum PlaneMethod {
32    /// Alternating step responses, measured and reported; the gains don't change.
33    StepTest(StepTestPlan),
34    /// The axis fitted in flight, its gains designed on the fit, then checked on attitude
35    /// steps.
36    Design(PlaneDesignPlan),
37}
38
39/// The share of the attitude loop's rate limit a plane identification excites its rate loop
40/// with: on the sim's planes it moved the angle of attack enough to fit the wing's stiffness
41/// without leaving the envelope (#533).
42pub const PLANE_IDENTIFY_SHARE: f32 = 0.3;
43
44/// How long a plane identification excites, in s: the window the sweep fitted, against the
45/// copter's 3 s (#533).
46pub const PLANE_IDENTIFY_S: f32 = 6.0;
47
48/// Largest overshoot a plane design allows, as a fraction of the step: ArduPilot's copter
49/// target, `1 + AUTOTUNE_AGGR/2` at its default `AUTOTUNE_AGGR` 0.1 (`AC_AutoTune_Multi`);
50/// neither ArduPlane's autotune nor PX4's has a step target.
51pub const PLANE_MAX_OVERSHOOT: f32 = 0.05;
52
53/// The 10–90% rise a plane design allows, in time constants: the attitude loop asks for the
54/// error over its time constant, as PX4's does (`FW_R_TC`, `FW_P_TC`), so the response is
55/// first order, which rises in 2.2.
56pub const PLANE_RISE_PER_TIME_CONSTANT: f32 = 2.2;
57
58/// The time constants a plane design picks from, in s: PX4's `FW_R_TC` and `FW_P_TC` range
59/// from 0.2 up, and the Alia 250's roll needed up to 1.5 on the sim (#533).
60pub const PLANE_TIME_CONSTANT_RANGE_S: [f32; 2] = [0.2, 1.5];
61
62/// The share of the surfaces' throw (less the trim) a plane design may use: a fifth held back
63/// for what the fit misses, since a step that clips measures the surfaces, not the loop (#533).
64pub const PLANE_MOMENT_SHARE: f32 = 0.8;
65
66/// A plane design stage: fit the stage's axis ([`ProbeConfig::IdentifyWing`] on its rate
67/// loop), design its rate gains and time constant on the fit
68/// ([`WingDesign`](crate::tuning::WingDesign)), then fly pairs of attitude steps on them until
69/// a pair meets the design's targets. A pair that sags (unsettled, or slower than the rise
70/// allowed) raises I by half, one that overshoots or clips raises the time constant by 15%:
71/// a held attitude bleeds airspeed, which the fit at constant airspeed doesn't see (#533).
72/// Tunes the whole axis ([`PlaneAxisGains`]); its stages are the angle loops.
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct PlaneDesignPlan {
75    /// The identification on the axis's rate loop.
76    pub identify: IdentifyConfig,
77    /// The design's targets and the limits its model flies under.
78    pub design: WingDesignConfig,
79    /// The attitude step a pair flies, each way; its amplitude should be the design's.
80    pub verify: StepConfig,
81    /// Most pairs before the stage fails ([`AutotuneAbort::Unverified`]). Positive.
82    pub max_verify_pairs: usize,
83    /// Design candidates stepped per update: about 4,000 multiplies each. Positive.
84    pub candidates_per_update: usize,
85    /// Steady enough to start each probe.
86    pub settle: Settle,
87}
88
89impl PlaneDesignPlan {
90    /// The plane defaults for `target`'s axis on a plane flying `config`: a 6 s identification
91    /// at [`PLANE_IDENTIFY_SHARE`] of the axis's rate limit, a design to
92    /// [`PLANE_MAX_OVERSHOOT`], [`PLANE_RISE_PER_TIME_CONSTANT`], and
93    /// [`PLANE_MAX_SATURATED_S`] within [`PLANE_TIME_CONSTANT_RANGE_S`] and
94    /// [`PLANE_MOMENT_SHARE`] of the throw, the step [`StepTestPlan::plane`]'s, up to 8
95    /// pairs, 4 candidates per update, from [`PLANE_STEP_SETTLE`].
96    ///
97    /// # Examples
98    ///
99    /// ```
100    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizerConfig};
101    /// use stable_flight::tuning::autotune::{PLANE_IDENTIFY_SHARE, PlaneDesignPlan};
102    ///
103    /// let config = PlaneStabilizerConfig::default();
104    /// let plan = PlaneDesignPlan::for_plane(PlaneLoop::Pitch, &config);
105    /// let max_rate = config.max_attitude_rate_radps.y;
106    /// assert_eq!(plan.identify.amplitude, PLANE_IDENTIFY_SHARE * max_rate);
107    /// assert_eq!(plan.design.amplitude_rad, plan.verify.amplitude);
108    /// assert!(plan.validate().is_ok());
109    /// ```
110    pub fn for_plane(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
111        let axis = target.axis();
112        let max_rate_radps = config.max_attitude_rate_radps[axis];
113        // The axis's attitude step, whichever loop names the stage.
114        let angle = match target {
115            PlaneLoop::RollRate | PlaneLoop::Roll => PlaneLoop::Roll,
116            PlaneLoop::PitchRate | PlaneLoop::Pitch => PlaneLoop::Pitch,
117        };
118        let verify = StepTestPlan::plane(angle, config).step;
119        Self {
120            identify: IdentifyConfig {
121                amplitude: PLANE_IDENTIFY_SHARE * max_rate_radps,
122                duration_s: PLANE_IDENTIFY_S,
123                washout_tc_s: 0.2,
124                noisy: None,
125            },
126            design: WingDesignConfig {
127                amplitude_rad: verify.amplitude,
128                step_duration_s: verify.duration_s,
129                max_rate_radps,
130                max_moment: PLANE_MOMENT_SHARE * (1.0 - config.rate.trim[axis].abs()),
131                max_integral: config.rate.max_integral,
132                static_trim: config.rate.trim[axis],
133                max_overshoot: PLANE_MAX_OVERSHOOT,
134                max_saturated_s: PLANE_MAX_SATURATED_S,
135                time_constant_range_s: PLANE_TIME_CONSTANT_RANGE_S,
136                rise_per_time_constant: PLANE_RISE_PER_TIME_CONSTANT,
137            },
138            verify,
139            max_verify_pairs: 8,
140            candidates_per_update: 4,
141            settle: PLANE_STEP_SETTLE,
142        }
143    }
144
145    /// Checks the identification, the design, the step, and that the counts are positive.
146    pub fn validate(&self) -> Result<(), InvalidConfig> {
147        self.identify
148            .validate()
149            .map_err(|e| e.in_section("identify"))?;
150        self.design.validate().map_err(|e| e.in_section("design"))?;
151        self.verify.validate().map_err(|e| e.in_section("verify"))?;
152        check("max_verify_pairs", self.max_verify_pairs > 0, "positive")?;
153        check(
154            "candidates_per_update",
155            self.candidates_per_update > 0,
156            "positive",
157        )
158    }
159}
160
161/// A plane rate step: 8°/s held for 1 s. A held rate turns the aircraft away from the attitude
162/// its loops hold, so the step stays small: 8° of rotation by the end (#533).
163pub const PLANE_RATE_STEP: StepConfig = StepConfig {
164    amplitude: 8.0 * DEG,
165    duration_s: 1.0,
166    settle_band: 0.1,
167    filter_hz: 0.0,
168};
169
170/// A plane roll step: 30°, a turn's bank, held 4 s: long enough to settle at the 0.4–0.6 s
171/// time constants the sim's planes fly.
172pub const PLANE_ROLL_STEP: StepConfig = StepConfig {
173    amplitude: 30.0 * DEG,
174    duration_s: 4.0,
175    settle_band: 0.1,
176    filter_hz: 0.0,
177};
178
179/// A plane pitch step: 10°, a climb or dive the airspeed survives at cruise thrust, held 4 s.
180pub const PLANE_PITCH_STEP: StepConfig = StepConfig {
181    amplitude: 10.0 * DEG,
182    ..PLANE_ROLL_STEP
183};
184
185/// Level before each plane step: within 3° of the held attitude and 0.1 rad/s on each axis
186/// for 1 s. A wing in an attitude hold rides its phugoid, so the band is wider than a
187/// copter's (2.5°, [`COPTER_STEP_SETTLE`](super::COPTER_STEP_SETTLE)); the airspeed has a
188/// settle of its own ([`AirspeedSettle`]). On the sim's four planes every step settled
189/// inside [`PlaneEnvelope::for_plane`]'s 20 s (#534).
190pub const PLANE_STEP_SETTLE: Settle = Settle {
191    tilt_rad: 3.0 * DEG,
192    rate_radps: 0.1,
193    hold_s: 1.0,
194    max_speed_mps: DEFAULT_SETTLE_SPEED_MPS,
195};
196
197/// How long a plane step may clip and still count, in s: 10 ticks at 250 Hz, as a copter's
198/// ([`COPTER_MAX_SATURATED_S`](super::COPTER_MAX_SATURATED_S)). The sim's planes don't clip
199/// on [`PLANE_ROLL_STEP`] or [`PLANE_PITCH_STEP`] (#310).
200pub const PLANE_MAX_SATURATED_S: f32 = 0.042;
201
202impl StepTestPlan {
203    /// The plane defaults for `target` on a plane flying `config`: three pairs of
204    /// [`PLANE_RATE_STEP`] (roll and pitch rate), [`PLANE_ROLL_STEP`] (roll), or
205    /// [`PLANE_PITCH_STEP`] (pitch), each no larger than `config`'s bank or pitch limit, from
206    /// [`PLANE_STEP_SETTLE`], each clipping for up to [`PLANE_MAX_SATURATED_S`], allowing 3
207    /// clipped and 10 stalled steps in a row. A step replaces the saturated setpoint, so a step
208    /// past the limit would fly an attitude the airframe's limit forbids: the Alia 250's 20°
209    /// bank limit holds its roll steps to 20°, and at 30° its roll stage sank past the
210    /// envelope's 40 m.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizerConfig};
216    /// use stable_flight::tuning::autotune::{PLANE_PITCH_STEP, StepTestPlan};
217    ///
218    /// let config = PlaneStabilizerConfig { max_bank_rad: 0.2, ..Default::default() };
219    /// assert_eq!(StepTestPlan::plane(PlaneLoop::Pitch, &config).step, PLANE_PITCH_STEP);
220    /// assert_eq!(StepTestPlan::plane(PlaneLoop::Roll, &config).step.amplitude, 0.2);
221    /// ```
222    pub fn plane(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
223        let capped = |step: StepConfig, limit_rad: f32| StepConfig {
224            amplitude: step.amplitude.min(limit_rad),
225            ..step
226        };
227        let step = match target {
228            PlaneLoop::RollRate | PlaneLoop::PitchRate => PLANE_RATE_STEP,
229            PlaneLoop::Roll => capped(PLANE_ROLL_STEP, config.max_bank_rad),
230            PlaneLoop::Pitch => capped(PLANE_PITCH_STEP, config.max_pitch_rad),
231        };
232        Self {
233            step,
234            pairs: 3,
235            settle: PLANE_STEP_SETTLE,
236            max_saturated_s: PLANE_MAX_SATURATED_S,
237            max_invalid: 3,
238            max_stalled: 10,
239        }
240    }
241}
242
243impl StagePlan<PlaneSide> {
244    /// A design of `target`'s axis with the plane defaults for `config`
245    /// ([`PlaneDesignPlan::for_plane`]).
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizerConfig};
251    /// use stable_flight::tuning::autotune::{PlaneAutotune, PlaneEnvelope, StagePlan};
252    ///
253    /// let config = PlaneStabilizerConfig::default();
254    /// let plan = [PlaneLoop::Roll, PlaneLoop::Pitch].map(|t| StagePlan::plane_design(t, &config));
255    /// assert!(PlaneAutotune::new(&plan, PlaneEnvelope::for_plane(&config)).is_ok());
256    /// ```
257    pub fn plane_design(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
258        Self {
259            target,
260            method: PlaneMethod::Design(PlaneDesignPlan::for_plane(target, config)),
261        }
262    }
263
264    /// A step test of `target` with the plane defaults for `config`
265    /// ([`StepTestPlan::plane`]).
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizerConfig};
271    /// use stable_flight::tuning::autotune::{PlaneAutotune, PlaneEnvelope, StagePlan};
272    ///
273    /// let config = PlaneStabilizerConfig::default();
274    /// let plan = [PlaneLoop::Roll, PlaneLoop::Pitch].map(|t| StagePlan::plane_step_test(t, &config));
275    /// assert!(PlaneAutotune::new(&plan, PlaneEnvelope::for_plane(&config)).is_ok());
276    /// ```
277    pub fn plane_step_test(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
278        Self {
279            target,
280            method: PlaneMethod::StepTest(StepTestPlan::plane(target, config)),
281        }
282    }
283}
284
285/// Limits that end a plane stage, and how steady the wing must fly before a probe starts.
286/// Angles are from level, in the airplane frame.
287#[derive(Clone, Copy, Debug, PartialEq)]
288pub struct PlaneEnvelope {
289    /// Bank beyond this aborts the stage, in rad.
290    pub max_bank_rad: f32,
291    /// Pitch, up or down, beyond this aborts the stage, in rad.
292    pub max_pitch_rad: f32,
293    /// A roll, pitch, or yaw rate beyond this aborts the stage, in rad/s.
294    pub max_rate_radps: f32,
295    /// Sinking more than this below the altitude at the start aborts, in m.
296    pub max_altitude_loss_m: f32,
297    /// Airspeed below this aborts, in m/s: the wing nears its stall. A missing airspeed never
298    /// counts.
299    pub min_airspeed_mps: f32,
300    /// Airspeed above this aborts, in m/s: a dive the loops weren't tuned for.
301    pub max_airspeed_mps: f32,
302    /// Steady enough to start a probe, unless the stage's method sets its own.
303    pub settle: Settle,
304    /// How long to wait for a settle, in s ([`Envelope`](super::Envelope)'s).
305    pub settle_timeout_s: f32,
306    /// How long the committed gains have to bring the wing back inside the limits after a
307    /// candidate, or after a freeze, in s ([`Envelope`](super::Envelope)'s). Non-negative.
308    pub recovery_s: f32,
309    /// How long the host may go without a fresh vehicle state before the run fails, in s
310    /// ([`Envelope`](super::Envelope)'s). Positive.
311    pub max_stale_s: f32,
312    /// The airspeed a probe starts at, besides the settle's attitude and rates.
313    pub settle_airspeed: AirspeedSettle,
314}
315
316/// Steady enough in airspeed to start a plane probe: within `band_mps` of `trim_mps` and
317/// changing by less than `max_change_mps2`, for the settle's hold. In an attitude hold a wing
318/// rides its phugoid, trading airspeed for climb over several seconds with its attitude and
319/// rates still, and a step started on that swing reads the loop wrong: on the sim, steps
320/// started ±1.7 m/s off the airplane's trim read 0–2% overshoot where the same gains overshot
321/// 4–5% from steady flight, so the stage passed gains the plane spec failed (#534). A missing
322/// airspeed never holds a probe back.
323#[derive(Clone, Copy, Debug, PartialEq)]
324pub struct AirspeedSettle {
325    /// The airspeed the hold trims to, in m/s.
326    pub trim_mps: f32,
327    /// How far from `trim_mps` still counts, in m/s. Positive.
328    pub band_mps: f32,
329    /// The fastest the airspeed may change, in m/s². Positive.
330    pub max_change_mps2: f32,
331}
332
333impl AirspeedSettle {
334    /// Whether `motion`'s airspeed is within the band and steady (or missing).
335    fn holds(&self, motion: &Motion) -> bool {
336        motion.airspeed_mps.is_none_or(|airspeed_mps| {
337            (airspeed_mps - self.trim_mps).abs() < self.band_mps
338                && motion.airspeed_change_mps2.abs() < self.max_change_mps2
339        })
340    }
341}
342
343impl PlaneEnvelope {
344    /// Limits for a plane flying `config`: 60° of bank and 30° of pitch (a 30° roll step and
345    /// a 10° pitch step from the hold, with room to overshoot), 4 rad/s, 40 m of sink, and
346    /// airspeed between 0.9 × `config`'s minimum and its maximum; settle as
347    /// [`PLANE_STEP_SETTLE`] with the airspeed within 1 m/s of `config`'s trim and changing by
348    /// under 0.2 m/s² ([`AirspeedSettle`]), waiting up to 20 s, 2 s to recover, 2 s without a
349    /// fresh state.
350    /// On the sim the airplane slowed past its minimum within a few steps unless the hold
351    /// trimmed its pitch for airspeed; with the trim, these limits never tripped on a sound
352    /// start (#533).
353    ///
354    /// # Examples
355    ///
356    /// ```
357    /// use stable_flight::stabilizers::plane::PlaneStabilizerConfig;
358    /// use stable_flight::tuning::autotune::PlaneEnvelope;
359    ///
360    /// let config = PlaneStabilizerConfig::default();
361    /// let envelope = PlaneEnvelope::for_plane(&config);
362    /// assert_eq!(envelope.min_airspeed_mps, 0.9 * config.min_airspeed_mps);
363    /// ```
364    pub fn for_plane(config: &PlaneStabilizerConfig) -> Self {
365        Self {
366            max_bank_rad: 60.0 * DEG,
367            max_pitch_rad: 30.0 * DEG,
368            max_rate_radps: 4.0,
369            max_altitude_loss_m: 40.0,
370            min_airspeed_mps: 0.9 * config.min_airspeed_mps,
371            max_airspeed_mps: config.max_airspeed_mps,
372            settle: PLANE_STEP_SETTLE,
373            settle_timeout_s: 20.0,
374            recovery_s: 2.0,
375            max_stale_s: 2.0,
376            settle_airspeed: AirspeedSettle {
377                trim_mps: config.trim_airspeed_mps,
378                band_mps: 1.0,
379                max_change_mps2: 0.2,
380            },
381        }
382    }
383
384    /// Checks that every limit and time is positive and finite, the airspeed band in order,
385    /// and settling ([`check_settle`](Self::check_settle)) tighter than aborting.
386    pub fn validate(&self) -> Result<(), InvalidConfig> {
387        check_positive("max_bank_rad", self.max_bank_rad)?;
388        check_positive("max_pitch_rad", self.max_pitch_rad)?;
389        check_positive("max_rate_radps", self.max_rate_radps)?;
390        check_positive("max_altitude_loss_m", self.max_altitude_loss_m)?;
391        check_positive("min_airspeed_mps", self.min_airspeed_mps)?;
392        check(
393            "max_airspeed_mps",
394            self.max_airspeed_mps > self.min_airspeed_mps && self.max_airspeed_mps.is_finite(),
395            "finite and above min_airspeed_mps",
396        )?;
397        check_positive("settle_timeout_s", self.settle_timeout_s)?;
398        check_limit("recovery_s", self.recovery_s)?;
399        check_positive("max_stale_s", self.max_stale_s)?;
400        let airspeed = &self.settle_airspeed;
401        check_positive("settle_airspeed.trim_mps", airspeed.trim_mps)?;
402        check_positive("settle_airspeed.band_mps", airspeed.band_mps)?;
403        check_positive("settle_airspeed.max_change_mps2", airspeed.max_change_mps2)?;
404        self.check_settle(&self.settle)
405    }
406
407    /// Checks that `settle` is positive, tighter than the bank, pitch, and rate limits, and
408    /// fits in `settle_timeout_s`.
409    pub fn check_settle(&self, settle: &Settle) -> Result<(), InvalidConfig> {
410        check(
411            "settle.tilt_rad",
412            settle.tilt_rad > 0.0 && settle.tilt_rad < self.max_bank_rad.min(self.max_pitch_rad),
413            "positive and below max_bank_rad and max_pitch_rad",
414        )?;
415        check(
416            "settle.rate_radps",
417            settle.rate_radps > 0.0 && settle.rate_radps < self.max_rate_radps,
418            "positive and below max_rate_radps",
419        )?;
420        check(
421            "settle.hold_s",
422            settle.hold_s > 0.0 && settle.hold_s < self.settle_timeout_s,
423            "positive and below settle_timeout_s",
424        )
425    }
426
427    /// The limit `motion` breaks, if any. NaN never counts as a breach.
428    fn breach(&self, motion: &Motion, start_altitude_m: f32) -> Option<AutotuneAbort> {
429        let airspeed_mps = motion.airspeed_mps;
430        if motion.bank_rad > self.max_bank_rad || motion.pitch_rad > self.max_pitch_rad {
431            Some(AutotuneAbort::Tilt)
432        } else if motion.rate_radps > self.max_rate_radps {
433            Some(AutotuneAbort::Rate)
434        } else if start_altitude_m - motion.altitude_m > self.max_altitude_loss_m {
435            Some(AutotuneAbort::AltitudeLoss)
436        } else if airspeed_mps.is_some_and(|mps| mps < self.min_airspeed_mps) {
437            Some(AutotuneAbort::AirspeedLow)
438        } else if airspeed_mps.is_some_and(|mps| mps > self.max_airspeed_mps) {
439            Some(AutotuneAbort::AirspeedHigh)
440        } else {
441            None
442        }
443    }
444}
445
446impl SideConfig<PlaneSide> for PlaneStabilizerConfig {
447    fn side(&self) -> &PlaneStabilizerConfig {
448        self
449    }
450
451    fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
452        self
453    }
454}
455
456impl SideConfig<PlaneSide> for TailsitterStabilizerConfig {
457    fn side(&self) -> &PlaneStabilizerConfig {
458        &self.plane
459    }
460
461    fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
462        &mut self.plane
463    }
464}
465
466impl SideConfig<PlaneSide> for QuadPlaneStabilizerConfig {
467    fn side(&self) -> &PlaneStabilizerConfig {
468        &self.plane
469    }
470
471    fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
472        &mut self.plane
473    }
474}
475
476impl Side for PlaneSide {
477    type Target = PlaneLoop;
478    type Gains = PlaneAxisGains;
479    type Config = PlaneStabilizerConfig;
480    type Method = PlaneMethod;
481    type Envelope = PlaneEnvelope;
482    type Procedure = PlaneProcedure;
483
484    fn gains(target: PlaneLoop, config: &PlaneStabilizerConfig) -> PlaneAxisGains {
485        target.gains(config)
486    }
487
488    fn set_gains(target: PlaneLoop, config: &mut PlaneStabilizerConfig, gains: PlaneAxisGains) {
489        target.set_gains(config, gains);
490    }
491
492    /// An identification excites an angle loop's axis on the rate loop under it; every other
493    /// probe runs on `target` itself.
494    fn probed_loop(target: PlaneLoop, probe: &ProbeConfig) -> PlaneLoop {
495        match probe {
496            ProbeConfig::Identify(_) | ProbeConfig::IdentifyWing(_) => {
497                target.inner().unwrap_or(target)
498            }
499            ProbeConfig::Step(_) => target,
500        }
501    }
502
503    fn validate_method(method: &PlaneMethod) -> Result<(), InvalidConfig> {
504        match method {
505            PlaneMethod::StepTest(plan) => {
506                plan.validate().map_err(|e| e.in_section("plan.step_test"))
507            }
508            PlaneMethod::Design(plan) => plan.validate().map_err(|e| e.in_section("plan.design")),
509        }
510    }
511
512    fn method_settle(method: &PlaneMethod) -> Option<Settle> {
513        match method {
514            PlaneMethod::StepTest(plan) => Some(plan.settle),
515            PlaneMethod::Design(plan) => Some(plan.settle),
516        }
517    }
518
519    fn procedure(method: PlaneMethod) -> PlaneProcedure {
520        PlaneProcedure::new(method)
521    }
522
523    fn decide(
524        procedure: &mut PlaneProcedure,
525        on: Decide,
526        stage: StageView<'_, Self>,
527    ) -> Action<PlaneAxisGains> {
528        procedure.next(on, stage.target.gains(stage.config))
529    }
530
531    fn take_verdict(_procedure: &mut PlaneProcedure) -> Option<Verdict<PlaneAxisGains>> {
532        None
533    }
534
535    fn validate_envelope(envelope: &PlaneEnvelope) -> Result<(), InvalidConfig> {
536        envelope.validate()
537    }
538
539    fn check_settle(envelope: &PlaneEnvelope, settle: &Settle) -> Result<(), InvalidConfig> {
540        envelope.check_settle(settle)
541    }
542
543    fn waits(envelope: &PlaneEnvelope) -> Waits {
544        Waits {
545            settle: envelope.settle,
546            settle_timeout_s: envelope.settle_timeout_s,
547            recovery_s: envelope.recovery_s,
548            max_stale_s: envelope.max_stale_s,
549        }
550    }
551
552    fn breach(
553        envelope: &PlaneEnvelope,
554        motion: &Motion,
555        start_altitude_m: f32,
556    ) -> Option<AutotuneAbort> {
557        envelope.breach(motion, start_altitude_m)
558    }
559
560    /// Raw: the plane's rate loop flies the unfiltered rates.
561    fn filter_rates(
562        _filters: &mut RateFilters,
563        _config: &PlaneStabilizerConfig,
564        rates_radps: Vec3,
565        _dt: f32,
566    ) -> Vec3 {
567        rates_radps
568    }
569
570    /// An attitude setpoint's bank and pitch (a NaN axis is level, as the stabilizer reads
571    /// it), a blend's plane side's, and level for anything else.
572    fn attitude_target(setpoint: &Setpoint) -> Vec2 {
573        let plane = match setpoint {
574            Setpoint::Plane(plane) => plane,
575            Setpoint::Blend(blend) => &blend.plane,
576            _ => return Vec2::zeros(),
577        };
578        Vec2::new(zero_if_nan(plane.roll_rad), zero_if_nan(plane.pitch_rad))
579    }
580
581    /// Both axes near the held attitude and still, and the airspeed steady near trim
582    /// ([`PlaneEnvelope::settle_airspeed`]): a wing moves over the ground, so its ground speed
583    /// doesn't count.
584    fn settles(
585        envelope: &PlaneEnvelope,
586        settle: &Settle,
587        motion: &Motion,
588        _target: PlaneLoop,
589    ) -> bool {
590        (0..2).all(|axis| steady_axis(settle, motion, axis))
591            && envelope.settle_airspeed.holds(motion)
592    }
593
594    /// The loop's own axis near the held attitude and still.
595    fn holds(settle: &Settle, motion: &Motion, target: PlaneLoop) -> bool {
596        steady_axis(settle, motion, target.axis())
597    }
598}
599
600/// Whether `motion` is within `settle` of the held attitude about `axis` (0 roll, 1 pitch).
601fn steady_axis(settle: &Settle, motion: &Motion, axis: usize) -> bool {
602    motion.axis_tilt_error_rad[axis] < settle.tilt_rad
603        && motion.axis_rate_radps[axis] < settle.rate_radps
604}
605
606#[cfg(test)]
607mod tests;