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_`) 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_P`, `_I`, `_D` | `body_rate.gains` |
29//! | `STAB_RATE_YAW_P`, `_I`, `_D` | `body_rate.yaw_gains` |
30//! | `STAB_RATE_IMAX` | `body_rate.max_integral` |
31//! | `STAB_ATT_P`, `_I`, `_D` | `attitude.gains` |
32//! | `STAB_ATT_AMAX_X`, `_Y` | `attitude.max_angles_rad` |
33//! | `STAB_ATT_IMAX` | `attitude.max_integral` |
34//! | `STAB_ATT_RMAX_X`, `_Y` | `attitude.max_rate_radps` |
35//! | `STAB_YAW_P`, `_I`, `_D` | `yaw.gains` |
36//! | `STAB_YAW_IMAX` | `yaw.max_integral` |
37//! | `STAB_YAW_RMAX` | `yaw.max_rate_radps` |
38//! | `STAB_FS_RATE_X`, `_Y`, `_Z` | `full_scale_rates_radps` |
39//! | `STAB_THR_EXPO` | `thrust_curve_exponent` |
40//!
41//! # Copter guidance ([`CopterGuidanceConfig`](crate::guidance::copter::CopterGuidanceConfig))
42//!
43//! | Name | Field |
44//! |---|---|
45//! | `GUID_ALT_P`, `_I`, `_D` | `altitude.gains` |
46//! | `GUID_ALT_IMAX` | `altitude.max_integral` |
47//! | `GUID_ALT_HOVER` | `altitude.hover_thrust` |
48//! | `GUID_LAT_POS_P` | `lateral.position_p` |
49//! | `GUID_LAT_VEL_P`, `_I`, `_D` | `lateral.velocity` |
50//! | `GUID_LAT_IMAX` | `lateral.max_integral` |
51//! | `GUID_NAV_PERIOD` | `navigation_period_s` |
52//! | `GUID_TILT_MAX` | `max_tilt_rad` |
53//! | `GUID_DESC_MAX` | `max_descent_mps` |
54//! | `GUID_LAND_SPD` | `land_speed_mps` |
55//! | `GUID_STICK_X`, `_Y` | `max_stick_angles_rad` |
56//!
57//! # Examples
58//!
59//! ```
60//! use stable_flight::params::Params;
61//! use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
62//! use stable_flight::Configurable;
63//!
64//! let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
65//!
66//! stabilizer.set_param("STAB_RATE_P", 0.2).expect("valid value");
67//! assert_eq!(stabilizer.param("STAB_RATE_P"), Some(0.2));
68//! assert_eq!(stabilizer.config().body_rate.gains.p, 0.2);
69//!
70//! stabilizer.set_param("STAB_ATT_AMAX_X", 30.0).expect("valid value"); // degrees
71//! assert!((stabilizer.config().attitude.max_angles_rad.x - 30f32.to_radians()).abs() < 1e-6);
72//!
73//! assert!(stabilizer.set_param("STAB_RATE_IMAX", -1.0).is_err()); // fails validation
74//! assert!(stabilizer.set_param("NO_SUCH_PARAM", 1.0).is_err());
75//!
76//! let mut count = 0;
77//! stabilizer.visit_params(&mut |_name, _value| count += 1);
78//! assert_eq!(count, 24);
79//! ```
80
81use core::fmt;
82
83use crate::Configurable;
84use crate::controllers::InvalidConfig;
85
86#[cfg(feature = "param-metadata")]
87pub mod metadata;
88#[cfg(test)]
89mod tests;
90
91/// Longest param name in bytes: MAVLink's `param_id` field.
92pub const MAX_NAME_LEN: usize = 16;
93
94/// One named `f32` field of a config `C`: how to read it and how to write it, unvalidated.
95pub struct Param<C> {
96    name: &'static str,
97    get: fn(&C) -> f32,
98    set: fn(&mut C, f32),
99}
100
101impl<C> Param<C> {
102    /// A param named `name`, read by `get` and written (unvalidated) by `set`, in the param's
103    /// unit. `get` must read back what `set` wrote, up to unit-conversion rounding: no
104    /// clamping or quantizing (the [`Params`] stores-or-rejects contract). Use it to give your
105    /// own config a [`ParamTable`]:
106    ///
107    /// ```
108    /// use stable_flight::params::{Param, ParamTable};
109    ///
110    /// #[derive(Clone, Copy)]
111    /// struct TrimConfig {
112    ///     roll_trim_rad: f32,
113    /// }
114    ///
115    /// impl ParamTable for TrimConfig {
116    ///     const PARAMS: &'static [Param<Self>] = &[Param::new(
117    ///         "TRIM_ROLL",
118    ///         |c| c.roll_trim_rad.to_degrees(),
119    ///         |c, v| c.roll_trim_rad = v.to_radians(),
120    ///     )];
121    /// }
122    ///
123    /// let mut config = TrimConfig { roll_trim_rad: 0.0 };
124    /// TrimConfig::PARAMS[0].set(&mut config, 90.0);
125    /// assert!((config.roll_trim_rad - core::f32::consts::FRAC_PI_2).abs() < 1e-6);
126    /// ```
127    pub const fn new(name: &'static str, get: fn(&C) -> f32, set: fn(&mut C, f32)) -> Self {
128        Self { name, get, set }
129    }
130
131    /// The param's name, e.g. `"STAB_RATE_P"`.
132    pub fn name(&self) -> &'static str {
133        self.name
134    }
135
136    /// The param's value in `config`, in the param's unit.
137    pub fn get(&self, config: &C) -> f32 {
138        (self.get)(config)
139    }
140
141    /// Writes `value` (in the param's unit) into `config` without validating it.
142    pub fn set(&self, config: &mut C, value: f32) {
143        (self.set)(config, value)
144    }
145}
146
147/// A config that exposes its fields as named params.
148///
149/// Names must be unique within a table and across the components combined into one view
150/// (e.g. a [`FlightLoop`](crate::FlightLoop)'s guidance and stabilizer), and at most
151/// [`MAX_NAME_LEN`] bytes.
152pub trait ParamTable: Copy + 'static {
153    /// Every param, in a stable order.
154    const PARAMS: &'static [Param<Self>];
155}
156
157/// Read, write, and list a component's tunable values by index or by name.
158///
159/// Implementors provide the four index methods; name lookup, [`param`](Params::param),
160/// [`set_param`](Params::set_param), and [`visit_params`](Params::visit_params) are built on
161/// them.
162///
163/// **Contract: a successful write stores the value as given**, up to the rounding of a unit
164/// conversion (degrees ↔ radians); an out-of-range value is rejected, never clamped or
165/// adjusted. Implementors must uphold it (for the blanket impl: each [`Param`] reads back what
166/// it wrote, and `set_config` commits the config unchanged or rejects it), because a link
167/// confirms a write by echoing the value it was sent.
168pub trait Params {
169    /// Number of params; their indices are `0..param_count()`.
170    fn param_count(&self) -> usize;
171
172    /// The name of the param at `index`, or `None` if it is out of range.
173    fn param_name(&self, index: usize) -> Option<&'static str>;
174
175    /// The value of the param at `index`, or `None` if it is out of range.
176    fn param_at(&self, index: usize) -> Option<f32>;
177
178    /// Sets the param at `index` to `value`. Out of range is [`ParamError::Unknown`]. On error
179    /// the config is unchanged.
180    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError>;
181
182    /// The index of the param called `name`, or `None` if there is no such param. On a
183    /// duplicate name, the first index.
184    fn param_index(&self, name: &str) -> Option<usize> {
185        (0..self.param_count()).find(|&i| self.param_name(i) == Some(name))
186    }
187
188    /// The value of the param called `name`, or `None` if there is no such param.
189    fn param(&self, name: &str) -> Option<f32> {
190        self.param_at(self.param_index(name)?)
191    }
192
193    /// Sets the param called `name` to `value`. On error the config is unchanged.
194    fn set_param(&mut self, name: &str, value: f32) -> Result<(), ParamError> {
195        let index = self.param_index(name).ok_or(ParamError::Unknown)?;
196        self.set_param_at(index, value)
197    }
198
199    /// Calls `f` with every param's name and value, in index order.
200    fn visit_params(&self, f: &mut dyn FnMut(&'static str, f32)) {
201        for i in 0..self.param_count() {
202            if let (Some(name), Some(value)) = (self.param_name(i), self.param_at(i)) {
203                f(name, value);
204            }
205        }
206    }
207}
208
209impl<T> Params for T
210where
211    T: Configurable,
212    T::Config: ParamTable,
213{
214    fn param_count(&self) -> usize {
215        T::Config::PARAMS.len()
216    }
217
218    fn param_name(&self, index: usize) -> Option<&'static str> {
219        T::Config::PARAMS.get(index).map(Param::name)
220    }
221
222    fn param_at(&self, index: usize) -> Option<f32> {
223        T::Config::PARAMS.get(index).map(|p| p.get(self.config()))
224    }
225
226    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
227        let param = T::Config::PARAMS.get(index).ok_or(ParamError::Unknown)?;
228        if !value.is_finite() {
229            return Err(ParamError::NotFinite);
230        }
231        let mut config = *self.config();
232        param.set(&mut config, value);
233        self.set_config(config).map_err(ParamError::Invalid)
234    }
235}
236
237/// Why a param write ([`Params::set_param`], [`Params::set_param_at`]) was rejected.
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum ParamError {
241    /// No param has that name or index.
242    Unknown,
243    /// The value is NaN or infinite.
244    NotFinite,
245    /// The new config failed validation.
246    Invalid(InvalidConfig),
247}
248
249impl fmt::Display for ParamError {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        match self {
252            ParamError::Unknown => f.write_str("unknown param"),
253            ParamError::NotFinite => f.write_str("param value must be finite"),
254            ParamError::Invalid(e) => write!(f, "invalid param value: {e}"),
255        }
256    }
257}
258
259impl core::error::Error for ParamError {
260    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
261        match self {
262            ParamError::Invalid(e) => Some(e),
263            _ => None,
264        }
265    }
266}
267
268/// A [`Param`] for a config field path: `param!("NAME", a.b)`, or `param!(deg "NAME", a.b)` to
269/// expose a radian field in degrees.
270macro_rules! param {
271    (deg $name:literal, $($field:ident).+) => {
272        $crate::params::Param::new(
273            $name,
274            |c| c.$($field).+.to_degrees(),
275            |c, v| c.$($field).+ = v.to_radians(),
276        )
277    };
278    ($name:literal, $($field:ident).+) => {
279        $crate::params::Param::new($name, |c| c.$($field).+, |c, v| c.$($field).+ = v)
280    };
281}
282pub(crate) use param;