stable-flight 0.2.0

no_std autopilot core for Stable Flight: copter, plane, tailsitter, and quadplane guidance and stabilizers, waypoint navigation, failsafe, autotune, mixers, and the per-tick flight loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Falling back when a link-fed commander goes quiet: see [`FailsafeCommander`].
//!
//! A companion computer's link drops (late USB enumeration, a brownout, a crashed bridge), and
//! the flight controller, not the companion, decides what happens then. The primary commander
//! reports how long ago it last heard the link ([`LinkedCommander`]); when that exceeds a
//! timeout, a [`Fallback`] such as [`HoldCommander`] flies until the link has been back long
//! enough.

use crate::commanders::TouchdownDetector;
use crate::controllers::{InvalidConfig, check_limit, check_positive};
use crate::{
    Command, Commander, ControlInput, ControlMode, FailsafeState, FlightRegime, LandCommand, Vec2,
    VehicleState, WaypointCommand,
};

#[cfg(test)]
mod tests;

/// A [`Commander`] fed by a link, which knows how long ago it last heard it.
pub trait LinkedCommander: Commander {
    /// Seconds since the last valid message, as of the last
    /// [`next_command`](Commander::next_command) call; `None` if none has arrived. Measured on
    /// this side from the `dt` the commander is given, so it needs no clock from the sender.
    fn since_update_s(&self) -> Option<f32>;

    /// Sets the arm state this commander reports to `armed`. A [`FailsafeCommander`] calls it
    /// when it hands control back, with the vehicle's actual arm state, so an arm request this
    /// commander latched while the fallback flew (and that the vehicle never acted on) is
    /// dropped rather than arming the vehicle at the handover.
    fn sync_arm(&mut self, armed: bool);

    /// Sets the regime this commander requests to `regime`. A [`FailsafeCommander`] calls it
    /// when it hands control back, with the regime the fallback flew, so a regime request from
    /// before the link went quiet (or latched while the fallback flew) is dropped rather than
    /// transitioning the vehicle at the handover.
    fn sync_regime(&mut self, regime: FlightRegime);
}

/// A [`Commander`] that flies while a [`FailsafeCommander`]'s primary is stale.
pub trait Fallback: Commander {
    /// The failsafe switched to this fallback, with the vehicle in `state` and `last` the
    /// command that flew the tick before (disarmed and neutral before the first tick), so a
    /// fallback can keep its arm state or finish what it was doing, e.g. a land. Called once
    /// per switch, before this tick's [`next_command`](Commander::next_command). The default
    /// does nothing.
    fn engage(&mut self, state: &VehicleState, last: &Command) {
        let _ = (state, last);
    }

    /// Whether the primary may take over again once fresh. `false` keeps the fallback flying,
    /// e.g. a landing that must finish. The default always releases.
    fn can_release(&self) -> bool {
        true
    }
}

/// When a [`FailsafeCommander`] falls back, and when it returns.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FailsafeConfig {
    /// The primary is stale once this many seconds pass without a message. Must be positive
    /// and finite.
    pub timeout_s: f32,
    /// The primary takes over again only after it has been fresh this long without a break,
    /// so a flapping link doesn't toggle control. Must be non-negative and finite.
    pub recover_after_s: f32,
    /// How far a stick axis (normalized) must move before the primary's sticks take back an
    /// armed vehicle from the fallback, so a forgotten joystick resending the same positions
    /// can't drop the vehicle out of a hold. Must be positive and finite.
    pub takeover_stick_delta: f32,
}

impl Default for FailsafeConfig {
    /// Fall back after 1 s without a message; return after 1 s of messages, sticks once one axis
    /// has moved 0.1.
    fn default() -> Self {
        Self {
            timeout_s: 1.0,
            recover_after_s: 1.0,
            takeover_stick_delta: 0.1,
        }
    }
}

impl FailsafeConfig {
    /// Checks the documented requirements of every field.
    ///
    /// # Errors
    ///
    /// [`InvalidConfig`] naming the first field out of range.
    pub fn validate(&self) -> Result<(), InvalidConfig> {
        check_positive("timeout_s", self.timeout_s)?;
        check_limit("recover_after_s", self.recover_after_s)?;
        check_positive("takeover_stick_delta", self.takeover_stick_delta)
    }
}

/// Flies a link-fed `primary` while it is fresh, and a `fallback` otherwise.
///
/// - **Starts in the fallback**: until the primary is heard, nothing it says is trusted.
/// - **Falls back** as soon as the primary has gone [`timeout_s`](FailsafeConfig::timeout_s)
///   without a message, [engaging](Fallback::engage) the fallback with the current state and
///   arm state.
/// - **Returns** once the primary has been fresh for
///   [`recover_after_s`](FailsafeConfig::recover_after_s) without a break and the fallback
///   [can release](Fallback::can_release). To an **armed** vehicle, sticks (an attitude or rate
///   command) take over only once an axis has moved
///   [`takeover_stick_delta`](FailsafeConfig::takeover_stick_delta) from where it was when the
///   primary recovered, so a joystick left at low throttle can't drop the vehicle out of a hold;
///   a waypoint, or anything to a disarmed vehicle, takes over at once.
/// - **At the handover**, the primary's arm state is [synced](LinkedCommander::sync_arm) to the
///   vehicle's (disarmed if either the vehicle or the primary is), so an arm request made while
///   the fallback flew doesn't arm the vehicle; a new one does. Its regime is
///   [synced](LinkedCommander::sync_regime) to the one the fallback flew (a [`HoldCommander`]
///   flies [`FlightRegime::Copter`]), so a VTOL brought back to a hover stays there until the
///   primary requests plane again.
/// - **Arming:** the fallback may keep the vehicle armed or disarm it, but never arms it (a
///   [`HoldCommander`] keeps the arm state it was engaged with), and a fresh primary's disarm
///   is always honored, even while it waits to take over.
/// - **Landing:** while an armed land ([`ControlInput::Land`]) flies, from either commander, a
///   [`TouchdownDetector`] watches it. On touchdown the vehicle disarms and the primary's arm is
///   [synced](LinkedCommander::sync_arm) to it, so it stays disarmed until the primary arms
///   again. A land that carries on across a handover (a [`HoldCommander`] finishes the
///   primary's land when the link drops) keeps its detector; anything else (a hold, a
///   disarm, another input) starts it over, so a hold that follows a descent can't read as
///   touchdown.
///
/// The primary runs every tick, flying or not, so it keeps draining its link and timing its
/// freshness. [`failsafe`](Commander::failsafe) reports which commander flew.
///
/// # Examples
///
/// ```
/// use stable_flight::commanders::{
///     FailsafeCommander, FailsafeConfig, HoldCommander, LinkedCommander,
/// };
/// use stable_flight::{Command, Commander, FailsafeState, FlightRegime, VehicleState};
///
/// /// A link that was last heard `since_s` ago.
/// struct Link {
///     since_s: Option<f32>,
/// }
///
/// impl Commander for Link {
///     fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
///         Command::default()
///     }
/// }
///
/// impl LinkedCommander for Link {
///     fn since_update_s(&self) -> Option<f32> {
///         self.since_s
///     }
///
///     fn sync_arm(&mut self, _armed: bool) {}
///
///     fn sync_regime(&mut self, _regime: FlightRegime) {}
/// }
///
/// let link = Link { since_s: None };
/// let mut commander =
///     FailsafeCommander::new(link, HoldCommander::default(), FailsafeConfig::default())?;
/// commander.next_command(0.004, &VehicleState::default());
/// assert_eq!(commander.failsafe(), Some(FailsafeState::Fallback)); // never heard
/// # Ok::<(), stable_flight::controllers::InvalidConfig>(())
/// ```
#[derive(Debug)]
pub struct FailsafeCommander<P, F> {
    primary: P,
    fallback: F,
    config: FailsafeConfig,
    /// Which commander flew the last tick; `None` before the first.
    state: Option<FailsafeState>,
    /// How long the primary has been fresh without a break, while the fallback flies.
    fresh_for_s: f32,
    /// The last command flown, to engage the fallback with.
    last: Command,
    /// The primary's sticks when it recovered over an armed vehicle, waiting to move before
    /// they take over.
    takeover_reference: Option<ControlInput>,
    /// Watches a land the primary flies.
    touchdown: TouchdownDetector,
}

impl<P: LinkedCommander, F: Fallback> FailsafeCommander<P, F> {
    /// Flies `primary`, falling back to `fallback` per `config`.
    ///
    /// # Errors
    ///
    /// [`InvalidConfig`] if `config` fails [`FailsafeConfig::validate`].
    pub fn new(primary: P, fallback: F, config: FailsafeConfig) -> Result<Self, InvalidConfig> {
        config.validate()?;
        Ok(Self {
            primary,
            fallback,
            config,
            state: None,
            fresh_for_s: 0.0,
            last: Command::default(),
            takeover_reference: None,
            touchdown: TouchdownDetector::default(),
        })
    }

    /// The primary commander.
    pub fn primary(&self) -> &P {
        &self.primary
    }

    /// The fallback commander.
    pub fn fallback(&self) -> &F {
        &self.fallback
    }

    /// Switches to the fallback.
    fn fall_back(&mut self, state: &VehicleState) {
        self.state = Some(FailsafeState::Fallback);
        self.fresh_for_s = 0.0;
        self.takeover_reference = None;
        self.fallback.engage(state, &self.last);
    }

    /// Whether the recovered primary, flying `input`, may take over now: at once, unless it
    /// flies sticks over an armed vehicle, which must first move.
    fn may_take_over(&mut self, input: &ControlInput) -> bool {
        if !self.last.arm || !input.is_sticks() {
            return true;
        }
        let reference = *self.takeover_reference.get_or_insert(*input);
        sticks_moved(&reference, input, self.config.takeover_stick_delta)
    }

    /// `command`, disarmed (with the primary synced) once the armed land it flies touches down.
    /// Anything but an armed land starts the detector over.
    fn disarm_on_touchdown(&mut self, dt: f32, state: &VehicleState, command: Command) -> Command {
        if !command.arm || command.input.mode() != ControlMode::Land {
            self.touchdown.reset();
            return command;
        }
        if !self.touchdown.update(dt, state.velocity_mps.z) {
            return command;
        }
        self.primary.sync_arm(false);
        Command {
            arm: false,
            ..command
        }
    }

    /// Decides who flies this tick, given whether the primary is `fresh` and what it flies.
    /// Returns whether the primary took over this tick.
    fn update_state(
        &mut self,
        fresh: bool,
        dt: f32,
        input: &ControlInput,
        state: &VehicleState,
    ) -> bool {
        match self.state {
            Some(FailsafeState::Primary) if fresh => return false,
            None | Some(FailsafeState::Primary) => self.fall_back(state),
            _ => {}
        }
        // The fallback flies: is the primary back, and may it take over?
        self.fresh_for_s = if fresh { self.fresh_for_s + dt } else { 0.0 };
        let recovered =
            fresh && self.fresh_for_s >= self.config.recover_after_s && self.fallback.can_release();
        if !recovered {
            self.state = Some(FailsafeState::Fallback);
            self.takeover_reference = None;
            return false;
        }
        if !self.may_take_over(input) {
            self.state = Some(FailsafeState::AwaitingSticks);
            return false;
        }
        self.state = Some(FailsafeState::Primary);
        self.takeover_reference = None;
        true
    }
}

impl<P: LinkedCommander, F: Fallback> Commander for FailsafeCommander<P, F> {
    fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
        let primary = self.primary.next_command(dt, current_state);
        let fresh = self
            .primary
            .since_update_s()
            .is_some_and(|s| s <= self.config.timeout_s);

        let handed_over = self.update_state(fresh, dt, &primary.input, current_state);

        let command = if self.state == Some(FailsafeState::Primary) {
            if handed_over {
                // Drop an arm the primary latched while the fallback flew; keep its disarm.
                let armed = self.last.arm && primary.arm;
                self.primary.sync_arm(armed);
                // Keep flying the fallback's regime until the primary asks for another.
                self.primary.sync_regime(self.last.regime);
                Command::new(armed, primary.input).with_regime(self.last.regime)
            } else {
                primary
            }
        } else {
            let mut command = self.fallback.next_command(dt, current_state);
            // The fallback never arms, and a disarm from any source is honored.
            command.arm &= self.last.arm && (!fresh || primary.arm);
            command
        };
        let command = self.disarm_on_touchdown(dt, current_state, command);
        self.last = command;
        command
    }

    fn failsafe(&self) -> Option<FailsafeState> {
        self.state
    }
}

/// Whether the sticks in `now` moved more than `delta` on any axis from `reference`; a change of
/// kind (attitude ↔ rate) counts. A NaN axis never counts as moved.
fn sticks_moved(reference: &ControlInput, now: &ControlInput, delta: f32) -> bool {
    let moved = |a: f32, b: f32| (a - b).abs() > delta;
    match (reference, now) {
        (ControlInput::Attitude(a), ControlInput::Attitude(b)) => {
            moved(a.throttle, b.throttle)
                || moved(a.roll, b.roll)
                || moved(a.pitch, b.pitch)
                || moved(a.yaw, b.yaw)
        }
        (ControlInput::Rate(a), ControlInput::Rate(b)) => {
            moved(a.throttle, b.throttle)
                || moved(a.roll_rate, b.roll_rate)
                || moved(a.pitch_rate, b.pitch_rate)
                || moved(a.yaw_rate, b.yaw_rate)
        }
        _ => true,
    }
}

/// [`HoldCommander`]'s default speed back to the hold point, in m/s.
pub const DEFAULT_HOLD_SPEED_MPS: f32 = 2.0;

/// A [`Fallback`] that holds position: when engaged, it latches where the vehicle is
/// (horizontal position and altitude) and its arm state, then flies a waypoint there, at most
/// [`cruise_speed_mps`](Self::new) back to it after any drift. It never arms a disarmed
/// vehicle.
///
/// Engaged during an armed land ([`ControlInput::Land`]), it [finishes that
/// land](Self::is_landing) at the same position instead, as PX4 does when the link drops
/// mid-land; the [`FailsafeCommander`] disarms on touchdown.
///
/// It needs a position estimate. While the position isn't finite it retries the latch each
/// tick, flying a NaN waypoint meanwhile, which guidance treats as level at hover thrust (the
/// input policy). A vehicle without position needs a landing fallback instead.
///
/// # Examples
///
/// ```
/// use stable_flight::commanders::{Fallback, HoldCommander};
/// use stable_flight::{Command, Commander, ControlInput, LandCommand, Vec2, VehicleState};
///
/// let state = VehicleState { position_m: [3.0, 4.0, 10.0].into(), ..Default::default() };
/// let hovering = Command::new(true, ControlInput::Waypoint(Default::default()));
/// let mut hold = HoldCommander::default();
/// hold.engage(&state, &hovering);
///
/// let command = hold.next_command(0.004, &VehicleState::default());
/// assert!(command.arm);
/// let ControlInput::Waypoint(waypoint) = command.input else { panic!("a waypoint") };
/// assert_eq!((waypoint.position_m.x, waypoint.altitude_m), (3.0, 10.0));
///
/// let land = LandCommand { position_m: Vec2::new(1.0, 2.0) };
/// let landing = Command::new(true, ControlInput::Land(land));
/// hold.engage(&state, &landing);
/// assert!(hold.is_landing());
/// assert_eq!(hold.next_command(0.004, &state).input, landing.input);
/// ```
#[derive(Debug, Clone)]
pub struct HoldCommander {
    cruise_speed_mps: f32,
    hold: Option<WaypointCommand>,
    /// The land it finishes instead of holding.
    land: Option<LandCommand>,
    armed: bool,
}

impl Default for HoldCommander {
    /// Holds at [`DEFAULT_HOLD_SPEED_MPS`].
    fn default() -> Self {
        Self {
            cruise_speed_mps: DEFAULT_HOLD_SPEED_MPS,
            hold: None,
            land: None,
            armed: false,
        }
    }
}

impl HoldCommander {
    /// Holds, flying back to the hold point at most `cruise_speed_mps`.
    ///
    /// # Errors
    ///
    /// [`InvalidConfig`] unless `cruise_speed_mps` is positive and finite.
    pub fn new(cruise_speed_mps: f32) -> Result<Self, InvalidConfig> {
        check_positive("cruise_speed_mps", cruise_speed_mps)?;
        Ok(Self {
            cruise_speed_mps,
            ..Self::default()
        })
    }

    /// Whether it finishes a land rather than holding: it was engaged during an armed land.
    pub fn is_landing(&self) -> bool {
        self.land.is_some()
    }

    /// Latches `state`'s position as the hold point, if it is finite.
    fn latch(&mut self, state: &VehicleState) {
        let p = state.position_m;
        self.hold = p.iter().all(|c| c.is_finite()).then(|| WaypointCommand {
            position_m: p.xy(),
            altitude_m: p.z,
            cruise_speed_mps: self.cruise_speed_mps,
            ..Default::default()
        });
    }
}

impl Commander for HoldCommander {
    fn next_command(&mut self, _dt: f32, current_state: &VehicleState) -> Command {
        if let Some(land) = self.land {
            return Command::new(self.armed, ControlInput::Land(land));
        }
        if self.hold.is_none() {
            self.latch(current_state);
        }
        let waypoint = self.hold.unwrap_or(WaypointCommand {
            position_m: Vec2::repeat(f32::NAN),
            altitude_m: f32::NAN,
            cruise_speed_mps: self.cruise_speed_mps,
            ..Default::default()
        });
        Command::new(self.armed, ControlInput::Waypoint(waypoint))
    }
}

impl Fallback for HoldCommander {
    fn engage(&mut self, state: &VehicleState, last: &Command) {
        self.armed = last.arm;
        self.land = match last.input {
            ControlInput::Land(land) if last.arm => Some(land),
            _ => None,
        };
        self.latch(state);
    }
}