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        assert_dt(dt);
133
134        let gains = &config.gains;
135
136        let error = angle_diff(desired_yaw_rad, estimated_yaw_rad); // Use a helper to handle angle wrapping
137        if !error.is_finite() {
138            // Hold (no yaw rate) rather than letting NaN into the integral and derivative
139            // history, where it would stick; clamping passes NaN through. Forget the previous
140            // error too, so the first valid tick after the gap has no derivative kick.
141            self.derivative.forget();
142            return 0.0;
143        }
144        let error_derivative = self.derivative.step(error, dt);
145
146        self.integrated_error =
147            clamp_symmetric(self.integrated_error + dt * error, config.max_integral);
148
149        let yaw_rate =
150            gains.p * error + gains.i * self.integrated_error + gains.d * error_derivative;
151
152        clamp_symmetric(yaw_rate, config.max_rate_radps)
153    }
154
155    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
156    /// tick's I term picks up where the last left off (`rescale_integral`).
157    pub(crate) fn rescale_integral(
158        &mut self,
159        old: &YawControllerConfig,
160        new: &YawControllerConfig,
161    ) {
162        self.integrated_error = rescale_integral(self.integrated_error, old.gains.i, new.gains.i);
163    }
164}
165
166/// The shortest-path yaw error from `current_yaw` to `desired_yaw`, in [-π, π).
167///
168/// # Arguments
169///
170/// * `desired_yaw` - Desired yaw angle in radians.
171/// * `current_yaw` - Current yaw angle in radians.
172///
173/// # Returns
174///
175/// The shortest-path yaw error in radians, in [-π, π) (see [`wrap_angle`]).
176fn angle_diff(desired_yaw: f32, current_yaw: f32) -> f32 {
177    wrap_angle(desired_yaw - current_yaw)
178}
179
180#[cfg(test)]
181mod tests {
182
183    use std::f32::consts::PI;
184
185    use approx::assert_relative_eq;
186
187    use crate::controllers::Gains;
188
189    use super::*;
190
191    const EPSILON: f32 = 1e-5;
192
193    // Helper functions for test setup
194
195    /// A config with only proportional gain.
196    fn p_only_config(p_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
197        YawControllerConfig {
198            gains: Gains {
199                p: p_gain,
200                i: 0.0,
201                d: 0.0,
202            },
203            max_integral: 10.0,
204            max_rate_radps,
205        }
206    }
207
208    /// A config with only integral gain.
209    fn i_only_config(i_gain: f32, max_integral: f32, max_rate_radps: f32) -> YawControllerConfig {
210        YawControllerConfig {
211            gains: Gains {
212                p: 0.0,
213                i: i_gain,
214                d: 0.0,
215            },
216            max_integral,
217            max_rate_radps,
218        }
219    }
220
221    /// A config with only derivative gain.
222    fn d_only_config(d_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
223        YawControllerConfig {
224            gains: Gains {
225                p: 0.0,
226                i: 0.0,
227                d: d_gain,
228            },
229            max_integral: 10.0,
230            max_rate_radps,
231        }
232    }
233
234    /// Tests that the default controller configuration has expected values.
235    #[test]
236    fn test_default_config() {
237        let config = YawControllerConfig::default();
238
239        assert_relative_eq!(config.gains.p, 2.5, epsilon = EPSILON, max_relative = 1e-3);
240        assert_relative_eq!(config.gains.i, 0.0, epsilon = EPSILON, max_relative = 1e-3);
241        assert_relative_eq!(config.gains.d, 0.06, epsilon = EPSILON, max_relative = 1e-3);
242        assert_relative_eq!(
243            config.max_integral,
244            100.0,
245            epsilon = EPSILON,
246            max_relative = 1e-3
247        );
248        assert_relative_eq!(
249            config.max_rate_radps,
250            2.0,
251            epsilon = EPSILON,
252            max_relative = 1e-3
253        );
254    }
255
256    #[test]
257    fn default_is_zeroed_state() {
258        assert_eq!(
259            YawController::default(),
260            YawController {
261                derivative: DerivativeState::default(),
262                integrated_error: 0.0,
263            }
264        );
265    }
266
267    /// Tests that the proportional control term works correctly in isolation.
268    #[test]
269    fn test_proportional_control() {
270        // Test that the proportional term works correctly
271        let config = p_only_config(2.0, 5.0);
272        let mut controller = YawController::default();
273
274        // Simple case: 0.5 rad error should result in rate = 2.0 * 0.5 = 1.0 rad/s
275        let dt = 0.01;
276        let desired_yaw = 0.5;
277        let estimated_yaw = 0.0;
278
279        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
280        assert_relative_eq!(
281            rate,
282            1.0,
283            epsilon = EPSILON,
284            max_relative = 1e-3,
285            max_relative = 1e-3
286        );
287
288        // Test with negative error
289        let rate = controller.control(&config, dt, 0.0, 0.5);
290        assert_relative_eq!(rate, -1.0, epsilon = EPSILON, max_relative = 1e-3);
291    }
292
293    /// Tests that the integral control term accumulates correctly and respects limits.
294    #[test]
295    fn test_integral_control() {
296        // Test that the integral term accumulates and affects output
297        let config = i_only_config(1.0, 10.0, 5.0);
298        let mut controller = YawController::default();
299
300        // Apply constant error for several iterations
301        let dt = 1.0; // 1 second for easy calculation
302        let desired_yaw = 0.5;
303        let estimated_yaw = 0.0;
304
305        // First iteration: integral = 0.5 * 1.0 = 0.5
306        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
307        assert_relative_eq!(rate, 0.5, epsilon = EPSILON, max_relative = 1e-3);
308
309        // Second iteration: integral = 0.5 + 0.5 * 1.0 = 1.0
310        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
311        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
312
313        // Test integral clamping
314        let config = i_only_config(1.0, 1.5, 5.0);
315        let mut controller = YawController::default();
316
317        // Accumulate for 3 seconds to exceed max_integral
318        controller.control(&config, dt, desired_yaw, estimated_yaw); // 0.5
319        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.0
320        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.5
321        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
322
323        // Should be clamped at max_integral * i_gain = 1.5
324        assert_relative_eq!(rate, 1.5, epsilon = EPSILON, max_relative = 1e-3);
325    }
326
327    /// Tests that the derivative control term responds correctly to error changes.
328    #[test]
329    fn test_derivative_control() {
330        // Test that the derivative term works correctly
331        let config = d_only_config(2.0, 5.0);
332        let mut controller = YawController::default();
333
334        let dt = 1.0; // 1 second for easy calculation
335
336        // First call - establishes baseline error
337        let rate = controller.control(&config, dt, 0.5, 0.0);
338        assert_relative_eq!(
339            rate,
340            0.0,
341            epsilon = EPSILON,
342            max_relative = 1e-3,
343            max_relative = 1e-3
344        );
345
346        // Second call - error unchanged, derivative should be zero
347        let rate = controller.control(&config, dt, 0.5, 0.0);
348        assert_relative_eq!(rate, 0.0, epsilon = EPSILON, max_relative = 1e-3);
349
350        // Error increasing by 0.1 rad/s
351        let rate = controller.control(&config, dt, 0.6, 0.0);
352        assert_relative_eq!(rate, 0.2, epsilon = EPSILON, max_relative = 1e-3);
353
354        // Error decreasing by 0.2 rad/s
355        let rate = controller.control(&config, dt, 0.4, 0.0);
356        assert_relative_eq!(rate, -0.4, epsilon = EPSILON, max_relative = 1e-3);
357    }
358
359    /// Tests all PID components working together with detailed calculation.
360    #[test]
361    fn test_pid_combined() {
362        // Test all PID components working together
363        let config = YawControllerConfig {
364            gains: Gains {
365                p: 1.0,
366                i: 0.5,
367                d: 0.2,
368            },
369            max_integral: 10.0,
370            max_rate_radps: 5.0,
371        };
372
373        let mut controller = YawController::default();
374
375        let dt = 1.0;
376
377        // First call:
378        // - P term = 1.0 * 0.5 = 0.5
379        // - I term = 0.5 * (0.5 * 1.0) = 0.25
380        // - D term = 0 (no previous error)
381        // Total = 0.5 + 0.25 + 0 = 0.75
382        let rate = controller.control(&config, dt, 0.5, 0.0);
383        assert_relative_eq!(rate, 0.75, epsilon = EPSILON, max_relative = 1e-3);
384
385        // Second call with same error:
386        // - P term = 1.0 * 0.5 = 0.5
387        // - I term = 0.5 * (0.5 + 0.5) = 0.5
388        // - D term = 0.2 * (0.5 - 0.5) / 1.0 = 0
389        // Total = 0.5 + 0.5 + 0 = 1.0
390        let rate = controller.control(&config, dt, 0.5, 0.0);
391        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
392
393        // Third call with increased error:
394        // - P term = 1.0 * 0.6 = 0.6
395        // - I term = 0.5 * (0.5 + 0.5 + 0.6) = 0.8
396        // - D term = 0.2 * (0.6 - 0.5) / 1.0 = 0.02
397        // Total = 0.6 + 0.8 + 0.02 = 1.42
398        let rate = controller.control(&config, dt, 0.6, 0.0);
399        assert_relative_eq!(rate, 1.42, epsilon = EPSILON, max_relative = 1e-3);
400    }
401
402    /// Tests that the controller handles varying time steps correctly.
403    #[test]
404    fn test_varying_time_steps() {
405        let config = YawControllerConfig {
406            gains: Gains {
407                p: 0.0,
408                i: 1.0,
409                d: 0.0,
410            },
411            max_integral: 10.0,
412            max_rate_radps: 5.0,
413        };
414
415        let mut controller = YawController::default();
416
417        // Control with a 1-second time step
418        let rate_1s = controller.control(&config, 1.0, 0.5, 0.0);
419        assert_relative_eq!(rate_1s, 0.5, epsilon = EPSILON, max_relative = 1e-3);
420
421        // Next control with a 0.5-second time step should accumulate half as much
422        let rate_05s = controller.control(&config, 0.5, 0.5, 0.0);
423        assert_relative_eq!(
424            rate_05s,
425            0.5 + 0.25, // Previous 0.5 plus new 0.5*0.5
426            epsilon = EPSILON,
427            max_relative = 1e-3
428        );
429
430        // Next control with a 0.25-second time step
431        let rate_025s = controller.control(&config, 0.25, 0.5, 0.0);
432        assert_relative_eq!(
433            rate_025s,
434            0.5 + 0.25 + 0.125, // Plus new 0.5*0.25
435            epsilon = EPSILON,
436            max_relative = 1e-3
437        );
438    }
439
440    /// Tests controller behavior with very small time steps.
441    #[test]
442    fn test_small_time_steps() {
443        let config = YawControllerConfig {
444            gains: Gains {
445                p: 1.0,
446                i: 1.0,
447                d: 1.0,
448            },
449            max_integral: 10.0,
450            max_rate_radps: 5.0,
451        };
452
453        let mut controller = YawController::default();
454
455        // Use a very small time step
456        let dt = 0.000001; // 1 microsecond
457        let error = 0.5;
458        let rate = controller.control(&config, dt, error, 0.0);
459
460        // With a tiny dt:
461        // - P term = 1.0 * 0.5 = 0.5
462        // - I term = 1.0 * 0.5 * 1e-6 ≈ 0.0000005 (effectively 0)
463        // - D term = undefined (first call)
464        assert_relative_eq!(
465            rate,
466            0.5, // Only P term is significant
467            epsilon = EPSILON,
468            max_relative = 1e-3
469        );
470
471        // Second call with same error should still have negligible I term
472        let rate = controller.control(&config, dt, error, 0.0);
473        assert_relative_eq!(
474            rate,
475            0.5, // P term only, I term still tiny
476            epsilon = EPSILON,
477            max_relative = 1e-3
478        );
479    }
480
481    /// Tests that angle wrapping is handled correctly at ±π boundaries.
482    #[test]
483    fn test_angle_wrapping() {
484        // Test angle wrapping when crossing the ±π boundary
485        let config = p_only_config(1.0, 5.0);
486        let mut controller = YawController::default();
487
488        let dt = 0.01;
489
490        // Test case: desired = 175°, current = -175°
491        // Shortest path is -10° (not +350°)
492        let desired_yaw = 175.0 * PI / 180.0;
493        let estimated_yaw = -175.0 * PI / 180.0;
494
495        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
496        let expected_rate = -10.0 * PI / 180.0; // -10 degrees converted to radians
497        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
498
499        // Test case: desired = -175°, current = 175°
500        // Shortest path is +10° (not -350°)
501        let desired_yaw = -175.0 * PI / 180.0;
502        let estimated_yaw = 175.0 * PI / 180.0;
503
504        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
505        let expected_rate = 10.0 * PI / 180.0; // 10 degrees converted to radians
506        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
507    }
508
509    /// Directly tests the angle_diff helper function with various inputs.
510    #[test]
511    fn angle_diff_is_the_shortest_signed_path() {
512        let deg = PI / 180.0;
513        // (desired, current, expected error)
514        let cases = [
515            (0.5, 0.0, 0.5),                        // no wrapping needed
516            (PI + 0.1, -PI - 0.1, 0.2),             // wraps across ±π
517            (350.0 * deg, 10.0 * deg, -20.0 * deg), // turn left through north
518            (10.0 * deg, 350.0 * deg, 20.0 * deg),  // turn right through north
519            (PI, -PI, 0.0),                         // same heading
520            (0.0, 2.0 * PI, 0.0),                   // same heading, one turn apart
521            (5.0, 5.0 - 2.0 * PI, 0.0),             // [0, 2π) heading vs its [-π, π) form
522        ];
523        for (desired, current, expected) in cases {
524            assert_relative_eq!(
525                angle_diff(desired, current),
526                expected,
527                epsilon = EPSILON,
528                max_relative = 1e-3
529            );
530        }
531    }
532
533    #[test]
534    fn test_valid_inputs() {
535        let config = YawControllerConfig::default();
536        let mut controller = YawController::default();
537        let dt = 0.01;
538
539        // Valid inputs should not panic
540        let _ = controller.control(&config, dt, 0.0, 0.0);
541        let _ = controller.control(&config, dt, PI, -PI);
542        let _ = controller.control(&config, dt, 2.0 * PI, 0.0);
543    }
544
545    #[test]
546    #[should_panic(expected = "dt must be positive and finite")]
547    fn zero_dt_panics() {
548        let config = YawControllerConfig::default();
549        let mut controller = YawController::default();
550        let dt = 0.0;
551        let _ = controller.control(&config, dt, 0.0, 0.0);
552    }
553
554    #[test]
555    fn any_finite_target_is_equivalent_to_its_wrapped_heading() {
556        // (target, equivalent target within [-π, π))
557        let cases = [
558            (3.0 * PI, -PI),
559            (10.0 * PI + 0.5, 0.5),
560            (-7.0 * PI / 2.0, PI / 2.0),
561            (1000.0, wrap_angle(1000.0)),
562        ];
563        let config = YawControllerConfig::default();
564        for (target, equivalent) in cases {
565            let rate = YawController::default().control(&config, 0.01, target, 0.2);
566            let expected = YawController::default().control(&config, 0.01, equivalent, 0.2);
567            assert_relative_eq!(rate, expected, epsilon = 1e-3);
568        }
569    }
570
571    #[test]
572    fn non_finite_target_holds_and_does_not_poison_later_ticks() {
573        let config = YawControllerConfig::default();
574        let mut controller = YawController::default();
575        for target in [f32::NAN, f32::INFINITY] {
576            assert!(controller.control(&config, 0.01, target, 0.2) == 0.0);
577        }
578        let after = controller.control(&config, 0.01, 1.0, 0.2);
579        let fresh = YawController::default().control(&config, 0.01, 1.0, 0.2);
580        assert_relative_eq!(after, fresh);
581    }
582
583    #[test]
584    fn nan_gap_does_not_cause_a_derivative_kick() {
585        // P+D only, so the only difference a stale previous error could make is the D term.
586        let config = YawControllerConfig {
587            gains: Gains {
588                p: 1.0,
589                i: 0.0,
590                d: 0.5,
591            },
592            max_integral: 1.0,
593            max_rate_radps: 100.0,
594        };
595        let mut controller = YawController::default();
596
597        controller.control(&config, 0.01, 1.0, 0.2); // error 0.8 becomes the previous error
598        controller.control(&config, 0.01, f32::NAN, 0.2); // gap
599        let after_gap = controller.control(&config, 0.01, 0.5, 0.2); // error 0.3
600
601        // Without the reset, D would add 0.5 * (0.3 - 0.8) / 0.01 = -25 rad/s.
602        let fresh = YawController::default().control(&config, 0.01, 0.5, 0.2);
603        assert_relative_eq!(after_gap, fresh);
604    }
605
606    /// Tests that output rate is properly limited to `max_rate_radps`.
607    #[test]
608    fn test_max_rate_limiting() {
609        // Test that output is clamped to max_rate_radps
610        let config = p_only_config(10.0, 2.0);
611        let mut controller = YawController::default();
612
613        let dt = 0.01;
614
615        // Error of 0.5 rad with P=10 would give 5.0 rad/s
616        // Should be limited to 2.0 rad/s
617        let rate = controller.control(&config, dt, 0.5, 0.0);
618
619        assert_relative_eq!(rate, 2.0, epsilon = EPSILON, max_relative = 1e-3);
620
621        // Test negative limiting too
622        let rate = controller.control(&config, dt, -0.5, 0.0);
623        assert_relative_eq!(rate, -2.0, epsilon = EPSILON, max_relative = 1e-3);
624    }
625
626    /// Tests a realistic maneuver to verify controller convergence and stability.
627    #[test]
628    fn test_realistic_maneuvers() {
629        // Test a realistic 90-degree turn maneuver
630        let config = YawControllerConfig {
631            gains: Gains {
632                p: 2.0,
633                i: 0.3,
634                d: 0.5,
635            },
636            max_integral: 5.0,
637            max_rate_radps: 3.0,
638        };
639
640        let mut controller = YawController::default();
641
642        let dt = 0.1; // 0.1 seconds
643
644        // Simulate a 90-degree turn
645        let desired_yaw = 90.0 * PI / 180.0;
646        let mut current_yaw = 0.0;
647        let mut rates = Vec::new();
648
649        // Simulate control loop for 2 seconds (20 iterations)
650        for _ in 0..20 {
651            let rate = controller.control(&config, dt, desired_yaw, current_yaw);
652            rates.push(rate);
653
654            // Simple integration to update current yaw for next iteration
655            current_yaw += rate * dt;
656
657            // Normalize to [-PI, PI] for realism
658            if current_yaw > PI {
659                current_yaw -= 2.0 * PI;
660            } else if current_yaw < -PI {
661                current_yaw += 2.0 * PI;
662            }
663        }
664
665        // Verify the controller converges to the desired yaw
666        assert!(
667            (desired_yaw - current_yaw).abs() < 0.1,
668            "Controller should converge to desired yaw (within 0.1 rad)"
669        );
670
671        // Verify that the final rate approaches zero as error decreases
672        assert!(
673            rates.last().unwrap().abs() < 0.2,
674            "Rate should approach zero as error decreases"
675        );
676
677        // Additional checks for controller behavior:
678
679        // Initial rates should be high (turning toward target)
680        assert!(
681            rates[0] > 1.0,
682            "Initial rate should be high when error is large"
683        );
684
685        // Rates should gradually decrease as we approach target
686        assert!(
687            rates[0] > rates[rates.len() / 2] && rates[rates.len() / 2] > rates[rates.len() - 1],
688            "Rates should decrease as controller approaches target"
689        );
690    }
691
692    #[test]
693    fn validate_rejects_negative_or_non_finite_limits() {
694        // (max_integral, max_rate_radps, offending field)
695        let cases = [(-1.0, 1.0, "max_integral"), (1.0, -1.0, "max_rate_radps")];
696        for (max_integral, max_rate_radps, field) in cases {
697            let config = YawControllerConfig {
698                max_integral,
699                max_rate_radps,
700                ..Default::default()
701            };
702            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
703        }
704    }
705
706    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
707    #[test]
708    fn invalid_limits_give_neutral_output_without_panicking() {
709        for bad in [-1.0, f32::NAN] {
710            let config = YawControllerConfig {
711                gains: Gains {
712                    p: 1.0,
713                    i: 1.0,
714                    d: 0.0,
715                },
716                max_integral: bad,
717                max_rate_radps: bad,
718            };
719            let mut controller = YawController::default();
720            assert_eq!(
721                controller.control(&config, 0.1, 1.0, 0.0),
722                0.0,
723                "limit {bad}"
724            );
725            assert_eq!(controller.integrated_error, 0.0, "limit {bad}");
726        }
727    }
728
729    /// A gain change between ticks applies on the next tick and keeps the integral.
730    #[test]
731    fn gain_change_between_ticks_keeps_state() {
732        let mut config = i_only_config(1.0, 10.0, 10.0);
733        let mut controller = YawController::default();
734        controller.control(&config, 1.0, 0.5, 0.0);
735        let integral = controller.integrated_error;
736
737        config.gains.i = 2.0;
738        let rate = controller.control(&config, 0.01, 0.0, 0.0);
739
740        assert_eq!(controller.integrated_error, integral);
741        assert_relative_eq!(rate, 2.0 * integral, epsilon = EPSILON);
742    }
743}