stable_flight/commanders/tune_hold.rs
1//! The attitude hold a plane autotune flies in: [`PlaneTuneHold`].
2
3use core::f32::consts::{FRAC_PI_2, PI};
4
5use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
6use crate::math::{DEG, clamp_symmetric, lagged, wrap_angle};
7use crate::{
8 AbsoluteAttitudeCommand, Command, Commander, ControlInput, FlightRegime, Vec2, VehicleState,
9 WaypointCommand,
10};
11
12#[cfg(test)]
13mod tests;
14
15/// [`PlaneTuneHold`] settings.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct PlaneTuneHoldConfig {
18 /// The thrust the hold flies, in `[0, 1]`, before its altitude trim: the airframe's cruise
19 /// thrust, or the thrust it flies level on.
20 pub thrust: f32,
21 /// How much the thrust trim adds per m below the altitude the hold started at (takes off
22 /// above it), as a pilot holds height with the throttle. Higher: holds the height
23 /// tighter, and moves the thrust under a pitch step more. 0 turns it off. Non-negative.
24 pub thrust_per_m: f32,
25 /// The farthest the thrust trim moves the thrust from [`thrust`](Self::thrust).
26 /// Non-negative.
27 pub max_thrust_trim: f32,
28 /// How slowly the thrust trim follows the altitude, in s (a first-order time constant).
29 pub thrust_time_constant_s: f32,
30 /// The airspeed the pitch trim holds, in m/s: the plane stabilizer's trim airspeed.
31 pub trim_airspeed_mps: f32,
32 /// How far the trim pitches the nose per m/s of airspeed off trim, in rad per m/s: down
33 /// when slow, up when fast. Higher: holds the airspeed tighter, and stirs the phugoid.
34 pub pitch_per_mps: f32,
35 /// How slowly the trim follows the airspeed, in s (a first-order time constant): slow
36 /// enough that a probe's few seconds don't see it move.
37 pub trim_time_constant_s: f32,
38 /// The farthest the trim pitches the nose from where the hold started, in rad.
39 pub max_trim_rad: f32,
40 /// Beyond this distance from where the hold started, the hold turns back toward it
41 /// between probes ([`allow_turn`](PlaneTuneHold::allow_turn)), in m.
42 pub return_radius_m: f32,
43 /// The bank of that turn, in rad.
44 pub turn_bank_rad: f32,
45 /// What [`recover`](PlaneTuneHold::recover) flies: a hover where the vehicle is
46 /// ([`FlightRegime::Copter`], for a VTOL), or wings level ([`FlightRegime::Plane`]).
47 pub recover_to: FlightRegime,
48}
49
50impl PlaneTuneHoldConfig {
51 /// A hold at `thrust`, trimming pitch toward `trim_airspeed_mps` by 1° per m/s over 5 s
52 /// and within 10° of the start (a pilot's FBWA trim; the sim's airplane held its airspeed
53 /// through a tune this way, and slowed past its minimum within a few steps without it,
54 /// #533), trimming thrust by 0.01 per m below the start over 10 s and within 0.1 (the
55 /// Alia 250 sank 0.2 m/s on its thrust alone, past the envelope's 40 m within 3 minutes,
56 /// #534), turning back at 20° of bank beyond 600 m, and recovering wings level.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// use stable_flight::commanders::PlaneTuneHoldConfig;
62 ///
63 /// let config = PlaneTuneHoldConfig::new(0.55, 18.0);
64 /// assert!(config.validate().is_ok());
65 /// ```
66 pub fn new(thrust: f32, trim_airspeed_mps: f32) -> Self {
67 Self {
68 thrust,
69 thrust_per_m: 0.01,
70 max_thrust_trim: 0.1,
71 thrust_time_constant_s: 10.0,
72 trim_airspeed_mps,
73 pitch_per_mps: DEG,
74 trim_time_constant_s: 5.0,
75 max_trim_rad: 10.0 * DEG,
76 return_radius_m: 600.0,
77 turn_bank_rad: 20.0 * DEG,
78 recover_to: FlightRegime::Plane,
79 }
80 }
81
82 /// Checks that thrust is in `[0, 1]`, its trim's gain and limit non-negative, the
83 /// airspeed, gains, time constants, trim limit, and radius positive, and the turn's bank
84 /// in `(0, 60°]`.
85 pub fn validate(&self) -> Result<(), InvalidConfig> {
86 check("thrust", (0.0..=1.0).contains(&self.thrust), "in [0, 1]")?;
87 check_limit("thrust_per_m", self.thrust_per_m)?;
88 check_limit("max_thrust_trim", self.max_thrust_trim)?;
89 check_positive("thrust_time_constant_s", self.thrust_time_constant_s)?;
90 check_positive("trim_airspeed_mps", self.trim_airspeed_mps)?;
91 check_positive("pitch_per_mps", self.pitch_per_mps)?;
92 check_positive("trim_time_constant_s", self.trim_time_constant_s)?;
93 check_positive("max_trim_rad", self.max_trim_rad)?;
94 check_positive("return_radius_m", self.return_radius_m)?;
95 check(
96 "turn_bank_rad",
97 self.turn_bank_rad > 0.0 && self.turn_bank_rad <= 60.0 * DEG,
98 "in (0, 60°]",
99 )
100 }
101}
102
103/// Flies the steady attitude hold a plane autotune's probes ride on
104/// ([`PlaneAutotune`](crate::tuning::autotune::PlaneAutotune)): wings level, the pitch trimmed
105/// slowly toward trim airspeed and the thrust slowly toward the height it started at, as a
106/// pilot flies ArduPilot's AUTOTUNE in FBWA, holding height with the throttle. A probe's steps
107/// stand out against a hold that doesn't move; a line held by the energy control answers a
108/// pitch step with its own pitch (#533).
109///
110/// - **Start:** the first command holds the attitude and position the vehicle has, wings
111/// level; requests [`FlightRegime::Plane`].
112/// - **Return:** past [`return_radius_m`](PlaneTuneHoldConfig::return_radius_m) from the
113/// start, flying away from it, and only while the host allows it
114/// ([`allow_turn`](Self::allow_turn): between probes), the hold banks toward the start
115/// until it heads within 10° of it, or has turned around (within 10° of reversing its
116/// heading): a start inside the turn's circle stays abeam however long it turns. The host
117/// keeps the supervisor from starting a probe meanwhile
118/// ([`Supervisor::set_maneuvering`](crate::tuning::autotune::Supervisor::set_maneuvering)
119/// with [`turning`](Self::turning)).
120/// - **Recover** ([`recover`](Self::recover), e.g. after an envelope breach): a VTOL hovers
121/// where it is, on its rotors; a plane flies wings level.
122///
123/// # Examples
124///
125/// ```
126/// use stable_flight::commanders::{PlaneTuneHold, PlaneTuneHoldConfig};
127/// use stable_flight::{Commander, ControlInput, FlightRegime, VehicleState};
128///
129/// let mut hold = PlaneTuneHold::new(PlaneTuneHoldConfig::new(0.55, 18.0));
130/// let state = VehicleState { pitch_rad: 0.05, airspeed_mps: Some(18.0), ..Default::default() };
131/// let command = hold.next_command(0.004, &state);
132/// assert_eq!(command.regime, FlightRegime::Plane);
133/// let ControlInput::AbsoluteAttitude(attitude) = command.input else { unreachable!() };
134/// assert_eq!((attitude.roll_rad, attitude.pitch_rad, attitude.thrust), (0.0, 0.05, 0.55));
135/// ```
136#[derive(Clone, Debug, PartialEq)]
137pub struct PlaneTuneHold {
138 config: PlaneTuneHoldConfig,
139 /// Where the hold started: (north, east) and altitude in m, and its pitch then, in rad.
140 start: Option<Start>,
141 /// The pitch the hold flies, in rad: the start's, trimmed for airspeed.
142 pitch_rad: f32,
143 /// The thrust the hold flies: the config's, trimmed for altitude.
144 thrust: f32,
145 turns_allowed: bool,
146 turn: Option<Turn>,
147 recovery: Recovery,
148}
149
150/// Where a [`PlaneTuneHold`] started.
151#[derive(Clone, Copy, Debug, PartialEq)]
152struct Start {
153 /// (north, east), in m.
154 position_m: Vec2,
155 altitude_m: f32,
156 pitch_rad: f32,
157}
158
159/// A turn back under way.
160#[derive(Clone, Copy, Debug, PartialEq)]
161struct Turn {
162 /// The bank, signed (right positive), in rad: its side is fixed when the turn starts.
163 bank_rad: f32,
164 /// The heading the turn started on, in rad.
165 from_heading_rad: f32,
166}
167
168/// Where a [`PlaneTuneHold`]'s recovery stands.
169#[derive(Clone, Copy, Debug, PartialEq)]
170enum Recovery {
171 /// Holding, not recovering.
172 Off,
173 /// Asked for; it fixes its command on the next state.
174 Requested,
175 /// Flying this command.
176 Flying(Command),
177}
178
179/// How close to the start's bearing a turn back ends, in rad.
180const TURN_DONE_RAD: f32 = 10.0 * DEG;
181
182impl PlaneTuneHold {
183 /// A hold with `config`.
184 ///
185 /// # Panics
186 ///
187 /// If `config` is invalid ([`PlaneTuneHoldConfig::validate`]).
188 pub fn new(config: PlaneTuneHoldConfig) -> Self {
189 if let Err(error) = config.validate() {
190 panic!("invalid PlaneTuneHoldConfig: {error}");
191 }
192 Self {
193 config,
194 start: None,
195 pitch_rad: 0.0,
196 thrust: config.thrust,
197 turns_allowed: false,
198 turn: None,
199 recovery: Recovery::Off,
200 }
201 }
202
203 /// Lets the hold turn back toward its start, or not: allow it between probes only. A turn
204 /// already under way finishes either way, so a probe never starts mid-turn as long as the
205 /// host holds probes off while [`turning`](Self::turning).
206 pub fn allow_turn(&mut self, allowed: bool) {
207 self.turns_allowed = allowed;
208 }
209
210 /// Whether the hold is turning back toward its start.
211 pub fn turning(&self) -> bool {
212 self.turn.is_some()
213 }
214
215 /// Ends the hold: from the next command, a VTOL hovers where it is, on its rotors, and a
216 /// plane flies wings level ([`PlaneTuneHoldConfig::recover_to`]).
217 pub fn recover(&mut self) {
218 if self.recovery == Recovery::Off {
219 self.recovery = Recovery::Requested;
220 self.turn = None;
221 }
222 }
223
224 /// Whether [`recover`](Self::recover) was called.
225 pub fn is_recovering(&self) -> bool {
226 self.recovery != Recovery::Off
227 }
228
229 /// Moves the pitch toward the trim for `state`'s airspeed, `dt` on: nose down when slow,
230 /// up when fast, within `max_trim_rad` of `start_pitch_rad`.
231 fn trim(&mut self, dt: f32, state: &VehicleState, start_pitch_rad: f32) {
232 let Some(airspeed_mps) = state.valid_airspeed_mps() else {
233 return;
234 };
235 let config = &self.config;
236 let fast_mps = airspeed_mps - config.trim_airspeed_mps;
237 let target_rad = (start_pitch_rad + fast_mps * config.pitch_per_mps).clamp(
238 start_pitch_rad - config.max_trim_rad,
239 start_pitch_rad + config.max_trim_rad,
240 );
241 self.pitch_rad = lagged(self.pitch_rad, target_rad, dt, config.trim_time_constant_s);
242 }
243
244 /// Moves the thrust toward the trim for `state`'s altitude, `dt` on: more when below
245 /// `start_altitude_m`, less above, within the config's limit, and in `[0, 1]`.
246 fn trim_thrust(&mut self, dt: f32, state: &VehicleState, start_altitude_m: f32) {
247 let config = &self.config;
248 let low_m = start_altitude_m - state.position_m.z;
249 if low_m.is_nan() {
250 return;
251 }
252 let trim = clamp_symmetric(low_m * config.thrust_per_m, config.max_thrust_trim);
253 let target = (config.thrust + trim).clamp(0.0, 1.0);
254 self.thrust = lagged(self.thrust, target, dt, config.thrust_time_constant_s);
255 }
256
257 /// The bank toward the start while turning back, 0 otherwise; starts a turn past the
258 /// return radius, flying away from the start, when turns are allowed, and ends it heading
259 /// within `TURN_DONE_RAD` of the start or of reversing the heading it started on.
260 fn bank_rad(&mut self, state: &VehicleState, start_m: Vec2) -> f32 {
261 let to_start_m = start_m - state.position_m.xy();
262 // Bearing clockwise from north (x north, y east); right bank turns clockwise.
263 let bearing_rad = libm::atan2f(to_start_m.y, to_start_m.x);
264 let heading_error_rad = wrap_angle(bearing_rad - state.heading_rad);
265 let away = heading_error_rad.abs() > FRAC_PI_2;
266 let beyond = to_start_m.norm() > self.config.return_radius_m;
267 if self.turn.is_none() && self.turns_allowed && beyond && away {
268 self.turn = Some(Turn {
269 bank_rad: self.config.turn_bank_rad.copysign(heading_error_rad),
270 from_heading_rad: state.heading_rad,
271 });
272 }
273 let Some(turn) = self.turn else {
274 return 0.0;
275 };
276 let turned_rad = wrap_angle(state.heading_rad - turn.from_heading_rad).abs();
277 let homing = heading_error_rad.abs() < TURN_DONE_RAD;
278 let reversed = turned_rad > PI - TURN_DONE_RAD;
279 if homing || reversed || heading_error_rad.is_nan() || turned_rad.is_nan() {
280 self.turn = None;
281 return 0.0;
282 }
283 turn.bank_rad
284 }
285
286 /// The command a recovery flies, fixed where it began: a hover at the vehicle's position
287 /// and altitude, or wings level at the hold's pitch.
288 fn recovery_command(&self, state: &VehicleState) -> Command {
289 match self.config.recover_to {
290 FlightRegime::Copter => Command::new(
291 true,
292 ControlInput::Waypoint(WaypointCommand {
293 position_m: state.position_m.xy(),
294 altitude_m: state.position_m.z,
295 ..Default::default()
296 }),
297 )
298 .with_regime(FlightRegime::Copter),
299 FlightRegime::Plane => self.attitude(0.0),
300 }
301 }
302
303 fn attitude(&self, roll_rad: f32) -> Command {
304 Command::new(
305 true,
306 ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
307 roll_rad,
308 pitch_rad: self.pitch_rad,
309 heading_rad: 0.0,
310 thrust: self.thrust,
311 }),
312 )
313 .with_regime(FlightRegime::Plane)
314 }
315}
316
317impl Commander for PlaneTuneHold {
318 fn next_command(&mut self, dt: f32, state: &VehicleState) -> Command {
319 match self.recovery {
320 Recovery::Off => {}
321 Recovery::Requested => {
322 let command = self.recovery_command(state);
323 self.recovery = Recovery::Flying(command);
324 return command;
325 }
326 Recovery::Flying(command) => return command,
327 }
328 let start = *self.start.get_or_insert_with(|| {
329 self.pitch_rad = state.pitch_rad;
330 Start {
331 position_m: state.position_m.xy(),
332 altitude_m: state.position_m.z,
333 pitch_rad: state.pitch_rad,
334 }
335 });
336 self.trim(dt, state, start.pitch_rad);
337 self.trim_thrust(dt, state, start.altitude_m);
338 let roll_rad = self.bank_rad(state, start.position_m);
339 self.attitude(roll_rad)
340 }
341}