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