Skip to main content

stable_flight/commanders/
failsafe.rs

1//! Falling back when a link-fed commander goes quiet: see [`FailsafeCommander`].
2//!
3//! A companion computer's link drops (late USB enumeration, a brownout, a crashed bridge), and
4//! the flight controller, not the companion, decides what happens then. The primary commander
5//! reports how long ago it last heard the link ([`LinkedCommander`]); when that exceeds a
6//! timeout, a [`Fallback`] such as [`HoldCommander`] flies until the link has been back long
7//! enough.
8
9use crate::commanders::{TouchdownConfig, TouchdownDetector};
10use crate::controllers::{InvalidConfig, check_limit, check_positive};
11use crate::{
12    Command, Commander, ControlInput, ControlMode, FailsafeState, FlightRegime, LandCommand, Vec2,
13    VehicleState, WaypointCommand,
14};
15
16#[cfg(test)]
17mod tests;
18
19/// A [`Commander`] fed by a link, which knows how long ago it last heard it.
20pub trait LinkedCommander: Commander {
21    /// Seconds since the last valid message, as of the last
22    /// [`next_command`](Commander::next_command) call; `None` if none has arrived. Measured on
23    /// this side from the `dt` the commander is given, so it needs no clock from the sender.
24    fn since_update_s(&self) -> Option<f32>;
25
26    /// Sets the arm state this commander reports to `armed`. A [`FailsafeCommander`] calls it
27    /// when it hands control back, with the vehicle's actual arm state, so an arm request this
28    /// commander latched while the fallback flew (and that the vehicle never acted on) is
29    /// dropped rather than arming the vehicle at the handover.
30    fn sync_arm(&mut self, armed: bool);
31
32    /// Sets the regime this commander requests to `regime`. A [`FailsafeCommander`] calls it
33    /// when it hands control back, with the regime the fallback flew, so a regime request from
34    /// before the link went quiet (or latched while the fallback flew) is dropped rather than
35    /// transitioning the vehicle at the handover.
36    fn sync_regime(&mut self, regime: FlightRegime);
37}
38
39/// A [`Commander`] that flies while a [`FailsafeCommander`]'s primary is stale.
40pub trait Fallback: Commander {
41    /// The failsafe switched to this fallback, with the vehicle in `state` and `last` the
42    /// command that flew the tick before (disarmed and neutral before the first tick), so a
43    /// fallback can keep its arm state or finish what it was doing, e.g. a land. Called once
44    /// per switch, before this tick's [`next_command`](Commander::next_command). The default
45    /// does nothing.
46    fn engage(&mut self, state: &VehicleState, last: &Command) {
47        let _ = (state, last);
48    }
49
50    /// Whether the primary may take over again once fresh. `false` keeps the fallback flying,
51    /// e.g. a landing that must finish. The default always releases.
52    fn can_release(&self) -> bool {
53        true
54    }
55}
56
57/// When a [`FailsafeCommander`] falls back, and when it returns.
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct FailsafeConfig {
60    /// The primary is stale once this many seconds pass without a message. Must be positive
61    /// and finite.
62    pub timeout_s: f32,
63    /// The primary takes over again only after it has been fresh this long without a break,
64    /// so a flapping link doesn't toggle control. Must be non-negative and finite.
65    pub recover_after_s: f32,
66    /// How far a stick axis (normalized) must move before the primary's sticks take back an
67    /// armed vehicle from the fallback, so a forgotten joystick resending the same positions
68    /// can't drop the vehicle out of a hold. Must be positive and finite.
69    pub takeover_stick_delta: f32,
70    /// When a land the primary flies has touched down, and the vehicle disarms.
71    pub touchdown: TouchdownConfig,
72}
73
74impl Default for FailsafeConfig {
75    /// Fall back after 1 s without a message; return after 1 s of messages, sticks once one axis
76    /// has moved 0.1; touchdown per [`TouchdownConfig::default`].
77    fn default() -> Self {
78        Self {
79            timeout_s: 1.0,
80            recover_after_s: 1.0,
81            takeover_stick_delta: 0.1,
82            touchdown: TouchdownConfig::default(),
83        }
84    }
85}
86
87impl FailsafeConfig {
88    /// Checks the documented requirements of every field, and the touchdown config
89    /// ([`TouchdownConfig::validate`], section `touchdown`).
90    ///
91    /// # Errors
92    ///
93    /// [`InvalidConfig`] naming the first field out of range.
94    pub fn validate(&self) -> Result<(), InvalidConfig> {
95        check_positive("timeout_s", self.timeout_s)?;
96        check_limit("recover_after_s", self.recover_after_s)?;
97        check_positive("takeover_stick_delta", self.takeover_stick_delta)?;
98        self.touchdown
99            .validate()
100            .map_err(|e| e.in_section("touchdown"))
101    }
102}
103
104/// Flies a link-fed `primary` while it is fresh, and a `fallback` otherwise.
105///
106/// - **Starts in the fallback**: until the primary is heard, nothing it says is trusted.
107/// - **Falls back** as soon as the primary has gone [`timeout_s`](FailsafeConfig::timeout_s)
108///   without a message, [engaging](Fallback::engage) the fallback with the current state and
109///   arm state.
110/// - **Returns** once the primary has been fresh for
111///   [`recover_after_s`](FailsafeConfig::recover_after_s) without a break and the fallback
112///   [can release](Fallback::can_release). To an **armed** vehicle, sticks (an attitude or rate
113///   command) take over only once an axis has moved
114///   [`takeover_stick_delta`](FailsafeConfig::takeover_stick_delta) from where it was when the
115///   primary recovered, so a joystick left at low throttle can't drop the vehicle out of a hold;
116///   a waypoint, or anything to a disarmed vehicle, takes over at once.
117/// - **At the handover**, the primary's arm state is [synced](LinkedCommander::sync_arm) to the
118///   vehicle's (disarmed if either the vehicle or the primary is), so an arm request made while
119///   the fallback flew doesn't arm the vehicle; a new one does. Its regime is
120///   [synced](LinkedCommander::sync_regime) to the one the fallback flew (a [`HoldCommander`]
121///   flies [`FlightRegime::Copter`]), so a VTOL brought back to a hover stays there until the
122///   primary requests plane again.
123/// - **Arming:** the fallback may keep the vehicle armed or disarm it, but never arms it (a
124///   [`HoldCommander`] keeps the arm state it was engaged with), and a fresh primary's disarm
125///   is always honored, even while it waits to take over.
126/// - **Landing:** while an armed land ([`ControlInput::Land`]) flies, from either commander, a
127///   [`TouchdownDetector`] watches it. On touchdown the vehicle disarms and the primary's arm is
128///   [synced](LinkedCommander::sync_arm) to it, so it stays disarmed until the primary arms
129///   again. A land that carries on across a handover (a [`HoldCommander`] finishes the
130///   primary's land when the link drops) keeps its detector; anything else (a hold, a
131///   disarm, another input) starts it over, so a hold that follows a descent can't read as
132///   touchdown.
133///
134/// The primary runs every tick, flying or not, so it keeps draining its link and timing its
135/// freshness. [`failsafe`](Commander::failsafe) reports which commander flew.
136///
137/// # Examples
138///
139/// ```
140/// use stable_flight::commanders::{
141///     FailsafeCommander, FailsafeConfig, HoldCommander, LinkedCommander,
142/// };
143/// use stable_flight::{Command, Commander, FailsafeState, FlightRegime, VehicleState};
144///
145/// /// A link that was last heard `since_s` ago.
146/// struct Link {
147///     since_s: Option<f32>,
148/// }
149///
150/// impl Commander for Link {
151///     fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
152///         Command::default()
153///     }
154/// }
155///
156/// impl LinkedCommander for Link {
157///     fn since_update_s(&self) -> Option<f32> {
158///         self.since_s
159///     }
160///
161///     fn sync_arm(&mut self, _armed: bool) {}
162///
163///     fn sync_regime(&mut self, _regime: FlightRegime) {}
164/// }
165///
166/// let link = Link { since_s: None };
167/// let mut commander =
168///     FailsafeCommander::new(link, HoldCommander::default(), FailsafeConfig::default())?;
169/// commander.next_command(0.004, &VehicleState::default());
170/// assert_eq!(commander.failsafe(), Some(FailsafeState::Fallback)); // never heard
171/// # Ok::<(), stable_flight::controllers::InvalidConfig>(())
172/// ```
173#[derive(Debug)]
174pub struct FailsafeCommander<P, F> {
175    primary: P,
176    fallback: F,
177    config: FailsafeConfig,
178    /// Which commander flew the last tick; `None` before the first.
179    state: Option<FailsafeState>,
180    /// How long the primary has been fresh without a break, while the fallback flies.
181    fresh_for_s: f32,
182    /// The last command flown, to engage the fallback with.
183    last: Command,
184    /// The primary's sticks when it recovered over an armed vehicle, waiting to move before
185    /// they take over.
186    takeover_reference: Option<ControlInput>,
187    /// Watches a land the primary flies.
188    touchdown: TouchdownDetector,
189}
190
191impl<P: LinkedCommander, F: Fallback> FailsafeCommander<P, F> {
192    /// Flies `primary`, falling back to `fallback` per `config`.
193    ///
194    /// # Errors
195    ///
196    /// [`InvalidConfig`] if `config` fails [`FailsafeConfig::validate`].
197    pub fn new(primary: P, fallback: F, config: FailsafeConfig) -> Result<Self, InvalidConfig> {
198        config.validate()?;
199        let touchdown = TouchdownDetector::new(config.touchdown)?;
200        Ok(Self {
201            primary,
202            fallback,
203            config,
204            state: None,
205            fresh_for_s: 0.0,
206            last: Command::default(),
207            takeover_reference: None,
208            touchdown,
209        })
210    }
211
212    /// The primary commander.
213    pub fn primary(&self) -> &P {
214        &self.primary
215    }
216
217    /// The fallback commander.
218    pub fn fallback(&self) -> &F {
219        &self.fallback
220    }
221
222    /// Switches to the fallback.
223    fn fall_back(&mut self, state: &VehicleState) {
224        self.state = Some(FailsafeState::Fallback);
225        self.fresh_for_s = 0.0;
226        self.takeover_reference = None;
227        self.fallback.engage(state, &self.last);
228    }
229
230    /// Whether the recovered primary, flying `input`, may take over now: at once, unless it
231    /// flies sticks over an armed vehicle, which must first move.
232    fn may_take_over(&mut self, input: &ControlInput) -> bool {
233        if !self.last.arm || !input.is_sticks() {
234            return true;
235        }
236        let reference = *self.takeover_reference.get_or_insert(*input);
237        sticks_moved(&reference, input, self.config.takeover_stick_delta)
238    }
239
240    /// `command`, disarmed (with the primary synced) once the armed land it flies touches down.
241    /// Anything but an armed land starts the detector over.
242    fn disarm_on_touchdown(&mut self, dt: f32, state: &VehicleState, command: Command) -> Command {
243        if !command.arm || command.input.mode() != ControlMode::Land {
244            self.touchdown.reset();
245            return command;
246        }
247        if !self.touchdown.update(dt, state.velocity_mps.z) {
248            return command;
249        }
250        self.primary.sync_arm(false);
251        Command {
252            arm: false,
253            ..command
254        }
255    }
256
257    /// Decides who flies this tick, given whether the primary is `fresh` and what it flies.
258    /// Returns whether the primary took over this tick.
259    fn update_state(
260        &mut self,
261        fresh: bool,
262        dt: f32,
263        input: &ControlInput,
264        state: &VehicleState,
265    ) -> bool {
266        match self.state {
267            Some(FailsafeState::Primary) if fresh => return false,
268            None | Some(FailsafeState::Primary) => self.fall_back(state),
269            _ => {}
270        }
271        // The fallback flies: is the primary back, and may it take over?
272        self.fresh_for_s = if fresh { self.fresh_for_s + dt } else { 0.0 };
273        let recovered =
274            fresh && self.fresh_for_s >= self.config.recover_after_s && self.fallback.can_release();
275        if !recovered {
276            self.state = Some(FailsafeState::Fallback);
277            self.takeover_reference = None;
278            return false;
279        }
280        if !self.may_take_over(input) {
281            self.state = Some(FailsafeState::AwaitingSticks);
282            return false;
283        }
284        self.state = Some(FailsafeState::Primary);
285        self.takeover_reference = None;
286        true
287    }
288}
289
290impl<P: LinkedCommander, F: Fallback> Commander for FailsafeCommander<P, F> {
291    fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
292        let primary = self.primary.next_command(dt, current_state);
293        let fresh = self
294            .primary
295            .since_update_s()
296            .is_some_and(|s| s <= self.config.timeout_s);
297
298        let handed_over = self.update_state(fresh, dt, &primary.input, current_state);
299
300        let command = if self.state == Some(FailsafeState::Primary) {
301            if handed_over {
302                // Drop an arm the primary latched while the fallback flew; keep its disarm.
303                let armed = self.last.arm && primary.arm;
304                self.primary.sync_arm(armed);
305                // Keep flying the fallback's regime until the primary asks for another.
306                self.primary.sync_regime(self.last.regime);
307                Command::new(armed, primary.input).with_regime(self.last.regime)
308            } else {
309                primary
310            }
311        } else {
312            let mut command = self.fallback.next_command(dt, current_state);
313            // The fallback never arms, and a disarm from any source is honored.
314            command.arm &= self.last.arm && (!fresh || primary.arm);
315            command
316        };
317        let command = self.disarm_on_touchdown(dt, current_state, command);
318        self.last = command;
319        command
320    }
321
322    fn failsafe(&self) -> Option<FailsafeState> {
323        self.state
324    }
325}
326
327/// Whether the sticks in `now` moved more than `delta` on any axis from `reference`; a change of
328/// kind (attitude ↔ rate) counts. A NaN axis never counts as moved.
329fn sticks_moved(reference: &ControlInput, now: &ControlInput, delta: f32) -> bool {
330    let moved = |a: f32, b: f32| (a - b).abs() > delta;
331    match (reference, now) {
332        (ControlInput::Attitude(a), ControlInput::Attitude(b)) => {
333            moved(a.throttle, b.throttle)
334                || moved(a.roll, b.roll)
335                || moved(a.pitch, b.pitch)
336                || moved(a.yaw, b.yaw)
337        }
338        (ControlInput::Rate(a), ControlInput::Rate(b)) => {
339            moved(a.throttle, b.throttle)
340                || moved(a.roll_rate, b.roll_rate)
341                || moved(a.pitch_rate, b.pitch_rate)
342                || moved(a.yaw_rate, b.yaw_rate)
343        }
344        _ => true,
345    }
346}
347
348/// [`HoldCommander`]'s default speed back to the hold point, in m/s.
349pub const DEFAULT_HOLD_SPEED_MPS: f32 = 2.0;
350
351/// A [`Fallback`] that holds position: when engaged, it latches where the vehicle is
352/// (horizontal position and altitude) and its arm state, then flies a waypoint there, at most
353/// [`cruise_speed_mps`](Self::new) back to it after any drift. It never arms a disarmed
354/// vehicle.
355///
356/// Engaged during an armed land ([`ControlInput::Land`]), it [finishes that
357/// land](Self::is_landing) at the same position instead, as PX4 does when the link drops
358/// mid-land; the [`FailsafeCommander`] disarms on touchdown.
359///
360/// It needs a position estimate. While the position isn't finite it retries the latch each
361/// tick, flying a NaN waypoint meanwhile, which guidance treats as level at hover thrust (the
362/// input policy). A vehicle without position needs a landing fallback instead.
363///
364/// # Examples
365///
366/// ```
367/// use stable_flight::commanders::{Fallback, HoldCommander};
368/// use stable_flight::{Command, Commander, ControlInput, LandCommand, Vec2, VehicleState};
369///
370/// let state = VehicleState { position_m: [3.0, 4.0, 10.0].into(), ..Default::default() };
371/// let hovering = Command::new(true, ControlInput::Waypoint(Default::default()));
372/// let mut hold = HoldCommander::default();
373/// hold.engage(&state, &hovering);
374///
375/// let command = hold.next_command(0.004, &VehicleState::default());
376/// assert!(command.arm);
377/// let ControlInput::Waypoint(waypoint) = command.input else { panic!("a waypoint") };
378/// assert_eq!((waypoint.position_m.x, waypoint.altitude_m), (3.0, 10.0));
379///
380/// let land = LandCommand { position_m: Vec2::new(1.0, 2.0) };
381/// let landing = Command::new(true, ControlInput::Land(land));
382/// hold.engage(&state, &landing);
383/// assert!(hold.is_landing());
384/// assert_eq!(hold.next_command(0.004, &state).input, landing.input);
385/// ```
386#[derive(Debug, Clone)]
387pub struct HoldCommander {
388    cruise_speed_mps: f32,
389    hold: Option<WaypointCommand>,
390    /// The land it finishes instead of holding.
391    land: Option<LandCommand>,
392    armed: bool,
393}
394
395impl Default for HoldCommander {
396    /// Holds at [`DEFAULT_HOLD_SPEED_MPS`].
397    fn default() -> Self {
398        Self {
399            cruise_speed_mps: DEFAULT_HOLD_SPEED_MPS,
400            hold: None,
401            land: None,
402            armed: false,
403        }
404    }
405}
406
407impl HoldCommander {
408    /// Holds, flying back to the hold point at most `cruise_speed_mps`.
409    ///
410    /// # Errors
411    ///
412    /// [`InvalidConfig`] unless `cruise_speed_mps` is positive and finite.
413    pub fn new(cruise_speed_mps: f32) -> Result<Self, InvalidConfig> {
414        check_positive("cruise_speed_mps", cruise_speed_mps)?;
415        Ok(Self {
416            cruise_speed_mps,
417            ..Self::default()
418        })
419    }
420
421    /// Whether it finishes a land rather than holding: it was engaged during an armed land.
422    pub fn is_landing(&self) -> bool {
423        self.land.is_some()
424    }
425
426    /// Latches `state`'s position as the hold point, if it is finite.
427    fn latch(&mut self, state: &VehicleState) {
428        let p = state.position_m;
429        self.hold = p.iter().all(|c| c.is_finite()).then(|| WaypointCommand {
430            position_m: p.xy(),
431            altitude_m: p.z,
432            cruise_speed_mps: self.cruise_speed_mps,
433            ..Default::default()
434        });
435    }
436}
437
438impl Commander for HoldCommander {
439    fn next_command(&mut self, _dt: f32, current_state: &VehicleState) -> Command {
440        if let Some(land) = self.land {
441            return Command::new(self.armed, ControlInput::Land(land));
442        }
443        if self.hold.is_none() {
444            self.latch(current_state);
445        }
446        let waypoint = self.hold.unwrap_or(WaypointCommand {
447            position_m: Vec2::repeat(f32::NAN),
448            altitude_m: f32::NAN,
449            cruise_speed_mps: self.cruise_speed_mps,
450            ..Default::default()
451        });
452        Command::new(self.armed, ControlInput::Waypoint(waypoint))
453    }
454}
455
456impl Fallback for HoldCommander {
457    fn engage(&mut self, state: &VehicleState, last: &Command) {
458        self.armed = last.arm;
459        self.land = match last.input {
460            ControlInput::Land(land) if last.arm => Some(land),
461            _ => None,
462        };
463        self.latch(state);
464    }
465}