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