1use crate::catalog::{motor_config, resolve, rows, table};
11use sim_core::{Config, ConfigError, MachineEntry};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Family {
16 S120,
18 S210,
20}
21
22impl Family {
23 pub fn parse(text: &str) -> Option<Self> {
25 match text {
26 "s120" => Some(Self::S120),
27 "s210" => Some(Self::S210),
28 _ => None,
29 }
30 }
31
32 pub fn name(self) -> &'static str {
33 match self {
34 Self::S120 => "s120",
35 Self::S210 => "s210",
36 }
37 }
38
39 fn mapping(self) -> &'static str {
40 table(match self {
41 Self::S120 => "siemens/parameters_s120.csv",
42 Self::S210 => "siemens/parameters_s210.csv",
43 })
44 }
45
46 pub fn of_article(article: &str) -> Option<Self> {
49 let article_in = |file: &'static str| rows(table(file)).into_iter().find(|r| r["part_number"] == article);
50 if article_in("siemens/converters_s210.csv").is_some_and(|r| r["series"] == "S210") {
51 Some(Self::S210)
52 } else if article_in("siemens/motor_modules_s120.csv").is_some() {
53 Some(Self::S120)
54 } else {
55 None
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum Basis {
63 Printed,
65 Derived,
67 None,
69}
70
71impl Basis {
72 pub fn name(self) -> &'static str {
73 match self {
74 Self::Printed => "printed",
75 Self::Derived => "derived",
76 Self::None => "none",
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq)]
83pub struct Row {
84 pub motor: String,
85 pub key: &'static str,
87 pub value: f64,
88 pub unit: &'static str,
89 pub parameter: String,
91 pub name: String,
92 pub parameter_value: Option<f64>,
93 pub parameter_unit: String,
94 pub basis: Basis,
95}
96
97#[derive(Debug, Clone, PartialEq)]
99pub enum Error {
100 Config(ConfigError),
101 NoDrive(String),
103 UnknownDrive(String),
105 NotRotaryServo(String),
107}
108
109impl From<ConfigError> for Error {
110 fn from(e: ConfigError) -> Self {
111 Self::Config(e)
112 }
113}
114
115pub const SETTINGS: &[(&str, &str, &str)] = &[
119 ("kv_1_s", "1/s", ""),
120 ("velocity_kp_nm_s_rad", "N m s/rad", ""),
121 ("velocity_tn_s", "s", ""),
122 ("velocity_feedforward_factor", "factor", "velocity_feedforward"),
123 ("torque_feedforward_factor", "factor", "torque_feedforward"),
124 ("precontrol_balance_s", "s", ""),
125 ("current_kp_v_a", "V/A", ""),
126 ("current_tn_s", "s", ""),
127 ("peak_torque_nm", "N m", ""),
128 ("max_speed_rad_s", "rad/s", ""),
129 ("velocity_filter_s", "s", "velocity_filter"),
130 ("torque_filter_s", "s", "torque_filter"),
131 ("notch_frequency_hz", "Hz", "notch_filter"),
132 ("notch_bandwidth_hz", "Hz", "notch_filter"),
133 ("off1_ramp_s", "s", "drive_monitoring"),
134 ("off3_ramp_s", "s", "drive_monitoring"),
135 ("pulse_off_speed_rad_s", "rad/s", "drive_monitoring"),
136 ("following_error_window_rad", "rad", "drive_monitoring"),
137 ("standstill_window_rad", "rad", "drive_monitoring"),
138 ("standstill_time_s", "s", "drive_monitoring"),
139 ("blocked_speed_rad_s", "rad/s", "drive_monitoring"),
140 ("blocked_time_s", "s", "drive_monitoring"),
141 ("ss1_time_s", "s", "drive_monitoring"),
142];
143
144fn drive_article<'a>(cfg: &'a Config, id: &str) -> &'a str {
146 let text = |path: String| cfg.get(&path).ok().and_then(|v| v.as_str());
147 text(format!("parts.{id}.drive")).or_else(|| text("parts.drive".into())).unwrap_or("")
148}
149
150pub fn list(entry: &MachineEntry, cfg: &Config, family: Option<Family>) -> Result<Vec<Row>, Error> {
153 list_resolved(entry, cfg, &resolve(entry, cfg)?, family)
154}
155
156pub fn list_resolved(
159 entry: &MachineEntry,
160 cfg: &Config,
161 resolved: &Config,
162 family: Option<Family>,
163) -> Result<Vec<Row>, Error> {
164 let machine = (entry.build)(resolved)?;
165 let mut out = Vec::new();
166 for (index, motor) in machine.motors().iter().enumerate() {
167 let own = motor_config(resolved, motor.id)?;
168 let servo = own.get("motor.kind").ok().and_then(|v| v.as_str()).is_none_or(|k| k == "servo");
169 if machine.motor_linear(index) || !servo {
170 return Err(Error::NotRotaryServo(motor.id.into()));
171 }
172 let article = drive_article(cfg, motor.id);
173 let family = match (family, article) {
174 (Some(family), _) => family,
175 (None, "") => return Err(Error::NoDrive(motor.id.into())),
176 (None, article) => Family::of_article(article).ok_or_else(|| Error::UnknownDrive(article.into()))?,
177 };
178 let mapping = rows(family.mapping());
179 for &(key, unit, effect) in SETTINGS {
180 let Ok(value) = own.f64(&format!("drive.{key}")) else { continue };
181 if !effect.is_empty() && !own.bool(&format!("effects.{effect}")).unwrap_or(false) {
182 continue;
183 }
184 if effect == "notch_filter" && own.f64("drive.notch_frequency_hz") == Ok(0.0) {
186 continue;
187 }
188 let found: Vec<_> = mapping.iter().filter(|r| r["config_key"] == key).collect();
189 let row = |parameter: &str, name: &str, converted, parameter_unit: &str, basis| Row {
190 motor: motor.id.into(),
191 key,
192 value,
193 unit,
194 parameter: parameter.into(),
195 name: name.into(),
196 parameter_value: converted,
197 parameter_unit: parameter_unit.into(),
198 basis,
199 };
200 if found.is_empty() {
201 out.push(row("", "", None, "", Basis::None));
202 }
203 for r in found {
204 let basis = if r["basis"] == "printed" { Basis::Printed } else { Basis::Derived };
205 out.push(row(r["parameter"], r["name"], Some(convert(r, &own, value)?), r["unit"], basis));
206 }
207 }
208 }
209 Ok(out)
210}
211
212fn convert(r: &crate::catalog::Row, own: &Config, value: f64) -> Result<f64, ConfigError> {
214 let factor: f64 =
215 r["factor"].parse().map_err(|_| ConfigError::Invalid(format!("parameters: factor {}", r["factor"])))?;
216 Ok(match r["rule"] {
217 "" => factor * value,
218 "constant" => factor,
219 "zero" => 0.0,
220 "notch_damping" => factor * value / (2.0 * own.positive("drive.notch_frequency_hz")?),
221 "ramp_time" => {
222 let max = own.positive("drive.max_speed_rad_s").or_else(|_| own.positive("drive.no_load_speed_rad_s"))?;
225 factor * value * max / own.positive("drive.rated_speed_rad_s")?
226 }
227 other => return Err(ConfigError::Invalid(format!("parameters: rule {other}"))),
228 })
229}