use super::{Action, Input, measure_again};
use crate::controllers::Gains;
use crate::tuning::autotune::{AutotuneAbort, DesignPlan, Outcome};
use crate::tuning::{Measurement, ProbeConfig};
const MAX_UNUSABLE_FITS: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::tuning::autotune) struct Design {
plan: DesignPlan,
inner: Option<Gains>,
gyro_cutoff_hz: f32,
designed: Gains,
stops: usize,
unusable: usize,
}
impl Design {
pub(super) fn new(plan: DesignPlan) -> Self {
Self {
plan,
inner: None,
gyro_cutoff_hz: 0.0,
designed: Gains::default(),
stops: 0,
unusable: 0,
}
}
pub(super) fn next(&mut self, input: Input) -> Action {
let identify = ProbeConfig::Identify(self.plan.identify);
match input {
Input::Start {
inner,
gyro_cutoff_hz,
..
} => {
self.inner = inner;
self.gyro_cutoff_hz = gyro_cutoff_hz;
Action::probe(identify)
}
Input::Measured {
measurement: Measurement::Identify(model),
gains,
stalled: false,
} => {
self.stops = 0;
match self
.plan
.gains(&model, gains, self.inner, self.gyro_cutoff_hz)
{
Ok(designed) => {
self.designed = designed;
Action::Hold { gains: designed }
}
Err(error) => self.refit(AutotuneAbort::Design(error)),
}
}
Input::Measured {
measurement: Measurement::Identify(_),
stalled: true,
..
}
| Input::Stalled { .. } => measure_again(&mut self.stops, identify),
Input::Held { settled: true, .. } => Action::Finish {
gains: self.designed,
outcome: Outcome::Designed,
steps: None,
baseline: None,
},
Input::Held { settled: false, .. } => self.refit(AutotuneAbort::NotSettled),
Input::Breached { reason, .. } => self.refit(reason),
Input::Aborted { abort, .. } => Action::Fail(AutotuneAbort::Probe(abort)),
Input::Measured { .. } => Action::Fail(AutotuneAbort::Interrupted),
}
}
fn refit(&mut self, abort: AutotuneAbort) -> Action {
self.unusable += 1;
if self.unusable >= MAX_UNUSABLE_FITS {
Action::Fail(abort)
} else {
Action::probe(ProbeConfig::Identify(self.plan.identify))
}
}
}