Skip to main content

stable_flight/
params.rs

1//! A flat name → `f32` view over the config tree, for live tuning from a ground station.
2//!
3//! The config is the only store: [`Params::param`] reads a field of the component's config,
4//! and [`Params::set_param`] writes a copy and commits it through
5//! [`Configurable::set_config`], which validates it (an invalid value is rejected and the
6//! config unchanged) and applies the integrator policy. Any [`Configurable`] whose config
7//! implements [`ParamTable`] gets [`Params`]; [`FlightLoop`](crate::FlightLoop) combines its
8//! guidance's and stabilizer's.
9//!
10//! Names are uppercase ASCII of at most [`MAX_NAME_LEN`] bytes (MAVLink's `param_id`),
11//! prefixed by component (`STAB_`, `GUID_`, `PSTAB_`, `PGUID_`, `TRAN_`) and loop. Vector components end in `_X`/`_Y`/`_Z`
12//! (roll/pitch/yaw for angles and rates). Angles and angular rates are in degrees and deg/s,
13//! as ground stations show them, and convert to the config's radians at this boundary;
14//! everything else is in the config field's own unit.
15//!
16//! Params are addressed by index, `0..param_count()`, in a stable table order; name lookup
17//! scans the names. Index access is what paced output uses (a cursor that sends a few params
18//! per tick).
19//!
20//! Units, descriptions, groups, and valid ranges are in the `metadata` module (feature
21//! `param-metadata`), one table per config next to its [`ParamTable`]. The tables below map
22//! names to config fields.
23//!
24//! # Copter stabilizer ([`CopterStabilizerConfig`](crate::stabilizers::copter::CopterStabilizerConfig))
25//!
26//! | Name | Field |
27//! |---|---|
28//! | `STAB_RATE_RLL_P`, `_I`, `_D` | `body_rate.roll_gains` |
29//! | `STAB_RATE_PIT_P`, `_I`, `_D` | `body_rate.pitch_gains` |
30//! | `STAB_RATE_YAW_P`, `_I`, `_D` | `body_rate.yaw_gains` |
31//! | `STAB_RATE_IMAX` | `body_rate.max_integral` |
32//! | `STAB_RATE_IMAX_Z` | `body_rate.yaw_max_integral` |
33//! | `STAB_ATT_RLL_P`, `_I`, `_D` | `attitude.roll_gains` |
34//! | `STAB_ATT_PIT_P`, `_I`, `_D` | `attitude.pitch_gains` |
35//! | `STAB_ATT_AMAX_X`, `_Y` | `attitude.max_angles_rad` |
36//! | `STAB_ATT_IMAX` | `attitude.max_integral` |
37//! | `STAB_ATT_RMAX_X`, `_Y` | `attitude.max_rate_radps` |
38//! | `STAB_YAW_P`, `_I`, `_D` | `yaw.gains` |
39//! | `STAB_YAW_IMAX` | `yaw.max_integral` |
40//! | `STAB_YAW_RMAX` | `yaw.max_rate_radps` |
41//! | `STAB_FS_RATE_X`, `_Y`, `_Z` | `full_scale_rates_radps` |
42//! | `STAB_THR_EXPO` | `thrust_curve_exponent` |
43//! | `STAB_GYRO_FLT` | `gyro_cutoff_hz` |
44//!
45//! # Copter guidance ([`CopterGuidanceConfig`](crate::guidance::copter::CopterGuidanceConfig))
46//!
47//! | Name | Field |
48//! |---|---|
49//! | `GUID_ALT_P`, `_I`, `_D` | `altitude.gains` |
50//! | `GUID_ALT_IMAX` | `altitude.max_integral` |
51//! | `GUID_ALT_HOVER` | `altitude.hover_thrust` |
52//! | `GUID_LAT_POS_P` | `lateral.position_p` |
53//! | `GUID_LAT_VEL_P`, `_I`, `_D` | `lateral.velocity` |
54//! | `GUID_LAT_IMAX` | `lateral.max_integral` |
55//! | `GUID_LAT_ACC` | `lateral.max_accel_mps2` |
56//! | `GUID_LAT_BRK` | `lateral.brake_mps2` |
57//! | `GUID_NAV_PERIOD` | `navigation_period_s` |
58//! | `GUID_TILT_MAX` | `max_tilt_rad` |
59//! | `GUID_DESC_MAX` | `max_descent_mps` |
60//! | `GUID_DESC_ACC` | `descent_accel_mps2` |
61//! | `GUID_CLIMB_DEC` | `climb_decel_mps2` |
62//! | `GUID_LAND_SPD` | `land_speed_mps` |
63//! | `GUID_YAW_SLEW` | `waypoint_yaw_radps` |
64//! | `GUID_HDG_RATE` | `heading_rate_radps` |
65//! | `GUID_YAW_MIN_LEG` | `waypoint_yaw_min_leg_m` |
66//! | `GUID_YAW_YLD_ERR` | `heading_yield_rad` |
67//! | `GUID_YAW_YLD_S` | `heading_yield_s` |
68//! | `GUID_WND_HDG_SPD` | `wind_heading_min_mps` |
69//! | `GUID_THR_MIN` | `thrust.min_thrust` |
70//! | `GUID_SINK_LIM` | `thrust.sink_limit_mps` |
71//! | `GUID_SINK_GAIN` | `thrust.sink_gain` |
72//! | `GUID_BOOST_MAX` | `thrust.max_boost_thrust` |
73//! | `GUID_STICK_X`, `_Y` | `max_stick_angles_rad` |
74//! | `GUID_WND_BCOEF_X`, `_Y` | `wind.ballistic_kgpm2` |
75//! | `GUID_WND_MCOEF_X`, `_Y` | `wind.momentum_per_s` |
76//! | `GUID_WND_F_NSE` | `wind.force_noise_mps2` |
77//! | `GUID_WND_P_NSE` | `wind.process_noise_mps_per_rt_s` |
78//!
79//! # Plane stabilizer ([`PlaneStabilizerConfig`](crate::stabilizers::plane::PlaneStabilizerConfig))
80//!
81//! | Name | Field |
82//! |---|---|
83//! | `PSTAB_RLL_P`, `_I`, `_FF` | `rate.roll` |
84//! | `PSTAB_PIT_P`, `_I`, `_FF` | `rate.pitch` |
85//! | `PSTAB_YAW_P`, `_I`, `_FF` | `rate.yaw` |
86//! | `PSTAB_IMAX` | `rate.max_integral` |
87//! | `PSTAB_RLL_TRIM`, `PSTAB_PIT_TRIM`, `PSTAB_YAW_TRIM` | `rate.trim` |
88//! | `PSTAB_TC_X`, `_Y` | `time_constant_s` |
89//! | `PSTAB_RMAX_X`, `_Y` | `max_attitude_rate_radps` |
90//! | `PSTAB_BRATE_X`, `_Y`, `_Z` | `max_body_rate_radps` |
91//! | `PSTAB_BANK_MAX` | `max_bank_rad` |
92//! | `PSTAB_PIT_MAX` | `max_pitch_rad` |
93//! | `PSTAB_ASPD_TRIM`, `_MIN`, `_MAX` | `trim_airspeed_mps`, `min_airspeed_mps`, `max_airspeed_mps` |
94//! | `PSTAB_THR_EXPO` | `thrust_curve_exponent` |
95//!
96//! # Plane guidance ([`PlaneGuidanceConfig`](crate::guidance::plane::PlaneGuidanceConfig))
97//!
98//! | Name | Field |
99//! |---|---|
100//! | `PGUID_BANK_MAX` | `max_bank_rad` |
101//! | `PGUID_PIT_UP`, `PGUID_PIT_DN` | `max_pitch_up_rad`, `max_pitch_down_rad` |
102//! | `PGUID_ACRO_X`, `_Y`, `_Z` | `max_rate_radps` |
103//! | `PGUID_TRIM_PIT` | `trim_pitch_rad` |
104//! | `PGUID_CRUISE` | `cruise_thrust` |
105//! | `PGUID_L1_PERIOD`, `PGUID_L1_DAMP` | `l1_period_s`, `l1_damping` |
106//! | `PGUID_LOIT_RAD` | `loiter_radius_m` |
107//! | `PGUID_ALT_P`, `_I`, `_IMAX` | `altitude_p`, `altitude_i`, `altitude_max_integral` |
108//! | `PGUID_TCONST` | `tecs.time_constant_s` |
109//! | `PGUID_CLMB_MAX`, `PGUID_SINK_MIN`, `PGUID_SINK_MAX` | `tecs.max_climb_mps`, `tecs.min_sink_mps`, `tecs.max_sink_mps` |
110//! | `PGUID_THR_DAMP`, `PGUID_INTEG`, `PGUID_PTCH_DAMP`, `PGUID_PTCH_INTEG` | `tecs.thrust_damping`, `tecs.integrator_gain`, `tecs.pitch_damping`, `tecs.pitch_integrator_gain` |
111//! | `PGUID_SPDWEIGHT` | `tecs.speed_weight` |
112//! | `PGUID_RLL2THR` | `tecs.roll_compensation` |
113//! | `PGUID_ASPD_MIN`, `PGUID_ASPD_MAX` | `tecs.min_airspeed_mps`, `tecs.max_airspeed_mps` |
114//! | `PGUID_THR_MIN`, `PGUID_THR_MAX` | `min_thrust`, `max_thrust` |
115//! | `PGUID_CLMB_THR` | `climb_thrust_per_rad` |
116//!
117//! # Transition ([`TransitionConfig`](crate::guidance::vtol::TransitionConfig))
118//!
119//! | Name | Field |
120//! |---|---|
121//! | `TRAN_FW_RATE`, `TRAN_FW_DONE`, `TRAN_FW_MAX` | `forward_rate_radps`, `forward_done_rad`, `forward_max_tilt_rad` |
122//! | `TRAN_ASPD_MIN` | `min_airspeed_mps` |
123//! | `TRAN_VT_RATE`, `TRAN_VT_DONE` | `back_rate_radps`, `back_done_rad` |
124//! | `TRAN_TIMEOUT` | `timeout_s` |
125//! | `TRAN_MIN_HGT`, `TRAN_FW_MIN_HGT` | `min_height_m`, `plane_min_height_m` |
126//! | `TRAN_FW_THR`, `TRAN_VT_THR` | `forward_thrust`, `back_thrust` |
127//! | `TRAN_VT_SINK_LIM`, `TRAN_VT_SINK_GN` | `back_sink_limit_mps`, `back_sink_gain` |
128//! | `TRAN_HANDOFF` | `handoff_s` |
129//! | `TRAN_ROLL_MAX` | `roll_limit_rad` |
130//!
131//! # Lift transition ([`LiftTransitionConfig`](crate::guidance::vtol::LiftTransitionConfig))
132//!
133//! A lift+cruise VTOL's; names shared with the tailsitter's table mean the same.
134//!
135//! | Name | Field |
136//! |---|---|
137//! | `TRAN_ASPD_MIN` | `min_airspeed_mps` |
138//! | `TRAN_FW_RAMP` | `lift_ramp_s` |
139//! | `TRAN_TIMEOUT` | `timeout_s` |
140//! | `TRAN_MIN_HGT`, `TRAN_FW_MIN_HGT` | `min_height_m`, `plane_min_height_m` |
141//! | `TRAN_VT_RAMP`, `TRAN_VT_SPD`, `TRAN_VT_TIMEOUT` | `back_ramp_s`, `back_speed_mps`, `back_timeout_s` |
142//! | `TRAN_VT_DEC`, `TRAN_VT_DEC_I` | `back_decel_mps2`, `back_decel_i` |
143//! | `TRAN_FW_THR`, `TRAN_PSH_SLEW` | `forward_thrust`, `pusher_slew_per_s` |
144//! | `TRAN_HANDOFF` | `handoff_s` |
145//! | `TRAN_ROLL_MAX` | `roll_limit_rad` |
146//!
147//! # Examples
148//!
149//! ```
150//! use stable_flight::params::Params;
151//! use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
152//! use stable_flight::Configurable;
153//!
154//! let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
155//!
156//! stabilizer.set_param("STAB_RATE_RLL_P", 0.2).expect("valid value");
157//! assert_eq!(stabilizer.param("STAB_RATE_RLL_P"), Some(0.2));
158//! assert_eq!(stabilizer.config().body_rate.roll_gains.p, 0.2);
159//!
160//! stabilizer.set_param("STAB_ATT_AMAX_X", 30.0).expect("valid value"); // degrees
161//! assert!((stabilizer.config().attitude.max_angles_rad.x - 30f32.to_radians()).abs() < 1e-6);
162//!
163//! assert!(stabilizer.set_param("STAB_RATE_IMAX", -1.0).is_err()); // fails validation
164//! assert!(stabilizer.set_param("NO_SUCH_PARAM", 1.0).is_err());
165//!
166//! let mut count = 0;
167//! stabilizer.visit_params(&mut |_name, _value| count += 1);
168//! assert_eq!(count, 32);
169//! ```
170
171use core::fmt;
172
173use crate::Configurable;
174use crate::controllers::InvalidConfig;
175
176#[cfg(feature = "param-metadata")]
177pub mod metadata;
178#[cfg(test)]
179mod tests;
180
181/// Longest param name in bytes: MAVLink's `param_id` field.
182pub const MAX_NAME_LEN: usize = 16;
183
184/// One named `f32` field of a config `C`: how to read it and how to write it, unvalidated.
185pub struct Param<C> {
186    name: &'static str,
187    get: fn(&C) -> f32,
188    set: fn(&mut C, f32),
189}
190
191impl<C> Param<C> {
192    /// A param named `name`, read by `get` and written (unvalidated) by `set`, in the param's
193    /// unit. `get` must read back what `set` wrote, up to unit-conversion rounding: no
194    /// clamping or quantizing (the [`Params`] stores-or-rejects contract). Use it to give your
195    /// own config a [`ParamTable`]:
196    ///
197    /// ```
198    /// use stable_flight::params::{Param, ParamTable};
199    ///
200    /// #[derive(Clone, Copy)]
201    /// struct TrimConfig {
202    ///     roll_trim_rad: f32,
203    /// }
204    ///
205    /// impl ParamTable for TrimConfig {
206    ///     const PARAMS: &'static [Param<Self>] = &[Param::new(
207    ///         "TRIM_ROLL",
208    ///         |c| c.roll_trim_rad.to_degrees(),
209    ///         |c, v| c.roll_trim_rad = v.to_radians(),
210    ///     )];
211    /// }
212    ///
213    /// let mut config = TrimConfig { roll_trim_rad: 0.0 };
214    /// TrimConfig::PARAMS[0].set(&mut config, 90.0);
215    /// assert!((config.roll_trim_rad - core::f32::consts::FRAC_PI_2).abs() < 1e-6);
216    /// ```
217    pub const fn new(name: &'static str, get: fn(&C) -> f32, set: fn(&mut C, f32)) -> Self {
218        Self { name, get, set }
219    }
220
221    /// The param's name, e.g. `"STAB_RATE_RLL_P"`.
222    pub fn name(&self) -> &'static str {
223        self.name
224    }
225
226    /// The param's value in `config`, in the param's unit.
227    pub fn get(&self, config: &C) -> f32 {
228        (self.get)(config)
229    }
230
231    /// Writes `value` (in the param's unit) into `config` without validating it.
232    pub fn set(&self, config: &mut C, value: f32) {
233        (self.set)(config, value)
234    }
235}
236
237/// A config that exposes its fields as named params.
238///
239/// Names must be unique within a table and across the components combined into one view
240/// (e.g. a [`FlightLoop`](crate::FlightLoop)'s guidance and stabilizer), and at most
241/// [`MAX_NAME_LEN`] bytes.
242pub trait ParamTable: Copy + 'static {
243    /// Every param, in a stable order.
244    const PARAMS: &'static [Param<Self>];
245}
246
247/// Read, write, and list a component's tunable values by index or by name.
248///
249/// Implementors provide the four index methods; name lookup, [`param`](Params::param),
250/// [`set_param`](Params::set_param), and [`visit_params`](Params::visit_params) are built on
251/// them.
252///
253/// **Contract: a successful write stores the value as given**, up to the rounding of a unit
254/// conversion (degrees ↔ radians); an out-of-range value is rejected, never clamped or
255/// adjusted. Implementors must uphold it (for the blanket impl: each [`Param`] reads back what
256/// it wrote, and `set_config` commits the config unchanged or rejects it), because a link
257/// confirms a write by echoing the value it was sent.
258pub trait Params {
259    /// Number of params; their indices are `0..param_count()`.
260    fn param_count(&self) -> usize;
261
262    /// The name of the param at `index`, or `None` if it is out of range.
263    fn param_name(&self, index: usize) -> Option<&'static str>;
264
265    /// The value of the param at `index`, or `None` if it is out of range.
266    fn param_at(&self, index: usize) -> Option<f32>;
267
268    /// Sets the param at `index` to `value`. Out of range is [`ParamError::Unknown`]. On error
269    /// the config is unchanged.
270    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError>;
271
272    /// The index of the param called `name`, or `None` if there is no such param. On a
273    /// duplicate name, the first index.
274    fn param_index(&self, name: &str) -> Option<usize> {
275        (0..self.param_count()).find(|&i| self.param_name(i) == Some(name))
276    }
277
278    /// The value of the param called `name`, or `None` if there is no such param.
279    fn param(&self, name: &str) -> Option<f32> {
280        self.param_at(self.param_index(name)?)
281    }
282
283    /// Sets the param called `name` to `value`. On error the config is unchanged.
284    fn set_param(&mut self, name: &str, value: f32) -> Result<(), ParamError> {
285        let index = self.param_index(name).ok_or(ParamError::Unknown)?;
286        self.set_param_at(index, value)
287    }
288
289    /// Calls `f` with every param's name and value, in index order.
290    fn visit_params(&self, f: &mut dyn FnMut(&'static str, f32)) {
291        for i in 0..self.param_count() {
292            if let (Some(name), Some(value)) = (self.param_name(i), self.param_at(i)) {
293                f(name, value);
294            }
295        }
296    }
297}
298
299impl<T> Params for T
300where
301    T: Configurable,
302    T::Config: ParamTable,
303{
304    fn param_count(&self) -> usize {
305        T::Config::PARAMS.len()
306    }
307
308    fn param_name(&self, index: usize) -> Option<&'static str> {
309        T::Config::PARAMS.get(index).map(Param::name)
310    }
311
312    fn param_at(&self, index: usize) -> Option<f32> {
313        T::Config::PARAMS.get(index).map(|p| p.get(self.config()))
314    }
315
316    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
317        let param = T::Config::PARAMS.get(index).ok_or(ParamError::Unknown)?;
318        if !value.is_finite() {
319            return Err(ParamError::NotFinite);
320        }
321        let mut config = *self.config();
322        param.set(&mut config, value);
323        self.set_config(config).map_err(ParamError::Invalid)
324    }
325}
326
327/// Where a combined index falls when `parts`' params are chained in order: the part, and the
328/// index within it. `None` past the last. How a composite (e.g.
329/// [`FlightLoop`](crate::FlightLoop): guidance, then stabilizer) presents its parts' params as
330/// one table.
331pub(crate) fn locate(parts: &[&dyn Params], index: usize) -> Option<(usize, usize)> {
332    let mut index = index;
333    for (part, params) in parts.iter().enumerate() {
334        let count = params.param_count();
335        if index < count {
336            return Some((part, index));
337        }
338        index -= count;
339    }
340    None
341}
342
343/// Why a param write ([`Params::set_param`], [`Params::set_param_at`]) was rejected.
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345#[non_exhaustive]
346pub enum ParamError {
347    /// No param has that name or index.
348    Unknown,
349    /// The value is NaN or infinite.
350    NotFinite,
351    /// The new config failed validation.
352    Invalid(InvalidConfig),
353}
354
355impl fmt::Display for ParamError {
356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357        match self {
358            ParamError::Unknown => f.write_str("unknown param"),
359            ParamError::NotFinite => f.write_str("param value must be finite"),
360            ParamError::Invalid(e) => write!(f, "invalid param value: {e}"),
361        }
362    }
363}
364
365impl core::error::Error for ParamError {
366    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
367        match self {
368            ParamError::Invalid(e) => Some(e),
369            _ => None,
370        }
371    }
372}
373
374/// A [`Param`] for a config field path: `param!("NAME", a.b)`, or `param!(deg "NAME", a.b)` to
375/// expose a radian field in degrees.
376macro_rules! param {
377    (deg $name:literal, $($field:ident).+) => {
378        $crate::params::Param::new(
379            $name,
380            |c| c.$($field).+.to_degrees(),
381            |c, v| c.$($field).+ = v.to_radians(),
382        )
383    };
384    ($name:literal, $($field:ident).+) => {
385        $crate::params::Param::new($name, |c| c.$($field).+, |c, v| c.$($field).+ = v)
386    };
387}
388pub(crate) use param;