use crate::commanders::{TouchdownConfig, 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;
pub trait LinkedCommander: Commander {
fn since_update_s(&self) -> Option<f32>;
fn sync_arm(&mut self, armed: bool);
fn sync_regime(&mut self, regime: FlightRegime);
}
pub trait Fallback: Commander {
fn engage(&mut self, state: &VehicleState, last: &Command) {
let _ = (state, last);
}
fn can_release(&self) -> bool {
true
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FailsafeConfig {
pub timeout_s: f32,
pub recover_after_s: f32,
pub takeover_stick_delta: f32,
pub touchdown: TouchdownConfig,
}
impl Default for FailsafeConfig {
fn default() -> Self {
Self {
timeout_s: 1.0,
recover_after_s: 1.0,
takeover_stick_delta: 0.1,
touchdown: TouchdownConfig::default(),
}
}
}
impl FailsafeConfig {
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)?;
self.touchdown
.validate()
.map_err(|e| e.in_section("touchdown"))
}
}
#[derive(Debug)]
pub struct FailsafeCommander<P, F> {
primary: P,
fallback: F,
config: FailsafeConfig,
state: Option<FailsafeState>,
fresh_for_s: f32,
last: Command,
takeover_reference: Option<ControlInput>,
touchdown: TouchdownDetector,
}
impl<P: LinkedCommander, F: Fallback> FailsafeCommander<P, F> {
pub fn new(primary: P, fallback: F, config: FailsafeConfig) -> Result<Self, InvalidConfig> {
config.validate()?;
let touchdown = TouchdownDetector::new(config.touchdown)?;
Ok(Self {
primary,
fallback,
config,
state: None,
fresh_for_s: 0.0,
last: Command::default(),
takeover_reference: None,
touchdown,
})
}
pub fn primary(&self) -> &P {
&self.primary
}
pub fn fallback(&self) -> &F {
&self.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);
}
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)
}
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
}
}
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),
_ => {}
}
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 {
let armed = self.last.arm && primary.arm;
self.primary.sync_arm(armed);
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);
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
}
}
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,
}
}
pub const DEFAULT_HOLD_SPEED_MPS: f32 = 2.0;
#[derive(Debug, Clone)]
pub struct HoldCommander {
cruise_speed_mps: f32,
hold: Option<WaypointCommand>,
land: Option<LandCommand>,
armed: bool,
}
impl Default for HoldCommander {
fn default() -> Self {
Self {
cruise_speed_mps: DEFAULT_HOLD_SPEED_MPS,
hold: None,
land: None,
armed: false,
}
}
}
impl HoldCommander {
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()
})
}
pub fn is_landing(&self) -> bool {
self.land.is_some()
}
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);
}
}