stable_flight/commanders/touchdown.rs
1//! Decides when a landing vehicle has touched down: see [`TouchdownDetector`].
2
3use crate::controllers::{InvalidConfig, check, check_positive};
4
5#[cfg(test)]
6mod tests;
7
8/// Sinking faster than this, in m/s, shows the descent has begun. A constant, not a
9/// [`TouchdownConfig`] field: copter guidance's land speed
10/// ([`land_speed_mps`](crate::guidance::copter::CopterGuidanceConfig::land_speed_mps)) is
11/// validated above it, so every land is seen to descend. PX4 keeps the same coupling by capping
12/// its threshold at the land speed (`MulticopterLandDetector`, `LNDMC_Z_VEL_MAX`).
13pub const DESCENDING_MPS: f32 = 0.2;
14
15/// Default [`TouchdownConfig::stopped_mps`]: tighter than PX4's multicopter `LNDMC_Z_VEL_MAX`
16/// (0.25 m/s), whose land detector also checks thrust and motion, where this one has only the
17/// vertical speed.
18pub const DEFAULT_STOPPED_MPS: f32 = 0.1;
19
20/// Default [`TouchdownConfig::hold_s`]: PX4's multicopter land detector and ArduCopter's
21/// `LAND_DETECTOR_TRIGGER_SEC` both wait 1 s.
22pub const DEFAULT_TOUCHDOWN_HOLD_S: f32 = 1.0;
23
24/// What counts as stopped on the ground for a [`TouchdownDetector`].
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct TouchdownConfig {
27 /// Vertical speed below this, in m/s either way, counts as stopped. Wider: a landing gear
28 /// that bounces, or a noisy vertical speed, still reads as stopped; too wide, and a slow
29 /// final sink does too, disarming above the ground. Must be positive and below
30 /// [`DESCENDING_MPS`]. Defaults to [`DEFAULT_STOPPED_MPS`].
31 pub stopped_mps: f32,
32 /// How long, in seconds, the vehicle must stay stopped after descending to count as down.
33 /// Longer: a bounce or a pause in the sink is less likely to disarm in the air, but the
34 /// motors run longer on the ground. Must be positive and finite. Defaults to
35 /// [`DEFAULT_TOUCHDOWN_HOLD_S`].
36 pub hold_s: f32,
37}
38
39impl Default for TouchdownConfig {
40 fn default() -> Self {
41 Self {
42 stopped_mps: DEFAULT_STOPPED_MPS,
43 hold_s: DEFAULT_TOUCHDOWN_HOLD_S,
44 }
45 }
46}
47
48impl TouchdownConfig {
49 /// Checks that `stopped_mps` is in `(0, DESCENDING_MPS)` and `hold_s` is positive and
50 /// finite.
51 ///
52 /// # Errors
53 ///
54 /// [`InvalidConfig`] naming the first field out of range.
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// use stable_flight::commanders::TouchdownConfig;
60 ///
61 /// let config = TouchdownConfig { hold_s: 0.0, ..TouchdownConfig::default() };
62 /// assert_eq!(config.validate().unwrap_err().to_string(), "hold_s must be positive and finite");
63 /// ```
64 pub fn validate(&self) -> Result<(), InvalidConfig> {
65 check(
66 "stopped_mps",
67 self.stopped_mps > 0.0 && self.stopped_mps < DESCENDING_MPS,
68 "in (0, DESCENDING_MPS)",
69 )?;
70 check_positive("hold_s", self.hold_s)
71 }
72}
73
74/// Detects touchdown during a land ([`ControlInput::Land`](crate::ControlInput::Land)) from
75/// the vertical speed alone.
76///
77/// Landing guidance keeps lowering its altitude target, so a vehicle still in the air can't
78/// hold a vertical speed near zero for long: its thrust falls until it sinks. Once the vehicle
79/// has sunk faster than [`DESCENDING_MPS`], staying within
80/// ±[`stopped_mps`](TouchdownConfig::stopped_mps) for [`hold_s`](TouchdownConfig::hold_s) means
81/// the ground stopped it. Before the descent begins (the hover the land started from), nothing
82/// counts. Touchdown latches until [`reset`](Self::reset).
83///
84/// It works only while a land is flown; hovering would read as touchdown. A non-finite speed
85/// restarts the stopped timer without clearing the descent.
86///
87/// # Examples
88///
89/// ```
90/// use stable_flight::commanders::TouchdownDetector;
91///
92/// let mut detector = TouchdownDetector::default();
93/// assert!(!detector.update(0.5, 0.0)); // hovering before the descent: not down
94/// assert!(!detector.update(0.5, -0.7)); // descending
95/// assert!(!detector.update(0.5, 0.0)); // stopped for 0.5 s
96/// assert!(detector.update(0.6, 0.0)); // stopped for 1.1 s: down
97/// ```
98#[derive(Debug, Default, Clone)]
99pub struct TouchdownDetector {
100 config: TouchdownConfig,
101 descended: bool,
102 /// Seconds stopped since the descent; `None` while moving.
103 stopped_s: Option<f32>,
104 touched_down: bool,
105}
106
107impl TouchdownDetector {
108 /// A detector that reads touchdown per `config`; [`Default`] uses
109 /// [`TouchdownConfig::default`].
110 ///
111 /// # Errors
112 ///
113 /// [`InvalidConfig`] if `config` fails [`TouchdownConfig::validate`].
114 pub fn new(config: TouchdownConfig) -> Result<Self, InvalidConfig> {
115 config.validate()?;
116 Ok(Self {
117 config,
118 ..Self::default()
119 })
120 }
121
122 /// Advances by `dt` seconds with the vertical speed `vertical_speed_mps` (up positive) and
123 /// returns whether the vehicle has touched down.
124 pub fn update(&mut self, dt: f32, vertical_speed_mps: f32) -> bool {
125 if self.touched_down {
126 return true;
127 }
128 if vertical_speed_mps < -DESCENDING_MPS {
129 self.descended = true;
130 }
131 self.stopped_s = if self.descended && vertical_speed_mps.abs() < self.config.stopped_mps {
132 Some(self.stopped_s.unwrap_or(0.0) + dt)
133 } else {
134 None
135 };
136 self.touched_down = self.stopped_s.is_some_and(|s| s >= self.config.hold_s);
137 self.touched_down
138 }
139
140 /// Whether touchdown has been detected.
141 pub fn touched_down(&self) -> bool {
142 self.touched_down
143 }
144
145 /// Forgets the descent and any touchdown, for a new land; keeps the config.
146 pub fn reset(&mut self) {
147 *self = Self {
148 config: self.config,
149 ..Self::default()
150 };
151 }
152}