Skip to main content

sim_machines/
lib.rs

1//! The registration list: the one place outside a machine crate that names a machine.
2//! App, CLI and PLC link pick every machine up from here.
3
4use sim_core::{Config, ConfigError, MachineEntry, Translations};
5use std::path::Path;
6
7pub use sim_netlist::FileError;
8
9pub static MACHINES: &[&MachineEntry] = &[
10    &machine_t_gantry::ENTRY,
11    &machine_single_axis::ENTRY,
12    &machine_delta_d3::ENTRY,
13    &machine_delta_d2::ENTRY,
14    &machine_parallel_scara::ENTRY,
15    &machine_delta_linear::ENTRY,
16    &machine_delta_d4::ENTRY,
17    &machine_delta_h4::ENTRY,
18    &machine_joint_kit::SCREW,
19    &machine_joint_kit::RACK,
20    &machine_joint_kit::LINEAR_MOTOR,
21    &machine_joint_kit::ROTARY_TABLE,
22    &machine_joint_kit::URDF_ARM,
23    &machine_joint_kit::SCARA,
24    &machine_crank_cam::SLIDER_CRANK,
25    &machine_crank_cam::ROTARY_KNIFE,
26    &machine_crank_cam::FLYING_SAW,
27    &machine_joint_kit::PALLETISER,
28    &machine_hexapod::ENTRY,
29    &machine_cable_robot::PLANAR,
30    &machine_cable_robot::SPATIAL,
31    &machine_crank_cam::DISC_CAM,
32    &machine_tripod::ENTRY,
33    &machine_wafer_handler::ENTRY,
34    &machine_crank_cam::TOGGLE_PRESS,
35    &machine_joint_kit::ARM_ON_TRACK,
36    &machine_winder::ENTRY,
37    &machine_hexapod_rotary::ENTRY,
38    &machine_crank_cam::GENEVA_DRIVE,
39    &machine_crank_cam::CAM_INDEXER,
40    &machine_mover_track::ENTRY,
41    &machine_overhead_crane::ENTRY,
42];
43
44pub const LANGUAGES: &[&str] = &["en", "de"];
45
46pub fn find(id: &str) -> Option<&'static MachineEntry> {
47    MACHINES.iter().copied().find(|m| m.id == id)
48}
49
50/// Everything core, components and `machine` name, in one language, and every registered machine's own name (for lists
51/// of machines). Front ends add their own labels. A registered machine's labels come from its own crate first, then from
52/// the shared components, never from another machine's (where several machine crates had the same key, the last
53/// registered one's wording won on every machine without its own). A machine file has no labels of its own: its tables
54/// are the registered machines', so it borrows theirs, beneath the shared ones.
55pub fn translations(lang: &str, machine: &MachineEntry) -> Translations {
56    let mut out = Translations::default();
57    let texts = |sources: &'static [(&'static str, &'static str)]| {
58        sources.iter().filter(move |(l, _)| *l == lang).map(|(_, text)| *text)
59    };
60    if !MACHINES.iter().any(|m| m.id == machine.id && std::ptr::eq(m.i18n, machine.i18n)) {
61        MACHINES.iter().flat_map(|m| texts(m.i18n)).for_each(|t| out.add(t));
62    }
63    texts(sim_core::i18n::I18N).chain(texts(sim_components::I18N)).for_each(|t| out.add(t));
64    for m in MACHINES {
65        let name =
66            texts(m.i18n).flat_map(str::lines).find(|l| l.split_once('=').is_some_and(|(k, _)| k.trim() == m.key));
67        name.into_iter().for_each(|line| out.add(line));
68    }
69    texts(machine.i18n).for_each(|t| out.add(t));
70    out
71}
72
73/// A machine from a machine file (TOML, or JSON by its extension), checked in full against the tables the registered
74/// machines have; see docs/machine-files.md. Front ends take it like an entry of `MACHINES`. An error names the line
75/// in a TOML file; in a JSON file the key alone.
76pub fn load_file(path: &Path) -> Result<&'static MachineEntry, FileError> {
77    let fail = |error, line| FileError { file: path.into(), line, error };
78    let text = std::fs::read_to_string(path).map_err(|e| fail(ConfigError::Parse(e.to_string()), None))?;
79    let json = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("json"));
80    let toml_text = if json { json_to_toml(&text).map_err(|e| fail(e, None))? } else { text };
81    let known = known_configs();
82    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("machine");
83    sim_netlist::from_text(&toml_text, !json, stem, known).map_err(|(error, line)| fail(error, line))
84}
85
86/// The default configs of the registered machines, parsed once: the keys a machine file may have.
87fn known_configs() -> &'static [Config] {
88    static KNOWN: std::sync::OnceLock<Vec<Config>> = std::sync::OnceLock::new();
89    KNOWN.get_or_init(|| MACHINES.iter().map(|m| m.config()).collect())
90}
91
92/// A machine file's TOML text, checked as `load_file` checks a file, with `id` where `machine.id` names none: for an
93/// FMU, which carries the file among its resources. The same text and id give the same entry, as `load_file` does.
94pub fn load_text(toml_text: &str, id: &str) -> Result<&'static MachineEntry, ConfigError> {
95    sim_netlist::from_text(toml_text, false, id, known_configs()).map_err(|(error, _)| error)
96}
97
98/// A JSON machine file as the TOML text of the same config.
99pub fn json_to_toml(text: &str) -> Result<String, ConfigError> {
100    let mut value: serde_json::Value =
101        serde_json::from_str(text).map_err(|e| ConfigError::Parse(format!("line {}: {e}", e.line())))?;
102    // JSON has one kind of number: a version written 1.0 is the version 1 the JSON Schema accepts.
103    for version in ["/format_version", "/machine/version"] {
104        if let Some(v) =
105            value.pointer_mut(version).filter(|v| v.as_f64().is_some_and(|f| f.fract() == 0.0 && f.abs() < 1e9))
106        {
107            *v = serde_json::Value::from(v.as_f64().unwrap_or_default() as i64);
108        }
109    }
110    let toml::Value::Table(table) = toml::Value::try_from(value).map_err(|e| ConfigError::Parse(e.to_string()))? else {
111        return Err(ConfigError::Parse("a machine file is a JSON object".into()));
112    };
113    toml::to_string(&table).map_err(|e| ConfigError::Parse(e.to_string()))
114}
115
116/// The JSON Schema of a machine file (`sim_netlist::json_schema`) as text: what schema/machine-file.schema.json holds.
117pub fn json_schema() -> String {
118    serde_json::to_string_pretty(&sim_netlist::json_schema()).expect("a TOML value is written as JSON")
119        + "
120"
121}