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