Skip to main content

FlightLoop

Struct FlightLoop 

Source
pub struct FlightLoop<C, V, G, S, M, T> { /* private fields */ }
Expand description

Sequences one control tick: commander → estimate → guide → stabilize → mix → actuate → telemetry.

Call prime once before the first step.

The Command’s arm gates the motors: a disarmed tick skips guidance, the stabilizer, and the mixer and actuates ActuatorCommand::default (motors off). The first armed tick after a disarmed one (including the first tick) re-primes guidance and the stabilizer, so integrators start from zero.

§Examples

use std::time::Duration;
use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
use stable_flight::mixers::TableMixer;
use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
use stable_flight::{
    Actuator, ActuatorCommand, AttitudeCommand, Command, Commander, ControlInput, FlightLoop,
    StateSource, VehicleState,
};

struct Hover;
impl Commander for Hover {
    fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
        Command::armed(ControlInput::Attitude(AttitudeCommand {
            throttle: 0.5,
            ..Default::default()
        }))
    }
}

struct StillAir;
impl StateSource for StillAir {
    fn state(&mut self, _dt: Duration) -> VehicleState {
        VehicleState::default()
    }
}
impl Actuator for StillAir {
    fn actuate(&mut self, _command: &ActuatorCommand) {}
}

let mut flight_loop = FlightLoop::new(
    Hover,
    StillAir,
    CopterGuidance::new(CopterGuidanceConfig::default()),
    CopterStabilizer::new(CopterStabilizerConfig::default()),
    TableMixer::quad_x(),
    (), // no telemetry
);

flight_loop.prime();
for _ in 0..3 {
    flight_loop.step(Duration::from_millis(4)); // 250 Hz
}

The struct itself is unbounded (bounds live on the impl), so types that hold a FlightLoop — runners, firmware statics — needn’t repeat the six trait bounds.

Implementations§

Source§

impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>

Source

pub fn new( commander: C, vehicle: V, guidance: G, stabilizer: S, mixer: M, telemetry: T, ) -> Self

Assembles a loop from its six components. Does not touch the vehicle.

Source

pub fn prime(&mut self)

Takes the initial estimate (with dt = Duration::ZERO, per the StateSource convention) and primes guidance, then the stabilizer, from it. Call once before the first tick, so the commander’s first call sees a real state. The first armed tick primes them again from its fresh estimate (see the arm gate on FlightLoop).

Source

pub fn step(&mut self, dt: Duration)

Runs one tick with loop period dt.

The commander sees the state from the previous tick; guidance and the stabilizer see the fresh estimate. Telemetry receives a TelemetryRecord after actuation, with the Saturation guidance, the stabilizer, and the mixer report, merged. A disarmed tick actuates ActuatorCommand::default and records a neutral setpoint, zero control, no saturation, and FlightModeReport::copter_only (guidance didn’t fly); see FlightLoop for the arm gate. Allocation-free.

§Panics

If dt is zero on an armed tick: guidance and the stabilizer require a positive, finite step (a Duration is never negative or non-finite).

Source§

impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>

Accessors and between-ticks changes: they don’t run the pipeline, so they need none of its bounds.

Source

pub fn state(&self) -> &VehicleState

The most recent state estimate.

Source

pub fn setpoint(&self) -> &Setpoint

The setpoint guidance gave the stabilizer on the last tick, in the stabilizer’s frame (a View’s for a viewed stabilizer): the neutral one a disarmed tick records, and before the first tick a level, idle Setpoint::Attitude. An autotune settles to its attitude target.

§Examples
use std::time::Duration;
use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
use stable_flight::mixers::TableMixer;
use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
use stable_flight::{
    AbsoluteAttitudeCommand, Actuator, ActuatorCommand, Command, Commander, ControlInput,
    FlightLoop, Setpoint, StateSource, VehicleState,
};

struct Lean;
impl Commander for Lean {
    fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
        Command::armed(ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
            roll_rad: 0.1,
            thrust: 0.5,
            ..Default::default()
        }))
    }
}

struct StillAir;
impl StateSource for StillAir {
    fn state(&mut self, _dt: Duration) -> VehicleState {
        VehicleState::default()
    }
}
impl Actuator for StillAir {
    fn actuate(&mut self, _command: &ActuatorCommand) {}
}

let mut flight_loop = FlightLoop::new(
    Lean,
    StillAir,
    CopterGuidance::new(CopterGuidanceConfig::default()),
    CopterStabilizer::new(CopterStabilizerConfig::default()),
    TableMixer::quad_x(),
    (),
);
flight_loop.prime();
flight_loop.step(Duration::from_millis(4));
assert!(matches!(flight_loop.setpoint(), Setpoint::Attitude(a) if a.roll_rad == 0.1));
Source

pub fn commander(&self) -> &C

The commander, e.g. to read its failsafe state between ticks.

Source

pub fn vehicle(&self) -> &V

The vehicle, e.g. to read a simulator’s internals between ticks.

Source

pub fn guidance(&self) -> &G

The guidance, e.g. to read its config.

Source

pub fn stabilizer(&self) -> &S

The stabilizer, e.g. to read its config.

Source

pub fn armed(&self) -> bool

Whether the last tick was armed (false before the first tick). A disarm between ticks shows here after the next tick.

Source

pub fn set_guidance_config( &mut self, config: G::Config, ) -> Result<(), InvalidConfig>
where G: Configurable,

Retunes the guidance between ticks (Configurable::set_config): an invalid config is rejected and the current one kept.

Source

pub fn set_stabilizer_config( &mut self, config: S::Config, ) -> Result<(), InvalidConfig>
where S: Configurable,

Retunes the stabilizer between ticks (Configurable::set_config): an invalid config is rejected and the current one kept.

use stable_flight::{Configurable, FlightLoop};
flight_loop.step(Duration::from_millis(4));

let mut retuned = *flight_loop.stabilizer().config();
retuned.body_rate.roll_gains.p = 0.2;
flight_loop.set_stabilizer_config(retuned).expect("valid config");
flight_loop.step(Duration::from_millis(4)); // flies the new gains
Source

pub fn into_parts(self) -> (C, V, G, S, M, T)

Splits the loop back into (commander, vehicle, guidance, stabilizer, mixer, telemetry), e.g. to inspect test doubles after a run or to hand the vehicle to another runner.

use stable_flight::FlightLoop;

/// Counts actuations.
#[derive(Default)]
struct Bench {
    actuations: u32,
}
impl Actuator for Bench {
    fn actuate(&mut self, _: &ActuatorCommand) {
        self.actuations += 1;
    }
}

let mut flight_loop = FlightLoop::new(
    Hover,
    Bench::default(),
    CopterGuidance::new(CopterGuidanceConfig::default()),
    CopterStabilizer::new(CopterStabilizerConfig::default()),
    TableMixer::quad_x(),
    (),
);
flight_loop.prime();
flight_loop.step(Duration::from_millis(4));

let (_, bench, _, _, _, _) = flight_loop.into_parts();
assert_eq!(bench.actuations, 1);
Source§

impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>

The guidance’s params, then the stabilizer’s (see crate::params): combined indices run through the guidance’s first, then the stabilizer’s. Nothing checks that their names are disjoint: on a duplicate, name lookup finds the guidance’s and the stabilizer’s is reachable only by index, so table authors keep names unique across components (the copter tables use GUID_/STAB_ prefixes).

use stable_flight::params::Params;
use stable_flight::{Configurable, FlightLoop};

flight_loop.set_param("GUID_ALT_P", 2.5).expect("valid value");
flight_loop.set_param("STAB_RATE_RLL_P", 0.2).expect("valid value");
assert_eq!(flight_loop.guidance().config().altitude.gains.p, 2.5);
assert_eq!(flight_loop.param("STAB_RATE_RLL_P"), Some(0.2));

Autotune stages on a Tunable stabilizer, between ticks; forwarded so the loop hands out no &mut to its components.

Source

pub fn start_probe<L: Copy>(&mut self, target: L, config: ProbeConfig)
where S: Tunable<L>,

Starts a probe on one of the stabilizer’s loops, from the next tick (Tunable::start_probe).

§Panics

If config is invalid (ProbeConfig::validate).

Source

pub fn probe<L: Copy>(&self) -> Option<(L, ProbeStatus)>
where S: Tunable<L>,

The stabilizer’s current probe on its L loops, if any (Tunable::probe).

Source

pub fn stop_probe<L: Copy>(&mut self) -> Option<(L, ProbeStatus)>
where S: Tunable<L>,

Ends the probe on the stabilizer’s L loops and hands its loop back (Tunable::stop_probe).

Trait Implementations§

Source§

impl<C, V, G, S, M, T> Params for FlightLoop<C, V, G, S, M, T>
where G: Params, S: Params,

Source§

fn param_count(&self) -> usize

Number of params; their indices are 0..param_count().
Source§

fn param_name(&self, index: usize) -> Option<&'static str>

The name of the param at index, or None if it is out of range.
Source§

fn param_at(&self, index: usize) -> Option<f32>

The value of the param at index, or None if it is out of range.
Source§

fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError>

Sets the param at index to value. Out of range is ParamError::Unknown. On error the config is unchanged.
Source§

fn param_index(&self, name: &str) -> Option<usize>

The index of the param called name, or None if there is no such param. On a duplicate name, the first index.
Source§

fn param(&self, name: &str) -> Option<f32>

The value of the param called name, or None if there is no such param.
Source§

fn set_param(&mut self, name: &str, value: f32) -> Result<(), ParamError>

Sets the param called name to value. On error the config is unchanged.
Source§

fn visit_params(&self, f: &mut dyn FnMut(&'static str, f32))

Calls f with every param’s name and value, in index order.

Auto Trait Implementations§

§

impl<C, V, G, S, M, T> Forget for FlightLoop<C, V, G, S, M, T>

§

impl<C, V, G, S, M, T> Freeze for FlightLoop<C, V, G, S, M, T>
where C: Freeze, V: Freeze, G: Freeze, S: Freeze, M: Freeze, T: Freeze,

§

impl<C, V, G, S, M, T> Move for FlightLoop<C, V, G, S, M, T>

§

impl<C, V, G, S, M, T> RefUnwindSafe for FlightLoop<C, V, G, S, M, T>

§

impl<C, V, G, S, M, T> Send for FlightLoop<C, V, G, S, M, T>
where C: Send, V: Send, G: Send, S: Send, M: Send, T: Send,

§

impl<C, V, G, S, M, T> Sync for FlightLoop<C, V, G, S, M, T>
where C: Sync, V: Sync, G: Sync, S: Sync, M: Sync, T: Sync,

§

impl<C, V, G, S, M, T> Unpin for FlightLoop<C, V, G, S, M, T>
where C: Unpin, V: Unpin, G: Unpin, S: Unpin, M: Unpin, T: Unpin,

§

impl<C, V, G, S, M, T> UnsafeUnpin for FlightLoop<C, V, G, S, M, T>

§

impl<C, V, G, S, M, T> UnwindSafe for FlightLoop<C, V, G, S, M, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.