use crate::controllers::{InvalidConfig, check, check_positive};
#[cfg(test)]
mod tests;
pub const DESCENDING_MPS: f32 = 0.2;
pub const DEFAULT_STOPPED_MPS: f32 = 0.1;
pub const DEFAULT_TOUCHDOWN_HOLD_S: f32 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TouchdownConfig {
pub stopped_mps: f32,
pub hold_s: f32,
}
impl Default for TouchdownConfig {
fn default() -> Self {
Self {
stopped_mps: DEFAULT_STOPPED_MPS,
hold_s: DEFAULT_TOUCHDOWN_HOLD_S,
}
}
}
impl TouchdownConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check(
"stopped_mps",
self.stopped_mps > 0.0 && self.stopped_mps < DESCENDING_MPS,
"in (0, DESCENDING_MPS)",
)?;
check_positive("hold_s", self.hold_s)
}
}
#[derive(Debug, Default, Clone)]
pub struct TouchdownDetector {
config: TouchdownConfig,
descended: bool,
stopped_s: Option<f32>,
touched_down: bool,
}
impl TouchdownDetector {
pub fn new(config: TouchdownConfig) -> Result<Self, InvalidConfig> {
config.validate()?;
Ok(Self {
config,
..Self::default()
})
}
pub fn update(&mut self, dt: f32, vertical_speed_mps: f32) -> bool {
if self.touched_down {
return true;
}
if vertical_speed_mps < -DESCENDING_MPS {
self.descended = true;
}
self.stopped_s = if self.descended && vertical_speed_mps.abs() < self.config.stopped_mps {
Some(self.stopped_s.unwrap_or(0.0) + dt)
} else {
None
};
self.touched_down = self.stopped_s.is_some_and(|s| s >= self.config.hold_s);
self.touched_down
}
pub fn touched_down(&self) -> bool {
self.touched_down
}
pub fn reset(&mut self) {
*self = Self {
config: self.config,
..Self::default()
};
}
}