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