Skip to main content

machine_joint_kit/
lib.rs

1//! Machines built from one motor-driven joint per axis (`sim_components::chain::JointMachine`), one for each kind of
2//! transmission and mechanism the components offer, so that each can be run and sized:
3//!
4//! - `screw-axis`: a carriage on a ball screw (`slide`).
5//! - `rack-axis`: a carriage driven by a pinion on a rack through a planetary gearbox (`slide`).
6//! - `linear-motor-axis`: a carriage on an ironcore linear motor, no transmission (`slide`).
7//! - `rotary-table`: an indexing table behind a strain wave or worm gear (`table`).
8//! - `urdf-arm`: a serial six-axis arm whose bodies come from a URDF file (`arm`).
9//! - `scara`: a SCARA arm from a URDF file, its vertical joint on a ball screw (`arm`).
10//! - `palletiser`: a four-axis palletiser from a URDF file, a parallelogram keeping its flange level (`arm`).
11//! - `arm-on-track`: the six-axis arm on a carriage that runs on a floor track, a seventh joint driven by a rack and
12//!   pinion, its guide blocks loaded by the arm's reaction (`arm`).
13//!
14//! Each has its own default config in `config/`: `config/common.toml` with what all share, then the machine's file.
15
16mod arm;
17mod slide;
18mod table;
19mod tool;
20
21use sim_components::catalog::motor_config;
22use sim_components::chain::{JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism};
23use sim_components::joint::RotaryJoint;
24use sim_components::mech::{Gearbox, ThermalFeedback};
25use sim_core::{AxisInfo, Config, ConfigError, Machine, MachineEntry, MotorInfo};
26
27const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
28
29macro_rules! entry {
30    ($name:ident, $id:literal, $file:literal, $build:expr) => {
31        pub static $name: MachineEntry = MachineEntry {
32            id: $id,
33            key: concat!("machine-", $id),
34            default_config: concat!(
35                include_str!("../config/common.toml"),
36                "\n",
37                include_str!(concat!("../config/", $file))
38            ),
39            i18n: I18N,
40            build: |cfg| sim_components::base::mount(cfg, ($build)(cfg)?),
41            suite_configs: || suite_configs(&$name),
42        };
43    };
44}
45
46entry!(SCREW, "screw-axis", "screw.toml", |cfg| slide::build(cfg, slide::Kind::Screw));
47entry!(RACK, "rack-axis", "rack.toml", |cfg| slide::build(cfg, slide::Kind::Rack));
48entry!(LINEAR_MOTOR, "linear-motor-axis", "linear-motor.toml", |cfg| slide::build(cfg, slide::Kind::LinearMotor));
49entry!(ROTARY_TABLE, "rotary-table", "table.toml", table::build);
50entry!(URDF_ARM, "urdf-arm", "arm.toml", arm::build);
51entry!(SCARA, "scara", "scara.toml", arm::build);
52entry!(PALLETISER, "palletiser", "palletiser.toml", arm::build);
53entry!(ARM_ON_TRACK, "arm-on-track", "arm-on-track.toml", arm::build);
54
55/// The full configs of the SCARA and the six-axis arm in tool space (`kinematics.tool_space = true`), with a cycle of
56/// straight lines of the tool: for `--config`.
57pub const SCARA_TOOL_CONFIG: &str = include_str!("../config/scara-tool.toml");
58pub const ARM_TOOL_CONFIG: &str = include_str!("../config/arm-tool.toml");
59/// The five-axis and the seven-axis (redundant) example arms in tool space (`urdf/five-axis.urdf`,
60/// `urdf/seven-axis.urdf`), for `--config` with the `urdf-arm` machine.
61pub const ARM5_TOOL_CONFIG: &str = include_str!("../config/arm5-tool.toml");
62pub const ARM7_TOOL_CONFIG: &str = include_str!("../config/arm7-tool.toml");
63/// The six-axis arm on its track in tool space: the track's position beside the flange's pose.
64pub const ARM_ON_TRACK_TOOL_CONFIG: &str = include_str!("../config/arm-on-track-tool.toml");
65
66const G: f64 = 9.80665;
67
68/// Effects that take energy out or put it in; the standard suite runs with them off.
69pub const LOSSY_EFFECTS: [&str; 8] = [
70    "joint_friction",
71    "motor_friction",
72    "gearbox_drag",
73    "gearbox_lost_motion",
74    "gearbox_mesh_friction",
75    "gearbox_efficiency",
76    "torque_ripple",
77    "holding_brake",
78];
79
80/// The default config with every loss switched off.
81pub fn lossless_config(entry: &MachineEntry) -> Config {
82    let mut cfg = entry.config();
83    for effect in LOSSY_EFFECTS {
84        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
85    }
86    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
87    // And a joint's own gearbox's (`[gearbox.<k>]`, catalog::motor_config).
88    let own: Vec<String> = cfg
89        .get("gearbox")
90        .ok()
91        .and_then(|g| g.as_table())
92        .map(|t| t.iter().filter(|(_, v)| v.get("damping_nm_s_rad").is_some()).map(|(k, _)| k.clone()).collect())
93        .unwrap_or_default();
94    for id in own {
95        cfg.set_text(&format!("gearbox.{id}.damping_nm_s_rad = 0.0")).unwrap();
96    }
97    // Both where a machine has both (the SCARA's joints and its slide).
98    for stops in ["slide.stop_damping_n_s_m", "joint.stop_damping_nm_s_rad"] {
99        if cfg.get(stops).is_ok() {
100            cfg.set_text(&format!("{stops} = 0.0")).unwrap();
101        }
102    }
103    cfg
104}
105
106/// Loss-free rigid and elastic models, with and without the payload; the elastic one with the payload also with part
107/// heating and the temperature feedback (no loss, so nothing warms).
108///
109/// The six-axis arm without gravity: held by constant torques, as the suite holds it after its pulse, an arm whose
110/// upper arm stands up is an inverted pendulum and falls away from the pose, and the energy it then trades between
111/// height and speed dwarfs the pulse's (a real property, not a numerical one: the position loops hold it). Gravity's
112/// part of the dynamics is checked on the default config (static hold, loss budget) and in `rigid`'s tests.
113fn suite_configs(entry: &MachineEntry) -> Vec<Config> {
114    [(false, true), (false, false), (true, true), (true, false)]
115        .into_iter()
116        .map(|(elastic, payload)| {
117            let mut cfg = lossless_config(entry);
118            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
119            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
120            cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
121            cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
122            if ["urdf-arm", "palletiser", "arm-on-track"].contains(&entry.id) {
123                cfg.set_text("effects.gravity = false").unwrap();
124            }
125            cfg
126        })
127        .collect()
128}
129
130fn gravity(cfg: &Config) -> Result<f64, ConfigError> {
131    Ok(if cfg.bool("effects.gravity")? { G } else { 0.0 })
132}
133
134fn payload(cfg: &Config, key: &str) -> Result<f64, ConfigError> {
135    Ok(if cfg.bool("effects.payload")? { cfg.non_negative(key)? } else { 0.0 })
136}
137
138/// An axis whose limits are `axis.<id>.max_velocity_<unit>_s`, `max_acceleration_<unit>_s2` and `max_jerk_<unit>_s3`.
139fn axis(
140    cfg: &Config,
141    id: &'static str,
142    key: &'static str,
143    unit: &'static str,
144    (min, max): (f64, f64),
145) -> Result<AxisInfo, ConfigError> {
146    let get = |what: &str, rate: &str| cfg.positive(&format!("axis.{id}.max_{what}_{unit}_{rate}"));
147    Ok(AxisInfo {
148        id,
149        key,
150        unit,
151        min,
152        max,
153        max_vel: get("velocity", "s")?,
154        max_acc: get("acceleration", "s2")?,
155        max_jerk: get("jerk", "s3")?,
156    })
157}
158
159/// A joint machine of `joints` (each with its gear lever, `None` where the joint is driven without a converter, and
160/// its unit, "m" or "rad") and `axes`, one motor per joint.
161fn machine<M: Mechanism + 'static>(
162    cfg: &Config,
163    mechanism: M,
164    joints: Vec<(RotaryJoint, Option<f64>, &'static str)>,
165    axes: Vec<AxisInfo>,
166) -> Result<Box<dyn Machine>, ConfigError> {
167    let specs = joints
168        .into_iter()
169        .enumerate()
170        .map(|(k, (drive, gear_lever, unit))| JointSpec {
171            drive,
172            id: MOTOR_IDS[k],
173            key: JOINT_KEYS[k],
174            gear_lever,
175            unit,
176        })
177        .collect::<Vec<_>>();
178    let motors = (0..specs.len()).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
179    // Each joint's gearbox warms from its own efficiency (`[gearbox.<k>]` over `[gearbox]`).
180    let gear_efficiencies = (0..specs.len())
181        .map(|k| Gearbox::configured_efficiency(&motor_config(cfg, MOTOR_IDS[k])?))
182        .collect::<Result<_, _>>()?;
183    let mut machine = JointMachine::new(
184        mechanism,
185        specs,
186        cfg.bool("effects.joint_elasticity")?,
187        ThermalFeedback::from_config(cfg)?,
188        axes,
189        motors,
190    );
191    machine.gear_efficiencies = gear_efficiencies;
192    Ok(Box::new(machine))
193}
194
195/// `ratings.required_life_h`, where it is set.
196fn required_life(cfg: &Config) -> Option<f64> {
197    cfg.f64("ratings.required_life_h").ok()
198}
199
200#[cfg(test)]
201mod tests;