stable_flight/lib.rs
1//! [![github]](https://github.com/wboayue/stable-flight) [![crates-io]](https://crates.io/crates/stable-flight) [![license]](https://opensource.org/licenses/MIT)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [license]: https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge&labelColor=555555
6//!
7//! <br>
8//!
9//! Flight-control core for the Stable Flight controller: the pipeline traits ([`Commander`],
10//! [`StateSource`] + [`Actuator`] = [`Vehicle`], [`Guidance`], [`Stabilizer`], [`Mixer`],
11//! [`TelemetryPublisher`]), the data passed between them, copter guidance, the cascaded-PID
12//! stabilizers, the mixers, and [`FlightLoop`], which sequences one control tick.
13//!
14//! This crate is `no_std` and has no simulator, I/O, or timing dependencies, so the same code
15//! runs in software-in-the-loop simulation
16//! ([`stable-flight-sitl`](https://crates.io/crates/stable-flight-sitl)) and, later, on flight
17//! hardware. See the
18//! [architecture overview](https://github.com/wboayue/stable-flight/blob/main/architecture.md).
19
20#![cfg_attr(not(test), no_std)]
21
22pub mod commanders;
23pub mod composition;
24pub mod controllers;
25pub mod flight_loop;
26pub mod guidance;
27mod math;
28pub mod mixers;
29pub mod params;
30pub mod stabilizers;
31#[cfg(any(test, feature = "testing"))]
32pub mod testing;
33pub mod timing;
34
35use core::time::Duration;
36
37#[doc(inline)]
38pub use composition::ComposedVehicle;
39#[doc(inline)]
40pub use flight_loop::FlightLoop;
41
42use nalgebra::UnitQuaternion;
43
44pub use math::{euler_angles, wrap_angle};
45
46/// Re-export of the [`nalgebra`] version this crate's public types use; depend on it through
47/// here so the versions can't diverge.
48///
49/// # Examples
50///
51/// ```
52/// use stable_flight::VehicleState;
53/// use stable_flight::nalgebra::UnitQuaternion;
54///
55/// let state = VehicleState {
56/// attitude: UnitQuaternion::from_euler_angles(0.0, 0.1, 0.0),
57/// ..Default::default()
58/// };
59/// assert!(state.attitude.angle() > 0.0);
60/// ```
61pub use nalgebra;
62
63/// 2D vector used throughout the pipeline (waypoint positions, tilt, controller limits).
64///
65/// # Examples
66///
67/// ```
68/// use stable_flight::Vec2;
69///
70/// let tilt = Vec2::new(0.3, -0.1);
71/// assert_eq!(tilt.component_mul(&Vec2::new(2.0, 2.0)), Vec2::new(0.6, -0.2));
72/// ```
73pub type Vec2 = nalgebra::Vector2<f32>;
74
75/// 3D vector used throughout the pipeline (state vectors, moments, rates). Element-wise
76/// products are `component_mul`; `*` between two vectors is a matrix product.
77///
78/// # Examples
79///
80/// ```
81/// use stable_flight::Vec3;
82///
83/// let rates = Vec3::new(3.0, 4.0, 0.0);
84/// assert_eq!(rates.norm(), 5.0);
85/// ```
86pub type Vec3 = nalgebra::Vector3<f32>;
87
88/// Standard gravity, in m/s².
89pub const GRAVITY: f32 = 9.806_65;
90
91// Commanders
92
93/// Represents an entity that produces flight control commands.
94///
95/// The `Commander` trait is responsible for producing the next flight control command given the elapsed time (dt) and the current vehicle state (current_state).
96/// This allows for time-dependent and state-dependent command generation, such as ramping values, coordinating timed sequences, or adjusting commands based on the aircraft’s position or velocity.
97///
98/// Implementors of this trait may include:
99/// - **User input handlers**: Translate joystick/keyboard inputs into manual commands (e.g., [ControlInput::Attitude] or [ControlInput::Rate]).
100/// - **Navigation systems**: Generate waypoint commands (e.g., [ControlInput::Waypoint]) for autonomous flight to specific locations.
101/// - **Mission controllers**: Produce commands based on predefined flight plans or mission objectives.
102/// - **Formation controllers**: Maintain relative positioning between multiple aircraft in a formation.
103///
104/// # Examples
105///
106/// Implementing a simple `Commander` that always returns a constant `Attitude` command:
107/// ```
108/// use stable_flight::VehicleState;
109/// use stable_flight::{AttitudeCommand, Command, Commander, ControlInput};
110///
111/// struct ConstantAttitudeCommander;
112///
113/// impl Commander for ConstantAttitudeCommander {
114/// fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
115/// Command::armed(ControlInput::Attitude(AttitudeCommand {
116/// throttle: 0.5, // 50% throttle
117/// roll: 0.0, // No roll
118/// pitch: 0.0, // No pitch
119/// yaw: 0.0, // No yaw
120/// mode: 0, // Default mode
121/// }))
122/// }
123/// }
124/// ```
125pub trait Commander {
126 /// Produces the next command to be executed by the flight control system.
127 ///
128 /// # Parameters
129 ///
130 /// - `dt`: The time elapsed since the last command was generated in seconds.
131 /// This allows for time-dependent command generation, such as ramping up values
132 /// gradually or handling timed sequences.
133 /// - `current_state`: The current state of the vehicle, as a `VehicleState`.
134 /// Typically includes information like position, velocity, attitude, and other
135 /// relevant data, allowing the commander to generate state-dependent commands.
136 ///
137 /// # Returns
138 ///
139 /// A [`Command`]: whether the vehicle should be armed, and the [`ControlInput`] to fly.
140 /// `arm` is a level, not an event: return the desired state every tick.
141 fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command;
142
143 /// Which commander a failsafe let fly on the last [`next_command`](Self::next_command)
144 /// call, for a commander that has one
145 /// ([`FailsafeCommander`](crate::commanders::FailsafeCommander)). [`FlightLoop`] puts it in
146 /// the tick's [`TelemetryRecord::failsafe`]. The default reports none, so a commander that
147 /// wraps another must forward this to report the inner one's.
148 fn failsafe(&self) -> Option<FailsafeState> {
149 None
150 }
151}
152
153/// Which commander a [`FailsafeCommander`](crate::commanders::FailsafeCommander) let fly: its
154/// link-fed primary, or the fallback after the link went stale.
155///
156/// # Examples
157///
158/// ```
159/// use stable_flight::FailsafeState;
160///
161/// let link_ok = |state: Option<FailsafeState>| state != Some(FailsafeState::Fallback);
162/// assert!(link_ok(Some(FailsafeState::Primary)));
163/// assert!(link_ok(Some(FailsafeState::AwaitingSticks))); // heard, not yet in control
164/// assert!(link_ok(None)); // no failsafe: nothing to report
165/// assert!(!link_ok(Some(FailsafeState::Fallback)));
166/// ```
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
169#[non_exhaustive]
170pub enum FailsafeState {
171 /// The primary (link-fed) commander flies.
172 Primary,
173 /// The primary went stale, or hasn't been heard yet; the fallback flies.
174 Fallback,
175 /// The primary is fresh again, but flies sticks over an armed vehicle: the fallback flies
176 /// until a stick moves, so a forgotten joystick can't take over.
177 AwaitingSticks,
178}
179
180/// One tick's command from a [`Commander`]: whether the vehicle should be armed, and what to fly.
181///
182/// `arm` is vehicle-level and applies to every [`ControlInput`]. It is a level, not an event:
183/// a commander returns the desired state every tick (an edge-triggered source, such as a
184/// MAVLink arm request, latches it in the commander). While `arm` is `false`,
185/// [`FlightLoop`] holds the actuators at [`ActuatorCommand::default`] (motors off) and
186/// doesn't run guidance or the stabilizer; on the tick it turns `true`, it re-primes them so
187/// integrators start from zero.
188///
189/// # Examples
190///
191/// ```
192/// use stable_flight::{AttitudeCommand, Command, ControlInput};
193///
194/// let hover = Command::armed(ControlInput::Attitude(AttitudeCommand {
195/// throttle: 0.5,
196/// ..Default::default()
197/// }));
198/// assert!(hover.arm);
199///
200/// let switch_off = false;
201/// assert!(!Command::new(switch_off, hover.input).arm);
202/// ```
203#[derive(Debug, Default, Clone, Copy, PartialEq)]
204#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
205pub struct Command {
206 /// `true` to arm (motors may run), `false` to disarm (motors held off). Defaults to
207 /// `false`.
208 pub arm: bool,
209
210 /// What to fly while armed. Ignored while disarmed.
211 pub input: ControlInput,
212}
213
214impl Command {
215 /// A command with the given arm state.
216 pub fn new(arm: bool, input: ControlInput) -> Self {
217 Command { arm, input }
218 }
219
220 /// An armed command: fly `input`.
221 pub fn armed(input: ControlInput) -> Self {
222 Command::new(true, input)
223 }
224
225 /// A disarmed command: motors held off; `input` is carried for telemetry only.
226 pub fn disarmed(input: ControlInput) -> Self {
227 Command::new(false, input)
228 }
229}
230
231/// The control input part of a [`Command`]: what the flight system should fly.
232///
233/// The `ControlInput` enum encapsulates different types of commands that can be issued
234/// to control an aircraft. It supports five types of commands, categorized into four
235/// control paradigms:
236///
237/// * `Manual` - Low-level direct control inputs typically generated from user input devices.
238/// This includes:
239/// - `Attitude`: Controls the aircraft's orientation (roll, pitch, yaw).
240/// - `Rate`: Controls the aircraft's rotational rates (rate of change of roll, pitch, yaw).
241/// * `AbsoluteAttitude` - An absolute roll, pitch, and heading with collective thrust, from an
242/// offboard app (e.g. MAVLink `SET_ATTITUDE_TARGET`).
243/// * `Waypoint` - High-level navigational commands used for autonomous flight.
244/// * `Land` - Descend in place until touchdown.
245///
246/// This separation allows the flight control system to handle both manual piloting
247/// and automated navigation with a unified command interface.
248///
249/// # Examples
250///
251/// Creating a manual attitude command:
252/// ```
253/// use stable_flight::{ControlInput, AttitudeCommand};
254///
255/// let manual_cmd = ControlInput::Attitude(AttitudeCommand {
256/// throttle: 0.75, // 75% throttle
257/// roll: 0.1, // Slight right bank
258/// pitch: -0.05, // Slight nose down
259/// yaw: 0.0, // No yaw input
260/// ..Default::default()
261/// });
262/// ```
263///
264/// Creating a manual rate command:
265/// ```
266/// use stable_flight::{ControlInput, RateCommand};
267///
268/// let rate_cmd = ControlInput::Rate(RateCommand {
269/// throttle: 0.5, // 50% throttle
270/// roll_rate: 0.2, // Moderate roll rate
271/// pitch_rate: 0.1, // Moderate pitch rate
272/// yaw_rate: 0.0, // No yaw rate
273/// ..Default::default()
274/// });
275/// ```
276///
277/// Creating a waypoint command:
278/// ```
279/// use stable_flight::{ControlInput, Vec2, WaypointCommand};
280///
281/// let waypoint_cmd = ControlInput::Waypoint(WaypointCommand {
282/// position_m: Vec2::new(1000.0, 2000.0), // Target position in world coordinates
283/// velocity_mps: Some(Vec2::new(15.0, 0.0)), // Optional velocity to fly through it with
284/// altitude_m: 500.0, // Target altitude in meters
285/// cruise_speed_mps: 25.0, // Speed cap on the way
286/// roll_rad: Some(0.05), // Optional roll angle in radians
287/// });
288/// ```
289///
290/// # Notes
291/// - For `WaypointCommand`, optional fields like `velocity_mps` and `roll_rad` can be `None`. When `None`,
292/// the flight controller may use default values or ignore the parameter, depending on its implementation.
293/// - `#[non_exhaustive]`: new command kinds (e.g. fixed-wing) can be added without a breaking
294/// change. A [`Guidance`] that can't fly a variant must fall back to neutral, not panic (see
295/// [`Guidance::guide`]).
296#[derive(Debug, Clone, Copy, PartialEq)]
297#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
298#[non_exhaustive]
299pub enum ControlInput {
300 /// Direct manual control inputs for the aircraft's attitude (orientation).
301 ///
302 /// These values typically range from -1.0 to 1.0 (or 0.0 to 1.0 for throttle)
303 /// and directly influence the aircraft's roll, pitch, and yaw orientation.
304 /// The ranges are conventional and may not be enforced by the system.
305 Attitude(AttitudeCommand),
306
307 /// Direct manual control inputs for the aircraft's rotational rate.
308 ///
309 /// These values typically range from -1.0 to 1.0 (or 0.0 to 1.0 for throttle)
310 /// and directly influence the rate of change of roll, pitch, and yaw.
311 /// The ranges are conventional and may not be enforced by the system.
312 Rate(RateCommand),
313
314 /// Autonomous navigation command specifying a destination point.
315 ///
316 /// This command provides high-level navigational instructions that are translated
317 /// into appropriate control surface and throttle settings by the flight controller.
318 Waypoint(WaypointCommand),
319
320 /// An absolute attitude in radians and collective thrust, typically from an offboard app.
321 ///
322 /// Unlike [`ControlInput::Attitude`], the angles are not stick positions: roll and pitch
323 /// are flown as given (the stabilizer saturates them to its maximum tilt), and the heading
324 /// is an angle, not a rate.
325 AbsoluteAttitude(AbsoluteAttitudeCommand),
326
327 /// Hold a horizontal position and descend at a steady rate until the ground stops the
328 /// vehicle. Guidance only descends; deciding it has touched down and disarming is the
329 /// commander's job ([`TouchdownDetector`](crate::commanders::TouchdownDetector)).
330 Land(LandCommand),
331}
332
333/// Zero-throttle, centered-stick [`ControlInput::Attitude`].
334impl Default for ControlInput {
335 fn default() -> Self {
336 ControlInput::Attitude(AttitudeCommand::default())
337 }
338}
339
340impl ControlInput {
341 /// Whether this is pilot stick input (attitude or rate). After a link outage, the
342 /// failsafe hands an armed vehicle back to sticks only once they move, so a stick left
343 /// deflected can't take over unattended. Sticks are also a [stream](Self::is_stream).
344 ///
345 /// # Examples
346 ///
347 /// ```
348 /// use stable_flight::ControlInput;
349 ///
350 /// assert!(ControlInput::Attitude(Default::default()).is_sticks());
351 /// assert!(ControlInput::Rate(Default::default()).is_sticks());
352 /// assert!(!ControlInput::AbsoluteAttitude(Default::default()).is_sticks());
353 /// assert!(!ControlInput::Waypoint(Default::default()).is_sticks());
354 /// assert!(!ControlInput::Land(Default::default()).is_sticks());
355 /// ```
356 pub fn is_sticks(&self) -> bool {
357 matches!(self, ControlInput::Attitude(_) | ControlInput::Rate(_))
358 }
359
360 /// Whether this input is a stream that must keep arriving to stay valid (sticks and
361 /// absolute attitudes), unlike a waypoint or a land, which stays valid until replaced. A link-fed
362 /// commander treats a stream as stale once commands stop, even if other messages arrive.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use stable_flight::ControlInput;
368 ///
369 /// assert!(ControlInput::Attitude(Default::default()).is_stream());
370 /// assert!(ControlInput::Rate(Default::default()).is_stream());
371 /// assert!(ControlInput::AbsoluteAttitude(Default::default()).is_stream());
372 /// assert!(!ControlInput::Waypoint(Default::default()).is_stream());
373 /// assert!(!ControlInput::Land(Default::default()).is_stream());
374 /// ```
375 pub fn is_stream(&self) -> bool {
376 self.is_sticks() || matches!(self, ControlInput::AbsoluteAttitude(_))
377 }
378
379 /// Which kind of input this is, without its values: the flight mode a ground station shows.
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use stable_flight::{ControlInput, ControlMode};
385 ///
386 /// assert_eq!(ControlInput::Attitude(Default::default()).mode(), ControlMode::Attitude);
387 /// assert_eq!(ControlInput::Rate(Default::default()).mode(), ControlMode::Rate);
388 /// assert_eq!(ControlInput::Waypoint(Default::default()).mode(), ControlMode::Waypoint);
389 /// assert_eq!(
390 /// ControlInput::AbsoluteAttitude(Default::default()).mode(),
391 /// ControlMode::AbsoluteAttitude,
392 /// );
393 /// assert_eq!(ControlInput::Land(Default::default()).mode(), ControlMode::Land);
394 /// ```
395 pub fn mode(&self) -> ControlMode {
396 match self {
397 ControlInput::Attitude(_) => ControlMode::Attitude,
398 ControlInput::Rate(_) => ControlMode::Rate,
399 ControlInput::Waypoint(_) => ControlMode::Waypoint,
400 ControlInput::AbsoluteAttitude(_) => ControlMode::AbsoluteAttitude,
401 ControlInput::Land(_) => ControlMode::Land,
402 }
403 }
404}
405
406/// The kind of a [`ControlInput`], one variant per input variant: the flight mode, compact
407/// enough for a heartbeat. From [`ControlInput::mode`].
408///
409/// `#[non_exhaustive]` like [`ControlInput`]: a new input kind adds a mode, and a consumer
410/// that doesn't know it reports no mode.
411///
412/// The variant order is on the link's wire (`stable-flight-link`'s heartbeat): changing it is
413/// a protocol change, which bumps that crate's `PROTOCOL_VERSION`.
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
416#[non_exhaustive]
417pub enum ControlMode {
418 /// Stick inputs command attitude ([`ControlInput::Attitude`]).
419 Attitude,
420 /// Stick inputs command body rates ([`ControlInput::Rate`]).
421 Rate,
422 /// Autonomous flight to a waypoint ([`ControlInput::Waypoint`]).
423 Waypoint,
424 /// An offboard app commands an absolute attitude ([`ControlInput::AbsoluteAttitude`]).
425 AbsoluteAttitude,
426 /// Autonomous descent to touchdown ([`ControlInput::Land`]).
427 Land,
428}
429
430/// Represents direct manual control of an aircraft's attitude (orientation).
431///
432/// This struct encapsulates pilot inputs from control devices like joysticks,
433/// yokes, or keyboard/mouse combinations to control the aircraft's orientation
434/// (roll, pitch, yaw) and throttle. It is typically used within a `ControlInput::Attitude`
435/// variant to issue manual flight commands to the flight system.
436///
437/// # Value Ranges
438///
439/// - `throttle`: `0.0` (idle) to `1.0` (full power)
440/// - `roll`: `-1.0` (full left bank) to `1.0` (full right bank)
441/// - `pitch`: `-1.0` (full nose down) to `1.0` (full nose up)
442/// - `yaw`: `-1.0` (full left turn) to `1.0` (full right turn)
443/// - `mode`: `0` to `2` (specific meaning depends on the flight system)
444///
445/// Note: The specified ranges are conventional and recommended for typical use.
446/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
447/// depending on the flight system's implementation.
448///
449/// # Examples
450///
451/// Creating an `AttitudeCommand` for a slight climb with a right bank:
452/// ```
453/// use stable_flight::AttitudeCommand;
454///
455/// let cmd = AttitudeCommand {
456/// throttle: 0.75, // 75% throttle
457/// roll: 0.1, // Slight right bank
458/// pitch: 0.05, // Slight nose up
459/// yaw: 0.0, // No yaw input
460/// mode: 1, // Example mode (e.g., stabilized)
461/// };
462/// ```
463///
464/// # Default Implementation
465///
466/// The `Default` trait is implemented for `AttitudeCommand`, providing the following
467/// default values:
468/// - `throttle`: `0.0`
469/// - `roll`: `0.0`
470/// - `pitch`: `0.0`
471/// - `yaw`: `0.0`
472/// - `mode`: `0`
473#[derive(Debug, Default, Clone, Copy, PartialEq)]
474#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
475pub struct AttitudeCommand {
476 /// Controls the engine power output, ranging from `0.0` (idle) to `1.0` (maximum).
477 pub throttle: f32,
478
479 /// Controls the aircraft's roll/bank angle, ranging from `-1.0` (full left bank)
480 /// to `1.0` (full right bank).
481 pub roll: f32,
482
483 /// Controls the aircraft's pitch angle, ranging from `-1.0` (full nose down)
484 /// to `1.0` (full nose up).
485 pub pitch: f32,
486
487 /// Controls the aircraft's yaw rotation, ranging from `-1.0` (full left turn)
488 /// to `1.0` (full right turn).
489 pub yaw: f32,
490
491 /// Controls the aircraft's flight mode, ranging from `0` to `2`.
492 /// The specific meaning of each value depends on the flight system implementation
493 /// (e.g., `0` might be manual mode, `1` stabilized, `2` autonomous).
494 pub mode: u8,
495}
496
497/// Represents direct manual control of an aircraft's rotational rates.
498///
499/// This struct encapsulates pilot inputs from control devices like joysticks,
500/// yokes, or keyboard/mouse combinations to control the aircraft's rate of rotation
501/// (roll rate, pitch rate, yaw rate) and throttle. It is typically used within a
502/// `ControlInput::Rate` variant to issue manual flight commands to the flight system.
503///
504/// The "rate" refers to the speed of rotation around each axis, typically measured
505/// in a normalized range where `-1.0` and `1.0` represent the maximum rates supported
506/// by the flight system (e.g., radians per second, scaled to system limits).
507///
508/// # Value Ranges
509///
510/// - `throttle`: `0.0` (idle) to `1.0` (full power)
511/// - `roll_rate`: `-1.0` (maximum left roll rate) to `1.0` (maximum right roll rate)
512/// - `pitch_rate`: `-1.0` (maximum nose-down rate) to `1.0` (maximum nose-up rate)
513/// - `yaw_rate`: `-1.0` (maximum left yaw rate) to `1.0` (maximum right yaw rate)
514/// - `mode`: `0` to `2` (specific meaning depends on the flight system)
515///
516/// Note: The specified ranges are conventional and recommended for typical use.
517/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
518/// depending on the flight system's implementation.
519///
520/// # Examples
521///
522/// Creating a `RateCommand` for a moderate right roll and slight nose-up rate:
523/// ```
524/// use stable_flight::RateCommand;
525///
526/// let cmd = RateCommand {
527/// throttle: 0.6, // 60% throttle
528/// roll_rate: 0.3, // Moderate right roll rate
529/// pitch_rate: 0.1, // Slight nose-up rate
530/// yaw_rate: 0.0, // No yaw rate
531/// mode: 1, // Example mode (e.g., stabilized)
532/// };
533/// ```
534///
535/// # Default Implementation
536///
537/// The `Default` trait is implemented for `RateCommand`, providing the following
538/// default values:
539/// - `throttle`: `0.0`
540/// - `roll_rate`: `0.0`
541/// - `pitch_rate`: `0.0`
542/// - `yaw_rate`: `0.0`
543/// - `mode`: `0`
544#[derive(Debug, Default, Clone, Copy, PartialEq)]
545#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
546pub struct RateCommand {
547 /// Controls the engine power output, ranging from `0.0` (idle) to `1.0` (maximum).
548 pub throttle: f32,
549
550 /// Controls the aircraft's roll rate, ranging from `-1.0` (maximum left roll rate)
551 /// to `1.0` (maximum right roll rate).
552 pub roll_rate: f32,
553
554 /// Controls the aircraft's pitch rate, ranging from `-1.0` (maximum nose-down rate)
555 /// to `1.0` (maximum nose-up rate).
556 pub pitch_rate: f32,
557
558 /// Controls the aircraft's yaw rate, ranging from `-1.0` (maximum left yaw rate)
559 /// to `1.0` (maximum right yaw rate).
560 pub yaw_rate: f32,
561
562 /// Controls the aircraft's flight mode, ranging from `0` to `2`.
563 /// The specific meaning of each value depends on the flight system implementation
564 /// (e.g., `0` might be manual mode, `1` stabilized, `2` autonomous).
565 pub mode: u8,
566}
567
568/// Represents a navigational waypoint for autonomous flight.
569///
570/// A `WaypointCommand` instructs the aircraft to navigate to a specific position
571/// in 2D space at a given altitude, at up to a cruise speed, optionally flying through it
572/// with a given velocity and a desired roll angle during the approach. This struct is
573/// typically used within a `ControlInput::Waypoint` variant to issue autonomous navigation
574/// commands to the flight system.
575///
576/// # Value Ranges
577///
578/// - `position_m`: X, Y coordinates in 2D space (units and coordinate system depend on the flight system, typically meters in world coordinates)
579/// - `velocity_mps`: Optional velocity vector in meters per second (north, east), fed forward while flying to the waypoint
580/// - `altitude_m`: Target altitude in meters (typically non-negative; negative values may be interpreted as ground level or cause undefined behavior)
581/// - `cruise_speed_mps`: Speed cap in meters per second while flying to the waypoint; zero, negative, or NaN means no cap
582/// - `roll_rad`: Optional roll angle in radians (typically between `-π` and `π`; depends on system limits)
583///
584/// Note: The specified ranges are conventional and recommended for typical use.
585/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
586/// depending on the flight system's implementation.
587///
588/// # Examples
589///
590/// Creating a `WaypointCommand` to navigate to a position with a specific altitude and speed:
591/// ```
592/// use stable_flight::{Vec2, WaypointCommand};
593///
594/// let cmd = WaypointCommand {
595/// position_m: Vec2::new(1000.0, 2000.0), // Target position (X=1000m, Y=2000m)
596/// velocity_mps: Some(Vec2::new(15.0, 0.0)), // Fly through it northward at 15 m/s
597/// altitude_m: 500.0, // Target altitude of 500 meters
598/// cruise_speed_mps: 25.0, // At most 25 m/s on the way
599/// roll_rad: Some(0.05), // Slight right roll during approach
600/// };
601/// ```
602///
603/// # Behavior of Optional Fields
604///
605/// - If `velocity_mps` is `None`, the aircraft stops on the waypoint.
606/// [`WaypointFollower`](crate::commanders::WaypointFollower) fills it in along each leg so
607/// a route is flown at cruise speed.
608/// - If `roll_rad` is `None`, the flight system typically maintains a default roll (e.g., zero or coordinated turn behavior).
609///
610/// # Default Implementation
611///
612/// The `Default` trait is implemented for `WaypointCommand`, providing the following
613/// default values:
614/// - `position_m`: zero
615/// - `velocity_mps`: `None`
616/// - `altitude_m`: `0.0`
617/// - `cruise_speed_mps`: `0.0`
618/// - `roll_rad`: `None`
619#[derive(Debug, Default, Clone, Copy, PartialEq)]
620#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
621pub struct WaypointCommand {
622 /// The target position in 2D space (X, Y coordinates).
623 ///
624 /// The coordinate system and units depend on the flight system implementation
625 /// (typically meters in world coordinates).
626 pub position_m: Vec2,
627
628 /// Optional velocity, in meters per second (north, east), to fly through the waypoint
629 /// with.
630 ///
631 /// Guidance feeds it forward while flying to the waypoint (added to the position loop's
632 /// demand, then capped at `cruise_speed_mps`), so the aircraft passes the waypoint
633 /// instead of stopping on it. `None` stops on the waypoint.
634 /// [`WaypointFollower`](crate::commanders::WaypointFollower) fills it in along each leg
635 /// when it's `None`.
636 pub velocity_mps: Option<Vec2>,
637
638 /// Target altitude in meters.
639 ///
640 /// Typically non-negative; negative values may be interpreted as ground level
641 /// or cause undefined behavior depending on the flight system.
642 pub altitude_m: f32,
643
644 /// Cruise speed in meters per second: the most guidance asks for while flying to the
645 /// waypoint. Zero, negative, or NaN means no cap (the guidance's tilt limit still
646 /// bounds the speed).
647 pub cruise_speed_mps: f32,
648
649 /// Optional desired roll angle in radians.
650 ///
651 /// When provided, the aircraft will attempt to maintain this roll angle while
652 /// approaching the waypoint. This is useful for creating coordinated turns or
653 /// acrobatic maneuvers. If `None`, the flight system typically maintains a default
654 /// roll (e.g., zero or coordinated turn behavior). Values typically range between
655 /// `-π` and `π`, depending on system limits.
656 pub roll_rad: Option<f32>,
657}
658
659/// An absolute attitude and collective thrust, for [`ControlInput::AbsoluteAttitude`]: what
660/// an offboard app (e.g. MAVLink `SET_ATTITUDE_TARGET`) asks for, as opposed to the normalized
661/// stick positions of an [`AttitudeCommand`].
662///
663/// Per the input policy, nothing is rejected: the stabilizer saturates roll and pitch to its
664/// maximum tilt and flies NaN as level, a NaN heading holds the current heading-hold target,
665/// and thrust saturates to `[0, 1]` (NaN means none).
666///
667/// # Examples
668///
669/// A 10° right bank, holding north, at 45% thrust:
670/// ```
671/// use stable_flight::{AbsoluteAttitudeCommand, ControlInput};
672///
673/// let input = ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
674/// roll_rad: 10.0_f32.to_radians(),
675/// pitch_rad: 0.0,
676/// heading_rad: 0.0,
677/// thrust: 0.45,
678/// });
679/// ```
680#[derive(Debug, Default, Clone, Copy, PartialEq)]
681#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
682pub struct AbsoluteAttitudeCommand {
683 /// Roll in radians, right positive, per the
684 /// [frame contract](VehicleState#frame-contract)'s `roll_rad`.
685 pub roll_rad: f32,
686 /// Pitch in radians, nose up positive, per the
687 /// [frame contract](VehicleState#frame-contract)'s `pitch_rad`.
688 pub pitch_rad: f32,
689 /// Absolute heading in radians, in the
690 /// [frame contract](VehicleState#frame-contract)'s `heading_rad` convention; any value,
691 /// wrapped by guidance.
692 pub heading_rad: f32,
693 /// Collective thrust along the body axis, `0.0` to `1.0`. Unlike an [`AttitudeCommand`]'s
694 /// throttle, it is not boosted for tilt: the sender owns that compensation.
695 pub thrust: f32,
696}
697
698/// Where to land, for [`ControlInput::Land`]: guidance holds `position_m` while it descends.
699///
700/// # Examples
701///
702/// ```
703/// use stable_flight::{ControlInput, LandCommand, Vec2};
704///
705/// let input = ControlInput::Land(LandCommand { position_m: Vec2::new(10.0, -5.0) });
706/// ```
707#[derive(Debug, Default, Clone, Copy, PartialEq)]
708#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
709pub struct LandCommand {
710 /// Horizontal position to hold, in meters, in the same frame as
711 /// [`WaypointCommand::position_m`].
712 pub position_m: Vec2,
713}
714
715/// Represents the high-level control outputs from the stabilization system.
716///
717/// This struct encapsulates the desired thrust and moments to be applied to the
718/// vehicle, which are later translated to specific actuator commands by a `Mixer`.
719///
720/// # Examples
721///
722/// Creating a control output for a simple hover command:
723/// ```
724/// use stable_flight::{ControlOutput, Vec3};
725///
726/// let output = ControlOutput::new(
727/// 0.5, // 50% thrust
728/// Vec3::zeros() // No roll, pitch, or yaw moments
729/// );
730/// ```
731#[derive(Debug, Default, Clone, Copy, PartialEq)]
732#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
733pub struct ControlOutput {
734 /// Normalized thrust value, typically ranging from 0.0 (no thrust) to 1.0 (maximum thrust).
735 pub thrust: f32,
736
737 /// Control moments in roll (x), pitch (y), and yaw (z) axes.
738 /// Values are typically normalized between -1.0 and 1.0, where the magnitude
739 /// represents the proportion of maximum control authority in each axis.
740 pub moments: Vec3,
741}
742
743impl ControlOutput {
744 /// Creates a new `ControlOutput` with the specified thrust and control moments.
745 ///
746 /// # Parameters
747 ///
748 /// - `thrust`: Normalized thrust value, typically between 0.0 and 1.0.
749 /// - `moments`: Control moments as a 3D vector (roll, pitch, yaw).
750 ///
751 /// # Returns
752 ///
753 /// A new `ControlOutput` instance with the specified parameters.
754 pub fn new(thrust: f32, moments: Vec3) -> ControlOutput {
755 ControlOutput { thrust, moments }
756 }
757}
758
759/// Represents the physical state of a vehicle in 3D space.
760///
761/// This struct encapsulates all the key state information needed for flight control,
762/// including position, velocity, acceleration, attitude, and angular velocity.
763/// Quantities are plain SI `f32`s; field names carry the unit (`position_m`, `velocity_mps`, …).
764///
765/// # Frame contract
766///
767/// This table is the reference for how every [`StateSource`] reports state; a backend
768/// converts from its native frames at its boundary, and `testing::conformance` (`testing`
769/// feature) checks it.
770///
771/// Two frames are involved. Attitude follows aerospace convention: the NED world frame
772/// (`x` north, `y` east, `z` down) and the FRD body frame (`x` forward, `y` right, `z` down).
773/// Translation uses the same north and east axes but flips `z` to point **up**, so altitude
774/// and climb rate are positive: `position_m`/`velocity_mps`/`acceleration_mps2` `z` is NED `z`
775/// negated.
776///
777/// | Quantity | Frame | Units | Positive |
778/// |---|---|---|---|
779/// | `position_m` | `x` north, `y` east, `z` up | m | `z` is altitude above the backend's datum (e.g. sea level) |
780/// | `velocity_mps`, `acceleration_mps2` | as `position_m` | m/s, m/s² | `z` climbing |
781/// | `attitude` | NED world → FRD body, ZYX (yaw, pitch, roll); `UnitQuaternion::from_euler_angles(roll, pitch, heading)` | — | [`euler_angles`] of it match the fields below |
782/// | `roll_rad` | about body `x` | rad | right wing down |
783/// | `pitch_rad` | about body `y` | rad | nose up |
784/// | `heading_rad` | about NED `z` | rad | clockwise from north (east = π/2); any range, e.g. [0, 2π) or [-π, π) |
785/// | `angular_velocity_radps` | FRD body: `x` roll, `y` pitch, `z` yaw | rad/s | roll right, nose up, nose right |
786///
787/// # Examples
788///
789/// Creating a default vehicle state:
790/// ```
791/// use stable_flight::VehicleState;
792///
793/// let state = VehicleState::default();
794/// ```
795#[derive(Debug, Clone, Default, PartialEq)]
796#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
797pub struct VehicleState {
798 /// World position (north, east, up); see the [frame contract](VehicleState#frame-contract).
799 pub position_m: Vec3,
800
801 /// World velocity (north, east, up).
802 pub velocity_mps: Vec3,
803
804 /// World acceleration (north, east, up).
805 pub acceleration_mps2: Vec3,
806
807 /// Orientation quaternion representing the vehicle's attitude.
808 /// The quaternion represents the rotation from world frame to body frame.
809 pub attitude: UnitQuaternion<f32>,
810
811 /// Body angular velocity in roll (x), pitch (y), and yaw (z), in radians per second.
812 pub angular_velocity_radps: Vec3,
813
814 /// Current roll angle in radians, right wing down positive.
815 pub roll_rad: f32,
816
817 /// Current pitch angle in radians, nose up positive.
818 pub pitch_rad: f32,
819
820 /// Current heading (yaw) angle in radians.
821 /// 0 is north, with positive values rotating clockwise.
822 pub heading_rad: f32,
823 // Note: Additional fields for flight mode, GPS data, etc. may be added in the future.
824}
825
826/// Represents a physical vehicle that can be controlled by the flight system.
827///
828/// A `Vehicle` is anything that is both a [`StateSource`] and an [`Actuator`]; the blanket
829/// impl below provides it automatically, so implement those two traits rather than this one.
830/// The split mirrors hardware, where sensing (IMU, estimator) and actuation (ESC/servo output)
831/// are usually separate drivers, while a simulator bridge can implement both on one type.
832///
833/// Examples: a simulator bridge such as `RealFlightVehicle`, a hardware IMU/estimator paired
834/// with an ESC driver (see [`ComposedVehicle`]), or a test double such as
835/// `testing::NullVehicle` (`testing` feature).
836///
837/// # Timing contract
838///
839/// [`FlightLoop::step`] calls [`StateSource::state`] once, then
840/// [`Actuator::actuate`] once, every tick. A backend must:
841///
842/// - report state in the [`VehicleState` frame contract](VehicleState#frame-contract);
843/// - talk to its simulator or hardware at most once per call, and should not block for longer
844/// than a tick (document it if a blocking link can);
845/// - document how old the state from `state` is relative to the last `actuate`. A
846/// backend whose link sends controls and returns state in one round-trip exchanges in
847/// `actuate` and returns the cached result, so tick *n* stabilizes on state reported when
848/// the simulator received tick *n − 1*'s controls. A backend with a separate sensor read
849/// should read fresh state in `state`;
850/// - produce real state on the priming call (`dt == Duration::ZERO`, made once by
851/// [`FlightLoop::prime`] before any `actuate`), contacting the simulator if it must, and
852/// document what it returns if that fails.
853///
854/// # Examples
855///
856/// ```
857/// use std::time::Duration;
858/// use stable_flight::{Actuator, ActuatorCommand, StateSource, Vehicle, VehicleState};
859///
860/// struct HoverSim {
861/// state: VehicleState,
862/// }
863///
864/// impl StateSource for HoverSim {
865/// fn state(&mut self, _dt: Duration) -> VehicleState {
866/// self.state.clone()
867/// }
868/// }
869///
870/// impl Actuator for HoverSim {
871/// fn actuate(&mut self, _command: &ActuatorCommand) {}
872/// }
873///
874/// fn requires_vehicle(_: &impl Vehicle) {}
875/// requires_vehicle(&HoverSim { state: VehicleState::default() });
876/// ```
877pub trait Vehicle: StateSource + Actuator {}
878
879impl<T: StateSource + Actuator> Vehicle for T {}
880
881/// Where the flight loop's vehicle state comes from.
882///
883/// The name describes the role, not how the state is obtained. Implementors include:
884/// - **Simulator backends** that report the simulator's true state (e.g. `RealFlightVehicle`);
885/// - **Test doubles** that report a fixed state (`testing::NullVehicle`);
886/// - **Estimators** that fuse sensor readings into an estimate (IMU, baro, mag, GNSS).
887///
888/// Every implementor reports in the [`VehicleState` frame contract](VehicleState#frame-contract).
889pub trait StateSource {
890 /// Returns the current vehicle state.
891 ///
892 /// Takes `&mut self` because sources typically advance internal state on each call
893 /// (a filter's predict/update, a simulator exchange's bookkeeping).
894 ///
895 /// # Parameters
896 /// - `dt`: Time elapsed since the previous call. The first call, made once before the
897 /// control loop starts, passes `Duration::ZERO`; implementations may use it to
898 /// initialize (see `RealFlightVehicle`).
899 fn state(&mut self, dt: Duration) -> VehicleState;
900}
901
902/// Component responsible for controlling the vehicle's actuators.
903///
904/// The `Actuator` trait defines the interface for components that translate
905/// actuator commands into actual physical actions, such as moving control surfaces
906/// or adjusting motor speeds.
907///
908/// Implementors of this trait may include:
909/// - **Motor controllers**: Control electric motors for thrust
910/// - **Servo drivers**: Position control surfaces like elevators and ailerons
911/// - **Simulation interfaces**: Send control commands to physics engines
912pub trait Actuator {
913 /// Actuates the vehicle's control surfaces and/or motors based on the command.
914 ///
915 /// # Parameters
916 ///
917 /// - `actuator_command`: The command values to apply to the actuators.
918 fn actuate(&mut self, actuator_command: &ActuatorCommand);
919}
920
921/// What the [`Stabilizer`] should hold this tick, as produced by a [`Guidance`].
922///
923/// A [`ControlInput`] says what the operator or mission wants (stick positions, a waypoint);
924/// a `Setpoint` is the inner-loop target derived from it. Attitude targets are physical
925/// angles in radians; rates and thrust are normalized. The stabilizer owns the physical
926/// limits (maximum tilt and rates) and the thrust curve, and saturates out-of-range or NaN
927/// inputs per the input policy.
928///
929/// `#[non_exhaustive]`: new setpoint kinds (e.g. fixed-wing) can be added without a breaking
930/// change. A [`Stabilizer`] that can't fly a variant must fall back to neutral, not panic (see
931/// [`Stabilizer::stabilize`]).
932///
933/// # Examples
934///
935/// ```
936/// use stable_flight::{AttitudeSetpoint, Setpoint};
937///
938/// // Level, north-facing hover at half linear thrust.
939/// let hover = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
940/// ```
941#[derive(Debug, Clone, Copy, PartialEq)]
942#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
943#[non_exhaustive]
944pub enum Setpoint {
945 /// Hold a roll/pitch attitude and an absolute heading.
946 Attitude(AttitudeSetpoint),
947 /// Hold body rates.
948 Rate(RateSetpoint),
949}
950
951/// Attitude target for the [`Stabilizer`]; see [`Setpoint`].
952#[derive(Debug, Default, Clone, Copy, PartialEq)]
953#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
954pub struct AttitudeSetpoint {
955 /// Roll target in radians, right positive, per the
956 /// [frame contract](VehicleState#frame-contract)'s `roll_rad`. The stabilizer saturates it
957 /// to its maximum tilt; NaN means level.
958 pub roll_rad: f32,
959 /// Pitch target in radians, nose up positive, per the
960 /// [frame contract](VehicleState#frame-contract)'s `pitch_rad`. The stabilizer saturates it
961 /// to its maximum tilt; NaN means level.
962 pub pitch_rad: f32,
963 /// Absolute heading target in radians, in the
964 /// [frame contract](VehicleState#frame-contract)'s `heading_rad` convention.
965 pub heading_rad: f32,
966 /// Linear collective thrust, `0.0` to `1.0`, before the stabilizer's thrust curve.
967 pub thrust: f32,
968}
969
970/// Body-rate target for the [`Stabilizer`]; see [`Setpoint`].
971#[derive(Debug, Default, Clone, Copy, PartialEq)]
972#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
973pub struct RateSetpoint {
974 /// Roll rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (right positive).
975 pub roll_rate: f32,
976 /// Pitch rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (nose up
977 /// positive).
978 pub pitch_rate: f32,
979 /// Yaw rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (nose right
980 /// positive).
981 pub yaw_rate: f32,
982 /// Linear collective thrust, `0.0` to `1.0`, before the stabilizer's thrust curve.
983 pub thrust: f32,
984}
985
986/// Passes the sticks through as rates, with `throttle` as `thrust`; `mode` is dropped.
987///
988/// # Examples
989///
990/// ```
991/// use stable_flight::{RateCommand, RateSetpoint};
992///
993/// let command = RateCommand {
994/// throttle: 0.6,
995/// roll_rate: 0.1,
996/// pitch_rate: -0.2,
997/// yaw_rate: 0.3,
998/// mode: 2,
999/// };
1000/// let setpoint = RateSetpoint::from(&command);
1001/// assert_eq!(
1002/// setpoint,
1003/// RateSetpoint { roll_rate: 0.1, pitch_rate: -0.2, yaw_rate: 0.3, thrust: 0.6 }
1004/// );
1005/// ```
1006impl From<&RateCommand> for RateSetpoint {
1007 fn from(command: &RateCommand) -> Self {
1008 // Exhaustive destructuring: a new field fails to compile here until it is mapped.
1009 let RateCommand {
1010 throttle,
1011 roll_rate,
1012 pitch_rate,
1013 yaw_rate,
1014 mode: _,
1015 } = *command;
1016 Self {
1017 roll_rate,
1018 pitch_rate,
1019 yaw_rate,
1020 thrust: throttle,
1021 }
1022 }
1023}
1024
1025/// Turns the commander's [`ControlInput`] into an inner-loop [`Setpoint`].
1026///
1027/// Guidance only runs while the [`Command`] is armed, so it never sees `arm`.
1028///
1029/// Guidance is the outer loop: waypoint navigation (position and altitude hold), and the
1030/// interpretation of pilot sticks that needs memory, such as integrating yaw stick into a
1031/// heading-hold target. The [`Stabilizer`] then tracks the setpoint. [`FlightLoop`] calls both
1032/// every tick; a guidance that runs its loops slower paces them itself from `dt`. Why they are
1033/// split is in the
1034/// [architecture overview](https://github.com/wboayue/stable-flight/blob/main/architecture.md#core-components).
1035///
1036/// # Examples
1037///
1038/// A guidance that flies rate commands through unchanged, and otherwise levels out with
1039/// thrust cut:
1040///
1041/// ```
1042/// use stable_flight::{AttitudeSetpoint, ControlInput, Guidance, Setpoint, VehicleState};
1043///
1044/// struct RateOnly;
1045///
1046/// impl Guidance for RateOnly {
1047/// fn guide(&mut self, _dt: f32, input: &ControlInput, state: &VehicleState) -> Setpoint {
1048/// match input {
1049/// ControlInput::Rate(rate) => Setpoint::Rate(rate.into()),
1050/// _ => Setpoint::Attitude(AttitudeSetpoint {
1051/// heading_rad: state.heading_rad,
1052/// ..Default::default()
1053/// }),
1054/// }
1055/// }
1056/// }
1057/// ```
1058pub trait Guidance {
1059 /// Produces this tick's inner-loop setpoint.
1060 ///
1061 /// # Parameters
1062 ///
1063 /// - `dt`: Time elapsed since the last guidance step in seconds. Must be positive and
1064 /// finite; implementations may assert it (runners guarantee it).
1065 /// - `input`: The commander's current control input.
1066 /// - `state`: The current estimated state of the vehicle.
1067 ///
1068 /// # Unsupported inputs
1069 ///
1070 /// [`ControlInput`] is `#[non_exhaustive]`. For a variant it can't fly, an implementation
1071 /// returns a neutral setpoint — level attitude, the current heading, zero thrust (what the
1072 /// input policy gives a NaN command) — and must not panic.
1073 fn guide(&mut self, dt: f32, input: &ControlInput, state: &VehicleState) -> Setpoint;
1074
1075 /// Resets guidance and primes it from a known-good vehicle state.
1076 ///
1077 /// Clears runtime state (integrators, held outputs) and warms the rest (e.g. the
1078 /// heading-hold target) so guidance starts from where the vehicle is rather than from
1079 /// zero. [`FlightLoop`] calls it before the first tick and again each time the
1080 /// [`Command`] arms, since guidance doesn't run while disarmed. The default does
1081 /// nothing.
1082 fn prime(&mut self, _state: &VehicleState) {}
1083
1084 /// What the last [`guide`](Self::guide) call clipped to a limit. [`FlightLoop`] merges it
1085 /// into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
1086 fn saturation(&self) -> Saturation {
1087 Saturation::default()
1088 }
1089}
1090
1091/// Component responsible for flight control and stabilization: the inner loop.
1092///
1093/// The `Stabilizer` trait defines the interface for components that implement
1094/// control algorithms to track a [`Setpoint`] from [`Guidance`], producing the thrust and
1095/// moments that the [`Mixer`] turns into actuator commands.
1096///
1097/// Implementors of this trait may include:
1098/// - **PID controllers**: Simple feedback control for attitude stability
1099/// - **LQR controllers**: Optimal control for complex flight dynamics
1100/// - **Model predictive controllers**: Advanced control with future prediction
1101/// - **Cascaded control systems**: Hierarchical controllers for different aspects of flight
1102pub trait Stabilizer {
1103 /// Generates control outputs based on the current setpoint and vehicle state.
1104 ///
1105 /// # Parameters
1106 ///
1107 /// - `dt`: Time elapsed since the last control step in seconds. Must be positive and
1108 /// finite; implementations may assert it (runners guarantee it).
1109 /// - `setpoint`: The attitude or rate target to track.
1110 /// - `state`: The current estimated state of the vehicle.
1111 ///
1112 /// # Returns
1113 ///
1114 /// A `ControlOutput` containing the desired thrust and control moments.
1115 ///
1116 /// # Unsupported setpoints
1117 ///
1118 /// [`Setpoint`] is `#[non_exhaustive]`. For a variant it can't fly, an implementation
1119 /// returns a neutral output — zero thrust and moments ([`ControlOutput::default`]) — and
1120 /// must not panic.
1121 fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput;
1122
1123 /// Resets the stabilizer and primes it from a known-good vehicle state.
1124 ///
1125 /// Clears runtime state (integrators, derivative history) and warms any filters so
1126 /// control starts from where the vehicle is. [`FlightLoop`] calls it before the first
1127 /// tick and again each time the [`Command`] arms, after [`Guidance::prime`]. The default
1128 /// does nothing.
1129 fn prime(&mut self, _state: &VehicleState) {}
1130
1131 /// What the last [`stabilize`](Self::stabilize) call clipped to a limit. [`FlightLoop`]
1132 /// merges it into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
1133 fn saturation(&self) -> Saturation {
1134 Saturation::default()
1135 }
1136}
1137
1138/// Which limits the pipeline hit on one tick, as reported by [`Guidance::saturation`],
1139/// [`Stabilizer::saturation`], and [`Mixer::saturation`], merged by [`FlightLoop`] into
1140/// [`TelemetryRecord::saturation`].
1141///
1142/// A saturated tick is not an error: limits are how the pipeline stays safe. Flags that stay
1143/// set across many ticks point at tuning or authority problems (e.g. a rate loop pinned at
1144/// full moment, or a mixer giving up collective to hold attitude). New flags may be added, so
1145/// the struct is `#[non_exhaustive]`; build one with [`Saturation::default`] and set fields.
1146///
1147/// # Examples
1148///
1149/// ```
1150/// use stable_flight::Saturation;
1151///
1152/// let mut guidance = Saturation::default();
1153/// guidance.tilt = true;
1154/// let mut mixer = Saturation::default();
1155/// mixer.mixer_thrust = true;
1156///
1157/// let tick = guidance.merge(mixer);
1158/// assert!(tick.tilt && tick.mixer_thrust && tick.any());
1159/// assert!(!Saturation::default().any());
1160/// ```
1161#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1162#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1163#[non_exhaustive]
1164pub struct Saturation {
1165 /// A requested tilt was capped: guidance's waypoint tilt limit, or the stabilizer's
1166 /// maximum roll/pitch angle.
1167 pub tilt: bool,
1168 /// Collective thrust was clipped to `[0, 1]` (the altitude loop, or the attitude-mode
1169 /// boost). The altitude loop's flag means its thrust sits on a bound, so it is also set
1170 /// when the tilt boost cuts thrust to 0 while inverted, and in a steady hover if
1171 /// `hover_thrust` is 1.
1172 pub thrust: bool,
1173 /// The rate loop's moment output hit ±1, per axis (roll, pitch, yaw).
1174 pub moments: [bool; 3],
1175 /// The mixer lowered collective thrust to keep the moments (a motor would pass full
1176 /// throttle).
1177 pub mixer_thrust: bool,
1178 /// The mixer couldn't deliver the moments in full: it scaled them down, its upward shift
1179 /// was limited near idle, or a motor was clipped. Expected while armed at idle on the
1180 /// ground, where any attitude error is clipped at zero thrust.
1181 pub mixer_moments: bool,
1182}
1183
1184impl Saturation {
1185 /// The union of two reports: a flag set in either is set.
1186 pub fn merge(self, other: Self) -> Self {
1187 // Exhaustive destructuring: a new flag fails to compile here until it is merged.
1188 let Saturation {
1189 tilt,
1190 thrust,
1191 moments,
1192 mixer_thrust,
1193 mixer_moments,
1194 } = other;
1195 Saturation {
1196 tilt: self.tilt || tilt,
1197 thrust: self.thrust || thrust,
1198 moments: [
1199 self.moments[0] || moments[0],
1200 self.moments[1] || moments[1],
1201 self.moments[2] || moments[2],
1202 ],
1203 mixer_thrust: self.mixer_thrust || mixer_thrust,
1204 mixer_moments: self.mixer_moments || mixer_moments,
1205 }
1206 }
1207
1208 /// True when any flag is set.
1209 pub fn any(&self) -> bool {
1210 // Exhaustive destructuring: a new flag fails to compile here until it is checked.
1211 let Saturation {
1212 tilt,
1213 thrust,
1214 moments,
1215 mixer_thrust,
1216 mixer_moments,
1217 } = *self;
1218 tilt || thrust || moments.iter().any(|&m| m) || mixer_thrust || mixer_moments
1219 }
1220}
1221
1222/// A pipeline component whose gains and limits can be read and replaced between ticks.
1223///
1224/// The config is plain `Copy` data that the component owns as its single source of truth;
1225/// [`set_config`](Self::set_config) is the one write point and validates before committing,
1226/// so a running loop can be retuned without ever flying an invalid config. Implemented by
1227/// [`CopterGuidance`](guidance::copter::CopterGuidance) and
1228/// [`CopterStabilizer`](stabilizers::copter::CopterStabilizer); [`FlightLoop`] reaches them
1229/// through [`set_guidance_config`](FlightLoop::set_guidance_config) and
1230/// [`set_stabilizer_config`](FlightLoop::set_stabilizer_config).
1231///
1232/// # Examples
1233///
1234/// ```
1235/// use stable_flight::Configurable;
1236/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
1237///
1238/// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
1239///
1240/// let mut retuned = *stabilizer.config();
1241/// retuned.body_rate.gains.p = 0.2;
1242/// assert!(stabilizer.set_config(retuned).is_ok());
1243///
1244/// retuned.body_rate.max_integral = -1.0;
1245/// assert!(stabilizer.set_config(retuned).is_err());
1246/// assert_eq!(stabilizer.config().body_rate.gains.p, 0.2); // unchanged
1247/// ```
1248pub trait Configurable {
1249 /// The component's config.
1250 type Config: Copy;
1251
1252 /// The config the component flies.
1253 fn config(&self) -> &Self::Config;
1254
1255 /// Replaces the config if it is valid; otherwise keeps the current one and returns the
1256 /// error. Call it between ticks: the new config applies from the next tick, and runtime
1257 /// state (integrals, derivative history, timers) is kept. A changed integral gain rescales
1258 /// its integral so the I term carries over without a bump; across a zero gain the
1259 /// integral resets (`architecture.md#config-ownership`).
1260 fn set_config(&mut self, config: Self::Config) -> Result<(), controllers::InvalidConfig>;
1261}
1262
1263/// Component responsible for publishing telemetry data from the flight system.
1264///
1265/// The `TelemetryPublisher` trait defines the interface for components that send
1266/// flight data to external systems for logging, monitoring, or visualization.
1267/// This can include sending data to ground control stations, logging systems,
1268/// or other monitoring tools.
1269///
1270/// Implementors of this trait may include:
1271/// - **Mavlink publishers**: Send telemetry via the MAVLink protocol
1272/// - **Data loggers**: Record flight data for later analysis
1273/// - **Visualization interfaces**: Send data to real-time flight displays
1274pub trait TelemetryPublisher {
1275 /// Publishes one control-loop tick to external systems.
1276 ///
1277 /// Fire-and-forget: the flight loop cannot act on a telemetry failure, so implementations
1278 /// handle (log) their own errors instead of returning them.
1279 ///
1280 /// # Parameters
1281 ///
1282 /// - `record`: Everything the loop produced this tick; see [`TelemetryRecord`].
1283 fn publish(&mut self, record: &TelemetryRecord);
1284}
1285
1286/// One control-loop tick, as handed to a [`TelemetryPublisher`].
1287///
1288/// The loop assembles it after actuating, so every stage's output is available. Fields borrow
1289/// from the loop and live only for the tick; publishers copy what they need to keep. New
1290/// fields can be added without changing the `publish` signature (struct literals, as in tests,
1291/// need the new field; `testing::RecordedTick::as_record`, behind the `testing` feature,
1292/// builds one from an owned copy).
1293///
1294/// # Examples
1295///
1296/// ```
1297/// use std::time::Duration;
1298/// use stable_flight::{
1299/// ActuatorCommand, Command, ControlOutput, Saturation, Setpoint, TelemetryPublisher,
1300/// TelemetryRecord, VehicleState,
1301/// };
1302///
1303/// struct ThrustLogger;
1304///
1305/// impl TelemetryPublisher for ThrustLogger {
1306/// fn publish(&mut self, record: &TelemetryRecord) {
1307/// println!("{:?}: thrust {}", record.dt, record.control.thrust);
1308/// }
1309/// }
1310///
1311/// let command = Command::default();
1312/// let setpoint = Setpoint::Attitude(Default::default());
1313/// let state = VehicleState::default();
1314/// let control = ControlOutput::default();
1315/// let actuators = ActuatorCommand::default();
1316///
1317/// ThrustLogger.publish(&TelemetryRecord {
1318/// dt: Duration::from_millis(4),
1319/// command: &command,
1320/// setpoint: &setpoint,
1321/// state: &state,
1322/// control: &control,
1323/// actuators: &actuators,
1324/// saturation: Saturation::default(),
1325/// failsafe: None,
1326/// });
1327/// ```
1328#[derive(Debug, Clone, Copy)]
1329pub struct TelemetryRecord<'a> {
1330 /// Nominal loop period (`1 / target frequency`), not measured elapsed time.
1331 pub dt: Duration,
1332 /// Command the commander produced.
1333 pub command: &'a Command,
1334 /// Setpoint guidance derived from `command` (neutral while disarmed).
1335 pub setpoint: &'a Setpoint,
1336 /// Estimated vehicle state the stabilizer acted on.
1337 pub state: &'a VehicleState,
1338 /// Stabilizer output (thrust and moments; zero while disarmed).
1339 pub control: &'a ControlOutput,
1340 /// Mixer output sent to the actuators ([`ActuatorCommand::default`] while disarmed).
1341 pub actuators: &'a ActuatorCommand,
1342 /// Limits guidance, the stabilizer, and the mixer hit this tick, merged
1343 /// ([`Saturation::default`] while disarmed).
1344 pub saturation: Saturation,
1345 /// Which commander a failsafe let fly this tick ([`Commander::failsafe`]); `None` without
1346 /// a failsafe.
1347 pub failsafe: Option<FailsafeState>,
1348}
1349
1350/// One tick's actuator outputs: motors and servos, as generic slots.
1351///
1352/// The [`Mixer`] decides what each slot does
1353/// ([`QuadCopterMixer`](crate::mixers::QuadCopterMixer)'s motor `0` is front-left; a
1354/// tricopter's servo `0` might be its tail tilt); the backend's mapping decides which output
1355/// channel each slot drives. Slots a mixer doesn't use stay at their default.
1356///
1357/// The default (all zeros: motors off, servos centered) is what [`FlightLoop`] actuates while
1358/// disarmed.
1359///
1360/// # Examples
1361///
1362/// A quadcopter uses the first four motors:
1363/// ```
1364/// use stable_flight::ActuatorCommand;
1365///
1366/// let mut cmd = ActuatorCommand::default();
1367/// cmd.motors[..4].copy_from_slice(&[0.5; 4]); // Four motors at 50% power
1368/// ```
1369///
1370/// A tricopter adds a tail servo for yaw:
1371/// ```
1372/// use stable_flight::ActuatorCommand;
1373///
1374/// let mut cmd = ActuatorCommand::default();
1375/// cmd.motors[..3].copy_from_slice(&[0.5; 3]);
1376/// cmd.servos[0] = 0.2; // Tail tilted for a slight yaw
1377/// ```
1378#[derive(Debug, Clone, Copy, Default, PartialEq)]
1379#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1380pub struct ActuatorCommand {
1381 /// Motor outputs, from 0.0 (off) to 1.0 (full power). The mixer sets which physical motor
1382 /// each index is.
1383 pub motors: [f32; 8],
1384
1385 /// Servo outputs, from -1.0 to 1.0, with 0.0 centered. The mixer sets what each index moves
1386 /// (a control surface, a tilt servo).
1387 pub servos: [f32; 8],
1388}
1389
1390// == Mixers ==
1391
1392/// Component responsible for converting control outputs to actuator commands.
1393///
1394/// The `Mixer` trait defines the interface for components that translate
1395/// generalized control outputs (thrust and moments) into specific actuator
1396/// commands appropriate for the vehicle configuration. It maps abstract control
1397/// concepts to physical actuator movements.
1398///
1399/// Implementors of this trait may include:
1400/// - **Quadcopter mixers**: Map controls to four motors in different configurations (X, +)
1401/// - **Hexacopter mixers**: Map controls to six motors
1402/// - **Fixed-wing mixers**: Map controls to a throttle motor and control-surface servos
1403pub trait Mixer {
1404 /// Transforms abstract control outputs into specific actuator commands.
1405 ///
1406 /// This method is the core functionality of the `Mixer` trait, providing the critical
1407 /// translation layer between the stabilization system's desired control effects and
1408 /// the actual physical actuator settings needed to achieve those effects.
1409 ///
1410 /// # Parameters
1411 ///
1412 /// * `controls` - Reference to a [`ControlOutput`] struct containing normalized thrust
1413 /// and moment values that represent the desired control effect.
1414 ///
1415 /// # Returns
1416 ///
1417 /// An [`ActuatorCommand`] containing specific actuator settings appropriate for the
1418 /// vehicle's physical configuration. The mixer assigns each `motors` and `servos` slot its
1419 /// meaning; slots it doesn't use stay at their default:
1420 ///
1421 /// * For multicopters: the `motors` array
1422 /// * For fixed-wing: a throttle motor, with control surfaces on `servos`
1423 /// * For tilting or hybrid vehicles: both
1424 ///
1425 /// # Examples
1426 ///
1427 /// ```
1428 /// use stable_flight::{ControlOutput, Mixer, Vec3};
1429 /// use stable_flight::mixers::QuadCopterMixer;
1430 ///
1431 /// let mut mixer = QuadCopterMixer::default();
1432 ///
1433 /// // Create control output with 70% thrust and slight roll right
1434 /// let control_output = ControlOutput::new(
1435 /// 0.7, // 70% thrust
1436 /// Vec3::new(0.1, 0.0, 0.0) // slight roll right, no pitch, no yaw
1437 /// );
1438 ///
1439 /// // Convert abstract controls into specific motor commands
1440 /// let actuator_command = mixer.mix(&control_output);
1441 ///
1442 /// // Now actuator_command contains specific motor values for a quadcopter
1443 /// ```
1444 fn mix(&mut self, controls: &ControlOutput) -> ActuatorCommand;
1445
1446 /// What the last [`mix`](Self::mix) call couldn't deliver in full. [`FlightLoop`] merges
1447 /// it into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
1448 fn saturation(&self) -> Saturation {
1449 Saturation::default()
1450 }
1451}