use crate::Vec3;
use super::{InvalidConfig, check, check_limit, rescale_integral};
use crate::math::{assert_dt, clamp_symmetric};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RateGains {
pub p: f32,
pub i: f32,
pub ff: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaneRateControllerConfig {
pub roll: RateGains,
pub pitch: RateGains,
pub yaw: RateGains,
pub max_integral: f32,
pub trim: Vec3,
}
impl Default for PlaneRateControllerConfig {
fn default() -> Self {
PlaneRateControllerConfig {
roll: RateGains {
p: 0.05,
i: 0.1,
ff: 0.5,
},
pitch: RateGains {
p: 0.08,
i: 0.1,
ff: 0.5,
},
yaw: RateGains {
p: 0.05,
i: 0.0,
ff: 0.3,
},
max_integral: 2.0,
trim: Vec3::zeros(),
}
}
}
impl PlaneRateControllerConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
let (r, p, y) = (self.roll, self.pitch, self.yaw);
let fields = [
("roll.p", r.p),
("roll.i", r.i),
("roll.ff", r.ff),
("pitch.p", p.p),
("pitch.i", p.i),
("pitch.ff", p.ff),
("yaw.p", y.p),
("yaw.i", y.i),
("yaw.ff", y.ff),
("max_integral", self.max_integral),
];
for (field, value) in fields {
check_limit(field, value)?;
}
let trims = [
("trim.x", self.trim.x),
("trim.y", self.trim.y),
("trim.z", self.trim.z),
];
for (field, value) in trims {
check(field, (-1.0..=1.0).contains(&value), "in [-1, 1]")?;
}
Ok(())
}
fn axis_gains(&self) -> [RateGains; 3] {
[self.roll, self.pitch, self.yaw]
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PlaneRateController {
integrated_error: Vec3,
}
impl PlaneRateController {
pub fn control(
&mut self,
config: &PlaneRateControllerConfig,
dt: f32,
desired_radps: Vec3,
current_radps: Vec3,
scale: f32,
integrate: bool,
) -> Vec3 {
assert_dt(dt);
if !scale.is_finite() {
return Vec3::zeros();
}
let gains = config.axis_gains();
let scale_squared = scale * scale;
Vec3::from_fn(|axis, _| {
let (desired, current) = (desired_radps[axis], current_radps[axis]);
let error = desired - current;
let trim = scale_squared * config.trim[axis];
if !error.is_finite() {
return clamp_symmetric(trim, 1.0);
}
if integrate {
self.integrated_error[axis] = clamp_symmetric(
self.integrated_error[axis] + error * dt,
config.max_integral,
);
}
let RateGains { p, i, ff } = gains[axis];
let feedback = p * error + i * self.integrated_error[axis];
clamp_symmetric(scale_squared * feedback + trim + scale * ff * desired, 1.0)
})
}
pub(crate) fn clear_integral(&mut self) {
self.integrated_error = Vec3::zeros();
}
pub(crate) fn rescale_integral(
&mut self,
old: &PlaneRateControllerConfig,
new: &PlaneRateControllerConfig,
) {
let (old, new) = (old.axis_gains(), new.axis_gains());
self.integrated_error = Vec3::from_fn(|axis, _| {
rescale_integral(self.integrated_error[axis], old[axis].i, new[axis].i)
});
}
}