1use crate::drive::{Drive, DriveParams};
9use sim_core::{Config, ConfigError};
10
11type Result<T> = std::result::Result<T, ConfigError>;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15pub enum Reaction {
16 Off1,
19 Off3,
21 Sto,
23 CurrentLimit,
26}
27
28impl Reaction {
29 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 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#[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 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#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
75pub struct Settings {
76 pub reaction: Reaction,
77 pub off1_deceleration: f64,
81 pub off3_deceleration: f64,
82 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 pub torque_band: f64,
97}
98
99impl Settings {
100 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 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#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
149pub struct Watch {
150 still: f64,
151 blocked: f64,
152}
153
154impl Watch {
155 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#[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
191pub 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 #[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 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 #[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 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}