use super::procedure::{Action, PlaneProcedure, Verdict};
use super::side::{Decide, Motion, RateFilters, Side, SideConfig, StageView, Waits, zero_if_nan};
use super::{AutotuneAbort, DEFAULT_SETTLE_SPEED_MPS, Settle, StagePlan, StepTestPlan, Supervisor};
use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
use crate::math::DEG;
use crate::stabilizers::plane::{PlaneAxisGains, PlaneLoop, PlaneStabilizerConfig};
use crate::stabilizers::vtol::{QuadPlaneStabilizerConfig, TailsitterStabilizerConfig};
use crate::tuning::{IdentifyConfig, ProbeConfig, StepConfig, WingDesignConfig};
use crate::{Setpoint, Vec2, Vec3};
pub type PlaneAutotune = Supervisor<PlaneSide>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlaneSide;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PlaneMethod {
StepTest(StepTestPlan),
Design(PlaneDesignPlan),
}
pub const PLANE_IDENTIFY_SHARE: f32 = 0.3;
pub const PLANE_IDENTIFY_S: f32 = 6.0;
pub const PLANE_MAX_OVERSHOOT: f32 = 0.05;
pub const PLANE_RISE_PER_TIME_CONSTANT: f32 = 2.2;
pub const PLANE_TIME_CONSTANT_RANGE_S: [f32; 2] = [0.2, 1.5];
pub const PLANE_MOMENT_SHARE: f32 = 0.8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaneDesignPlan {
pub identify: IdentifyConfig,
pub design: WingDesignConfig,
pub verify: StepConfig,
pub max_verify_pairs: usize,
pub candidates_per_update: usize,
pub settle: Settle,
}
impl PlaneDesignPlan {
pub fn for_plane(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
let axis = target.axis();
let max_rate_radps = config.max_attitude_rate_radps[axis];
let angle = match target {
PlaneLoop::RollRate | PlaneLoop::Roll => PlaneLoop::Roll,
PlaneLoop::PitchRate | PlaneLoop::Pitch => PlaneLoop::Pitch,
};
let verify = StepTestPlan::plane(angle, config).step;
Self {
identify: IdentifyConfig {
amplitude: PLANE_IDENTIFY_SHARE * max_rate_radps,
duration_s: PLANE_IDENTIFY_S,
washout_tc_s: 0.2,
noisy: None,
},
design: WingDesignConfig {
amplitude_rad: verify.amplitude,
step_duration_s: verify.duration_s,
max_rate_radps,
max_moment: PLANE_MOMENT_SHARE * (1.0 - config.rate.trim[axis].abs()),
max_integral: config.rate.max_integral,
static_trim: config.rate.trim[axis],
max_overshoot: PLANE_MAX_OVERSHOOT,
max_saturated_s: PLANE_MAX_SATURATED_S,
time_constant_range_s: PLANE_TIME_CONSTANT_RANGE_S,
rise_per_time_constant: PLANE_RISE_PER_TIME_CONSTANT,
},
verify,
max_verify_pairs: 8,
candidates_per_update: 4,
settle: PLANE_STEP_SETTLE,
}
}
pub fn validate(&self) -> Result<(), InvalidConfig> {
self.identify
.validate()
.map_err(|e| e.in_section("identify"))?;
self.design.validate().map_err(|e| e.in_section("design"))?;
self.verify.validate().map_err(|e| e.in_section("verify"))?;
check("max_verify_pairs", self.max_verify_pairs > 0, "positive")?;
check(
"candidates_per_update",
self.candidates_per_update > 0,
"positive",
)
}
}
pub const PLANE_RATE_STEP: StepConfig = StepConfig {
amplitude: 8.0 * DEG,
duration_s: 1.0,
settle_band: 0.1,
filter_hz: 0.0,
};
pub const PLANE_ROLL_STEP: StepConfig = StepConfig {
amplitude: 30.0 * DEG,
duration_s: 4.0,
settle_band: 0.1,
filter_hz: 0.0,
};
pub const PLANE_PITCH_STEP: StepConfig = StepConfig {
amplitude: 10.0 * DEG,
..PLANE_ROLL_STEP
};
pub const PLANE_STEP_SETTLE: Settle = Settle {
tilt_rad: 3.0 * DEG,
rate_radps: 0.1,
hold_s: 1.0,
max_speed_mps: DEFAULT_SETTLE_SPEED_MPS,
};
pub const PLANE_MAX_SATURATED_S: f32 = 0.042;
impl StepTestPlan {
pub fn plane(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
let capped = |step: StepConfig, limit_rad: f32| StepConfig {
amplitude: step.amplitude.min(limit_rad),
..step
};
let step = match target {
PlaneLoop::RollRate | PlaneLoop::PitchRate => PLANE_RATE_STEP,
PlaneLoop::Roll => capped(PLANE_ROLL_STEP, config.max_bank_rad),
PlaneLoop::Pitch => capped(PLANE_PITCH_STEP, config.max_pitch_rad),
};
Self {
step,
pairs: 3,
settle: PLANE_STEP_SETTLE,
max_saturated_s: PLANE_MAX_SATURATED_S,
max_invalid: 3,
max_stalled: 10,
}
}
}
impl StagePlan<PlaneSide> {
pub fn plane_design(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
Self {
target,
method: PlaneMethod::Design(PlaneDesignPlan::for_plane(target, config)),
}
}
pub fn plane_step_test(target: PlaneLoop, config: &PlaneStabilizerConfig) -> Self {
Self {
target,
method: PlaneMethod::StepTest(StepTestPlan::plane(target, config)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaneEnvelope {
pub max_bank_rad: f32,
pub max_pitch_rad: f32,
pub max_rate_radps: f32,
pub max_altitude_loss_m: f32,
pub min_airspeed_mps: f32,
pub max_airspeed_mps: f32,
pub settle: Settle,
pub settle_timeout_s: f32,
pub recovery_s: f32,
pub max_stale_s: f32,
pub settle_airspeed: AirspeedSettle,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AirspeedSettle {
pub trim_mps: f32,
pub band_mps: f32,
pub max_change_mps2: f32,
}
impl AirspeedSettle {
fn holds(&self, motion: &Motion) -> bool {
motion.airspeed_mps.is_none_or(|airspeed_mps| {
(airspeed_mps - self.trim_mps).abs() < self.band_mps
&& motion.airspeed_change_mps2.abs() < self.max_change_mps2
})
}
}
impl PlaneEnvelope {
pub fn for_plane(config: &PlaneStabilizerConfig) -> Self {
Self {
max_bank_rad: 60.0 * DEG,
max_pitch_rad: 30.0 * DEG,
max_rate_radps: 4.0,
max_altitude_loss_m: 40.0,
min_airspeed_mps: 0.9 * config.min_airspeed_mps,
max_airspeed_mps: config.max_airspeed_mps,
settle: PLANE_STEP_SETTLE,
settle_timeout_s: 20.0,
recovery_s: 2.0,
max_stale_s: 2.0,
settle_airspeed: AirspeedSettle {
trim_mps: config.trim_airspeed_mps,
band_mps: 1.0,
max_change_mps2: 0.2,
},
}
}
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_positive("max_bank_rad", self.max_bank_rad)?;
check_positive("max_pitch_rad", self.max_pitch_rad)?;
check_positive("max_rate_radps", self.max_rate_radps)?;
check_positive("max_altitude_loss_m", self.max_altitude_loss_m)?;
check_positive("min_airspeed_mps", self.min_airspeed_mps)?;
check(
"max_airspeed_mps",
self.max_airspeed_mps > self.min_airspeed_mps && self.max_airspeed_mps.is_finite(),
"finite and above min_airspeed_mps",
)?;
check_positive("settle_timeout_s", self.settle_timeout_s)?;
check_limit("recovery_s", self.recovery_s)?;
check_positive("max_stale_s", self.max_stale_s)?;
let airspeed = &self.settle_airspeed;
check_positive("settle_airspeed.trim_mps", airspeed.trim_mps)?;
check_positive("settle_airspeed.band_mps", airspeed.band_mps)?;
check_positive("settle_airspeed.max_change_mps2", airspeed.max_change_mps2)?;
self.check_settle(&self.settle)
}
pub fn check_settle(&self, settle: &Settle) -> Result<(), InvalidConfig> {
check(
"settle.tilt_rad",
settle.tilt_rad > 0.0 && settle.tilt_rad < self.max_bank_rad.min(self.max_pitch_rad),
"positive and below max_bank_rad and max_pitch_rad",
)?;
check(
"settle.rate_radps",
settle.rate_radps > 0.0 && settle.rate_radps < self.max_rate_radps,
"positive and below max_rate_radps",
)?;
check(
"settle.hold_s",
settle.hold_s > 0.0 && settle.hold_s < self.settle_timeout_s,
"positive and below settle_timeout_s",
)
}
fn breach(&self, motion: &Motion, start_altitude_m: f32) -> Option<AutotuneAbort> {
let airspeed_mps = motion.airspeed_mps;
if motion.bank_rad > self.max_bank_rad || motion.pitch_rad > self.max_pitch_rad {
Some(AutotuneAbort::Tilt)
} else if motion.rate_radps > self.max_rate_radps {
Some(AutotuneAbort::Rate)
} else if start_altitude_m - motion.altitude_m > self.max_altitude_loss_m {
Some(AutotuneAbort::AltitudeLoss)
} else if airspeed_mps.is_some_and(|mps| mps < self.min_airspeed_mps) {
Some(AutotuneAbort::AirspeedLow)
} else if airspeed_mps.is_some_and(|mps| mps > self.max_airspeed_mps) {
Some(AutotuneAbort::AirspeedHigh)
} else {
None
}
}
}
impl SideConfig<PlaneSide> for PlaneStabilizerConfig {
fn side(&self) -> &PlaneStabilizerConfig {
self
}
fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
self
}
}
impl SideConfig<PlaneSide> for TailsitterStabilizerConfig {
fn side(&self) -> &PlaneStabilizerConfig {
&self.plane
}
fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
&mut self.plane
}
}
impl SideConfig<PlaneSide> for QuadPlaneStabilizerConfig {
fn side(&self) -> &PlaneStabilizerConfig {
&self.plane
}
fn side_mut(&mut self) -> &mut PlaneStabilizerConfig {
&mut self.plane
}
}
impl Side for PlaneSide {
type Target = PlaneLoop;
type Gains = PlaneAxisGains;
type Config = PlaneStabilizerConfig;
type Method = PlaneMethod;
type Envelope = PlaneEnvelope;
type Procedure = PlaneProcedure;
fn gains(target: PlaneLoop, config: &PlaneStabilizerConfig) -> PlaneAxisGains {
target.gains(config)
}
fn set_gains(target: PlaneLoop, config: &mut PlaneStabilizerConfig, gains: PlaneAxisGains) {
target.set_gains(config, gains);
}
fn probed_loop(target: PlaneLoop, probe: &ProbeConfig) -> PlaneLoop {
match probe {
ProbeConfig::Identify(_) | ProbeConfig::IdentifyWing(_) => {
target.inner().unwrap_or(target)
}
ProbeConfig::Step(_) => target,
}
}
fn validate_method(method: &PlaneMethod) -> Result<(), InvalidConfig> {
match method {
PlaneMethod::StepTest(plan) => {
plan.validate().map_err(|e| e.in_section("plan.step_test"))
}
PlaneMethod::Design(plan) => plan.validate().map_err(|e| e.in_section("plan.design")),
}
}
fn method_settle(method: &PlaneMethod) -> Option<Settle> {
match method {
PlaneMethod::StepTest(plan) => Some(plan.settle),
PlaneMethod::Design(plan) => Some(plan.settle),
}
}
fn procedure(method: PlaneMethod) -> PlaneProcedure {
PlaneProcedure::new(method)
}
fn decide(
procedure: &mut PlaneProcedure,
on: Decide,
stage: StageView<'_, Self>,
) -> Action<PlaneAxisGains> {
procedure.next(on, stage.target.gains(stage.config))
}
fn take_verdict(_procedure: &mut PlaneProcedure) -> Option<Verdict<PlaneAxisGains>> {
None
}
fn validate_envelope(envelope: &PlaneEnvelope) -> Result<(), InvalidConfig> {
envelope.validate()
}
fn check_settle(envelope: &PlaneEnvelope, settle: &Settle) -> Result<(), InvalidConfig> {
envelope.check_settle(settle)
}
fn waits(envelope: &PlaneEnvelope) -> Waits {
Waits {
settle: envelope.settle,
settle_timeout_s: envelope.settle_timeout_s,
recovery_s: envelope.recovery_s,
max_stale_s: envelope.max_stale_s,
}
}
fn breach(
envelope: &PlaneEnvelope,
motion: &Motion,
start_altitude_m: f32,
) -> Option<AutotuneAbort> {
envelope.breach(motion, start_altitude_m)
}
fn filter_rates(
_filters: &mut RateFilters,
_config: &PlaneStabilizerConfig,
rates_radps: Vec3,
_dt: f32,
) -> Vec3 {
rates_radps
}
fn attitude_target(setpoint: &Setpoint) -> Vec2 {
let plane = match setpoint {
Setpoint::Plane(plane) => plane,
Setpoint::Blend(blend) => &blend.plane,
_ => return Vec2::zeros(),
};
Vec2::new(zero_if_nan(plane.roll_rad), zero_if_nan(plane.pitch_rad))
}
fn settles(
envelope: &PlaneEnvelope,
settle: &Settle,
motion: &Motion,
_target: PlaneLoop,
) -> bool {
(0..2).all(|axis| steady_axis(settle, motion, axis))
&& envelope.settle_airspeed.holds(motion)
}
fn holds(settle: &Settle, motion: &Motion, target: PlaneLoop) -> bool {
steady_axis(settle, motion, target.axis())
}
}
fn steady_axis(settle: &Settle, motion: &Motion, axis: usize) -> bool {
motion.axis_tilt_error_rad[axis] < settle.tilt_rad
&& motion.axis_rate_radps[axis] < settle.rate_radps
}
#[cfg(test)]
mod tests;