1pub mod api;
54pub mod api3;
55
56use sim_components::{Sim, load_config};
57use sim_core::{Config, ConfigError, MachineEntry, Translations};
58use std::fmt::Write;
59
60pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
62
63pub const MODEL_IDENTIFIER: &str = "sim_fmi";
65
66pub const LOG_CATEGORIES: [(&str, &str); 4] = [
69 ("logEvents", "fmi-log-events"),
70 ("logStatusWarning", "fmi-log-warning"),
71 ("logStatusError", "fmi-log-error"),
72 ("logAll", "fmi-log-all"),
73];
74
75#[derive(Debug, Clone, PartialEq)]
77pub enum Kind {
78 Signal(usize),
80 Setpoint(usize),
82 Enable,
83 Cycle,
85 Target(usize),
87 Move,
88 PathText,
91 PathFile,
92 TrajectoryFile,
95 RunPath,
96 TimeOptimal,
98 Machine,
99 ConfigFile,
100 Effect(String),
102 DriveMode(usize),
105 Torque(usize),
106 Velocity(usize),
107 StopCategory,
110}
111
112#[derive(Debug, Clone, PartialEq)]
113pub struct Variable {
114 pub name: String,
115 pub kind: Kind,
116 pub description: String,
117 pub unit: String,
118 pub start: Option<String>,
120}
121
122impl Variable {
123 pub fn causality(&self) -> &'static str {
124 match self.kind {
125 Kind::Signal(0) => "independent",
126 Kind::Signal(_) => "output",
127 Kind::Setpoint(_)
128 | Kind::Enable
129 | Kind::Cycle
130 | Kind::Target(_)
131 | Kind::Move
132 | Kind::PathText
133 | Kind::PathFile
134 | Kind::TrajectoryFile
135 | Kind::RunPath
136 | Kind::DriveMode(_)
137 | Kind::Torque(_)
138 | Kind::Velocity(_)
139 | Kind::StopCategory => "input",
140 Kind::Machine | Kind::ConfigFile | Kind::TimeOptimal | Kind::Effect(_) => "parameter",
141 }
142 }
143 pub fn type_name(&self) -> &'static str {
144 match self.kind {
145 Kind::Signal(_) | Kind::Setpoint(_) | Kind::Target(_) | Kind::Torque(_) | Kind::Velocity(_) => "Real",
146 Kind::Enable | Kind::Cycle | Kind::Move | Kind::RunPath | Kind::TimeOptimal | Kind::Effect(_) => "Boolean",
147 Kind::Machine
148 | Kind::ConfigFile
149 | Kind::PathText
150 | Kind::PathFile
151 | Kind::TrajectoryFile
152 | Kind::DriveMode(_)
153 | Kind::StopCategory => "String",
154 }
155 }
156}
157
158pub fn texts(lang: &str, entry: &MachineEntry) -> Translations {
160 let mut tr = sim_machines::translations(lang, entry);
161 I18N.iter().filter(|(l, _)| *l == lang).for_each(|(_, text)| tr.add(text));
162 tr
163}
164
165pub struct Model {
167 pub entry: &'static MachineEntry,
168 pub config_text: String,
169 pub lang: String,
170 pub variables: Vec<Variable>,
171 pub guid: String,
173 pub xml: String,
174 pub fmi: u8,
176}
177
178impl Model {
179 pub fn new(entry: &'static MachineEntry, config_text: &str, lang: &str) -> Result<Self, ConfigError> {
181 Self::with_fmi(entry, config_text, lang, 2)
182 }
183
184 pub fn with_fmi(entry: &'static MachineEntry, config_text: &str, lang: &str, fmi: u8) -> Result<Self, ConfigError> {
186 let fmi = if fmi == 3 { 3 } else { 2 };
187 let cfg = load_config(entry, config_text)?;
188 let sim = Sim::new(entry, &cfg)?;
189 let tr = texts(lang, entry);
190 let variables = variables(entry.id, &sim, &cfg, &tr);
191 let unsigned = description(entry, &cfg, &tr, &variables, "", fmi, sim.dt)?;
192 let guid = guid(&unsigned);
193 let xml = description(entry, &cfg, &tr, &variables, &guid, fmi, sim.dt)?;
194 Ok(Self { entry, config_text: config_text.into(), lang: lang.into(), variables, guid, xml, fmi })
195 }
196
197 pub fn files(&self) -> Vec<(String, Vec<u8>)> {
199 let mut out = vec![
200 ("modelDescription.xml".into(), self.xml.clone().into_bytes()),
201 ("resources/model.txt".into(), format!("{}\n{}\n", self.entry.id, self.lang).into_bytes()),
202 ("resources/config.toml".into(), self.config_text.clone().into_bytes()),
203 ];
204 if !is_registered(self.entry) {
205 out.push(("resources/machine.toml".into(), self.entry.default_config.as_bytes().to_vec()));
206 }
207 out
208 }
209}
210
211pub fn is_registered(entry: &MachineEntry) -> bool {
213 sim_machines::find(entry.id).is_some_and(|known| std::ptr::eq(known, entry))
214}
215
216pub fn machine_of(resources: &std::path::Path, id: &str) -> Result<&'static MachineEntry, ConfigError> {
219 match std::fs::read_to_string(resources.join("machine.toml")) {
220 Ok(text) => sim_machines::load_text(&text, id),
221 Err(_) => sim_machines::find(id).ok_or_else(|| ConfigError::Missing(id.into())),
222 }
223}
224
225fn variables(machine: &str, sim: &Sim, cfg: &Config, tr: &Translations) -> Vec<Variable> {
226 let infos = sim.signal_infos();
227 let mut out: Vec<Variable> = infos
228 .iter()
229 .cloned()
230 .enumerate()
231 .map(|(i, s)| Variable {
232 description: format!("{} · {}", tr.tr(&s.owner_key), tr.tr(&s.quantity_key)),
233 name: s.id,
234 kind: Kind::Signal(i),
235 unit: s.unit,
236 start: None,
237 })
238 .collect();
239 for (i, axis) in sim.machine.axes().iter().enumerate() {
240 let description = format!("{} · {}", tr.tr(axis.key), tr.tr("fmi-setpoint"));
241 out.push(Variable {
242 name: format!("command.setpoint.{}", axis.id),
243 kind: Kind::Setpoint(i),
244 description,
245 unit: axis.unit.into(),
246 start: Some(format!("{:?}", sim.control.set_pos[i])),
247 });
248 }
249 let flag = |name: &str, kind: Kind, key: &str, start: bool| Variable {
250 name: name.into(),
251 kind,
252 description: tr.tr(key).into(),
253 unit: String::new(),
254 start: Some(start.to_string()),
255 };
256 out.push(flag("command.enable", Kind::Enable, "fmi-enable", true));
257 out.push(flag("command.cycle", Kind::Cycle, "fmi-cycle", false));
258 for (i, axis) in sim.machine.axes().iter().enumerate() {
259 let description = format!("{} · {}", tr.tr(axis.key), tr.tr("fmi-target"));
260 out.push(Variable {
261 name: format!("command.target.{}", axis.id),
262 kind: Kind::Target(i),
263 description,
264 unit: axis.unit.into(),
265 start: Some(format!("{:?}", sim.control.set_pos[i])),
266 });
267 }
268 out.push(flag("command.move", Kind::Move, "fmi-move", false));
269 let text = |name: &str, kind: Kind, key: &str, start: &str| Variable {
270 name: name.into(),
271 kind,
272 description: tr.tr(key).into(),
273 unit: String::new(),
274 start: Some(start.into()),
275 };
276 out.push(text("command.path", Kind::PathText, "fmi-path", ""));
277 out.push(text("command.path_file", Kind::PathFile, "fmi-path-file", ""));
278 out.push(text("command.trajectory_file", Kind::TrajectoryFile, "fmi-trajectory-file", ""));
279 out.push(flag("command.run_path", Kind::RunPath, "fmi-run-path", false));
280 for (k, motor) in sim.machine.motors().iter().enumerate() {
281 let owner = tr.tr(motor.key);
282 let mut mode = text(&format!("command.mode.{}", motor.id), Kind::DriveMode(k), "fmi-drive-mode", "position");
283 mode.description = format!("{owner} · {}", mode.description);
284 out.push(mode);
285 let unit_of = |signal: &str, fallback: &str| {
287 let id = format!("motor.{}.{signal}", motor.id);
288 infos.iter().find(|s| s.id == id).map_or(fallback.to_string(), |s| s.unit.clone())
289 };
290 for (name, kind, key, unit) in [
291 ("torque", Kind::Torque(k), "fmi-torque", unit_of("torque", "N m")),
292 ("velocity", Kind::Velocity(k), "fmi-velocity", unit_of("speed", "rad/s")),
293 ] {
294 out.push(Variable {
295 name: format!("command.{name}.{}", motor.id),
296 kind,
297 description: format!("{owner} · {}", tr.tr(key)),
298 unit,
299 start: Some("0.0".into()),
300 });
301 }
302 }
303 out.push(flag("time_optimal", Kind::TimeOptimal, "fmi-time-optimal", false));
304 out.push(text("machine", Kind::Machine, "fmi-machine", machine));
305 out.push(text("config_file", Kind::ConfigFile, "fmi-config-file", ""));
306 for (path, value) in cfg.leaves() {
307 if let (Some(name), Some(on)) = (path.strip_prefix("effects."), value.as_bool()) {
308 out.push(flag(&path, Kind::Effect(name.into()), &format!("effect-{name}"), on));
309 }
310 }
311 out.push(text("command.stop_category", Kind::StopCategory, "fmi-stop-category", "0"));
313 out
314}
315
316fn escape(text: &str) -> String {
317 text.replace('&', "&")
318 .replace('<', "<")
319 .replace('>', ">")
320 .replace('"', """)
321 .replace('\'', "'")
322 .replace('\n', " ")
323}
324
325fn description(
327 entry: &MachineEntry,
328 cfg: &Config,
329 tr: &Translations,
330 variables: &[Variable],
331 guid: &str,
332 fmi: u8,
333 dt: f64,
334) -> Result<String, ConfigError> {
335 let v3 = fmi == 3;
336 let mut x = String::new();
337 let tool = format!("sim-fmi {}", env!("CARGO_PKG_VERSION"));
338 let (name, about) = (escape(entry.id), escape(tr.tr(entry.key)));
339 let _ = writeln!(x, r#"<?xml version="1.0" encoding="UTF-8"?>"#);
340 if v3 {
341 let _ = writeln!(
342 x,
343 r#"<fmiModelDescription fmiVersion="3.0" modelName="{name}" instantiationToken="{guid}" description="{about}" generationTool="{tool}" variableNamingConvention="flat">"#
344 );
345 let _ = writeln!(
346 x,
347 r#" <CoSimulation modelIdentifier="{MODEL_IDENTIFIER}" canHandleVariableCommunicationStepSize="true" fixedInternalStepSize="{dt:?}" canBeInstantiatedOnlyOncePerProcess="false" canGetAndSetFMUState="true" canSerializeFMUState="true" providesDirectionalDerivatives="true" providesAdjointDerivatives="true" hasEventMode="false"/>"#
348 );
349 } else {
350 let _ = writeln!(
351 x,
352 r#"<fmiModelDescription fmiVersion="2.0" modelName="{name}" guid="{guid}" description="{about}" generationTool="{tool}" variableNamingConvention="flat" numberOfEventIndicators="0">"#
353 );
354 let _ = writeln!(
355 x,
356 r#" <CoSimulation modelIdentifier="{MODEL_IDENTIFIER}" canHandleVariableCommunicationStepSize="true" canInterpolateInputs="false" canBeInstantiatedOnlyOncePerProcess="false" canNotUseMemoryManagementFunctions="true" canGetAndSetFMUstate="true" canSerializeFMUstate="true" providesDirectionalDerivative="true"/>"#
357 );
358 }
359 let mut units: Vec<&str> = variables.iter().map(|v| v.unit.as_str()).filter(|u| !u.is_empty()).collect();
360 units.sort();
361 units.dedup();
362 let _ = writeln!(x, " <UnitDefinitions>");
363 for unit in units {
364 let _ = writeln!(x, r#" <Unit name="{}"/>"#, escape(unit));
365 }
366 let _ = writeln!(x, " </UnitDefinitions>");
367 let _ = writeln!(x, " <LogCategories>");
368 for (name, key) in LOG_CATEGORIES {
369 let _ = writeln!(x, r#" <Category name="{name}" description="{}"/>"#, escape(tr.tr(key)));
370 }
371 let _ = writeln!(x, " </LogCategories>");
372 let _ = writeln!(
373 x,
374 r#" <DefaultExperiment startTime="0" stepSize="{:?}"/>"#,
375 cfg.positive("profile.setpoint_interval_s")?
376 );
377 let _ = writeln!(x, " <ModelVariables>");
378 let written: Vec<usize> =
382 (0..variables.len()).filter(|&i| v3 || variables[i].causality() != "independent").collect();
383 for &vr in &written {
384 let v = &variables[vr];
385 let variability = match (v.causality(), v.type_name()) {
386 ("parameter", _) => "fixed",
387 (_, "Real") => "continuous",
388 _ => "discrete",
389 };
390 let attributes = format!(
391 r#"name="{}" valueReference="{vr}" causality="{}" variability="{variability}" description="{}""#,
392 escape(&v.name),
393 v.causality(),
394 escape(&v.description)
395 );
396 let start = v.start.as_ref().map_or(String::new(), |s| format!(r#" start="{}""#, escape(s)));
397 let unit = if v.unit.is_empty() { String::new() } else { format!(r#" unit="{}""#, escape(&v.unit)) };
398 match (v3, v.type_name()) {
399 (true, "String") => {
401 let _ = writeln!(x, " <String {attributes}>");
402 let _ = writeln!(x, r#" <Start value="{}"/>"#, escape(v.start.as_deref().unwrap_or("")));
403 let _ = writeln!(x, " </String>");
404 }
405 (true, type_name) => {
406 let _ = writeln!(
407 x,
408 " <{} {attributes}{start}{unit}/>",
409 if type_name == "Real" { "Float64" } else { type_name }
410 );
411 }
412 (false, type_name) => {
413 let _ = writeln!(x, " <ScalarVariable {attributes}>");
414 let _ = writeln!(x, " <{type_name}{start}{unit}/>");
415 let _ = writeln!(x, " </ScalarVariable>");
416 }
417 }
418 }
419 let _ = writeln!(x, " </ModelVariables>");
420 let outputs: Vec<usize> =
423 variables.iter().enumerate().filter(|(_, v)| v.causality() == "output").map(|(i, _)| i).collect();
424 let _ = writeln!(x, " <ModelStructure>");
425 if v3 {
426 for vr in &outputs {
427 let _ = writeln!(x, r#" <Output valueReference="{vr}" dependencies=""/>"#);
428 }
429 for vr in &outputs {
430 let _ = writeln!(x, r#" <InitialUnknown valueReference="{vr}"/>"#);
431 }
432 } else {
433 for (list, dependencies) in [("Outputs", r#" dependencies="""#), ("InitialUnknowns", "")] {
434 let _ = writeln!(x, " <{list}>");
435 for vr in &outputs {
436 let index = written.iter().position(|w| w == vr).expect("outputs are listed") + 1;
438 let _ = writeln!(x, r#" <Unknown index="{index}"{dependencies}/>"#);
439 }
440 let _ = writeln!(x, " </{list}>");
441 }
442 }
443 let _ = writeln!(x, " </ModelStructure>");
444 let _ = writeln!(x, "</fmiModelDescription>");
445 Ok(x)
446}
447
448fn guid(text: &str) -> String {
451 let fnv = |offset: u64| text.bytes().fold(offset, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3));
452 let (a, b) = (fnv(0xcbf2_9ce4_8422_2325), fnv(0x6c62_272e_07bb_0142));
453 format!(
454 "{{{:08x}-{:04x}-{:04x}-{:04x}-{:012x}}}",
455 a >> 32,
456 (a >> 16) & 0xffff,
457 a & 0xffff,
458 b >> 48,
459 b & 0xffff_ffff_ffff
460 )
461}
462
463pub fn binary_path(file_name: &str) -> Option<String> {
465 let extension = file_name.rsplit_once('.')?.1.to_ascii_lowercase();
466 let platform = match extension.as_str() {
467 "dll" => "win64",
468 "so" => "linux64",
469 "dylib" => "darwin64",
470 _ => return None,
471 };
472 Some(format!("binaries/{platform}/{MODEL_IDENTIFIER}.{extension}"))
473}
474
475pub fn binary_path3(file_name: &str, bytes: &[u8]) -> Option<String> {
479 let extension = file_name.rsplit_once('.')?.1.to_ascii_lowercase();
480 let u16_at = |i: usize| Some(u16::from_le_bytes(bytes.get(i..i.checked_add(2)?)?.try_into().ok()?));
481 let u32_at = |i: usize| Some(u32::from_le_bytes(bytes.get(i..i.checked_add(4)?)?.try_into().ok()?));
482 let (system, machine) = match extension.as_str() {
484 "dll" if bytes.starts_with(b"MZ") => {
485 let pe = u32_at(0x3c)? as usize;
486 if bytes.get(pe..pe.checked_add(4)?)? != b"PE\0\0" {
487 return None;
488 }
489 ("windows", u32::from(u16_at(pe + 4)?))
490 }
491 "so" if bytes.starts_with(b"\x7fELF") => ("linux", u32::from(u16_at(18)?)),
492 "dylib" if bytes.starts_with(&[0xcf, 0xfa, 0xed, 0xfe]) => ("darwin", u32_at(4)?),
493 _ => return None,
494 };
495 let architecture = match (system, machine) {
496 ("windows", 0x8664) | ("linux", 62) | ("darwin", 0x0100_0007) => "x86_64",
497 ("windows", 0xaa64) | ("linux", 183) | ("darwin", 0x0100_000c) => "aarch64",
498 _ => return None,
499 };
500 Some(format!("binaries/{architecture}-{system}/{MODEL_IDENTIFIER}.{extension}"))
501}
502
503pub fn crc32(data: &[u8]) -> u32 {
505 let mut crc = !0u32;
506 for &byte in data {
507 crc ^= byte as u32;
508 for _ in 0..8 {
509 crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
510 }
511 }
512 !crc
513}
514
515pub fn zip(files: &[(String, Vec<u8>)]) -> Vec<u8> {
517 let (mut out, mut central) = (Vec::new(), Vec::new());
518 for (name, data) in files {
519 let (crc, size, offset) = (crc32(data), data.len() as u32, out.len() as u32);
520 let common = |out: &mut Vec<u8>| {
522 out.extend(20u16.to_le_bytes());
523 out.extend(0x0800u16.to_le_bytes());
524 out.extend(0u16.to_le_bytes());
525 out.extend([0, 0, 0x21, 0]);
526 out.extend(crc.to_le_bytes());
527 out.extend(size.to_le_bytes());
528 out.extend(size.to_le_bytes());
529 out.extend((name.len() as u16).to_le_bytes());
530 out.extend(0u16.to_le_bytes());
531 };
532 out.extend(0x0403_4b50u32.to_le_bytes());
533 common(&mut out);
534 out.extend(name.as_bytes());
535 out.extend(data);
536 central.extend(0x0201_4b50u32.to_le_bytes());
537 central.extend(20u16.to_le_bytes());
538 common(&mut central);
539 central.extend([0u8; 10]);
541 central.extend(offset.to_le_bytes());
542 central.extend(name.as_bytes());
543 }
544 let (start, length) = (out.len() as u32, central.len() as u32);
545 out.extend(central);
546 out.extend(0x0605_4b50u32.to_le_bytes());
547 out.extend([0u8; 4]);
548 out.extend((files.len() as u16).to_le_bytes());
549 out.extend((files.len() as u16).to_le_bytes());
550 out.extend(length.to_le_bytes());
551 out.extend(start.to_le_bytes());
552 out.extend(0u16.to_le_bytes());
553 out
554}
555
556#[cfg(test)]
557mod tests {
558 #[test]
559 fn crc32_of_the_standard_check_string() {
560 assert_eq!(super::crc32(b"123456789"), 0xcbf4_3926);
561 }
562
563 #[test]
565 fn a_binary_is_known_by_its_extension_in_any_case() {
566 assert_eq!(super::binary_path("SIM_FMI.DLL").as_deref(), Some("binaries/win64/sim_fmi.dll"));
567 assert_eq!(super::binary_path("libsim_fmi.So").as_deref(), Some("binaries/linux64/sim_fmi.so"));
568 assert_eq!(super::binary_path("sim_fmi.exe"), None);
569 }
570
571 #[test]
573 fn an_fmi3_binary_goes_to_the_folder_of_its_architecture() {
574 let mut pe = vec![0u8; 0x48];
575 pe[..2].copy_from_slice(b"MZ");
576 pe[0x3c] = 0x40;
577 pe[0x40..0x44].copy_from_slice(b"PE\0\0");
578 pe[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
579 assert_eq!(super::binary_path3("SIM_FMI.DLL", &pe).as_deref(), Some("binaries/x86_64-windows/sim_fmi.dll"));
580 let mut elf = b"\x7fELF".to_vec();
581 elf.resize(20, 0);
582 elf[18] = 183;
583 assert_eq!(super::binary_path3("libsim_fmi.so", &elf).as_deref(), Some("binaries/aarch64-linux/sim_fmi.so"));
584 let macho = [[0xcf, 0xfa, 0xed, 0xfe], 0x0100_0007u32.to_le_bytes()].concat();
585 assert_eq!(
586 super::binary_path3("libsim_fmi.dylib", &macho).as_deref(),
587 Some("binaries/x86_64-darwin/sim_fmi.dylib")
588 );
589 let universal = [0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2];
590 assert_eq!(super::binary_path3("libsim_fmi.dylib", &universal), None);
591 assert_eq!(super::binary_path3("sim_fmi.dll", b"windows binary"), None);
592 let me = std::fs::read(std::env::current_exe().unwrap()).unwrap();
594 let extension = if cfg!(windows) {
595 "dll"
596 } else if cfg!(target_os = "macos") {
597 "dylib"
598 } else {
599 "so"
600 };
601 let path = super::binary_path3(&format!("sim_fmi.{extension}"), &me).unwrap();
602 assert!(path.contains(std::env::consts::ARCH), "{path}");
603 }
604
605 #[test]
607 fn every_export_message_exists_in_every_language() {
608 let sources = [include_str!("lib.rs"), include_str!("api.rs"), include_str!("api3.rs")].concat();
609 let keys: Vec<&str> = sources
610 .split('"')
611 .filter(|s| s.starts_with("fmi-") && s.len() > 4 && s.chars().all(|c| c.is_ascii_lowercase() || c == '-'))
612 .collect();
613 assert!(keys.len() >= 10, "{keys:?}");
614 for (lang, text) in super::I18N {
615 let tr = sim_core::Translations::parse(text);
616 for key in &keys {
617 assert!(tr.has(key), "no '{lang}' entry for '{key}'");
618 }
619 }
620 }
621}