Skip to main content

sim_components/
fault.rs

1//! What trips a drive and how it stops then, as servo drives do it (Siemens SINAMICS names the parameters given here):
2//! each drive watches its following error against a window (p2546), its following error at standstill against a
3//! tighter one (p2542, after p2543), whether it is held at its torque limit at low speed for longer than a time (F07900
4//! "motor blocked", p2175 and p2177), and optionally its torque against the model's expected torque (as a robot
5//! controller detects a collision). The first monitor that trips a drive stops all of them, each by its own fault
6//! reaction (`Reaction`). On with effects.drive_monitoring; the controller runs it (`Controller::update`).
7
8use crate::drive::{Drive, DriveParams};
9use sim_core::{Config, ConfigError};
10
11type Result<T> = std::result::Result<T, ConfigError>;
12
13/// How a drive stops when the drives trip.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15pub enum Reaction {
16    /// OFF1: the speed setpoint ramps down on the ramp-function generator's ramp (p1121), the speed controller
17    /// following it; at standstill the pulses go off.
18    Off1,
19    /// OFF3: the same on the fast-stop ramp (p1135).
20    Off3,
21    /// STO (as OFF2): the pulses go off at once and the motor coasts.
22    Sto,
23    /// The speed setpoint drops to zero at once (OFF3 with a ramp time of 0): the speed controller brakes at the torque
24    /// limit, which the current limit sets.
25    CurrentLimit,
26}
27
28impl Reaction {
29    /// As `drive.fault_reaction` names it.
30    pub fn parse(name: &str) -> Option<Self> {
31        Some(match name {
32            "off1" => Self::Off1,
33            "off3" => Self::Off3,
34            "sto" => Self::Sto,
35            "current_limit" => Self::CurrentLimit,
36            _ => return None,
37        })
38    }
39
40    /// Translation key of a line telling how a drive (the argument) stops by it.
41    pub fn key(self) -> &'static str {
42        match self {
43            Self::Off1 => "reaction-off1",
44            Self::Off3 => "reaction-off3",
45            Self::Sto => "reaction-sto",
46            Self::CurrentLimit => "reaction-current-limit",
47        }
48    }
49}
50
51/// The monitor that tripped the drives.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
53pub enum Monitor {
54    FollowingError,
55    Standstill,
56    Blocked,
57    TorqueBand,
58}
59
60impl Monitor {
61    /// Translation key of its name.
62    pub fn key(self) -> &'static str {
63        match self {
64            Self::FollowingError => "monitor-following-error",
65            Self::Standstill => "monitor-standstill",
66            Self::Blocked => "monitor-blocked",
67            Self::TorqueBand => "monitor-torque-band",
68        }
69    }
70}
71
72/// One drive's fault reaction and monitoring, from `[drive]` (and its motor's `[drive.<id>]`). Angles and speeds at the
73/// motor, rad and rad/s (m and m/s for a linear motor).
74#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
75pub struct Settings {
76    pub reaction: Reaction,
77    /// The ramps' decelerations, rad/s^2: the rated speed over `drive.off1_ramp_s` and `off3_ramp_s`, the times from the
78    /// rated speed to standstill. The drive's p1121 and p1135 count from its maximum speed p1082 instead (S120 List
79    /// Manual p. 528, 530): p1121 = `off1_ramp_s` x p1082 / rated speed, as `sim-cli parameters` converts it.
80    pub off1_deceleration: f64,
81    pub off3_deceleration: f64,
82    /// Once its ramp is down, a drive takes its pulses off below this speed (p1226).
83    pub pulse_off_speed: f64,
84    pub following_window: f64,
85    pub standstill_window: f64,
86    pub standstill_time: f64,
87    pub blocked_speed: f64,
88    pub blocked_time: f64,
89    /// The band around the expected torque, as a share of the peak torque; 0: that monitor is off. The expected torque is
90    /// the feedforward (`Drive::torque_ff`) and, with `drive.torque_feedforward_model = "inertia"` (no gravity in it), the
91    /// torque that holds the planned pose (`Drive::torque_hold`), and the friction the machine's own model takes of the
92    /// motor's torque at its state (`motor.<id>.torque_friction`, given to `Watch::check`); where the machine does not
93    /// report that, the friction at the planned speed (the characteristic of the friction feedforward where the drive has
94    /// one, else `Machine::steady_friction`) in `Drive::torque_hold`. A held load and the friction are expected, a lasting
95    /// extra load is not.
96    pub torque_band: f64,
97}
98
99impl Settings {
100    /// From a motor's config (`catalog::motor_config`). A config without the keys (one written before 14 November
101    /// 2026) gets the values of the shipped configs.
102    pub fn from_config(cfg: &Config, p: &DriveParams) -> Result<Self> {
103        let value = |key: &str, default: f64| -> Result<f64> {
104            let path = format!("drive.{key}");
105            if cfg.get(&path).is_err() {
106                return Ok(default);
107            }
108            cfg.non_negative(&path)
109        };
110        let reaction = match cfg.get("drive.fault_reaction") {
111            Err(_) => Reaction::Off3,
112            Ok(v) => v
113                .as_str()
114                .and_then(Reaction::parse)
115                .ok_or_else(|| ConfigError::Invalid("drive.fault_reaction".into()))?,
116        };
117        let deceleration = |key: &str, default: f64| -> Result<f64> {
118            let ramp = value(key, default)?;
119            Ok(if ramp > 0.0 { p.rated_speed / ramp } else { f64::INFINITY })
120        };
121        Ok(Self {
122            reaction,
123            off1_deceleration: deceleration("off1_ramp_s", 1.0)?,
124            off3_deceleration: deceleration("off3_ramp_s", 0.1)?,
125            pulse_off_speed: value("pulse_off_speed_rad_s", 2.09)?,
126            following_window: value("following_error_window_rad", 1.0)?,
127            standstill_window: value("standstill_window_rad", 0.1)?,
128            standstill_time: value("standstill_time_s", 1.0)?,
129            blocked_speed: value("blocked_speed_rad_s", 12.57)?,
130            blocked_time: value("blocked_time_s", 3.0)?,
131            torque_band: value("torque_band", 0.0)?,
132        })
133    }
134
135    /// The deceleration of its stop ramp, rad/s^2: infinite at the current limit, `None` for STO (no ramp).
136    pub fn deceleration(&self) -> Option<f64> {
137        match self.reaction {
138            Reaction::Off1 => Some(self.off1_deceleration),
139            Reaction::Off3 => Some(self.off3_deceleration),
140            Reaction::CurrentLimit => Some(f64::INFINITY),
141            Reaction::Sto => None,
142        }
143    }
144}
145
146/// One drive's monitoring as it runs: how long its setpoint has stood still and how long it has been held at its
147/// torque limit at low speed.
148#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
149pub struct Watch {
150    still: f64,
151    blocked: f64,
152}
153
154impl Watch {
155    /// One base step of `dt` of the drive's monitoring, after its loops, its motor's peak torque `peak` and the friction
156    /// torque the machine's model takes of it now (`friction`, beside `Drive::torque_hold`): the monitor that trips it,
157    /// the first in the order of `Monitor`.
158    pub fn check(&mut self, s: &Settings, d: &Drive, friction: f64, peak: f64, dt: f64) -> Option<Monitor> {
159        let error = d.following_error.abs();
160        self.still = if d.vel_set == 0.0 && d.acc_set == 0.0 { self.still + dt } else { 0.0 };
161        self.blocked = if d.at_limit && d.measured_speed().abs() < s.blocked_speed { self.blocked + dt } else { 0.0 };
162        if error > s.following_window {
163            Some(Monitor::FollowingError)
164        } else if self.still >= s.standstill_time && error > s.standstill_window {
165            Some(Monitor::Standstill)
166        } else if self.blocked >= s.blocked_time {
167            Some(Monitor::Blocked)
168        } else if s.torque_band > 0.0
169            && (d.torque - d.torque_ff - d.torque_hold - friction).abs() > s.torque_band * peak
170        {
171            Some(Monitor::TorqueBand)
172        } else {
173            None
174        }
175    }
176}
177
178/// The first trip since the drives were last enabled: which monitor of which drive, when (s), and the tool pose then;
179/// how far each tool axis has gone since (the stopping distance, in the axis' unit, final once `stopped`); and when
180/// the machine stood (s): every drive off and every motor below its pulse-off speed.
181#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
182pub struct Fault {
183    pub monitor: Monitor,
184    pub drive: usize,
185    pub time: f64,
186    pub pose: Vec<f64>,
187    pub stopping: Vec<f64>,
188    pub stopped: Option<f64>,
189}
190
191/// A stop ramp's next speed setpoint after `dt`: from `speed` towards zero at `deceleration`, not beyond.
192pub fn ramp(speed: f64, deceleration: f64, dt: f64) -> f64 {
193    speed.signum() * (speed.abs() - deceleration * dt).max(0.0)
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    /// By hand: from 300 rad/s on a 0.1 s ramp from the rated speed of 314 rad/s (3140 rad/s^2), 0.01 s takes 31.4 rad/s
201    /// off; a ramp near its end stops at zero and does not swing through.
202    #[test]
203    fn a_stop_ramp_takes_the_deceleration_off_and_ends_at_zero() {
204        assert!((ramp(300.0, 314.0 / 0.1, 0.01) - 268.6).abs() < 1e-12);
205        assert!((ramp(-300.0, 3140.0, 0.01) + 268.6).abs() < 1e-12);
206        assert_eq!(ramp(10.0, 3140.0, 0.01), 0.0);
207        assert_eq!(ramp(10.0, f64::INFINITY, 0.01), 0.0);
208    }
209
210    fn settings() -> Settings {
211        Settings {
212            reaction: Reaction::Off3,
213            off1_deceleration: 314.0,
214            off3_deceleration: 3140.0,
215            pulse_off_speed: 2.09,
216            following_window: 1.0,
217            standstill_window: 0.1,
218            standstill_time: 1.0,
219            blocked_speed: 12.57,
220            blocked_time: 3.0,
221            torque_band: 0.0,
222        }
223    }
224
225    /// The number of steps of 1/1024 s (exact in binary, so that the times add up exactly) until `drive` trips, and on
226    /// what; `None` within 10 s.
227    fn steps_to_trip(s: &Settings, drive: &Drive) -> Option<(usize, Monitor)> {
228        let mut watch = Watch::default();
229        (1..=10_240).find_map(|k| watch.check(s, drive, 0.0, 3.8, 1.0 / 1024.0).map(|m| (k, m)))
230    }
231
232    /// By hand, in steps of 1/1024 s: a following error of 1.01 rad is beyond the 1 rad window at once. 0.2 rad, within it,
233    /// is beyond the standstill window of 0.1 rad once the setpoint has stood still 1 s, at the 1024th step (moving, it
234    /// never trips). A drive held at its torque limit at standstill (below 12.57 rad/s as measured) trips "blocked" after
235    /// 3 s, the 3072nd step. Torque 2.0 N m against an expected 0.5 N m is 1.5 N m
236    /// off: beyond a band of 0.3 times the peak torque 3.8 N m (1.14), within one of 0.4 (1.52).
237    #[test]
238    fn each_monitor_trips_at_its_hand_counted_step() {
239        let s = settings();
240        let drive = |f: &dyn Fn(&mut Drive)| {
241            let mut d = Drive::default();
242            f(&mut d);
243            d
244        };
245        assert_eq!(steps_to_trip(&s, &drive(&|d| d.following_error = -1.01)), Some((1, Monitor::FollowingError)));
246        assert_eq!(steps_to_trip(&s, &drive(&|d| d.following_error = 0.2)), Some((1024, Monitor::Standstill)));
247        let moving = drive(&|d| (d.following_error, d.vel_set) = (0.2, 1.0));
248        assert_eq!(steps_to_trip(&s, &moving), None);
249        assert_eq!(steps_to_trip(&s, &drive(&|d| d.at_limit = true)), Some((3072, Monitor::Blocked)));
250        let off = drive(&|d| (d.torque, d.torque_ff) = (2.0, 0.5));
251        assert_eq!(steps_to_trip(&Settings { torque_band: 0.3, ..settings() }, &off), Some((1, Monitor::TorqueBand)));
252        assert_eq!(steps_to_trip(&Settings { torque_band: 0.4, ..settings() }, &off), None);
253        // A held load with the constant-inertia feedforward (torque_ff 0): 2.0 N m is the weight the pose needs, so the
254        // band sees 2.0 - 0 - 2.0 = 0; with 3.5 N m it sees 1.5 N m as above: 1.14 trips, 1.52 does not.
255        let held = |torque: f64| drive(&|d| (d.torque, d.torque_ff, d.torque_hold) = (torque, 0.0, 2.0));
256        let band = Settings { torque_band: 0.3, ..settings() };
257        assert_eq!(steps_to_trip(&band, &held(2.0)), None);
258        assert_eq!(steps_to_trip(&band, &held(3.5)), Some((1, Monitor::TorqueBand)));
259        assert_eq!(steps_to_trip(&Settings { torque_band: 0.4, ..settings() }, &held(3.5)), None);
260    }
261}