Skip to main content

stable_flight/
testing.rs

1//! Test doubles for the pipeline traits. Enabled by the `testing` feature (and in this
2//! crate's own tests); off by default.
3//!
4//! Use these in tests of anything built on the core — runners, backends, firmware glue — instead
5//! of writing per-crate mocks. They allocate nothing, so they also work in `no_std` tests.
6//!
7//! - [`NullVehicle`]: returns a fixed state and counts calls.
8//! - [`ConstantCommander`]: emits the same [`Command`] every tick.
9//! - [`RecordingTelemetry`]: keeps copies of the last `N` ticks in a fixed-size ring.
10//! - [`settled_yaw_rate`]: closed-loop check of a body-rate config's yaw loop against a
11//!   constant torque, e.g. an airframe's measured hover yaw imbalance.
12//! - [`conformance`]: physical scenarios that check a backend's `VehicleState` against the
13//!   frame contract, and [`conformance_tests!`](crate::conformance_tests) to run them.
14//!
15//! Recover a double after running a [`FlightLoop`](crate::FlightLoop) with
16//! [`FlightLoop::into_parts`](crate::FlightLoop::into_parts).
17//!
18//! ```toml
19//! [dev-dependencies]
20//! stable-flight = { version = "0.2", features = ["testing"] }
21//! ```
22
23use core::time::Duration;
24
25use crate::controllers::{BodyRateController, BodyRateControllerConfig};
26use crate::{
27    Actuator, ActuatorCommand, Command, Commander, ControlOutput, FailsafeState, FlightModeReport,
28    Saturation, Setpoint, StateSource, TelemetryPublisher, TelemetryRecord, Vec3, VehicleState,
29    WindEstimate,
30};
31
32pub mod conformance;
33
34#[cfg(test)]
35mod tests;
36
37/// A vehicle that reports a fixed state, ignores commands, and counts both.
38///
39/// # Examples
40///
41/// ```
42/// use std::time::Duration;
43/// use stable_flight::testing::NullVehicle;
44/// use stable_flight::{Actuator, ActuatorCommand, StateSource};
45///
46/// let mut vehicle = NullVehicle::default();
47/// vehicle.state(Duration::ZERO);
48/// vehicle.actuate(&ActuatorCommand::default());
49/// assert_eq!((vehicle.state_reads(), vehicle.actuations()), (1, 1));
50/// ```
51#[derive(Debug, Clone, Default)]
52pub struct NullVehicle {
53    state: VehicleState,
54    state_reads: u64,
55    actuations: u64,
56    last_actuation: Option<ActuatorCommand>,
57}
58
59impl NullVehicle {
60    /// A vehicle at rest at the origin (`VehicleState::default()`).
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// A vehicle that always reports `state`.
66    pub fn with_state(state: VehicleState) -> Self {
67        NullVehicle {
68            state,
69            ..Self::default()
70        }
71    }
72
73    /// How many times `state` was called (including priming).
74    pub fn state_reads(&self) -> u64 {
75        self.state_reads
76    }
77
78    /// How many times `actuate` was called.
79    pub fn actuations(&self) -> u64 {
80        self.actuations
81    }
82
83    /// The most recent actuator command, if any.
84    pub fn last_actuation(&self) -> Option<&ActuatorCommand> {
85        self.last_actuation.as_ref()
86    }
87}
88
89impl StateSource for NullVehicle {
90    fn state(&mut self, _dt: Duration) -> VehicleState {
91        self.state_reads += 1;
92        self.state.clone()
93    }
94}
95
96impl Actuator for NullVehicle {
97    fn actuate(&mut self, actuator_command: &ActuatorCommand) {
98        self.actuations += 1;
99        self.last_actuation = Some(*actuator_command);
100    }
101}
102
103/// A commander that emits the same command every tick. The default is a disarmed,
104/// zero-throttle attitude command.
105///
106/// # Examples
107///
108/// ```
109/// use stable_flight::testing::ConstantCommander;
110/// use stable_flight::{AttitudeCommand, Command, Commander, ControlInput, VehicleState};
111///
112/// let hover = Command::armed(ControlInput::Attitude(AttitudeCommand {
113///     throttle: 0.5,
114///     ..Default::default()
115/// }));
116/// let mut commander = ConstantCommander::new(hover);
117/// let command = commander.next_command(0.004, &VehicleState::default());
118/// assert!(command.arm);
119/// assert!(matches!(
120///     command.input,
121///     ControlInput::Attitude(AttitudeCommand { throttle: 0.5, .. })
122/// ));
123/// ```
124#[derive(Debug, Default, Clone, Copy)]
125pub struct ConstantCommander {
126    command: Command,
127}
128
129impl ConstantCommander {
130    /// Emits `command` every tick.
131    pub fn new(command: Command) -> Self {
132        ConstantCommander { command }
133    }
134}
135
136impl Commander for ConstantCommander {
137    fn next_command(&mut self, _dt: f32, _current_state: &VehicleState) -> Command {
138        self.command
139    }
140}
141
142/// An owned copy of one [`TelemetryRecord`]; fields mean what they do there.
143#[derive(Debug, Clone)]
144#[allow(missing_docs)]
145pub struct RecordedTick {
146    pub dt: Duration,
147    pub command: Command,
148    pub setpoint: Setpoint,
149    pub state: VehicleState,
150    pub control: ControlOutput,
151    pub actuators: ActuatorCommand,
152    pub saturation: Saturation,
153    pub failsafe: Option<FailsafeState>,
154    pub flight_mode: FlightModeReport,
155    pub wind: Option<WindEstimate>,
156}
157
158impl RecordedTick {
159    /// Borrows this tick as a [`TelemetryRecord`], e.g. to replay it into another sink.
160    pub fn as_record(&self) -> TelemetryRecord<'_> {
161        TelemetryRecord {
162            dt: self.dt,
163            command: &self.command,
164            setpoint: &self.setpoint,
165            state: &self.state,
166            control: &self.control,
167            actuators: &self.actuators,
168            saturation: self.saturation,
169            failsafe: self.failsafe,
170            flight_mode: self.flight_mode,
171            wind: self.wind,
172        }
173    }
174}
175
176impl From<&TelemetryRecord<'_>> for RecordedTick {
177    fn from(record: &TelemetryRecord<'_>) -> Self {
178        RecordedTick {
179            dt: record.dt,
180            command: *record.command,
181            setpoint: *record.setpoint,
182            state: record.state.clone(),
183            control: *record.control,
184            actuators: *record.actuators,
185            saturation: record.saturation,
186            failsafe: record.failsafe,
187            flight_mode: record.flight_mode,
188            wind: record.wind,
189        }
190    }
191}
192
193/// A telemetry sink that keeps the last `N` ticks (a fixed-size ring, no allocation) and
194/// counts all of them.
195///
196/// Ticks are stored inline, roughly 200 bytes each, so the recorder is about `200 × N` bytes
197/// wherever it lives. Keep `N` small (hundreds) for a stack-allocated recorder; `N = 10_000`
198/// overflows a default test thread's stack. `N = 0` only counts.
199///
200/// # Examples
201///
202/// ```
203/// use std::time::Duration;
204/// use stable_flight::testing::RecordingTelemetry;
205/// use stable_flight::{
206///     ActuatorCommand, Command, ControlOutput, Saturation, Setpoint, TelemetryPublisher,
207///     TelemetryRecord, VehicleState,
208/// };
209///
210/// let mut telemetry = RecordingTelemetry::<2>::new();
211/// for thrust in [0.1, 0.2, 0.3] {
212///     telemetry.publish(&TelemetryRecord {
213///         dt: Duration::from_millis(4),
214///         command: &Command::default(),
215///         setpoint: &Setpoint::Attitude(Default::default()),
216///         state: &VehicleState::default(),
217///         control: &ControlOutput { thrust, ..Default::default() },
218///         actuators: &ActuatorCommand::default(),
219///         saturation: Saturation::default(),
220///         failsafe: None,
221///         flight_mode: Default::default(),
222///         wind: None,
223///     });
224/// }
225///
226/// assert_eq!(telemetry.total(), 3);
227/// let kept: Vec<f32> = telemetry.iter().map(|tick| tick.control.thrust).collect();
228/// assert_eq!(kept, [0.2, 0.3]); // oldest first; 0.1 was overwritten
229/// ```
230#[derive(Debug, Clone)]
231pub struct RecordingTelemetry<const N: usize> {
232    ticks: [Option<RecordedTick>; N],
233    total: u64,
234}
235
236impl<const N: usize> RecordingTelemetry<N> {
237    /// An empty recorder.
238    pub fn new() -> Self {
239        RecordingTelemetry {
240            ticks: core::array::from_fn(|_| None),
241            total: 0,
242        }
243    }
244
245    /// Ticks published so far, including ones no longer kept.
246    pub fn total(&self) -> u64 {
247        self.total
248    }
249
250    /// The most recent tick, if any.
251    pub fn last(&self) -> Option<&RecordedTick> {
252        let newest = self.total.checked_sub(1)?;
253        self.slot(newest)
254    }
255
256    /// The kept ticks, oldest first (at most `N`).
257    pub fn iter(&self) -> impl Iterator<Item = &RecordedTick> {
258        let kept = self.total.min(N as u64);
259        (self.total - kept..self.total).filter_map(|index| self.slot(index))
260    }
261
262    fn slot(&self, index: u64) -> Option<&RecordedTick> {
263        if N == 0 {
264            return None;
265        }
266        self.ticks[(index % N as u64) as usize].as_ref()
267    }
268}
269
270impl<const N: usize> Default for RecordingTelemetry<N> {
271    fn default() -> Self {
272        Self::new()
273    }
274}
275
276impl<const N: usize> TelemetryPublisher for RecordingTelemetry<N> {
277    fn publish(&mut self, record: &TelemetryRecord) {
278        if N > 0 {
279            self.ticks[(self.total % N as u64) as usize] = Some(RecordedTick::from(record));
280        }
281        self.total += 1;
282    }
283}
284
285/// Yaw acceleration of the [`settled_yaw_rate`] model per unit of normalized yaw moment, in
286/// rad/s².
287const YAW_MODEL_GAIN: f32 = 20.0;
288
289/// Tick of the [`settled_yaw_rate`] simulation, in seconds (250 Hz).
290const YAW_MODEL_DT: f32 = 0.004;
291
292/// Simulated time [`settled_yaw_rate`] runs before reading the rate, in seconds.
293const YAW_MODEL_DURATION_S: f32 = 60.0;
294
295/// The yaw rate in rad/s that a [`BodyRateController`] with `config` settles at while
296/// commanding zero rate against a constant yaw `disturbance` torque (normalized moment, nose
297/// right positive).
298///
299/// It flies a first-order yaw model, `ω̇ = 20 · (moment − disturbance)`, from rest for 60 s at
300/// 250 Hz. The integral cancels the disturbance up to its authority `yaw_gains.i ·
301/// yaw_max_integral`, so the result is 0 below it and `−(disturbance − i · yaw_max_integral) /
302/// p` above (a steady acro drift). The model has no inertia beyond the integrator, so it
303/// checks authority and steady state, not tuning.
304///
305/// # Examples
306///
307/// ```
308/// use stable_flight::controllers::{BodyRateControllerConfig, Gains};
309/// use stable_flight::testing::settled_yaw_rate;
310///
311/// let config = BodyRateControllerConfig {
312///     yaw_gains: Gains { p: 0.6, i: 0.2, d: 0.0 },
313///     yaw_max_integral: 1.0,
314///     ..Default::default()
315/// };
316/// // Within the integral's 0.2 authority: held at zero rate.
317/// assert!(settled_yaw_rate(&config, 0.15).abs() < 1e-3);
318/// // Past it: a steady counterclockwise drift of (0.4 - 0.2) / 0.6 rad/s.
319/// assert!((settled_yaw_rate(&config, 0.4) + 0.2 / 0.6).abs() < 1e-3);
320/// ```
321pub fn settled_yaw_rate(config: &BodyRateControllerConfig, disturbance: f32) -> f32 {
322    let mut controller = BodyRateController::default();
323    let mut rate_radps = 0.0;
324    for _ in 0..(YAW_MODEL_DURATION_S / YAW_MODEL_DT) as usize {
325        let moment = controller.control(
326            config,
327            YAW_MODEL_DT,
328            Vec3::zeros(),
329            Vec3::new(0.0, 0.0, rate_radps),
330        );
331        rate_radps += YAW_MODEL_GAIN * (moment.z - disturbance) * YAW_MODEL_DT;
332    }
333    rate_radps
334}