stable-flight 0.1.0

no_std flight-control core for Stable Flight: pipeline traits, copter guidance, cascaded-PID stabilizers, mixers, and the per-tick flight loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! One control-loop tick, independent of how ticks are scheduled.
//!
//! [`FlightLoop`] owns the six pipeline components and runs them in order for a single tick.
//! It has no clock, threads, or signal handling: a runner decides when to call
//! [`FlightLoop::step`] and with what `dt` (a wall-clock runner in `stable-flight-sitl` today;
//! a lockstep simulator runner or a hardware timer interrupt later).

use core::time::Duration;

use crate::controllers::InvalidConfig;
use crate::params::{ParamError, Params};
use crate::{
    ActuatorCommand, AttitudeSetpoint, Commander, Configurable, ControlOutput, Guidance, Mixer,
    Saturation, Setpoint, Stabilizer, TelemetryPublisher, TelemetryRecord, Vehicle, VehicleState,
};

#[cfg(test)]
mod tests;

/// Sequences one control tick: commander → estimate → guide → stabilize → mix → actuate →
/// telemetry.
///
/// Call [`prime`](FlightLoop::prime) once before the first [`step`](FlightLoop::step).
///
/// The [`Command`](crate::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::QuadCopterMixer;
/// 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()),
///     QuadCopterMixer::default(),
///     (), // 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.
pub struct FlightLoop<C, V, G, S, M, T> {
    commander: C,
    vehicle: V,
    guidance: G,
    stabilizer: S,
    mixer: M,
    telemetry: T,
    /// Latest estimate; the commander sees the previous tick's state.
    state: VehicleState,
    /// Whether the previous tick was armed; a rising edge re-primes.
    armed: bool,
}

impl<C, V, G, S, M, T> FlightLoop<C, V, G, S, M, T>
where
    C: Commander,
    V: Vehicle,
    G: Guidance,
    S: Stabilizer,
    M: Mixer,
    T: TelemetryPublisher,
{
    /// Assembles a loop from its six components. Does not touch the vehicle.
    pub fn new(
        commander: C,
        vehicle: V,
        guidance: G,
        stabilizer: S,
        mixer: M,
        telemetry: T,
    ) -> Self {
        FlightLoop {
            commander,
            vehicle,
            guidance,
            stabilizer,
            mixer,
            telemetry,
            state: VehicleState::default(),
            armed: false,
        }
    }

    /// 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`]).
    ///
    /// [`StateSource`]: crate::StateSource
    pub fn prime(&mut self) {
        self.state = self.vehicle.state(Duration::ZERO);
        self.guidance.prime(&self.state);
        self.stabilizer.prime(&self.state);
    }

    /// 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, and
    /// no saturation; 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).
    pub fn step(&mut self, dt: Duration) {
        let dt_secs = dt.as_secs_f32();

        let command = self.commander.next_command(dt_secs, &self.state);
        self.state = self.vehicle.state(dt);

        let (setpoint, control, actuators, saturation) = if command.arm {
            if !self.armed {
                self.guidance.prime(&self.state);
                self.stabilizer.prime(&self.state);
            }
            let setpoint = self.guidance.guide(dt_secs, &command.input, &self.state);
            let control = self.stabilizer.stabilize(dt_secs, &setpoint, &self.state);
            let actuators = self.mixer.mix(&control);
            let saturation = self
                .guidance
                .saturation()
                .merge(self.stabilizer.saturation())
                .merge(self.mixer.saturation());
            (setpoint, control, actuators, saturation)
        } else {
            let setpoint = Setpoint::Attitude(AttitudeSetpoint {
                heading_rad: self.state.heading_rad,
                ..Default::default()
            });
            (
                setpoint,
                ControlOutput::default(),
                ActuatorCommand::default(),
                Saturation::default(),
            )
        };
        self.armed = command.arm;
        self.vehicle.actuate(&actuators);

        self.telemetry.publish(&TelemetryRecord {
            dt,
            command: &command,
            setpoint: &setpoint,
            state: &self.state,
            control: &control,
            actuators: &actuators,
            saturation,
            failsafe: self.commander.failsafe(),
        });
    }

    /// The most recent state estimate.
    pub fn state(&self) -> &VehicleState {
        &self.state
    }

    /// The commander, e.g. to read its [`failsafe`](Commander::failsafe) state between ticks.
    pub fn commander(&self) -> &C {
        &self.commander
    }

    /// The guidance, e.g. to read its config.
    pub fn guidance(&self) -> &G {
        &self.guidance
    }

    /// The stabilizer, e.g. to read its config.
    pub fn stabilizer(&self) -> &S {
        &self.stabilizer
    }

    /// Retunes the guidance between ticks ([`Configurable::set_config`]): an invalid config is
    /// rejected and the current one kept.
    pub fn set_guidance_config(&mut self, config: G::Config) -> Result<(), InvalidConfig>
    where
        G: Configurable,
    {
        self.guidance.set_config(config)
    }

    /// Retunes the stabilizer between ticks ([`Configurable::set_config`]): an invalid config
    /// is rejected and the current one kept.
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
    /// # use stable_flight::mixers::QuadCopterMixer;
    /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
    /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
    /// use stable_flight::{Configurable, FlightLoop};
    /// # struct Hover;
    /// # impl Commander for Hover {
    /// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
    /// #         Command::default()
    /// #     }
    /// # }
    /// # struct StillAir;
    /// # impl StateSource for StillAir {
    /// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
    /// # }
    /// # impl Actuator for StillAir {
    /// #     fn actuate(&mut self, _: &ActuatorCommand) {}
    /// # }
    /// # let mut flight_loop = FlightLoop::new(
    /// #     Hover,
    /// #     StillAir,
    /// #     CopterGuidance::new(CopterGuidanceConfig::default()),
    /// #     CopterStabilizer::new(CopterStabilizerConfig::default()),
    /// #     QuadCopterMixer::default(),
    /// #     (),
    /// # );
    /// # flight_loop.prime();
    /// flight_loop.step(Duration::from_millis(4));
    ///
    /// let mut retuned = *flight_loop.stabilizer().config();
    /// retuned.body_rate.gains.p = 0.2;
    /// flight_loop.set_stabilizer_config(retuned).expect("valid config");
    /// flight_loop.step(Duration::from_millis(4)); // flies the new gains
    /// ```
    pub fn set_stabilizer_config(&mut self, config: S::Config) -> Result<(), InvalidConfig>
    where
        S: Configurable,
    {
        self.stabilizer.set_config(config)
    }

    /// 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 std::time::Duration;
    /// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
    /// # use stable_flight::mixers::QuadCopterMixer;
    /// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
    /// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
    /// use stable_flight::FlightLoop;
    ///
    /// # struct Hover;
    /// # impl Commander for Hover {
    /// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
    /// #         Command::default()
    /// #     }
    /// # }
    /// /// Counts actuations.
    /// #[derive(Default)]
    /// struct Bench {
    ///     actuations: u32,
    /// }
    /// # impl StateSource for Bench {
    /// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
    /// # }
    /// 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()),
    ///     QuadCopterMixer::default(),
    ///     (),
    /// );
    /// flight_loop.prime();
    /// flight_loop.step(Duration::from_millis(4));
    ///
    /// let (_, bench, _, _, _, _) = flight_loop.into_parts();
    /// assert_eq!(bench.actuations, 1);
    /// ```
    pub fn into_parts(self) -> (C, V, G, S, M, T) {
        (
            self.commander,
            self.vehicle,
            self.guidance,
            self.stabilizer,
            self.mixer,
            self.telemetry,
        )
    }
}

/// 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 std::time::Duration;
/// # use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
/// # use stable_flight::mixers::QuadCopterMixer;
/// # use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
/// # use stable_flight::{Actuator, ActuatorCommand, Command, Commander, StateSource, VehicleState};
/// use stable_flight::params::Params;
/// use stable_flight::{Configurable, FlightLoop};
/// # struct Hover;
/// # impl Commander for Hover {
/// #     fn next_command(&mut self, _: f32, _: &VehicleState) -> Command {
/// #         Command::default()
/// #     }
/// # }
/// # struct StillAir;
/// # impl StateSource for StillAir {
/// #     fn state(&mut self, _: Duration) -> VehicleState { VehicleState::default() }
/// # }
/// # impl Actuator for StillAir {
/// #     fn actuate(&mut self, _: &ActuatorCommand) {}
/// # }
/// # let mut flight_loop = FlightLoop::new(
/// #     Hover,
/// #     StillAir,
/// #     CopterGuidance::new(CopterGuidanceConfig::default()),
/// #     CopterStabilizer::new(CopterStabilizerConfig::default()),
/// #     QuadCopterMixer::default(),
/// #     (),
/// # );
///
/// flight_loop.set_param("GUID_ALT_P", 2.5).expect("valid value");
/// flight_loop.set_param("STAB_RATE_P", 0.2).expect("valid value");
/// assert_eq!(flight_loop.guidance().config().altitude.gains.p, 2.5);
/// assert_eq!(flight_loop.param("STAB_RATE_P"), Some(0.2));
/// ```
impl<C, V, G, S, M, T> Params for FlightLoop<C, V, G, S, M, T>
where
    G: Params,
    S: Params,
{
    fn param_count(&self) -> usize {
        self.guidance.param_count() + self.stabilizer.param_count()
    }

    fn param_name(&self, index: usize) -> Option<&'static str> {
        match self.split_param_index(index) {
            ParamOwner::Guidance(i) => self.guidance.param_name(i),
            ParamOwner::Stabilizer(i) => self.stabilizer.param_name(i),
        }
    }

    fn param_at(&self, index: usize) -> Option<f32> {
        match self.split_param_index(index) {
            ParamOwner::Guidance(i) => self.guidance.param_at(i),
            ParamOwner::Stabilizer(i) => self.stabilizer.param_at(i),
        }
    }

    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
        match self.split_param_index(index) {
            ParamOwner::Guidance(i) => self.guidance.set_param_at(i, value),
            ParamOwner::Stabilizer(i) => self.stabilizer.set_param_at(i, value),
        }
    }
}

/// The component a combined param index belongs to, with its index there.
enum ParamOwner {
    Guidance(usize),
    Stabilizer(usize),
}

impl<C, V, G: Params, S, M, T> FlightLoop<C, V, G, S, M, T> {
    fn split_param_index(&self, index: usize) -> ParamOwner {
        let guidance_count = self.guidance.param_count();
        if index < guidance_count {
            ParamOwner::Guidance(index)
        } else {
            ParamOwner::Stabilizer(index - guidance_count)
        }
    }
}