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 /// The setpoint the last tick flew (or recorded, disarmed), for an autotune to settle to
93 /// between ticks ([`FlightLoop::setpoint`]).
94 setpoint: Setpoint,
95}
96
97impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>
98where
99 C: Commander,
100 V: Vehicle,
101 G: Guidance,
102 S: Stabilizer,
103 M: Mixer,
104 T: TelemetryPublisher,
105{
106 /// Assembles a loop from its six components. Does not touch the vehicle.
107 pub fn new(
108 commander: C,
109 vehicle: V,
110 guidance: G,
111 stabilizer: S,
112 mixer: M,
113 telemetry: T,
114 ) -> Self {
115 FlightLoop {
116 commander,
117 vehicle,
118 guidance,
119 stabilizer,
120 mixer,
121 telemetry,
122 state: VehicleState::default(),
123 armed: false,
124 setpoint: Setpoint::Attitude(AttitudeSetpoint {
125 idle: true,
126 ..Default::default()
127 }),
128 }
129 }
130
131 /// Takes the initial estimate (with `dt = Duration::ZERO`, per the [`StateSource`]
132 /// convention) and primes guidance, then the stabilizer, from it. Call once before the
133 /// first tick, so the commander's first call sees a real state. The first armed tick
134 /// primes them again from its fresh estimate (see the arm gate on [`FlightLoop`]).
135 ///
136 /// [`StateSource`]: crate::StateSource
137 pub fn prime(&mut self) {
138 self.state = self.vehicle.state(Duration::ZERO);
139 self.guidance.prime(&self.state);
140 self.stabilizer.prime(&self.state);
141 }
142
143 /// Runs one tick with loop period `dt`.
144 ///
145 /// The commander sees the state from the previous tick; guidance and the stabilizer see
146 /// the fresh estimate. Telemetry receives a [`TelemetryRecord`] after actuation, with the
147 /// [`Saturation`] guidance, the stabilizer, and the mixer report, merged. A disarmed tick
148 /// actuates [`ActuatorCommand::default`] and records a neutral setpoint, zero control, no
149 /// saturation, and [`FlightModeReport::copter_only`] (guidance didn't fly); see
150 /// [`FlightLoop`] for the arm gate. Allocation-free.
151 ///
152 /// # Panics
153 ///
154 /// If `dt` is zero on an armed tick: guidance and the stabilizer require a positive, finite step (a
155 /// `Duration` is never negative or non-finite).
156 pub fn step(&mut self, dt: Duration) {
157 let dt_secs = dt.as_secs_f32();
158
159 let command = self.commander.next_command(dt_secs, &self.state);
160 self.state = self.vehicle.state(dt);
161
162 let copter_only = FlightModeReport::copter_only(command.regime);
163 let (setpoint, control, actuators, saturation, flight_mode) = if command.arm {
164 if !self.armed {
165 self.guidance.prime(&self.state);
166 self.stabilizer.prime(&self.state);
167 }
168 let setpoint =
169 self.guidance
170 .guide(dt_secs, command.regime, &command.input, &self.state);
171 let control = self.stabilizer.stabilize(dt_secs, &setpoint, &self.state);
172 let actuators = self.mixer.mix(&control);
173 let saturation = self
174 .guidance
175 .saturation()
176 .merge(self.stabilizer.saturation())
177 .merge(self.mixer.saturation());
178 let flight_mode = self.guidance.flight_mode().unwrap_or(copter_only);
179 (setpoint, control, actuators, saturation, flight_mode)
180 } else {
181 let setpoint = Setpoint::Attitude(AttitudeSetpoint {
182 heading_rad: self.state.heading_rad,
183 idle: true,
184 ..Default::default()
185 });
186 (
187 setpoint,
188 ControlOutput::default(),
189 ActuatorCommand::default(),
190 Saturation::default(),
191 copter_only,
192 )
193 };
194 self.armed = command.arm;
195 self.setpoint = setpoint;
196 self.vehicle.actuate(&actuators);
197
198 self.telemetry.publish(&TelemetryRecord {
199 dt,
200 command: &command,
201 setpoint: &setpoint,
202 state: &self.state,
203 control: &control,
204 actuators: &actuators,
205 saturation,
206 failsafe: self.commander.failsafe(),
207 flight_mode,
208 wind: self.guidance.wind(),
209 });
210 }
211}
212
213/// Accessors and between-ticks changes: they don't run the pipeline, so they need none of its
214/// bounds.
215impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T> {
216 /// The most recent state estimate.
217 pub fn state(&self) -> &VehicleState {
218 &self.state
219 }
220
221 /// The setpoint guidance gave the stabilizer on the last tick, in the stabilizer's frame
222 /// (a [`View`](crate::view::View)'s for a viewed stabilizer): the neutral one a disarmed
223 /// tick records, and before the first tick a level, idle [`Setpoint::Attitude`]. An
224 /// autotune settles to its attitude target.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// use std::time::Duration;
230 /// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
231 /// use stable_flight::mixers::TableMixer;
232 /// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
233 /// use stable_flight::{
234 /// AbsoluteAttitudeCommand, Actuator, ActuatorCommand, Command, Commander, ControlInput,
235 /// FlightLoop, Setpoint, StateSource, VehicleState,
236 /// };
237 ///
238 /// struct Lean;
239 /// impl Commander for Lean {
240 /// fn next_command(&mut self, _dt: f32, _state: &VehicleState) -> Command {
241 /// Command::armed(ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
242 /// roll_rad: 0.1,
243 /// thrust: 0.5,
244 /// ..Default::default()
245 /// }))
246 /// }
247 /// }
248 ///
249 /// struct StillAir;
250 /// impl StateSource for StillAir {
251 /// fn state(&mut self, _dt: Duration) -> VehicleState {
252 /// VehicleState::default()
253 /// }
254 /// }
255 /// impl Actuator for StillAir {
256 /// fn actuate(&mut self, _command: &ActuatorCommand) {}
257 /// }
258 ///
259 /// let mut flight_loop = FlightLoop::new(
260 /// Lean,
261 /// StillAir,
262 /// CopterGuidance::new(CopterGuidanceConfig::default()),
263 /// CopterStabilizer::new(CopterStabilizerConfig::default()),
264 /// TableMixer::quad_x(),
265 /// (),
266 /// );
267 /// flight_loop.prime();
268 /// flight_loop.step(Duration::from_millis(4));
269 /// assert!(matches!(flight_loop.setpoint(), Setpoint::Attitude(a) if a.roll_rad == 0.1));
270 /// ```
271 pub fn setpoint(&self) -> &Setpoint {
272 &self.setpoint
273 }
274
275 /// The commander, e.g. to read its [`failsafe`](Commander::failsafe) state between ticks.
276 pub fn commander(&self) -> &C {
277 &self.commander
278 }
279
280 /// The vehicle, e.g. to read a simulator's internals between ticks.
281 pub fn vehicle(&self) -> &V {
282 &self.vehicle
283 }
284
285 /// The guidance, e.g. to read its config.
286 pub fn guidance(&self) -> &G {
287 &self.guidance
288 }
289
290 /// The stabilizer, e.g. to read its config.
291 pub fn stabilizer(&self) -> &S {
292 &self.stabilizer
293 }
294
295 /// Whether the last tick was armed (false before the first tick). A disarm between ticks
296 /// shows here after the next tick.
297 pub fn armed(&self) -> bool {
298 self.armed
299 }
300
301 /// Retunes the guidance between ticks ([`Configurable::set_config`]): an invalid config is
302 /// rejected and the current one kept.
303 pub fn set_guidance_config(&mut self, config: G::Config) -> Result<(), InvalidConfig>
304 where
305 G: Configurable,
306 {
307 self.guidance.set_config(config)
308 }
309
310 /// Retunes the stabilizer between ticks ([`Configurable::set_config`]): an invalid config
311 /// is rejected and the current one kept.
312 ///
313 /// ```
314 /// # use std::time::Duration;
315 /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
316 /// # use stable_flight::mixers::TableMixer;
317 /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
318 /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
319 /// use stable_flight::{Configurable, FlightLoop};
320 /// # struct Hover;
321 /// # impl Commander for Hover {
322 /// # fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
323 /// # Command::default()
324 /// # }
325 /// # }
326 /// # struct StillAir;
327 /// # impl StateSource for StillAir {
328 /// # fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
329 /// # }
330 /// # impl Actuator for StillAir {
331 /// # fn actuate(&mut self, _: &ActuatorCommand) {}
332 /// # }
333 /// # let mut flight_loop = FlightLoop::new(
334 /// # Hover,
335 /// # StillAir,
336 /// # CopterGuidance::new(CopterGuidanceConfig::default()),
337 /// # CopterStabilizer::new(CopterStabilizerConfig::default()),
338 /// # TableMixer::quad_x(),
339 /// # (),
340 /// # );
341 /// # flight_loop.prime();
342 /// flight_loop.step(Duration::from_millis(4));
343 ///
344 /// let mut retuned = *flight_loop.stabilizer().config();
345 /// retuned.body_rate.roll_gains.p = 0.2;
346 /// flight_loop.set_stabilizer_config(retuned).expect("valid config");
347 /// flight_loop.step(Duration::from_millis(4)); // flies the new gains
348 /// ```
349 pub fn set_stabilizer_config(&mut self, config: S::Config) -> Result<(), InvalidConfig>
350 where
351 S: Configurable,
352 {
353 self.stabilizer.set_config(config)
354 }
355
356 /// Splits the loop back into `(commander, vehicle, guidance, stabilizer, mixer, telemetry)`,
357 /// e.g. to inspect test doubles after a run or to hand the vehicle to another runner.
358 ///
359 /// ```
360 /// # use std::time::Duration;
361 /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
362 /// # use stable_flight::mixers::TableMixer;
363 /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
364 /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
365 /// use stable_flight::FlightLoop;
366 ///
367 /// # struct Hover;
368 /// # impl Commander for Hover {
369 /// # fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
370 /// # Command::default()
371 /// # }
372 /// # }
373 /// /// Counts actuations.
374 /// #[derive(Default)]
375 /// struct Bench {
376 /// actuations: u32,
377 /// }
378 /// # impl StateSource for Bench {
379 /// # fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
380 /// # }
381 /// impl Actuator for Bench {
382 /// fn actuate(&mut self, _: &ActuatorCommand) {
383 /// self.actuations += 1;
384 /// }
385 /// }
386 ///
387 /// let mut flight_loop = FlightLoop::new(
388 /// Hover,
389 /// Bench::default(),
390 /// CopterGuidance::new(CopterGuidanceConfig::default()),
391 /// CopterStabilizer::new(CopterStabilizerConfig::default()),
392 /// TableMixer::quad_x(),
393 /// (),
394 /// );
395 /// flight_loop.prime();
396 /// flight_loop.step(Duration::from_millis(4));
397 ///
398 /// let (_, bench, _, _, _, _) = flight_loop.into_parts();
399 /// assert_eq!(bench.actuations, 1);
400 /// ```
401 pub fn into_parts(self) -> (C, V, G, S, M, T) {
402 (
403 self.commander,
404 self.vehicle,
405 self.guidance,
406 self.stabilizer,
407 self.mixer,
408 self.telemetry,
409 )
410 }
411}
412
413/// The guidance's params, then the stabilizer's (see [`crate::params`]): combined indices
414/// run through the guidance's first, then the stabilizer's. Nothing checks that their names
415/// are disjoint: on a duplicate, name lookup finds the guidance's and the stabilizer's is
416/// reachable only by index, so table authors keep names unique across components (the copter
417/// tables use `GUID_`/`STAB_` prefixes).
418///
419/// ```
420/// # use std::time::Duration;
421/// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
422/// # use stable_flight::mixers::TableMixer;
423/// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
424/// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
425/// use stable_flight::params::Params;
426/// use stable_flight::{Configurable, FlightLoop};
427/// # struct Hover;
428/// # impl Commander for Hover {
429/// # fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
430/// # Command::default()
431/// # }
432/// # }
433/// # struct StillAir;
434/// # impl StateSource for StillAir {
435/// # fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
436/// # }
437/// # impl Actuator for StillAir {
438/// # fn actuate(&mut self, _: &ActuatorCommand) {}
439/// # }
440/// # let mut flight_loop = FlightLoop::new(
441/// # Hover,
442/// # StillAir,
443/// # CopterGuidance::new(CopterGuidanceConfig::default()),
444/// # CopterStabilizer::new(CopterStabilizerConfig::default()),
445/// # TableMixer::quad_x(),
446/// # (),
447/// # );
448///
449/// flight_loop.set_param("GUID_ALT_P", 2.5).expect("valid value");
450/// flight_loop.set_param("STAB_RATE_RLL_P", 0.2).expect("valid value");
451/// assert_eq!(flight_loop.guidance().config().altitude.gains.p, 2.5);
452/// assert_eq!(flight_loop.param("STAB_RATE_RLL_P"), Some(0.2));
453/// ```
454/// Autotune stages on a [`Tunable`] stabilizer, between ticks; forwarded so the loop hands out
455/// no `&mut` to its components.
456impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T> {
457 /// Starts a probe on one of the stabilizer's loops, from the next tick
458 /// ([`Tunable::start_probe`]).
459 ///
460 /// # Panics
461 ///
462 /// If `config` is invalid ([`ProbeConfig::validate`]).
463 pub fn start_probe<L: Copy>(&mut self, target: L, config: ProbeConfig)
464 where
465 S: Tunable<L>,
466 {
467 self.stabilizer.start_probe(target, config);
468 }
469
470 /// The stabilizer's current probe on its `L` loops, if any ([`Tunable::probe`]).
471 pub fn probe<L: Copy>(&self) -> Option<(L, ProbeStatus)>
472 where
473 S: Tunable<L>,
474 {
475 self.stabilizer.probe()
476 }
477
478 /// Ends the probe on the stabilizer's `L` loops and hands its loop back
479 /// ([`Tunable::stop_probe`]).
480 pub fn stop_probe<L: Copy>(&mut self) -> Option<(L, ProbeStatus)>
481 where
482 S: Tunable<L>,
483 {
484 self.stabilizer.stop_probe()
485 }
486}
487
488impl<C, V, G, S, M, T> Params for FlightLoop<C, V, G, S, M, T>
489where
490 G: Params,
491 S: Params,
492{
493 fn param_count(&self) -> usize {
494 self.guidance.param_count() + self.stabilizer.param_count()
495 }
496
497 fn param_name(&self, index: usize) -> Option<&'static str> {
498 match locate(&[&self.guidance, &self.stabilizer], index)? {
499 (0, i) => self.guidance.param_name(i),
500 (_, i) => self.stabilizer.param_name(i),
501 }
502 }
503
504 fn param_at(&self, index: usize) -> Option<f32> {
505 match locate(&[&self.guidance, &self.stabilizer], index)? {
506 (0, i) => self.guidance.param_at(i),
507 (_, i) => self.stabilizer.param_at(i),
508 }
509 }
510
511 fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
512 match locate(&[&self.guidance, &self.stabilizer], index).ok_or(ParamError::Unknown)? {
513 (0, i) => self.guidance.set_param_at(i, value),
514 (_, i) => self.stabilizer.set_param_at(i, value),
515 }
516 }
517}