1use core::fmt;
6
7use super::procedure::{Action, Input, Procedure, Verdict};
8use super::{AutotuneAbort, Envelope, Method, Settle, YAW_AXIS, tilt_axis};
9use crate::controllers::gyro::GyroFilter;
10use crate::controllers::{Gains, InvalidConfig};
11use crate::math::euler_angles;
12use crate::stabilizers::copter::{CopterStabilizerConfig, TunedLoop};
13use crate::tuning::{Measurement, ProbeAbort, ProbeConfig, Tunable};
14use crate::{Configurable, Setpoint, Vec2, Vec3, VehicleState};
15use nalgebra::UnitQuaternion;
16
17pub trait Side: sealed::Sealed + Copy + fmt::Debug + PartialEq {
22 type Target: Copy + fmt::Debug + PartialEq;
24 type Gains: Copy + fmt::Debug + PartialEq;
26 type Config: Copy + fmt::Debug + PartialEq;
28 type Method: Copy + fmt::Debug + PartialEq;
30 type Envelope: Copy + fmt::Debug + PartialEq;
32 #[doc(hidden)]
34 type Procedure: Copy + fmt::Debug + PartialEq;
35
36 #[doc(hidden)]
38 fn gains(target: Self::Target, config: &Self::Config) -> Self::Gains;
39 #[doc(hidden)]
41 fn set_gains(target: Self::Target, config: &mut Self::Config, gains: Self::Gains);
42 #[doc(hidden)]
44 fn probed_loop(target: Self::Target, probe: &ProbeConfig) -> Self::Target;
45
46 #[doc(hidden)]
48 fn validate_method(method: &Self::Method) -> Result<(), InvalidConfig>;
49 #[doc(hidden)]
51 fn method_settle(method: &Self::Method) -> Option<Settle>;
52 #[doc(hidden)]
54 fn procedure(method: Self::Method) -> Self::Procedure;
55 #[doc(hidden)]
57 fn decide(
58 procedure: &mut Self::Procedure,
59 on: Decide,
60 stage: StageView<'_, Self>,
61 ) -> Action<Self::Gains>;
62 #[doc(hidden)]
64 fn take_verdict(procedure: &mut Self::Procedure) -> Option<Verdict<Self::Gains>>;
65
66 #[doc(hidden)]
68 fn validate_envelope(envelope: &Self::Envelope) -> Result<(), InvalidConfig>;
69 #[doc(hidden)]
71 fn check_settle(envelope: &Self::Envelope, settle: &Settle) -> Result<(), InvalidConfig>;
72 #[doc(hidden)]
74 fn waits(envelope: &Self::Envelope) -> Waits;
75 #[doc(hidden)]
77 fn breach(
78 envelope: &Self::Envelope,
79 motion: &Motion,
80 start_altitude_m: f32,
81 ) -> Option<AutotuneAbort>;
82
83 #[doc(hidden)]
85 fn filter_rates(
86 filters: &mut RateFilters,
87 config: &Self::Config,
88 rates_radps: Vec3,
89 dt: f32,
90 ) -> Vec3;
91 #[doc(hidden)]
93 fn attitude_target(setpoint: &Setpoint) -> Vec2;
94 #[doc(hidden)]
96 fn settles(
97 envelope: &Self::Envelope,
98 settle: &Settle,
99 motion: &Motion,
100 target: Self::Target,
101 ) -> bool;
102 #[doc(hidden)]
104 fn holds(settle: &Settle, motion: &Motion, target: Self::Target) -> bool;
105}
106
107mod sealed {
108 pub trait Sealed {}
109 impl Sealed for super::CopterSide {}
110 impl Sealed for super::super::PlaneSide {}
111}
112
113pub trait SideConfig<K: Side> {
115 fn side(&self) -> &K::Config;
117 fn side_mut(&mut self) -> &mut K::Config;
119}
120
121pub trait SideTunable<K: Side>: Tunable<K::Target> + Configurable<Config: SideConfig<K>> {}
124
125impl<K: Side, S> SideTunable<K> for S where
126 S: Tunable<K::Target> + Configurable<Config: SideConfig<K>>
127{
128}
129
130#[derive(Clone, Copy, Debug, PartialEq)]
133pub struct Waits {
134 pub(super) settle: Settle,
135 pub(super) settle_timeout_s: f32,
136 pub(super) recovery_s: f32,
137 pub(super) max_stale_s: f32,
138}
139
140#[derive(Clone, Debug, Default, PartialEq)]
142pub struct RateFilters(pub(super) [GyroFilter; 3]);
143
144pub struct StageView<'a, K: Side> {
147 pub(super) target: K::Target,
148 pub(super) config: &'a K::Config,
149 pub(super) run_start: Option<&'a K::Config>,
150}
151
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub struct CopterSide;
156
157impl SideConfig<CopterSide> for CopterStabilizerConfig {
158 fn side(&self) -> &CopterStabilizerConfig {
159 self
160 }
161
162 fn side_mut(&mut self) -> &mut CopterStabilizerConfig {
163 self
164 }
165}
166
167#[derive(Clone, Copy, Debug, PartialEq)]
169pub struct CopterProcedure(Procedure);
170
171impl Side for CopterSide {
172 type Target = TunedLoop;
173 type Gains = Gains;
174 type Config = CopterStabilizerConfig;
175 type Method = Method;
176 type Envelope = Envelope;
177 type Procedure = CopterProcedure;
178
179 fn gains(target: TunedLoop, config: &CopterStabilizerConfig) -> Gains {
180 target.gains(config)
181 }
182
183 fn set_gains(target: TunedLoop, config: &mut CopterStabilizerConfig, gains: Gains) {
184 *target.gains_mut(config) = gains;
185 }
186
187 fn probed_loop(target: TunedLoop, probe: &ProbeConfig) -> TunedLoop {
190 match probe {
191 ProbeConfig::Identify(_) | ProbeConfig::IdentifyWing(_) => {
192 target.inner().unwrap_or(target)
193 }
194 ProbeConfig::Step(_) => target,
195 }
196 }
197
198 fn validate_method(method: &Method) -> Result<(), InvalidConfig> {
199 method
200 .validate()
201 .map_err(|e| e.in_section(method.plan_section()))
202 }
203
204 fn method_settle(method: &Method) -> Option<Settle> {
205 method.settle()
206 }
207
208 fn procedure(method: Method) -> CopterProcedure {
209 CopterProcedure(Procedure::new(method))
210 }
211
212 fn decide(procedure: &mut CopterProcedure, on: Decide, stage: StageView<'_, Self>) -> Action {
213 let StageView {
214 target,
215 config,
216 run_start,
217 } = stage;
218 let gains = target.gains(config);
219 let input = match on {
220 Decide::Computing => return Action::Fail(AutotuneAbort::Interrupted),
222 Decide::Start => Input::Start {
223 gains,
224 inner: target.inner().map(|inner| inner.gains(config)),
225 run_start: run_start.map_or(gains, |run_start| target.gains(run_start)),
226 gyro: config.gyro_filters_on(tilt_axis(target).unwrap_or(YAW_AXIS)),
228 },
229 Decide::Measured {
230 measurement,
231 stalled,
232 } => Input::Measured {
233 measurement,
234 gains,
235 stalled,
236 },
237 Decide::Stalled => Input::Stalled { gains },
238 Decide::Aborted { abort } => Input::Aborted { abort, gains },
239 Decide::Breached { reason } => Input::Breached { reason, gains },
240 Decide::Held { settled } => Input::Held { settled, gains },
241 Decide::Unsettled => Input::Unsettled { gains },
242 };
243 procedure.0.next(input)
244 }
245
246 fn take_verdict(procedure: &mut CopterProcedure) -> Option<Verdict> {
247 procedure.0.take_verdict()
248 }
249
250 fn validate_envelope(envelope: &Envelope) -> Result<(), InvalidConfig> {
251 envelope.validate()
252 }
253
254 fn check_settle(envelope: &Envelope, settle: &Settle) -> Result<(), InvalidConfig> {
255 envelope.check_settle(settle)
256 }
257
258 fn waits(envelope: &Envelope) -> Waits {
259 Waits {
260 settle: envelope.settle,
261 settle_timeout_s: envelope.settle_timeout_s,
262 recovery_s: envelope.recovery_s,
263 max_stale_s: envelope.max_stale_s,
264 }
265 }
266
267 fn breach(
268 envelope: &Envelope,
269 motion: &Motion,
270 start_altitude_m: f32,
271 ) -> Option<AutotuneAbort> {
272 envelope.breach(motion, start_altitude_m)
273 }
274
275 fn filter_rates(
277 filters: &mut RateFilters,
278 config: &CopterStabilizerConfig,
279 rates_radps: Vec3,
280 dt: f32,
281 ) -> Vec3 {
282 Vec3::from_fn(|axis, _| {
283 let gyro = config.gyro_filters_on(axis);
284 filters.0[axis].apply(rates_radps[axis], dt, &gyro)
285 })
286 }
287
288 fn attitude_target(setpoint: &Setpoint) -> Vec2 {
289 attitude_target(setpoint)
290 }
291
292 fn settles(_envelope: &Envelope, settle: &Settle, motion: &Motion, target: TunedLoop) -> bool {
293 settle.holds_for(motion, target)
294 }
295
296 fn holds(settle: &Settle, motion: &Motion, target: TunedLoop) -> bool {
300 tilt_axis(target).map_or_else(
301 || settle.holds_yaw(motion),
302 |axis| settle.holds_axis(motion, axis),
303 )
304 }
305}
306
307pub struct Motion {
316 pub(super) tilt_rad: f32,
318 pub(super) bank_rad: f32,
320 pub(super) pitch_rad: f32,
322 pub(super) rate_radps: f32,
324 pub(super) axis_tilt_error_rad: [f32; 2],
326 pub(super) speed_mps: f32,
328 pub(super) axis_rate_radps: [f32; 2],
330 pub(super) yaw_rate_radps: f32,
332 pub(super) altitude_m: f32,
333 pub(super) airspeed_mps: Option<f32>,
335 pub(super) airspeed_change_mps2: f32,
338}
339
340impl Motion {
341 pub(super) fn of(
345 state: &VehicleState,
346 frame: &UnitQuaternion<f32>,
347 filtered_radps: Vec3,
348 target_rad: Vec2,
349 ) -> Self {
350 let (roll, pitch, _) = euler_angles(&(state.attitude * frame));
352 let raw_radps = frame.inverse_transform_vector(&state.angular_velocity_radps);
353 let filtered_radps = frame.inverse_transform_vector(&filtered_radps);
354 let roll_error_rad = (roll - target_rad.x).abs();
355 let pitch_error_rad = (pitch - target_rad.y).abs();
356 Self {
357 tilt_rad: roll.abs().max(pitch.abs()),
358 bank_rad: roll.abs(),
359 pitch_rad: pitch.abs(),
360 rate_radps: raw_radps.amax(),
361 axis_tilt_error_rad: [roll_error_rad, pitch_error_rad],
362 speed_mps: zero_if_nan(state.velocity_mps.xy().norm()),
363 axis_rate_radps: [filtered_radps.x.abs(), filtered_radps.y.abs()],
364 yaw_rate_radps: filtered_radps.z.abs(),
365 altitude_m: state.position_m.z,
366 airspeed_mps: state.valid_airspeed_mps(),
367 airspeed_change_mps2: 0.0,
368 }
369 }
370}
371
372pub(super) fn attitude_target(setpoint: &Setpoint) -> Vec2 {
378 let attitude = match setpoint {
379 Setpoint::Attitude(attitude) => attitude,
380 Setpoint::Blend(blend) => &blend.hover,
381 _ => return Vec2::zeros(),
382 };
383 Vec2::new(
384 zero_if_nan(attitude.roll_rad),
385 zero_if_nan(attitude.pitch_rad),
386 )
387}
388
389pub(super) fn zero_if_nan(value: f32) -> f32 {
391 if value.is_nan() { 0.0 } else { value }
392}
393
394#[derive(Clone, Copy, Debug, PartialEq)]
396pub enum Decide {
397 Start,
399 Measured {
401 measurement: Measurement,
402 stalled: bool,
403 },
404 Stalled,
406 Aborted { abort: ProbeAbort },
408 Breached { reason: AutotuneAbort },
410 Held { settled: bool },
412 Unsettled,
414 Computing,
416}