Skip to main content

stable_flight/commanders/
touchdown.rs

1//! Decides when a landing vehicle has touched down: see [`TouchdownDetector`].
2
3#[cfg(test)]
4mod tests;
5
6/// Sinking faster than this, in m/s, shows the descent has begun.
7pub const DESCENDING_MPS: f32 = 0.2;
8
9/// Vertical speed below this, in m/s either way, counts as stopped.
10pub const STOPPED_MPS: f32 = 0.1;
11
12/// How long, in seconds, the vehicle must stay stopped after descending to count as down.
13pub const TOUCHDOWN_HOLD_S: f32 = 1.0;
14
15/// Detects touchdown during a land ([`ControlInput::Land`](crate::ControlInput::Land)) from
16/// the vertical speed alone.
17///
18/// Landing guidance keeps lowering its altitude target, so a vehicle still in the air can't
19/// hold a vertical speed near zero for long: its thrust falls until it sinks. Once the vehicle
20/// has sunk faster than [`DESCENDING_MPS`], staying within ±[`STOPPED_MPS`] for
21/// [`TOUCHDOWN_HOLD_S`] means the ground stopped it. Before the descent begins (the hover the
22/// land started from), nothing counts. Touchdown latches until [`reset`](Self::reset).
23///
24/// It works only while a land is flown; hovering would read as touchdown. A non-finite speed
25/// restarts the stopped timer without clearing the descent.
26///
27/// # Examples
28///
29/// ```
30/// use stable_flight::commanders::TouchdownDetector;
31///
32/// let mut detector = TouchdownDetector::default();
33/// assert!(!detector.update(0.5, 0.0)); // hovering before the descent: not down
34/// assert!(!detector.update(0.5, -0.7)); // descending
35/// assert!(!detector.update(0.5, 0.0)); // stopped for 0.5 s
36/// assert!(detector.update(0.6, 0.0)); // stopped for 1.1 s: down
37/// ```
38#[derive(Debug, Default, Clone)]
39pub struct TouchdownDetector {
40    descended: bool,
41    /// Seconds stopped since the descent; `None` while moving.
42    stopped_s: Option<f32>,
43    touched_down: bool,
44}
45
46impl TouchdownDetector {
47    /// Advances by `dt` seconds with the vertical speed `vertical_speed_mps` (up positive) and
48    /// returns whether the vehicle has touched down.
49    pub fn update(&mut self, dt: f32, vertical_speed_mps: f32) -> bool {
50        if self.touched_down {
51            return true;
52        }
53        if vertical_speed_mps < -DESCENDING_MPS {
54            self.descended = true;
55        }
56        self.stopped_s = if self.descended && vertical_speed_mps.abs() < STOPPED_MPS {
57            Some(self.stopped_s.unwrap_or(0.0) + dt)
58        } else {
59            None
60        };
61        self.touched_down = self.stopped_s.is_some_and(|s| s >= TOUCHDOWN_HOLD_S);
62        self.touched_down
63    }
64
65    /// Whether touchdown has been detected.
66    pub fn touched_down(&self) -> bool {
67        self.touched_down
68    }
69
70    /// Forgets the descent and any touchdown, for a new land.
71    pub fn reset(&mut self) {
72        *self = Self::default();
73    }
74}