Skip to main content

machine_crank_cam/
lib.rs

1//! Crank and cam mechanisms, the core cases of a servo sizing tool, each a motor-driven joint
2//! (`sim_components::chain::JointMachine`) that can run an electronic cam (`sim_components::cam`) as its cycle:
3//!
4//! - `slider-crank`: a crank, a connecting rod and a slider on a guide, as in presses and pushers (`crank`).
5//! - `rotary-knife`: a knife roll cutting a moving web to format (`knife`).
6//! - `flying-saw`: a saw on a carriage that runs with the material while it cuts and returns (`saw`).
7//! - `disc-cam`: a cam disc turned by the servo lifting a roller follower on a slide against its spring (`disc`): the
8//!   mechanical cam, its lift law, contact force and pressure angle.
9//! - `toggle-press`: a crank pushing the knee of two links in line between the frame and the ram, a knuckle-joint press:
10//!   the force amplification towards the links' dead centre, the frame's stretch, the force capacity over the stroke
11//!   (`toggle`).
12//! - `geneva-drive` and `cam-indexer`: a rotary indexing table stepped on a station per turn of its driver, by a Geneva
13//!   wheel (its infinite jerk at the pin's entry) or by a cam index drive with the modified sine (`indexer`): the
14//!   contact force, the index accuracy in the dwell and the table's settling after each index.
15//!
16//! With `cam.run = false` (as shipped) the cycle is the config's `[[cycle.segment]]`, as on every machine: the crank
17//! swings through its working stroke and back as a servo press in pendulum mode does, the knife indexes, the saw's
18//! carriage moves. With `cam.run = true` the controller runs the mechanism's cam instead: the master (virtual, or the
19//! web or material) comes up to speed in `cam.ramp_s` and the slave follows; one pass is one master period.
20//!
21//! Each has its config in `config/`: `config/common.toml` with what all share, then the machine's file; beside it
22//! `<id>-cam.toml`, the same config with `cam.run = true`, a whole config to load.
23
24mod crank;
25mod disc;
26mod indexer;
27mod knife;
28mod saw;
29mod toggle;
30
31use sim_components::chain::{JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism};
32use sim_components::joint::RotaryJoint;
33use sim_components::mech::ThermalFeedback;
34use sim_core::{AxisInfo, Config, ConfigError, Machine, MachineEntry, MotorInfo};
35
36pub use crank::SliderCrank;
37pub use disc::DiscCam;
38pub use indexer::{Drive, Indexer, modified_sine};
39pub use knife::RotaryKnife;
40pub use saw::FlyingSaw;
41pub use toggle::TogglePress;
42
43const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
44
45/// The effects of `common.toml` that the machine does not model, refused switched on (`refuse_unmodelled`): the table's
46/// twist is the indexers', the follower's lift-off the disc cam's, and none has links to bend.
47const NO_TWIST_LIFT_OFF_OR_LINKS: &[&str] =
48    &["table_twist", "follower_lift_off", "link_bending", "link_bending_reaction"];
49
50macro_rules! entry {
51    ($name:ident, $id:literal, $file:literal, $build:expr, $unmodelled:expr) => {
52        pub static $name: MachineEntry = MachineEntry {
53            id: $id,
54            key: concat!("machine-", $id),
55            default_config: concat!(
56                include_str!("../config/common.toml"),
57                "\n",
58                include_str!(concat!("../config/", $file))
59            ),
60            i18n: I18N,
61            build: |cfg| {
62                sim_components::refuse_unmodelled(cfg, $unmodelled)?;
63                $build(cfg)
64            },
65            suite_configs: || suite_configs(&$name),
66        };
67    };
68}
69
70entry!(SLIDER_CRANK, "slider-crank", "slider-crank.toml", crank::build, NO_TWIST_LIFT_OFF_OR_LINKS);
71entry!(ROTARY_KNIFE, "rotary-knife", "rotary-knife.toml", knife::build, NO_TWIST_LIFT_OFF_OR_LINKS);
72entry!(FLYING_SAW, "flying-saw", "flying-saw.toml", saw::build, NO_TWIST_LIFT_OFF_OR_LINKS);
73entry!(DISC_CAM, "disc-cam", "disc-cam.toml", disc::build, &["table_twist", "link_bending", "link_bending_reaction"]);
74entry!(TOGGLE_PRESS, "toggle-press", "toggle-press.toml", toggle::build, NO_TWIST_LIFT_OFF_OR_LINKS);
75const INDEXER: &[&str] = &["follower_lift_off", "link_bending", "link_bending_reaction"];
76entry!(GENEVA_DRIVE, "geneva-drive", "geneva-drive.toml", indexer::build_geneva, INDEXER);
77entry!(CAM_INDEXER, "cam-indexer", "cam-indexer.toml", indexer::build_cam, INDEXER);
78
79const G: f64 = 9.80665;
80
81/// Effects that take energy out or put it in; the standard suite runs with them off.
82pub const LOSSY_EFFECTS: [&str; 6] =
83    ["joint_friction", "motor_friction", "gearbox_efficiency", "torque_ripple", "holding_brake", "process_force"];
84
85/// The default config with every loss switched off.
86pub fn lossless_config(entry: &MachineEntry) -> Config {
87    let mut cfg = entry.config();
88    for effect in LOSSY_EFFECTS {
89        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
90    }
91    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
92    let stops = if cfg.get("slide.stop_damping_n_s_m").is_ok() {
93        "slide.stop_damping_n_s_m"
94    } else {
95        "joint.stop_damping_nm_s_rad"
96    };
97    cfg.set_text(&format!("{stops} = 0.0")).unwrap();
98    cfg
99}
100
101/// Loss-free rigid and elastic models, with and without the payload.
102fn suite_configs(entry: &MachineEntry) -> Vec<Config> {
103    [(false, true), (false, false), (true, true), (true, false)]
104        .into_iter()
105        .map(|(elastic, payload)| {
106            let mut cfg = lossless_config(entry);
107            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
108            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
109            // The hanging ram makes the suite's middle of the stroke (265 degrees) unstable under a constant torque:
110            // -g m_x x'' = -4.50 N m/rad against J = 0.171 kg m^2, growing at 5.1 per second, so the crank fell over and
111            // rang in its stops. The drive's loop holds it; the default config, with gravity, takes the suite's short runs.
112            if entry.id == SLIDER_CRANK.id {
113                cfg.set_text("effects.gravity = false").unwrap();
114            }
115            cfg
116        })
117        .collect()
118}
119
120fn gravity(cfg: &Config) -> Result<f64, ConfigError> {
121    Ok(if cfg.bool("effects.gravity")? { G } else { 0.0 })
122}
123
124fn payload(cfg: &Config) -> Result<f64, ConfigError> {
125    Ok(if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 })
126}
127
128/// The master of `[cam]` where `cam.run` is on: its speed, the period of `cam`, and `cam.ramp_s`.
129fn master(cfg: &Config, speed: f64, period: f64) -> Result<Option<sim_core::CamMaster>, ConfigError> {
130    if !cfg.bool("cam.run")? {
131        return Ok(None);
132    }
133    Ok(Some(sim_core::CamMaster { speed, period, ramp_s: cfg.positive("cam.ramp_s")? }))
134}
135
136/// The axis `id` over `range`, its limits `axis.<id>.max_velocity_<unit>_s`, `max_acceleration_<unit>_s2` and
137/// `max_jerk_<unit>_s3`.
138fn axis(
139    cfg: &Config,
140    id: &'static str,
141    key: &'static str,
142    unit: &'static str,
143    (min, max): (f64, f64),
144) -> Result<AxisInfo, ConfigError> {
145    let get = |what: &str, rate: &str| cfg.positive(&format!("axis.{id}.max_{what}_{unit}_{rate}"));
146    Ok(AxisInfo {
147        id,
148        key,
149        unit,
150        min,
151        max,
152        max_vel: get("velocity", "s")?,
153        max_acc: get("acceleration", "s2")?,
154        max_jerk: get("jerk", "s3")?,
155    })
156}
157
158/// A joint machine of one joint (with its gear lever, `None` where it has no converter, and its unit) and its axis.
159/// A joint that turns on (`turns_on`: a crank, a knife roll, a disc, an indexer's driver) has no stops of its own: the
160/// axis range (`joint.min_angle_deg`, `max_angle_deg`) is what the cycle and paths may use, and a cam may run it on
161/// past that range, or ramp it down there when it is taken away. End stops are optional: `joint.stop_min_deg` /
162/// `joint.stop_max_deg` put the joint's stops (`effects.hard_stops`, `joint.stop_*`) at those angles, either alone or
163/// both.
164fn machine<M: Mechanism + 'static>(
165    cfg: &Config,
166    mechanism: M,
167    (mut drive, gear_lever, unit): (RotaryJoint, Option<f64>, &'static str),
168    axis: AxisInfo,
169    turns_on: bool,
170) -> Result<Box<dyn Machine>, ConfigError> {
171    if turns_on {
172        let stop = |key: &str, none: f64| -> Result<f64, ConfigError> {
173            if cfg.get(key).is_ok() { cfg.f64(key).map(f64::to_radians) } else { Ok(none) }
174        };
175        drive.range = (stop("joint.stop_min_deg", -1e12)?, stop("joint.stop_max_deg", 1e12)?);
176        if drive.range.0 >= drive.range.1 {
177            return Err(ConfigError::Invalid("joint.stop_min_deg".into()));
178        }
179    }
180    let spec = JointSpec { drive, id: MOTOR_IDS[0], key: JOINT_KEYS[0], gear_lever, unit };
181    sim_components::base::mount(
182        cfg,
183        Box::new(JointMachine::new(
184            mechanism,
185            vec![spec],
186            cfg.bool("effects.joint_elasticity")?,
187            ThermalFeedback::from_config(cfg)?,
188            vec![axis],
189            vec![MotorInfo { id: MOTOR_IDS[0], key: MOTOR_KEYS[0] }],
190        )),
191    )
192}
193
194/// A table of `<prefix>.<at>` against `<prefix>.<value>`, two arrays of the same length with `at` rising: linear between
195/// its points and 0 outside them (a press force that starts and ends with the table).
196#[derive(Debug, Clone, Default)]
197struct Table {
198    at: Vec<f64>,
199    value: Vec<f64>,
200}
201
202impl Table {
203    fn from_config(cfg: &Config, at: &str, value: &str) -> Result<Self, ConfigError> {
204        let read = |key: &str| -> Result<Vec<f64>, ConfigError> {
205            cfg.array(key)?
206                .iter()
207                .map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)))
208                .map(|f| f.filter(|f| sim_core::config::number(*f, key).is_ok()))
209                .collect::<Option<Vec<_>>>()
210                .ok_or_else(|| ConfigError::Type(key.into()))
211        };
212        let (a, v) = (read(at)?, read(value)?);
213        if a.is_empty() || a.len() != v.len() || a.windows(2).any(|w| w[1] <= w[0]) {
214            return Err(ConfigError::Invalid(at.into()));
215        }
216        Ok(Self { at: a, value: v })
217    }
218
219    fn at(&self, x: f64) -> f64 {
220        let (a, v) = (&self.at, &self.value);
221        if a.is_empty() || x < a[0] || x > a[a.len() - 1] {
222            return 0.0;
223        }
224        let i = a.partition_point(|p| *p <= x).clamp(1, a.len().max(2) - 1);
225        if a.len() == 1 {
226            return v[0];
227        }
228        let u = (x - a[i - 1]) / (a[i] - a[i - 1]);
229        v[i - 1] + u * (v[i] - v[i - 1])
230    }
231}
232
233/// The share of a process force that acts at speed `v` in the direction it works in: 0 at rest, below `smoothing` and
234/// backwards, 1 from twice `smoothing` on, linear between: the force fades out where the motion turns, not in a step,
235/// and a tool at rest in the material does not chatter against it on the speed loop's noise.
236fn forwards(v: f64, smoothing: f64) -> f64 {
237    (v / smoothing - 1.0).clamp(0.0, 1.0)
238}
239
240#[cfg(test)]
241mod disc_tests;
242#[cfg(test)]
243mod indexer_tests;
244#[cfg(test)]
245mod tests;
246#[cfg(test)]
247mod toggle_tests;