Skip to main content

stable_flight/controllers/
yaw.rs

1use crate::controllers::derivative::DerivativeState;
2use crate::controllers::{Gains, InvalidConfig, check_limit, rescale_integral};
3use crate::math::{assert_dt, clamp_symmetric, wrap_angle};
4
5/// Configures the yaw controller with PID gains and operational limits.
6///
7/// This structure defines the control parameters that determine how the yaw controller
8/// responds to heading errors, including responsiveness, stability, and maximum rates.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct YawControllerConfig {
11    /// PID gains that determine controller responsiveness.
12    ///
13    /// * `p` - Proportional gain: controls response strength relative to current error.
14    /// * `i` - Integral gain: eliminates steady-state errors over time.
15    /// * `d` - Derivative gain: provides damping to reduce overshoot and oscillation.
16    pub gains: Gains,
17
18    /// Maximum absolute value of the integrated heading error, in rad·s.
19    ///
20    /// Prevents integral windup by limiting accumulated error, which
21    /// could otherwise cause significant overshoot and control instability.
22    pub max_integral: f32,
23
24    /// Maximum angular rate in radians/second for yaw.
25    ///
26    /// Limits the output commands to physically achievable rates and
27    /// prevents excessive control demands that could destabilize the system.
28    pub max_rate_radps: f32,
29}
30
31impl Default for YawControllerConfig {
32    fn default() -> Self {
33        Self {
34            // Heading hold, flight-checked on RealFlight's QuadCopterX (#62).
35            gains: Gains {
36                p: 2.5,
37                i: 0.0,
38                d: 0.06,
39            },
40            max_integral: 100.0, // Arbitrary limit
41            max_rate_radps: 2.0, // 2 rad/s (~114°/s) for yaw
42        }
43    }
44}
45
46impl YawControllerConfig {
47    /// Checks the config: `max_integral` and `max_rate_radps` must be non-negative and finite.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use stable_flight::controllers::YawControllerConfig;
53    ///
54    /// assert!(YawControllerConfig::default().validate().is_ok());
55    /// let bad = YawControllerConfig { max_rate_radps: f32::NAN, ..Default::default() };
56    /// assert!(bad.validate().is_err());
57    /// ```
58    pub fn validate(&self) -> Result<(), InvalidConfig> {
59        check_limit("max_integral", self.max_integral)?;
60        check_limit("max_rate_radps", self.max_rate_radps)
61    }
62}
63
64/// Yaw controller that maintains a desired heading using PID control.
65///
66/// This controller:
67/// * Takes desired and actual heading measurements
68/// * Calculates the shortest path error accounting for angle wrapping
69/// * Applies PID control to generate appropriate yaw rate commands
70/// * Incorporates anti-windup protection and output limiting
71///
72/// It holds only state (integral and derivative history); gains and limits come from the
73/// [`YawControllerConfig`] passed to each [`control`](Self::control) call, so they can change
74/// between ticks without resetting the state.
75#[derive(Clone, Debug, Default, PartialEq)]
76pub struct YawController {
77    /// Previous error for the derivative term; empty on the first tick and after a gap.
78    derivative: DerivativeState<f32>,
79    integrated_error: f32,
80}
81
82impl YawController {
83    /// Calculates desired yaw rate based on current and target headings.
84    ///
85    /// This implementation:
86    /// 1. Calculates the shortest-path heading error
87    /// 2. Updates the integral term with anti-windup protection
88    /// 3. Applies the PID formula
89    /// 5. Limits the output rate to configured maximum values
90    ///
91    /// # Arguments
92    ///
93    /// * `config` - Gains and limits; assumed valid ([`YawControllerConfig::validate`]). An
94    ///   invalid limit does not panic: a negative or NaN limit acts as 0.
95    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
96    /// * `desired_yaw_rad` - Target yaw angle in radians. Any finite value is accepted; the
97    ///   error is wrapped to the shortest path, so `desired_yaw_rad` and `desired_yaw_rad + 2πk` are
98    ///   equivalent. A non-finite target (or estimate) yields a zero rate and leaves the
99    ///   controller state untouched.
100    /// * `estimated_yaw_rad` - Current measured yaw angle in radians.
101    ///
102    /// # Returns
103    ///
104    /// Desired yaw rate in rad/s, limited to configured maximum rates.
105    ///
106    /// # Panics
107    ///
108    /// If `dt` is not positive and finite.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use std::f32::consts::PI;
114    /// use stable_flight::controllers::{YawController, YawControllerConfig};
115    ///
116    /// let config = YawControllerConfig::default();
117    /// let mut controller = YawController::default();
118    /// let dt = 0.02;
119    /// let desired_yaw_rad = PI / 4.0;  // 45 degrees
120    /// let current_yaw_rad = 0.0;       // 0 degrees
121    ///
122    /// let yaw_rate = controller.control(&config, dt, desired_yaw_rad, current_yaw_rad);
123    /// // Returns a rate command to turn toward the desired heading
124    /// ```
125    pub fn control(
126        &mut self,
127        config: &YawControllerConfig,
128        dt: f32,
129        desired_yaw_rad: f32,
130        estimated_yaw_rad: f32,
131    ) -> f32 {
132        let error = angle_diff(desired_yaw_rad, estimated_yaw_rad); // Use a helper to handle angle wrapping
133        self.control_error(config, dt, error)
134    }
135
136    /// The PID of [`control`](Self::control) on a yaw error already taken (radians, the short
137    /// way round): for a caller that measures the error itself, e.g. from quaternions. The
138    /// output is clamped to `max_rate_radps`; a non-finite error gives zero.
139    ///
140    /// # Panics
141    ///
142    /// If `dt` is not positive and finite.
143    pub(crate) fn control_error(
144        &mut self,
145        config: &YawControllerConfig,
146        dt: f32,
147        error: f32,
148    ) -> f32 {
149        assert_dt(dt);
150
151        let gains = &config.gains;
152
153        if !error.is_finite() {
154            // Hold (no yaw rate) rather than letting NaN into the integral and derivative
155            // history, where it would stick; clamping passes NaN through. Forget the previous
156            // error too, so the first valid tick after the gap has no derivative kick.
157            self.derivative.forget();
158            return 0.0;
159        }
160        let error_derivative = self.derivative.step(error, dt);
161
162        self.integrated_error =
163            clamp_symmetric(self.integrated_error + dt * error, config.max_integral);
164
165        let yaw_rate =
166            gains.p * error + gains.i * self.integrated_error + gains.d * error_derivative;
167
168        clamp_symmetric(yaw_rate, config.max_rate_radps)
169    }
170
171    /// Zeroes the integral, keeping the derivative history.
172    pub(crate) fn clear_integral(&mut self) {
173        self.integrated_error = 0.0;
174    }
175
176    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
177    /// tick's I term picks up where the last left off (`rescale_integral`).
178    pub(crate) fn rescale_integral(
179        &mut self,
180        old: &YawControllerConfig,
181        new: &YawControllerConfig,
182    ) {
183        self.integrated_error = rescale_integral(self.integrated_error, old.gains.i, new.gains.i);
184    }
185
186    /// Restarts with no derivative history, keeping the integral.
187    pub(crate) fn hand_back(&mut self) {
188        self.derivative = DerivativeState::default();
189    }
190}
191
192/// The shortest-path yaw error from `current_yaw` to `desired_yaw`, in [-π, π).
193///
194/// # Arguments
195///
196/// * `desired_yaw` - Desired yaw angle in radians.
197/// * `current_yaw` - Current yaw angle in radians.
198///
199/// # Returns
200///
201/// The shortest-path yaw error in radians, in [-π, π) (see [`wrap_angle`]).
202pub(crate) fn angle_diff(desired_yaw: f32, current_yaw: f32) -> f32 {
203    wrap_angle(desired_yaw - current_yaw)
204}
205
206#[cfg(test)]
207mod tests {
208
209    use std::f32::consts::PI;
210
211    use approx::assert_relative_eq;
212
213    use crate::controllers::Gains;
214
215    use super::*;
216
217    const EPSILON: f32 = 1e-5;
218
219    /// Handing back clears the derivative history and keeps the integral.
220    #[test]
221    fn hand_back_keeps_the_integral() {
222        let config = YawControllerConfig {
223            gains: Gains {
224                p: 1.0,
225                i: 2.0,
226                d: 0.5,
227            },
228            ..p_only_config(1.0, 10.0)
229        };
230        let mut controller = YawController::default();
231        controller.control_error(&config, 0.1, 0.5);
232        let integral = controller.integrated_error;
233
234        controller.hand_back();
235
236        assert_eq!(controller.integrated_error, integral);
237        assert_eq!(controller.derivative, DerivativeState::default());
238    }
239
240    // Helper functions for test setup
241
242    /// A config with only proportional gain.
243    fn p_only_config(p_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
244        YawControllerConfig {
245            gains: Gains {
246                p: p_gain,
247                i: 0.0,
248                d: 0.0,
249            },
250            max_integral: 10.0,
251            max_rate_radps,
252        }
253    }
254
255    /// A config with only integral gain.
256    fn i_only_config(i_gain: f32, max_integral: f32, max_rate_radps: f32) -> YawControllerConfig {
257        YawControllerConfig {
258            gains: Gains {
259                p: 0.0,
260                i: i_gain,
261                d: 0.0,
262            },
263            max_integral,
264            max_rate_radps,
265        }
266    }
267
268    /// A config with only derivative gain.
269    fn d_only_config(d_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
270        YawControllerConfig {
271            gains: Gains {
272                p: 0.0,
273                i: 0.0,
274                d: d_gain,
275            },
276            max_integral: 10.0,
277            max_rate_radps,
278        }
279    }
280
281    /// Tests that the default controller configuration has expected values.
282    #[test]
283    fn test_default_config() {
284        let config = YawControllerConfig::default();
285
286        assert_relative_eq!(config.gains.p, 2.5, epsilon = EPSILON, max_relative = 1e-3);
287        assert_relative_eq!(config.gains.i, 0.0, epsilon = EPSILON, max_relative = 1e-3);
288        assert_relative_eq!(config.gains.d, 0.06, epsilon = EPSILON, max_relative = 1e-3);
289        assert_relative_eq!(
290            config.max_integral,
291            100.0,
292            epsilon = EPSILON,
293            max_relative = 1e-3
294        );
295        assert_relative_eq!(
296            config.max_rate_radps,
297            2.0,
298            epsilon = EPSILON,
299            max_relative = 1e-3
300        );
301    }
302
303    #[test]
304    fn default_is_zeroed_state() {
305        assert_eq!(
306            YawController::default(),
307            YawController {
308                derivative: DerivativeState::default(),
309                integrated_error: 0.0,
310            }
311        );
312    }
313
314    /// Tests that the proportional control term works correctly in isolation.
315    #[test]
316    fn test_proportional_control() {
317        // Test that the proportional term works correctly
318        let config = p_only_config(2.0, 5.0);
319        let mut controller = YawController::default();
320
321        // Simple case: 0.5 rad error should result in rate = 2.0 * 0.5 = 1.0 rad/s
322        let dt = 0.01;
323        let desired_yaw = 0.5;
324        let estimated_yaw = 0.0;
325
326        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
327        assert_relative_eq!(
328            rate,
329            1.0,
330            epsilon = EPSILON,
331            max_relative = 1e-3,
332            max_relative = 1e-3
333        );
334
335        // Test with negative error
336        let rate = controller.control(&config, dt, 0.0, 0.5);
337        assert_relative_eq!(rate, -1.0, epsilon = EPSILON, max_relative = 1e-3);
338    }
339
340    /// Tests that the integral control term accumulates correctly and respects limits.
341    #[test]
342    fn test_integral_control() {
343        // Test that the integral term accumulates and affects output
344        let config = i_only_config(1.0, 10.0, 5.0);
345        let mut controller = YawController::default();
346
347        // Apply constant error for several iterations
348        let dt = 1.0; // 1 second for easy calculation
349        let desired_yaw = 0.5;
350        let estimated_yaw = 0.0;
351
352        // First iteration: integral = 0.5 * 1.0 = 0.5
353        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
354        assert_relative_eq!(rate, 0.5, epsilon = EPSILON, max_relative = 1e-3);
355
356        // Second iteration: integral = 0.5 + 0.5 * 1.0 = 1.0
357        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
358        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
359
360        // Test integral clamping
361        let config = i_only_config(1.0, 1.5, 5.0);
362        let mut controller = YawController::default();
363
364        // Accumulate for 3 seconds to exceed max_integral
365        controller.control(&config, dt, desired_yaw, estimated_yaw); // 0.5
366        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.0
367        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.5
368        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
369
370        // Should be clamped at max_integral * i_gain = 1.5
371        assert_relative_eq!(rate, 1.5, epsilon = EPSILON, max_relative = 1e-3);
372    }
373
374    /// Tests that the derivative control term responds correctly to error changes.
375    #[test]
376    fn test_derivative_control() {
377        // Test that the derivative term works correctly
378        let config = d_only_config(2.0, 5.0);
379        let mut controller = YawController::default();
380
381        let dt = 1.0; // 1 second for easy calculation
382
383        // First call - establishes baseline error
384        let rate = controller.control(&config, dt, 0.5, 0.0);
385        assert_relative_eq!(
386            rate,
387            0.0,
388            epsilon = EPSILON,
389            max_relative = 1e-3,
390            max_relative = 1e-3
391        );
392
393        // Second call - error unchanged, derivative should be zero
394        let rate = controller.control(&config, dt, 0.5, 0.0);
395        assert_relative_eq!(rate, 0.0, epsilon = EPSILON, max_relative = 1e-3);
396
397        // Error increasing by 0.1 rad/s
398        let rate = controller.control(&config, dt, 0.6, 0.0);
399        assert_relative_eq!(rate, 0.2, epsilon = EPSILON, max_relative = 1e-3);
400
401        // Error decreasing by 0.2 rad/s
402        let rate = controller.control(&config, dt, 0.4, 0.0);
403        assert_relative_eq!(rate, -0.4, epsilon = EPSILON, max_relative = 1e-3);
404    }
405
406    /// Tests all PID components working together with detailed calculation.
407    #[test]
408    fn test_pid_combined() {
409        // Test all PID components working together
410        let config = YawControllerConfig {
411            gains: Gains {
412                p: 1.0,
413                i: 0.5,
414                d: 0.2,
415            },
416            max_integral: 10.0,
417            max_rate_radps: 5.0,
418        };
419
420        let mut controller = YawController::default();
421
422        let dt = 1.0;
423
424        // First call:
425        // - P term = 1.0 * 0.5 = 0.5
426        // - I term = 0.5 * (0.5 * 1.0) = 0.25
427        // - D term = 0 (no previous error)
428        // Total = 0.5 + 0.25 + 0 = 0.75
429        let rate = controller.control(&config, dt, 0.5, 0.0);
430        assert_relative_eq!(rate, 0.75, epsilon = EPSILON, max_relative = 1e-3);
431
432        // Second call with same error:
433        // - P term = 1.0 * 0.5 = 0.5
434        // - I term = 0.5 * (0.5 + 0.5) = 0.5
435        // - D term = 0.2 * (0.5 - 0.5) / 1.0 = 0
436        // Total = 0.5 + 0.5 + 0 = 1.0
437        let rate = controller.control(&config, dt, 0.5, 0.0);
438        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
439
440        // Third call with increased error:
441        // - P term = 1.0 * 0.6 = 0.6
442        // - I term = 0.5 * (0.5 + 0.5 + 0.6) = 0.8
443        // - D term = 0.2 * (0.6 - 0.5) / 1.0 = 0.02
444        // Total = 0.6 + 0.8 + 0.02 = 1.42
445        let rate = controller.control(&config, dt, 0.6, 0.0);
446        assert_relative_eq!(rate, 1.42, epsilon = EPSILON, max_relative = 1e-3);
447    }
448
449    /// Tests that the controller handles varying time steps correctly.
450    #[test]
451    fn test_varying_time_steps() {
452        let config = YawControllerConfig {
453            gains: Gains {
454                p: 0.0,
455                i: 1.0,
456                d: 0.0,
457            },
458            max_integral: 10.0,
459            max_rate_radps: 5.0,
460        };
461
462        let mut controller = YawController::default();
463
464        // Control with a 1-second time step
465        let rate_1s = controller.control(&config, 1.0, 0.5, 0.0);
466        assert_relative_eq!(rate_1s, 0.5, epsilon = EPSILON, max_relative = 1e-3);
467
468        // Next control with a 0.5-second time step should accumulate half as much
469        let rate_05s = controller.control(&config, 0.5, 0.5, 0.0);
470        assert_relative_eq!(
471            rate_05s,
472            0.5 + 0.25, // Previous 0.5 plus new 0.5*0.5
473            epsilon = EPSILON,
474            max_relative = 1e-3
475        );
476
477        // Next control with a 0.25-second time step
478        let rate_025s = controller.control(&config, 0.25, 0.5, 0.0);
479        assert_relative_eq!(
480            rate_025s,
481            0.5 + 0.25 + 0.125, // Plus new 0.5*0.25
482            epsilon = EPSILON,
483            max_relative = 1e-3
484        );
485    }
486
487    /// Tests controller behavior with very small time steps.
488    #[test]
489    fn test_small_time_steps() {
490        let config = YawControllerConfig {
491            gains: Gains {
492                p: 1.0,
493                i: 1.0,
494                d: 1.0,
495            },
496            max_integral: 10.0,
497            max_rate_radps: 5.0,
498        };
499
500        let mut controller = YawController::default();
501
502        // Use a very small time step
503        let dt = 0.000001; // 1 microsecond
504        let error = 0.5;
505        let rate = controller.control(&config, dt, error, 0.0);
506
507        // With a tiny dt:
508        // - P term = 1.0 * 0.5 = 0.5
509        // - I term = 1.0 * 0.5 * 1e-6 ≈ 0.0000005 (effectively 0)
510        // - D term = undefined (first call)
511        assert_relative_eq!(
512            rate,
513            0.5, // Only P term is significant
514            epsilon = EPSILON,
515            max_relative = 1e-3
516        );
517
518        // Second call with same error should still have negligible I term
519        let rate = controller.control(&config, dt, error, 0.0);
520        assert_relative_eq!(
521            rate,
522            0.5, // P term only, I term still tiny
523            epsilon = EPSILON,
524            max_relative = 1e-3
525        );
526    }
527
528    /// Tests that angle wrapping is handled correctly at ±π boundaries.
529    #[test]
530    fn test_angle_wrapping() {
531        // Test angle wrapping when crossing the ±π boundary
532        let config = p_only_config(1.0, 5.0);
533        let mut controller = YawController::default();
534
535        let dt = 0.01;
536
537        // Test case: desired = 175°, current = -175°
538        // Shortest path is -10° (not +350°)
539        let desired_yaw = 175.0 * PI / 180.0;
540        let estimated_yaw = -175.0 * PI / 180.0;
541
542        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
543        let expected_rate = -10.0 * PI / 180.0; // -10 degrees converted to radians
544        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
545
546        // Test case: desired = -175°, current = 175°
547        // Shortest path is +10° (not -350°)
548        let desired_yaw = -175.0 * PI / 180.0;
549        let estimated_yaw = 175.0 * PI / 180.0;
550
551        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
552        let expected_rate = 10.0 * PI / 180.0; // 10 degrees converted to radians
553        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
554    }
555
556    /// Directly tests the angle_diff helper function with various inputs.
557    #[test]
558    fn angle_diff_is_the_shortest_signed_path() {
559        let deg = PI / 180.0;
560        // (desired, current, expected error)
561        let cases = [
562            (0.5, 0.0, 0.5),                        // no wrapping needed
563            (PI + 0.1, -PI - 0.1, 0.2),             // wraps across ±π
564            (350.0 * deg, 10.0 * deg, -20.0 * deg), // turn left through north
565            (10.0 * deg, 350.0 * deg, 20.0 * deg),  // turn right through north
566            (PI, -PI, 0.0),                         // same heading
567            (0.0, 2.0 * PI, 0.0),                   // same heading, one turn apart
568            (5.0, 5.0 - 2.0 * PI, 0.0),             // [0, 2π) heading vs its [-π, π) form
569        ];
570        for (desired, current, expected) in cases {
571            assert_relative_eq!(
572                angle_diff(desired, current),
573                expected,
574                epsilon = EPSILON,
575                max_relative = 1e-3
576            );
577        }
578    }
579
580    #[test]
581    fn test_valid_inputs() {
582        let config = YawControllerConfig::default();
583        let mut controller = YawController::default();
584        let dt = 0.01;
585
586        // Valid inputs should not panic
587        let _ = controller.control(&config, dt, 0.0, 0.0);
588        let _ = controller.control(&config, dt, PI, -PI);
589        let _ = controller.control(&config, dt, 2.0 * PI, 0.0);
590    }
591
592    #[test]
593    #[should_panic(expected = "dt must be positive and finite")]
594    fn zero_dt_panics() {
595        let config = YawControllerConfig::default();
596        let mut controller = YawController::default();
597        let dt = 0.0;
598        let _ = controller.control(&config, dt, 0.0, 0.0);
599    }
600
601    #[test]
602    fn any_finite_target_is_equivalent_to_its_wrapped_heading() {
603        // (target, equivalent target within [-π, π))
604        let cases = [
605            (3.0 * PI, -PI),
606            (10.0 * PI + 0.5, 0.5),
607            (-7.0 * PI / 2.0, PI / 2.0),
608            (1000.0, wrap_angle(1000.0)),
609        ];
610        let config = YawControllerConfig::default();
611        for (target, equivalent) in cases {
612            let rate = YawController::default().control(&config, 0.01, target, 0.2);
613            let expected = YawController::default().control(&config, 0.01, equivalent, 0.2);
614            assert_relative_eq!(rate, expected, epsilon = 1e-3);
615        }
616    }
617
618    #[test]
619    fn non_finite_target_holds_and_does_not_poison_later_ticks() {
620        let config = YawControllerConfig::default();
621        let mut controller = YawController::default();
622        for target in [f32::NAN, f32::INFINITY] {
623            assert!(controller.control(&config, 0.01, target, 0.2) == 0.0);
624        }
625        let after = controller.control(&config, 0.01, 1.0, 0.2);
626        let fresh = YawController::default().control(&config, 0.01, 1.0, 0.2);
627        assert_relative_eq!(after, fresh);
628    }
629
630    #[test]
631    fn nan_gap_does_not_cause_a_derivative_kick() {
632        // P+D only, so the only difference a stale previous error could make is the D term.
633        let config = YawControllerConfig {
634            gains: Gains {
635                p: 1.0,
636                i: 0.0,
637                d: 0.5,
638            },
639            max_integral: 1.0,
640            max_rate_radps: 100.0,
641        };
642        let mut controller = YawController::default();
643
644        controller.control(&config, 0.01, 1.0, 0.2); // error 0.8 becomes the previous error
645        controller.control(&config, 0.01, f32::NAN, 0.2); // gap
646        let after_gap = controller.control(&config, 0.01, 0.5, 0.2); // error 0.3
647
648        // Without the reset, D would add 0.5 * (0.3 - 0.8) / 0.01 = -25 rad/s.
649        let fresh = YawController::default().control(&config, 0.01, 0.5, 0.2);
650        assert_relative_eq!(after_gap, fresh);
651    }
652
653    /// Tests that output rate is properly limited to `max_rate_radps`.
654    #[test]
655    fn test_max_rate_limiting() {
656        // Test that output is clamped to max_rate_radps
657        let config = p_only_config(10.0, 2.0);
658        let mut controller = YawController::default();
659
660        let dt = 0.01;
661
662        // Error of 0.5 rad with P=10 would give 5.0 rad/s
663        // Should be limited to 2.0 rad/s
664        let rate = controller.control(&config, dt, 0.5, 0.0);
665
666        assert_relative_eq!(rate, 2.0, epsilon = EPSILON, max_relative = 1e-3);
667
668        // Test negative limiting too
669        let rate = controller.control(&config, dt, -0.5, 0.0);
670        assert_relative_eq!(rate, -2.0, epsilon = EPSILON, max_relative = 1e-3);
671    }
672
673    /// Tests a realistic maneuver to verify controller convergence and stability.
674    #[test]
675    fn test_realistic_maneuvers() {
676        // Test a realistic 90-degree turn maneuver
677        let config = YawControllerConfig {
678            gains: Gains {
679                p: 2.0,
680                i: 0.3,
681                d: 0.5,
682            },
683            max_integral: 5.0,
684            max_rate_radps: 3.0,
685        };
686
687        let mut controller = YawController::default();
688
689        let dt = 0.1; // 0.1 seconds
690
691        // Simulate a 90-degree turn
692        let desired_yaw = 90.0 * PI / 180.0;
693        let mut current_yaw = 0.0;
694        let mut rates = Vec::new();
695
696        // Simulate control loop for 2 seconds (20 iterations)
697        for _ in 0..20 {
698            let rate = controller.control(&config, dt, desired_yaw, current_yaw);
699            rates.push(rate);
700
701            // Simple integration to update current yaw for next iteration
702            current_yaw += rate * dt;
703
704            // Normalize to [-PI, PI] for realism
705            if current_yaw > PI {
706                current_yaw -= 2.0 * PI;
707            } else if current_yaw < -PI {
708                current_yaw += 2.0 * PI;
709            }
710        }
711
712        // Verify the controller converges to the desired yaw
713        assert!(
714            (desired_yaw - current_yaw).abs() < 0.1,
715            "Controller should converge to desired yaw (within 0.1 rad)"
716        );
717
718        // Verify that the final rate approaches zero as error decreases
719        assert!(
720            rates.last().unwrap().abs() < 0.2,
721            "Rate should approach zero as error decreases"
722        );
723
724        // Additional checks for controller behavior:
725
726        // Initial rates should be high (turning toward target)
727        assert!(
728            rates[0] > 1.0,
729            "Initial rate should be high when error is large"
730        );
731
732        // Rates should gradually decrease as we approach target
733        assert!(
734            rates[0] > rates[rates.len() / 2] && rates[rates.len() / 2] > rates[rates.len() - 1],
735            "Rates should decrease as controller approaches target"
736        );
737    }
738
739    #[test]
740    fn validate_rejects_negative_or_non_finite_limits() {
741        // (max_integral, max_rate_radps, offending field)
742        let cases = [(-1.0, 1.0, "max_integral"), (1.0, -1.0, "max_rate_radps")];
743        for (max_integral, max_rate_radps, field) in cases {
744            let config = YawControllerConfig {
745                max_integral,
746                max_rate_radps,
747                ..Default::default()
748            };
749            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
750        }
751    }
752
753    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
754    #[test]
755    fn invalid_limits_give_neutral_output_without_panicking() {
756        for bad in [-1.0, f32::NAN] {
757            let config = YawControllerConfig {
758                gains: Gains {
759                    p: 1.0,
760                    i: 1.0,
761                    d: 0.0,
762                },
763                max_integral: bad,
764                max_rate_radps: bad,
765            };
766            let mut controller = YawController::default();
767            assert_eq!(
768                controller.control(&config, 0.1, 1.0, 0.0),
769                0.0,
770                "limit {bad}"
771            );
772            assert_eq!(controller.integrated_error, 0.0, "limit {bad}");
773        }
774    }
775
776    /// A gain change between ticks applies on the next tick and keeps the integral.
777    #[test]
778    fn gain_change_between_ticks_keeps_state() {
779        let mut config = i_only_config(1.0, 10.0, 10.0);
780        let mut controller = YawController::default();
781        controller.control(&config, 1.0, 0.5, 0.0);
782        let integral = controller.integrated_error;
783
784        config.gains.i = 2.0;
785        let rate = controller.control(&config, 0.01, 0.0, 0.0);
786
787        assert_eq!(controller.integrated_error, integral);
788        assert_relative_eq!(rate, 2.0 * integral, epsilon = EPSILON);
789    }
790}