Skip to main content

stable_flight/
flight_loop.rs

1//! One control-loop tick, independent of how ticks are scheduled.
2//!
3//! [`FlightLoop`] owns the six pipeline components and runs them in order for a single tick.
4//! It has no clock, threads, or signal handling: a runner decides when to call
5//! [`FlightLoop::step`] and with what `dt` (a wall-clock runner in `stable-flight-sitl` today;
6//! a lockstep simulator runner or a hardware timer interrupt later).
7
8use core::time::Duration;
9
10use crate::controllers::InvalidConfig;
11use crate::params::{ParamError, Params};
12use crate::{
13    ActuatorCommand, AttitudeSetpoint, Commander, Configurable, ControlOutput, Guidance, Mixer,
14    Saturation, Setpoint, Stabilizer, TelemetryPublisher, TelemetryRecord, Vehicle, VehicleState,
15};
16
17#[cfg(test)]
18mod tests;
19
20/// Sequences one control tick: commander → estimate → guide → stabilize → mix → actuate →
21/// telemetry.
22///
23/// Call [`prime`](FlightLoop::prime) once before the first [`step`](FlightLoop::step).
24///
25/// The [`Command`](crate::Command)'s `arm` gates the motors: a disarmed tick skips guidance,
26/// the stabilizer, and the mixer and actuates [`ActuatorCommand::default`] (motors off). The
27/// first armed tick after a disarmed one (including the first tick) re-primes guidance and
28/// the stabilizer, so integrators start from zero.
29///
30/// # Examples
31///
32/// ```
33/// use std::time::Duration;
34/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
35/// use stable_flight::mixers::QuadCopterMixer;
36/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
37/// use stable_flight::{
38///     Actuator, ActuatorCommand, AttitudeCommand, Command, Commander, ControlInput, FlightLoop,
39///     StateSource, VehicleState,
40/// };
41///
42/// struct Hover;
43/// impl Commander for Hover {
44///     fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
45///         Command::armed(ControlInput::Attitude(AttitudeCommand {
46///             throttle: 0.5,
47///             ..Default::default()
48///         }))
49///     }
50/// }
51///
52/// struct StillAir;
53/// impl StateSource for StillAir {
54///     fn state(&mut self, _dt: Duration) -> VehicleState {
55///         VehicleState::default()
56///     }
57/// }
58/// impl Actuator for StillAir {
59///     fn actuate(&mut self, _command: &ActuatorCommand) {}
60/// }
61///
62/// let mut flight_loop = FlightLoop::new(
63///     Hover,
64///     StillAir,
65///     CopterGuidance::new(CopterGuidanceConfig::default()),
66///     CopterStabilizer::new(CopterStabilizerConfig::default()),
67///     QuadCopterMixer::default(),
68///     (), // no telemetry
69/// );
70///
71/// flight_loop.prime();
72/// for _ in 0..3 {
73///     flight_loop.step(Duration::from_millis(4)); // 250 Hz
74/// }
75/// ```
76///
77/// The struct itself is unbounded (bounds live on the `impl`), so types that hold a
78/// `FlightLoop` — runners, firmware statics — needn't repeat the six trait bounds.
79pub struct FlightLoop<C, V, G, S, M, T> {
80    commander: C,
81    vehicle: V,
82    guidance: G,
83    stabilizer: S,
84    mixer: M,
85    telemetry: T,
86    /// Latest estimate; the commander sees the previous tick's state.
87    state: VehicleState,
88    /// Whether the previous tick was armed; a rising edge re-primes.
89    armed: bool,
90}
91
92impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>
93where
94    C: Commander,
95    V: Vehicle,
96    G: Guidance,
97    S: Stabilizer,
98    M: Mixer,
99    T: TelemetryPublisher,
100{
101    /// Assembles a loop from its six components. Does not touch the vehicle.
102    pub fn new(
103        commander: C,
104        vehicle: V,
105        guidance: G,
106        stabilizer: S,
107        mixer: M,
108        telemetry: T,
109    ) -> Self {
110        FlightLoop {
111            commander,
112            vehicle,
113            guidance,
114            stabilizer,
115            mixer,
116            telemetry,
117            state: VehicleState::default(),
118            armed: false,
119        }
120    }
121
122    /// Takes the initial estimate (with `dt = Duration::ZERO`, per the [`StateSource`]
123    /// convention) and primes guidance, then the stabilizer, from it. Call once before the
124    /// first tick, so the commander's first call sees a real state. The first armed tick
125    /// primes them again from its fresh estimate (see the arm gate on [`FlightLoop`]).
126    ///
127    /// [`StateSource`]: crate::StateSource
128    pub fn prime(&mut self) {
129        self.state = self.vehicle.state(Duration::ZERO);
130        self.guidance.prime(&self.state);
131        self.stabilizer.prime(&self.state);
132    }
133
134    /// Runs one tick with loop period `dt`.
135    ///
136    /// The commander sees the state from the previous tick; guidance and the stabilizer see
137    /// the fresh estimate. Telemetry receives a [`TelemetryRecord`] after actuation, with the
138    /// [`Saturation`] guidance, the stabilizer, and the mixer report, merged. A disarmed tick
139    /// actuates [`ActuatorCommand::default`] and records a neutral setpoint, zero control, and
140    /// no saturation; see [`FlightLoop`] for the arm gate. Allocation-free.
141    ///
142    /// # Panics
143    ///
144    /// If `dt` is zero on an armed tick: guidance and the stabilizer require a positive, finite step (a
145    /// `Duration` is never negative or non-finite).
146    pub fn step(&mut self, dt: Duration) {
147        let dt_secs = dt.as_secs_f32();
148
149        let command = self.commander.next_command(dt_secs, &self.state);
150        self.state = self.vehicle.state(dt);
151
152        let (setpoint, control, actuators, saturation) = if command.arm {
153            if !self.armed {
154                self.guidance.prime(&self.state);
155                self.stabilizer.prime(&self.state);
156            }
157            let setpoint = self.guidance.guide(dt_secs, &command.input, &self.state);
158            let control = self.stabilizer.stabilize(dt_secs, &setpoint, &self.state);
159            let actuators = self.mixer.mix(&control);
160            let saturation = self
161                .guidance
162                .saturation()
163                .merge(self.stabilizer.saturation())
164                .merge(self.mixer.saturation());
165            (setpoint, control, actuators, saturation)
166        } else {
167            let setpoint = Setpoint::Attitude(AttitudeSetpoint {
168                heading_rad: self.state.heading_rad,
169                ..Default::default()
170            });
171            (
172                setpoint,
173                ControlOutput::default(),
174                ActuatorCommand::default(),
175                Saturation::default(),
176            )
177        };
178        self.armed = command.arm;
179        self.vehicle.actuate(&actuators);
180
181        self.telemetry.publish(&TelemetryRecord {
182            dt,
183            command: &command,
184            setpoint: &setpoint,
185            state: &self.state,
186            control: &control,
187            actuators: &actuators,
188            saturation,
189            failsafe: self.commander.failsafe(),
190        });
191    }
192
193    /// The most recent state estimate.
194    pub fn state(&self) -> &VehicleState {
195        &self.state
196    }
197
198    /// The commander, e.g. to read its [`failsafe`](Commander::failsafe) state between ticks.
199    pub fn commander(&self) -> &C {
200        &self.commander
201    }
202
203    /// The guidance, e.g. to read its config.
204    pub fn guidance(&self) -> &G {
205        &self.guidance
206    }
207
208    /// The stabilizer, e.g. to read its config.
209    pub fn stabilizer(&self) -> &S {
210        &self.stabilizer
211    }
212
213    /// Retunes the guidance between ticks ([`Configurable::set_config`]): an invalid config is
214    /// rejected and the current one kept.
215    pub fn set_guidance_config(&mut self, config: G::Config) -> Result<(), InvalidConfig>
216    where
217        G: Configurable,
218    {
219        self.guidance.set_config(config)
220    }
221
222    /// Retunes the stabilizer between ticks ([`Configurable::set_config`]): an invalid config
223    /// is rejected and the current one kept.
224    ///
225    /// ```
226    /// # use std::time::Duration;
227    /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
228    /// # use stable_flight::mixers::QuadCopterMixer;
229    /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
230    /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
231    /// use stable_flight::{Configurable, FlightLoop};
232    /// # struct Hover;
233    /// # impl Commander for Hover {
234    /// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
235    /// #         Command::default()
236    /// #     }
237    /// # }
238    /// # struct StillAir;
239    /// # impl StateSource for StillAir {
240    /// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
241    /// # }
242    /// # impl Actuator for StillAir {
243    /// #     fn actuate(&mut self, _: &ActuatorCommand) {}
244    /// # }
245    /// # let mut flight_loop = FlightLoop::new(
246    /// #     Hover,
247    /// #     StillAir,
248    /// #     CopterGuidance::new(CopterGuidanceConfig::default()),
249    /// #     CopterStabilizer::new(CopterStabilizerConfig::default()),
250    /// #     QuadCopterMixer::default(),
251    /// #     (),
252    /// # );
253    /// # flight_loop.prime();
254    /// flight_loop.step(Duration::from_millis(4));
255    ///
256    /// let mut retuned = *flight_loop.stabilizer().config();
257    /// retuned.body_rate.gains.p = 0.2;
258    /// flight_loop.set_stabilizer_config(retuned).expect("valid config");
259    /// flight_loop.step(Duration::from_millis(4)); // flies the new gains
260    /// ```
261    pub fn set_stabilizer_config(&mut self, config: S::Config) -> Result<(), InvalidConfig>
262    where
263        S: Configurable,
264    {
265        self.stabilizer.set_config(config)
266    }
267
268    /// Splits the loop back into `(commander, vehicle, guidance, stabilizer, mixer, telemetry)`,
269    /// e.g. to inspect test doubles after a run or to hand the vehicle to another runner.
270    ///
271    /// ```
272    /// # use std::time::Duration;
273    /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
274    /// # use stable_flight::mixers::QuadCopterMixer;
275    /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
276    /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
277    /// use stable_flight::FlightLoop;
278    ///
279    /// # struct Hover;
280    /// # impl Commander for Hover {
281    /// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
282    /// #         Command::default()
283    /// #     }
284    /// # }
285    /// /// Counts actuations.
286    /// #[derive(Default)]
287    /// struct Bench {
288    ///     actuations: u32,
289    /// }
290    /// # impl StateSource for Bench {
291    /// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
292    /// # }
293    /// impl Actuator for Bench {
294    ///     fn actuate(&mut self, _: &ActuatorCommand) {
295    ///         self.actuations += 1;
296    ///     }
297    /// }
298    ///
299    /// let mut flight_loop = FlightLoop::new(
300    ///     Hover,
301    ///     Bench::default(),
302    ///     CopterGuidance::new(CopterGuidanceConfig::default()),
303    ///     CopterStabilizer::new(CopterStabilizerConfig::default()),
304    ///     QuadCopterMixer::default(),
305    ///     (),
306    /// );
307    /// flight_loop.prime();
308    /// flight_loop.step(Duration::from_millis(4));
309    ///
310    /// let (_, bench, _, _, _, _) = flight_loop.into_parts();
311    /// assert_eq!(bench.actuations, 1);
312    /// ```
313    pub fn into_parts(self) -> (C, V, G, S, M, T) {
314        (
315            self.commander,
316            self.vehicle,
317            self.guidance,
318            self.stabilizer,
319            self.mixer,
320            self.telemetry,
321        )
322    }
323}
324
325/// The guidance's params, then the stabilizer's (see [`crate::params`]): combined indices
326/// run through the guidance's first, then the stabilizer's. Nothing checks that their names
327/// are disjoint: on a duplicate, name lookup finds the guidance's and the stabilizer's is
328/// reachable only by index, so table authors keep names unique across components (the copter
329/// tables use `GUID_`/`STAB_` prefixes).
330///
331/// ```
332/// # use std::time::Duration;
333/// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
334/// # use stable_flight::mixers::QuadCopterMixer;
335/// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
336/// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
337/// use stable_flight::params::Params;
338/// use stable_flight::{Configurable, FlightLoop};
339/// # struct Hover;
340/// # impl Commander for Hover {
341/// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
342/// #         Command::default()
343/// #     }
344/// # }
345/// # struct StillAir;
346/// # impl StateSource for StillAir {
347/// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
348/// # }
349/// # impl Actuator for StillAir {
350/// #     fn actuate(&mut self, _: &ActuatorCommand) {}
351/// # }
352/// # let mut flight_loop = FlightLoop::new(
353/// #     Hover,
354/// #     StillAir,
355/// #     CopterGuidance::new(CopterGuidanceConfig::default()),
356/// #     CopterStabilizer::new(CopterStabilizerConfig::default()),
357/// #     QuadCopterMixer::default(),
358/// #     (),
359/// # );
360///
361/// flight_loop.set_param("GUID_ALT_P", 2.5).expect("valid value");
362/// flight_loop.set_param("STAB_RATE_P", 0.2).expect("valid value");
363/// assert_eq!(flight_loop.guidance().config().altitude.gains.p, 2.5);
364/// assert_eq!(flight_loop.param("STAB_RATE_P"), Some(0.2));
365/// ```
366impl<C, V, G, S, M, T> Params for FlightLoop<C, V, G, S, M, T>
367where
368    G: Params,
369    S: Params,
370{
371    fn param_count(&self) -> usize {
372        self.guidance.param_count() + self.stabilizer.param_count()
373    }
374
375    fn param_name(&self, index: usize) -> Option<&'static str> {
376        match self.split_param_index(index) {
377            ParamOwner::Guidance(i) => self.guidance.param_name(i),
378            ParamOwner::Stabilizer(i) => self.stabilizer.param_name(i),
379        }
380    }
381
382    fn param_at(&self, index: usize) -> Option<f32> {
383        match self.split_param_index(index) {
384            ParamOwner::Guidance(i) => self.guidance.param_at(i),
385            ParamOwner::Stabilizer(i) => self.stabilizer.param_at(i),
386        }
387    }
388
389    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
390        match self.split_param_index(index) {
391            ParamOwner::Guidance(i) => self.guidance.set_param_at(i, value),
392            ParamOwner::Stabilizer(i) => self.stabilizer.set_param_at(i, value),
393        }
394    }
395}
396
397/// The component a combined param index belongs to, with its index there.
398enum ParamOwner {
399    Guidance(usize),
400    Stabilizer(usize),
401}
402
403impl<C, V, G: Params, S, M, T> FlightLoop<C, V, G, S, M, T> {
404    fn split_param_index(&self, index: usize) -> ParamOwner {
405        let guidance_count = self.guidance.param_count();
406        if index < guidance_count {
407            ParamOwner::Guidance(index)
408        } else {
409            ParamOwner::Stabilizer(index - guidance_count)
410        }
411    }
412}