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