Skip to main content

sim_fmi/
lib.rs

1//! FMI export: a machine as an FMI 2.0 or FMI 3.0 Co-Simulation FMU, for Simulink, OpenModelica, Dymola and other tools.
2//!
3//! One binary serves both versions: the `fmi2*` functions are in `api`, the `fmi3*` ones in `api3`, and both drive
4//! the same `api::Instance`. Model Exchange is not offered (docs/fmi.md says why: the controller is a sampled
5//! controller whose internal states the importer's integrator cannot see). An FMU state holds a snapshot of the
6//! simulation, which setting it restores at once, serialized or not (`api`).
7//! The directional derivatives of the outputs with respect to
8//! the inputs are exactly zero, because an input acts on the outputs only through the next communication step.
9//!
10//! The FMU carries one generic binary (`sim_fmi.dll`, `sim_fmi.so`) for every machine; which machine and which
11//! config it runs come from its resources (`resources/model.txt`: machine id and language; `resources/config.toml`).
12//! A machine from a machine file (docs/machine-files.md) is not registered: its file goes along as
13//! `resources/machine.toml`, and the FMU builds the machine from it when it is instantiated.
14//! The model description is generated from the machine's signal list and config, never written per machine:
15//!
16//! | variable                    | type    | causality   | meaning                                               |
17//! | --------------------------- | ------- | ----------- | ----------------------------------------------------- |
18//! | `time`                      | Real    | independent | simulated time, s (Real in 2.0 is Float64 in 3.0)     |
19//! | every other signal id       | Real    | output      | every signal of the simulation, with its unit         |
20//! | `command.setpoint.<axis>`   | Real    | input       | position setpoint, interpolated as from a PLC         |
21//! | `command.enable`            | Boolean | input       | false switches the drives off (brakes on)             |
22//! | `command.stop_category`     | String  | input       | how false stops them: "0" (off), "1" or "2"           |
23//! | `command.cycle`             | Boolean | input       | true starts the configured cycle, false stops it      |
24//! | `command.target.<axis>`     | Real    | input       | the target of a move                                  |
25//! | `command.move`              | Boolean | input       | turning true moves to the targets                     |
26//! | `command.path`              | String  | input       | a path as the text of a path file                     |
27//! | `command.path_file`         | String  | input       | a path file, used instead of `command.path`           |
28//! | `command.trajectory_file`   | String  | input       | poses at times, run instead of a path where not empty |
29//! | `command.run_path`          | Boolean | input       | turning true plans the path from here and runs it     |
30//! | `command.mode.<motor>`      | String  | input       | the drive's mode: "position", "velocity" or "torque"  |
31//! | `command.torque.<motor>`    | Real    | input       | torque setpoint in torque mode, N m (N if linear)    |
32//! | `command.velocity.<motor>`  | Real    | input       | speed setpoint in velocity mode, rad/s (m/s if linear)|
33//! | `time_optimal`              | Boolean | parameter   | paths timed as fast as the motors allow               |
34//! | `machine`                   | String  | parameter   | the machine of the registry                           |
35//! | `config_file`               | String  | parameter   | a config file to use instead of the one in the FMU    |
36//! | `effects.<name>`            | Boolean | parameter   | the effect switches, overriding the config's          |
37//!
38//! The value reference of a variable is its place in the list, unique across types. The names are the signal ids
39//! as CSV columns and OPC UA nodes have them; the naming convention is "flat", since ids such as `belt.1.tension`
40//! are not identifiers of the "structured" one.
41//! A position setpoint goes to the controller as `Command::Setpoint` whenever it differs from the one the
42//! controller follows; the controller interpolates towards it over `profile.setpoint_interval_s`, so the
43//! communication step should be that interval (the model description's default step). `fmi2DoStep` and `fmi3DoStep`
44//! run whole base steps (`sim.dt_s`) and refuse a communication step that is not a whole multiple of it.
45//! The triggers (`command.cycle`, `command.move`, `command.run_path`) act at the communication point where they have
46//! changed since the last one; a setpoint input, once set, takes the axes over whenever it differs from the setpoint
47//! the controller follows, so an importer drives the machine either by setpoints or by cycle, moves and paths.
48//! A motor whose `command.mode.<motor>` is "velocity" or "torque" takes `command.velocity.<motor>` or
49//! `command.torque.<motor>` as it stands at each communication point, held over the step, in place of the controller's
50//! plan (`sim_components::DriveMode`): the importer's own controller closes the loop. The mode changes at the
51//! communication point where the input differs from the drive's.
52
53pub mod api;
54pub mod api3;
55
56use sim_components::{Sim, load_config};
57use sim_core::{Config, ConfigError, MachineEntry, Translations};
58use std::fmt::Write;
59
60/// (language code, translation file contents) for the export's own labels and messages.
61pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
62
63/// The name of the binary in the FMU and of the C functions' library.
64pub const MODEL_IDENTIFIER: &str = "sim_fmi";
65
66/// The log categories of the model description, with their descriptions' keys: the commands the inputs gave and the
67/// states set, warnings, errors; `logAll` stands for all of them (`fmi2SetDebugLogging`, `fmi3SetDebugLogging`).
68pub 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/// What a variable stands for.
76#[derive(Debug, Clone, PartialEq)]
77pub enum Kind {
78    /// The signal at this place in `Sim::signal_infos`.
79    Signal(usize),
80    /// The position setpoint of the axis at this place.
81    Setpoint(usize),
82    Enable,
83    /// True runs the configured cycle (`Command::StartCycle` when it turns true), false stops it after its segment.
84    Cycle,
85    /// The target of a move for the axis at this place, and the trigger that starts it when it turns true.
86    Target(usize),
87    Move,
88    /// A path as the text of a path file (`sim_components::path`), or the name of such a file, which wins when it is
89    /// not empty; the trigger plans it from where the machine stands and runs it when it turns true.
90    PathText,
91    PathFile,
92    /// A trajectory file (poses at times, `path::parse_trajectory`), which `RunPath` runs instead of a path where it is
93    /// not empty.
94    TrajectoryFile,
95    RunPath,
96    /// Whether a path is timed as fast as the motors allow (`sim-cli --time-optimal`) or within the axis limits.
97    TimeOptimal,
98    Machine,
99    ConfigFile,
100    /// The switch `effects.<name>`.
101    Effect(String),
102    /// The operating mode of the motor at this place ("position", "velocity", "torque"), and its torque and speed
103    /// setpoints from outside (`sim_components::DriveMode`).
104    DriveMode(usize),
105    Torque(usize),
106    Velocity(usize),
107    /// The stop category ("0", "1" or "2", `sim_components::StopCategory`) by which `Enable` turning false stops the
108    /// drives; "0" switches them off at once, as before.
109    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    /// The start value as written in the model description; none for outputs.
119    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
158/// Every label the FMU shows, in one language: machines, components and the export's own.
159pub 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
165/// An FMU's content apart from its binaries: the machine, the config as text, and the model description generated from them.
166pub struct Model {
167    pub entry: &'static MachineEntry,
168    pub config_text: String,
169    pub lang: String,
170    pub variables: Vec<Variable>,
171    /// Changes whenever the model description does: a hash of it.
172    pub guid: String,
173    pub xml: String,
174    /// The FMI version of the model description: 2 or 3.
175    pub fmi: u8,
176}
177
178impl Model {
179    /// An FMI 2.0 FMU. `config_text` is read as a config file (`load_config`); `lang` is the language of the descriptions.
180    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    /// As `new`, for FMI 3.0 if `fmi` is 3 and FMI 2.0 otherwise. In 3.0 the GUID is the instantiation token.
185    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    /// The files of the FMU apart from its binaries, as (path in the archive, content).
198    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
211/// Whether `entry` is one of `sim_machines::MACHINES`, not a machine from a file.
212pub fn is_registered(entry: &MachineEntry) -> bool {
213    sim_machines::find(entry.id).is_some_and(|known| std::ptr::eq(known, entry))
214}
215
216/// The machine of an FMU's resources: from `machine.toml` where it carries a machine file, else the registered one
217/// of that id.
218pub 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        // The unit of the motor's own signal: N and m/s on a linear motor, N m and rad/s on a rotary one.
286        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    // Last, so that the value references of the variables before it stay as they were.
312    out.push(text("command.stop_category", Kind::StopCategory, "fmi-stop-category", "0"));
313    out
314}
315
316fn escape(text: &str) -> String {
317    text.replace('&', "&amp;")
318        .replace('<', "&lt;")
319        .replace('>', "&gt;")
320        .replace('"', "&quot;")
321        .replace('\'', "&apos;")
322        .replace('\n', "&#10;")
323}
324
325/// The model description of FMI `fmi` (2 or 3); `guid` empty for the text the GUID is the hash of; `dt` the base step.
326fn 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    // FMI 2.0 (2.2.7) gives an independent variable no start attribute, and FMIL (the FMI library of OpenModelica and
379    // other importers) reports one without it as an error; where none is declared, `time` is there implicitly. So 2.0
380    // leaves it out of the list (its value reference still answers), and 3.0, whose libraries accept it, declares it.
381    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            // FMI 3.0 gives a String's start as an element of its own.
400            (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    // Outputs are calculated during initialisation, so they are initial unknowns as well. They depend on no input
421    // directly (dependencies=""): a setpoint reaches them only through the next communication step.
422    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                // The index counts the variables as listed (from 1), not their value references.
437                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
448/// A GUID-shaped 128-bit hash (two FNV-1a 64-bit hashes with different offsets): stable across builds and platforms,
449/// which `std`'s hasher is not.
450fn 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
463/// Where a binary goes in the FMU, from its file name: `binaries/<platform>/sim_fmi.<extension>`.
464pub 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
475/// Where a binary goes in an FMI 3.0 FMU: `binaries/<architecture>-<system>/sim_fmi.<extension>`, the system from
476/// the extension and the architecture (x86_64 or aarch64) from the binary's header (PE, ELF or a thin 64-bit Mach-O).
477/// None for anything else, a universal Mach-O among it: FMI 3.0 wants one folder per architecture.
478pub 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    // PE machine, ELF e_machine, Mach-O cputype.
483    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
503/// The CRC-32 a zip archive carries per file.
504pub 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
515/// A zip archive of the files, stored without compression: an FMU is a zip, and stored entries need no library.
516pub 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        // Version 2.0, UTF-8 names (bit 11), stored, no time stamp (1980-01-01).
521        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        // Comment length, disk, internal and external attributes.
540        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    /// Windows does not care about case: `SIM_FMI.DLL` is the Windows binary, stored under the standard's name.
564    #[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    /// FMI 3.0 puts a binary in the folder of its architecture, read from its header.
572    #[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        // The test program itself has the header of the platform it runs on.
593        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    /// Every key the export shows has a German and an English entry.
606    #[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}