Skip to main content

sim_opcua/
plcopen.rs

1//! One axis as PLCopen motion sees it: the function blocks MC_Power, MC_Home, MC_MoveAbsolute, MC_MoveRelative,
2//! MC_Stop and MC_Reset, and of synchronised motion MC_GearIn, MC_GearOut, MC_CamIn and MC_CamOut, as handshake
3//! variables, and the axis state machine behind them.
4//!
5//! Each axis runs its own profile here and the link streams the positions to the controller with
6//! `Command::Setpoint`, one per setpoint interval, as a PLC drives servo drives over a fieldbus. So axes move
7//! independently and at the same time, MC_Stop brakes in the middle of a move, and a new move takes over from
8//! the one under way at the position and speed the axis has.
9//!
10//! The profile is a trapezoid: velocity, acceleration and deceleration are kept, jerk is not. The controller
11//! interpolates linearly between the streamed setpoints, so within one interval the speed is constant anyway.
12//! Parameters above the axis limits are cut to the limits.
13//!
14//! Synchronised motion (PLCopen Motion Control Part 1): the blocks sit in the slave's folder and name their master by
15//! its axis id (`GearIn.Master`, `CamIn.Master`). The slave follows the master's setpoint (MasterValueSource
16//! mcSetValue) in the same setpoint interval, the master moved first (`advance_all`). MC_GearIn brings the slave's
17//! speed to the ratio times the master's with its Acceleration (its Deceleration where the slave has to slow down),
18//! then holds the slave on the master's travel times the ratio: `InGear`. MC_CamIn holds the slave on the cam table at
19//! the master's position from its start: `InSync`. The table is the client's (`CamIn.Table`, CamTableID 0) or the
20//! machine's own electronic cam for this axis (CamTableID 1, `Machine::cam`), whose master may also be the machine's
21//! virtual one (`CamIn.Master` empty), run up to the cam's master speed. MC_GearOut and MC_CamOut end the coupling:
22//! the slave goes on at its speed (ContinuousMotion) until another block takes it over. Another block started on the
23//! slave aborts the coupling; a master that goes into ErrorStop or Disabled ends it with an error, the slave braking.
24
25use opcua::types::Variant;
26use sim_components::cam::{Cam, Law, Segment};
27use sim_core::{AxisInfo, CamMaster};
28
29/// PLCopen axis states, numbered as in TwinCAT's `MC_AxisStates`.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub enum State {
32    Disabled = 1,
33    Standstill = 2,
34    ErrorStop = 3,
35    Stopping = 4,
36    Homing = 5,
37    DiscreteMotion = 6,
38    ContinuousMotion = 7,
39    SynchronizedMotion = 8,
40}
41
42/// The function blocks with an `Execute` input, in this order, and their numeric inputs.
43pub const FBS: [&str; 9] =
44    ["Home", "MoveAbsolute", "MoveRelative", "Stop", "Reset", "GearIn", "GearOut", "CamIn", "CamOut"];
45const HOME: usize = 0;
46const MOVE_ABSOLUTE: usize = 1;
47const STOP: usize = 3;
48const RESET: usize = 4;
49const GEAR_IN: usize = 5;
50const GEAR_OUT: usize = 6;
51const CAM_IN: usize = 7;
52const CAM_OUT: usize = 8;
53/// The block of a motion no block reports on any more: the braking left by a refused re-trigger.
54const UNOWNED: usize = usize::MAX;
55const PARAMS: [&[&str]; 9] = [
56    &[],
57    &["Position", "Velocity", "Acceleration", "Deceleration", "Jerk"],
58    &["Distance", "Velocity", "Acceleration", "Deceleration", "Jerk"],
59    &["Deceleration"],
60    &[],
61    &["RatioNumerator", "RatioDenominator", "Acceleration", "Deceleration", "Jerk"],
62    &[],
63    &["MasterOffset", "SlaveOffset", "MasterScaling", "SlaveScaling", "StartMode", "CamTableID"],
64    &[],
65];
66/// The text inputs, block and name: the master's axis id and the client's cam table.
67pub const TEXTS: [(usize, &str); 3] = [(GEAR_IN, "Master"), (CAM_IN, "Master"), (CAM_IN, "Table")];
68
69/// `ErrorID` values.
70pub const ERR_NOT_POWERED: u16 = 1;
71pub const ERR_STATE: u16 = 2;
72pub const ERR_PARAMETER: u16 = 3;
73pub const ERR_RANGE: u16 = 4;
74pub const ERR_BUSY: u16 = 5;
75pub const ERR_REFUSED: u16 = 6;
76pub const ERR_DRIVES_OFF: u16 = 7;
77/// The drives went off because the machine ran into an obstacle (effects.crash).
78pub const ERR_CRASH: u16 = 8;
79/// MC_GearIn, MC_CamIn: no axis of that id, the slave itself, a master that is a slave itself, or no virtual master
80/// (the machine has no cam); or the master went into ErrorStop or Disabled while coupled.
81pub const ERR_MASTER: u16 = 9;
82/// MC_CamIn: the client's cam table cannot be read, or the machine has no cam of its own (CamTableID 1).
83pub const ERR_TABLE: u16 = 10;
84
85/// A function block's inputs and outputs. `Active` reads the same as `Busy`: there is no buffering. `done` is
86/// MC_GearIn's `InGear` and MC_CamIn's `InSync`, true beside `busy` while the slave is coupled.
87#[derive(Debug, Clone, Default)]
88pub struct Fb {
89    pub execute: bool,
90    pub done: bool,
91    pub busy: bool,
92    pub aborted: bool,
93    pub error: bool,
94    pub error_id: u16,
95    pub params: [f64; 6],
96}
97
98/// A slave's master: an axis by its index, or the machine's virtual cam master, run up `t` seconds ago from `from`.
99#[derive(Debug, Clone)]
100enum Master {
101    Axis(usize),
102    Virtual { run: CamMaster, t: f64, from: f64 },
103}
104
105/// How a slave follows its master.
106#[derive(Debug, Clone)]
107enum Coupling {
108    /// MC_GearIn: the ratio, whether the slave runs at the master's speed times it, and where the master stood.
109    Gear { ratio: f64, in_gear: bool, master_at: f64 },
110    /// MC_CamIn: the slave at `slave_ref + slave_scale * cam(master_scale * (m - master_ref) + master_offset)`.
111    Cam { cam: Cam, master_ref: f64, master_offset: f64, master_scale: f64, slave_ref: f64, slave_scale: f64 },
112}
113
114#[derive(Debug, Clone)]
115struct Motion {
116    fb: usize,
117    /// `None` brakes to a stop.
118    target: Option<f64>,
119    vel: f64,
120    acc: f64,
121    dec: f64,
122    /// Synchronised motion: the master and the coupling. The profile above is not used, but `dec` brakes where the
123    /// coupling ends with an error.
124    sync: Option<(Master, Coupling)>,
125    /// After MC_GearOut or MC_CamOut: the slave goes on at its speed (ContinuousMotion).
126    keeps: bool,
127}
128
129impl Motion {
130    fn profile(fb: usize, target: Option<f64>, vel: f64, acc: f64, dec: f64) -> Self {
131        Self { fb, target, vel, acc, dec, sync: None, keeps: false }
132    }
133}
134
135/// A cam table as the client writes it (`CamIn.Table`): lines of segments `master span, slave rise, law` (the laws of
136/// `Law::from_name`), or of points `master, slave[, slope]` (`sim_components::cam::parse_table`). `None` where it
137/// cannot be read.
138pub fn cam_table(text: &str) -> Option<Cam> {
139    let rows: Vec<Vec<&str>> = text
140        .lines()
141        .map(|l| l.split(',').map(str::trim).collect::<Vec<_>>())
142        .filter(|f| f[0].parse::<f64>().is_ok())
143        .collect();
144    if rows.iter().any(|f| f.len() == 3 && Law::from_name(f[2]).is_some()) {
145        let segments = rows
146            .iter()
147            .map(|f| match f[..] {
148                [master, slave, law] => Some(Segment {
149                    master: master.parse().ok()?,
150                    slave: slave.parse().ok()?,
151                    law: Law::from_name(law)?,
152                }),
153                _ => None,
154            })
155            .collect::<Option<Vec<_>>>()?;
156        return Cam::from_segments(&segments).ok();
157    }
158    Cam::from_table(&sim_components::cam::parse_table(text).ok()?).ok()
159}
160
161#[derive(Debug, Clone)]
162pub struct Axis {
163    info: AxisInfo,
164    home: f64,
165    /// MC_Power.Enable.
166    pub enable: bool,
167    pub fbs: [Fb; 9],
168    pub homed: bool,
169    /// The axis error; not 0 is ErrorStop.
170    pub error_id: u16,
171    /// The setpoint streamed to the controller, and its speed.
172    pub pos: f64,
173    pub vel: f64,
174    motion: Option<Motion>,
175    /// MC_Stop has been executed and its Execute is still held, or it still brakes.
176    stopping: bool,
177    /// The text inputs of `TEXTS`, in their order.
178    pub texts: [String; 3],
179    /// The machine's own electronic cam with this axis its slave (`Machine::cam`): the table over one master period,
180    /// and its master's speed and run-up. MC_CamIn takes it with CamTableID 1.
181    pub own_cam: Option<(Cam, CamMaster)>,
182}
183
184impl Axis {
185    /// An axis standing at `home`, the position MC_Home moves to. The numeric inputs start at the axis limits.
186    pub fn new(info: &AxisInfo, home: f64) -> Self {
187        let mut fbs: [Fb; 9] = Default::default();
188        for (fb, params) in fbs.iter_mut().zip(PARAMS) {
189            for (value, name) in fb.params.iter_mut().zip(params) {
190                *value = match *name {
191                    "Velocity" => info.max_vel,
192                    "Acceleration" | "Deceleration" => info.max_acc,
193                    "Jerk" => info.max_jerk,
194                    "Position" => home,
195                    "RatioNumerator" | "RatioDenominator" | "MasterScaling" | "SlaveScaling" | "StartMode" => 1.0,
196                    _ => 0.0,
197                };
198            }
199        }
200        Self {
201            info: info.clone(),
202            home,
203            enable: false,
204            fbs,
205            homed: false,
206            error_id: 0,
207            pos: home,
208            vel: 0.0,
209            motion: None,
210            stopping: false,
211            texts: Default::default(),
212            own_cam: None,
213        }
214    }
215
216    pub fn state(&self) -> State {
217        match &self.motion {
218            _ if self.error_id != 0 => State::ErrorStop,
219            _ if !self.enable => State::Disabled,
220            Some(m) if m.fb == HOME => State::Homing,
221            // MC_Stop's own braking, or MC_Stop done with its Execute held; never with another block's motion.
222            _ if self.stopping => State::Stopping,
223            Some(m) if m.sync.is_some() => State::SynchronizedMotion,
224            Some(m) if m.keeps => State::ContinuousMotion,
225            Some(_) => State::DiscreteMotion,
226            None => State::Standstill,
227        }
228    }
229
230    /// The axis this one follows as a slave, where its master is an axis.
231    pub fn master(&self) -> Option<usize> {
232        match self.motion.as_ref()?.sync.as_ref()? {
233            (Master::Axis(i), _) => Some(*i),
234            (Master::Virtual { .. }, _) => None,
235        }
236    }
237
238    /// A text input by its name after the block's (`GearIn.Master`, `CamIn.Master`, `CamIn.Table`), taken on the
239    /// block's rising edge. False for no such input.
240    pub fn set_text(&mut self, name: &str, value: String) -> bool {
241        let Some(k) = TEXTS.iter().position(|(fb, text)| name.split_once('.') == Some((FBS[*fb], *text))) else {
242            return false;
243        };
244        self.texts[k] = value;
245        true
246    }
247
248    pub fn moving(&self) -> bool {
249        self.motion.is_some()
250    }
251
252    /// The axis's variables as (name, value, writable), always in the same order. `drives_on` says whether the
253    /// controller's drives are on, `actual` is the simulated axis's position and velocity.
254    pub fn variables(&self, drives_on: bool, actual: (f64, f64)) -> Vec<(String, Variant, bool)> {
255        let status = self.enable && drives_on;
256        // Also with Enable off: the axis stays in ErrorStop until MC_Reset (PLCopen state diagram), and MC_Power says so.
257        let error = self.error_id != 0;
258        let mut out: Vec<(String, Variant, bool)> = vec![
259            ("Power.Enable".into(), self.enable.into(), true),
260            ("Power.Status".into(), status.into(), false),
261            ("Power.Valid".into(), (status && self.error_id == 0).into(), false),
262            ("Power.Error".into(), error.into(), false),
263            ("Power.ErrorID".into(), (if error { self.error_id } else { 0 }).into(), false),
264        ];
265        for (k, ((name, fb), params)) in FBS.iter().zip(&self.fbs).zip(PARAMS).enumerate() {
266            out.push((format!("{name}.Execute"), fb.execute.into(), true));
267            for (param, value) in params.iter().zip(fb.params) {
268                out.push((format!("{name}.{param}"), value.into(), true));
269            }
270            for ((_, text), value) in TEXTS.iter().zip(&self.texts).filter(|((fb, _), _)| *fb == k) {
271                out.push((format!("{name}.{text}"), value.as_str().into(), true));
272            }
273            let done = match k {
274                GEAR_IN => "InGear",
275                CAM_IN => "InSync",
276                _ => "Done",
277            };
278            for (output, value) in [
279                (done, fb.done),
280                ("Busy", fb.busy),
281                ("Active", fb.busy),
282                ("CommandAborted", fb.aborted),
283                ("Error", fb.error),
284            ] {
285                out.push((format!("{name}.{output}"), value.into(), false));
286            }
287            out.push((format!("{name}.ErrorID"), fb.error_id.into(), false));
288        }
289        let state = self.state();
290        out.extend([
291            ("State".into(), format!("{state:?}").into(), false),
292            ("StateID".into(), (state as i32).into(), false),
293            ("ActualPosition".into(), actual.0.into(), false),
294            ("ActualVelocity".into(), actual.1.into(), false),
295            ("IsHomed".into(), self.homed.into(), false),
296            ("Error".into(), (self.error_id != 0).into(), false),
297            ("ErrorID".into(), self.error_id.into(), false),
298        ]);
299        out
300    }
301
302    /// Ends the motion under way: its function block reports `CommandAborted`, or `Error` with `error`.
303    fn end_motion(&mut self, error: u16) {
304        if let Some(m) = self.motion.take()
305            && let Some(fb) = self.fbs.get_mut(m.fb)
306        {
307            (fb.busy, fb.aborted, fb.error, fb.error_id) = (false, error == 0, error != 0, error);
308        }
309        self.vel = 0.0;
310    }
311
312    /// An axis error: ErrorStop until MC_Reset.
313    pub fn fault(&mut self, error: u16) {
314        self.end_motion(error);
315        (self.error_id, self.stopping) = (error, false);
316    }
317
318    /// MC_Power.Enable. Switched off, a motion under way is aborted.
319    pub fn power(&mut self, on: bool) {
320        if !on {
321            self.end_motion(0);
322            self.stopping = false;
323        }
324        self.enable = on;
325    }
326
327    /// A numeric input, by its name after the function block's (`MoveAbsolute.Position`). False for no such input.
328    pub fn set_param(&mut self, name: &str, value: f64) -> bool {
329        let Some((fb, param)) = name.split_once('.') else { return false };
330        let Some(k) = FBS.iter().position(|f| *f == fb) else { return false };
331        let Some(p) = PARAMS[k].iter().position(|n| *n == param) else { return false };
332        self.fbs[k].params[p] = value;
333        true
334    }
335
336    /// `Execute` of function block `k` written. A rising edge starts it with the inputs it has then; `setpoint` is where
337    /// the controller's setpoint stands, `busy` whether the controller runs a move, path or cycle of the link's other
338    /// commands. A falling edge clears the outputs of a block that has finished; one still busy runs on and keeps its
339    /// outputs until the next rising edge.
340    /// A block of synchronised motion has no master here (`execute_in` gives it one).
341    pub fn execute(&mut self, k: usize, on: bool, setpoint: f64, busy: bool) {
342        self.execute_with(k, on, setpoint, busy, Err(ERR_MASTER));
343    }
344
345    /// `execute` with the master MC_GearIn and MC_CamIn would couple to: an axis (its index and where its setpoint
346    /// stands), `None` for the machine's virtual cam master, or why there is none.
347    fn execute_with(
348        &mut self,
349        k: usize,
350        on: bool,
351        setpoint: f64,
352        busy: bool,
353        master: Result<Option<(usize, f64)>, u16>,
354    ) {
355        let rising = on && !self.fbs[k].execute;
356        self.fbs[k].execute = on;
357        if !on {
358            if !self.fbs[k].busy {
359                let fb = &mut self.fbs[k];
360                (fb.done, fb.aborted, fb.error, fb.error_id) = (false, false, false, 0);
361            }
362            if k == STOP && self.motion.as_ref().is_none_or(|m| m.fb != STOP) {
363                self.stopping = false;
364            }
365            return;
366        }
367        if !rising {
368            return;
369        }
370        let fb = &mut self.fbs[k];
371        (fb.done, fb.aborted, fb.error, fb.error_id) = (false, false, false, 0);
372        if k == RESET {
373            self.error_id = 0;
374            self.fbs[k].done = true;
375            return;
376        }
377        let state = self.state();
378        let refuse = match state {
379            State::ErrorStop => ERR_STATE,
380            State::Disabled => ERR_NOT_POWERED,
381            State::Stopping if k != STOP => ERR_STATE,
382            State::Homing if k != STOP => ERR_STATE,
383            State::DiscreteMotion | State::ContinuousMotion | State::SynchronizedMotion if k == HOME => ERR_STATE,
384            _ if k == GEAR_OUT && !self.coupled_by(GEAR_IN) => ERR_STATE,
385            _ if k == CAM_OUT && !self.coupled_by(CAM_IN) => ERR_STATE,
386            _ if busy => ERR_BUSY,
387            _ => 0,
388        };
389        if k == GEAR_OUT || k == CAM_OUT {
390            self.decouple(k, refuse);
391            return;
392        }
393        if k == GEAR_IN || k == CAM_IN {
394            self.couple(k, refuse, setpoint, master);
395            return;
396        }
397        let p = self.fbs[k].params;
398        let a = &self.info;
399        // `min` would turn NaN into the limit: what is not a number stays one, to be refused below.
400        let cut = |v: f64, max: f64| if v.is_finite() { v.min(max) } else { f64::NAN };
401        let (target, vel, acc, dec) = match k {
402            HOME => (Some(self.home), 0.5 * a.max_vel, 0.5 * a.max_acc, 0.5 * a.max_acc),
403            STOP => (None, a.max_vel, a.max_acc, cut(p[0], a.max_acc)),
404            _ => {
405                let start = if self.moving() { self.pos } else { setpoint };
406                (
407                    Some(if k == MOVE_ABSOLUTE { p[0] } else { start + p[0] }),
408                    cut(p[1], a.max_vel),
409                    cut(p[2], a.max_acc),
410                    cut(p[3], a.max_acc),
411                )
412            }
413        };
414        let valid = [vel, acc, dec].iter().all(|v| v.is_finite() && *v > 0.0) && target.is_none_or(f64::is_finite);
415        let refuse = match target {
416            _ if refuse != 0 => refuse,
417            _ if !valid => ERR_PARAMETER,
418            Some(t) if t < a.min || t > a.max => ERR_RANGE,
419            _ => 0,
420        };
421        if refuse != 0 {
422            self.refused(k, refuse);
423            return;
424        }
425        self.take_over(k, setpoint, k == STOP, Motion::profile(k, target, vel, acc, dec));
426    }
427
428    /// Block `k` refused with `error`. Re-triggered while busy, the block gives up its motion, so that it reports Error
429    /// alone (Done, Busy, Error and CommandAborted are exclusive), and the axis brakes to a stop with the motion's
430    /// deceleration, a motion no block reports on, which a new move may take over (PLCopen Part 1 leaves this case
431    /// open). A coupling given up so brakes the slave too.
432    fn refused(&mut self, k: usize, error: u16) {
433        if self.fbs[k].busy
434            && let Some(m) = &mut self.motion
435        {
436            (m.fb, m.target, m.sync, m.keeps) = (UNOWNED, None, None, false);
437        }
438        let fb = &mut self.fbs[k];
439        (fb.busy, fb.done, fb.error, fb.error_id) = (false, false, true, error);
440    }
441
442    /// A new motion of block `k` takes over the one under way at its position and speed.
443    fn take_over(&mut self, k: usize, setpoint: f64, stopping: bool, motion: Motion) {
444        let (pos, vel_now) = if self.moving() { (self.pos, self.vel) } else { (setpoint, 0.0) };
445        self.end_motion(0);
446        (self.pos, self.vel, self.stopping) = (pos, vel_now, stopping);
447        // A block started again while busy is not aborted by itself.
448        (self.fbs[k].busy, self.fbs[k].aborted) = (true, false);
449        self.motion = Some(motion);
450    }
451
452    /// Whether the axis is coupled by block `k` (MC_GearIn or MC_CamIn).
453    fn coupled_by(&self, k: usize) -> bool {
454        self.motion.as_ref().is_some_and(|m| m.fb == k && m.sync.is_some())
455    }
456
457    /// MC_GearIn or MC_CamIn started: the coupling to `master` (see `execute_with`).
458    fn couple(&mut self, k: usize, refuse: u16, setpoint: f64, master: Result<Option<(usize, f64)>, u16>) {
459        let (p, a) = (self.fbs[k].params, &self.info);
460        let pos = if self.moving() { self.pos } else { setpoint };
461        let cut = |v: f64, max: f64| if v.is_finite() { v.min(max) } else { f64::NAN };
462        let positive = |v: f64| v.is_finite() && v > 0.0;
463        let finite_nonzero = |v: f64| v.is_finite() && v != 0.0;
464        // The master and where it stands, the coupling, and the deceleration that brakes the slave where it ends.
465        let coupled = || -> Result<(Master, Coupling, [f64; 2]), u16> {
466            if refuse != 0 {
467                return Err(refuse);
468            }
469            let master = master?;
470            if k == GEAR_IN {
471                let (ratio, acc, dec) = (p[0] / p[1], cut(p[2], a.max_acc), cut(p[3], a.max_acc));
472                let (Some((m, at)), true) = (master, finite_nonzero(ratio) && positive(acc) && positive(dec)) else {
473                    return Err(if master.is_none() { ERR_MASTER } else { ERR_PARAMETER });
474                };
475                return Ok((Master::Axis(m), Coupling::Gear { ratio, in_gear: false, master_at: at }, [acc, dec]));
476            }
477            let [master_offset, slave_offset, master_scale, slave_scale, mode, table] = p;
478            if !(master_offset.is_finite() && slave_offset.is_finite())
479                || !finite_nonzero(master_scale)
480                || !finite_nonzero(slave_scale)
481                || !(mode == 0.0 || mode == 1.0)
482            {
483                return Err(ERR_PARAMETER);
484            }
485            let cam = match table {
486                0.0 => cam_table(&self.texts[2]).ok_or(ERR_TABLE)?,
487                1.0 => self.own_cam.as_ref().ok_or(ERR_TABLE)?.0.clone(),
488                _ => return Err(ERR_PARAMETER),
489            };
490            let (master, at) = match master {
491                Some((m, at)) => (Master::Axis(m), at),
492                // The machine's virtual master, from rest at 0.
493                None => {
494                    let run = self.own_cam.as_ref().ok_or(ERR_MASTER)?.1;
495                    (Master::Virtual { run, t: 0.0, from: 0.0 }, 0.0)
496                }
497            };
498            // Absolute: where the table puts the slave now, where it has to stand (no ramp-in); relative: from where
499            // master and slave stand.
500            let (master_ref, slave_ref) = if mode == 0.0 {
501                let wanted = slave_offset + slave_scale * cam.at(master_scale * at + master_offset)[0];
502                if (wanted - pos).abs() > 1e-6 {
503                    return Err(ERR_RANGE);
504                }
505                (0.0, slave_offset)
506            } else {
507                (at, pos - slave_scale * cam.at(master_offset)[0])
508            };
509            let coupling = Coupling::Cam { cam, master_ref, master_offset, master_scale, slave_ref, slave_scale };
510            Ok((master, coupling, [a.max_acc, a.max_acc]))
511        };
512        match coupled() {
513            Err(error) => self.refused(k, error),
514            Ok((master, coupling, [acc, dec])) => {
515                let motion =
516                    Motion { sync: Some((master, coupling)), ..Motion::profile(k, None, self.info.max_vel, acc, dec) };
517                self.take_over(k, setpoint, false, motion);
518                // A cam is in sync from its start; a gear once the slave's speed has come to the master's.
519                self.fbs[k].done = k == CAM_IN;
520            }
521        }
522    }
523
524    /// MC_GearOut or MC_CamOut: the coupling ends, the slave goes on at its speed until another block takes it over;
525    /// the coupling block is no longer busy, and not aborted.
526    fn decouple(&mut self, k: usize, refuse: u16) {
527        if refuse != 0 {
528            let fb = &mut self.fbs[k];
529            (fb.error, fb.error_id) = (true, refuse);
530            return;
531        }
532        if let Some(m) = &mut self.motion {
533            let from = m.fb;
534            (m.fb, m.sync, m.keeps) = (UNOWNED, None, true);
535            (self.fbs[from].busy, self.fbs[from].done) = (false, false);
536        }
537        self.fbs[k].done = true;
538    }
539
540    /// A slave's interval `t` at its master's new place and speed; `lost` where the master went into ErrorStop or
541    /// Disabled: the coupling ends with ErrorID 9 and the slave brakes with the coupling's deceleration.
542    fn follow(&mut self, t: f64, (at, speed): (f64, f64), lost: bool) {
543        let Some(m) = &mut self.motion else { return };
544        let k = m.fb;
545        if lost {
546            (m.fb, m.target, m.sync) = (UNOWNED, None, None);
547            let fb = &mut self.fbs[k];
548            (fb.busy, fb.done, fb.error, fb.error_id) = (false, false, true, ERR_MASTER);
549            return self.advance(t, self.pos);
550        }
551        let (acc, dec) = (m.acc, m.dec);
552        match m.sync.as_mut().map(|(_, c)| c) {
553            Some(Coupling::Gear { ratio, in_gear, master_at }) => {
554                let wanted = *ratio * speed;
555                if *in_gear {
556                    // Geared: the master's travel times the ratio, exactly.
557                    self.pos += *ratio * (at - *master_at);
558                    self.vel = wanted;
559                } else {
560                    let braking = wanted.abs() < self.vel.abs() || wanted * self.vel < 0.0;
561                    let dv = if braking { dec } else { acc } * t;
562                    self.vel = wanted.clamp(self.vel - dv, self.vel + dv);
563                    self.pos += self.vel * t;
564                    *in_gear = self.vel == wanted;
565                    self.fbs[k].done = *in_gear;
566                }
567                *master_at = at;
568            }
569            Some(Coupling::Cam { cam, master_ref, master_offset, master_scale, slave_ref, slave_scale }) => {
570                let s = cam.at(*master_scale * (at - *master_ref) + *master_offset);
571                self.pos = *slave_ref + *slave_scale * s[0];
572                self.vel = *slave_scale * s[1] * *master_scale * speed;
573            }
574            None => {}
575        }
576    }
577
578    /// One setpoint interval `t` of the profile. Without a motion the axis follows `setpoint`, where the controller's
579    /// setpoint stands, so that the link's other commands and other axes' moves do not leave it behind.
580    pub fn advance(&mut self, t: f64, setpoint: f64) {
581        let Some(m) = &mut self.motion else {
582            (self.pos, self.vel) = (setpoint, 0.0);
583            return;
584        };
585        if m.keeps {
586            self.pos += self.vel * t;
587            return;
588        }
589        // The virtual master runs on; an axis master's slave follows in `advance_all`.
590        if let Some((Master::Virtual { run, t: since, from }, _)) = &mut m.sync {
591            *since += t;
592            let now = sim_components::cam::master_change(0.0, run.speed, run.ramp_s, *since, None);
593            let master = (*from + now[0], now[1]);
594            return self.follow(t, master, false);
595        }
596        if m.sync.is_some() {
597            return;
598        }
599        let m = &*m;
600        let v_wanted = match m.target {
601            None => 0.0,
602            Some(target) => {
603                // The highest speed from which steps of this grid still brake to a stop at the target, and no step
604                // beyond it.
605                let s = target - self.pos;
606                let brake = m.dec * t * ((0.25 + 2.0 * s.abs() / (m.dec * t * t)).sqrt() - 0.5);
607                s.signum() * m.vel.min(brake).min(s.abs() / t)
608            }
609        };
610        let braking = v_wanted.abs() < self.vel.abs() || v_wanted * self.vel < 0.0;
611        let dv = if braking { m.dec } else { m.acc } * t;
612        let vel = v_wanted.clamp(self.vel - dv, self.vel + dv);
613        // Braking ends at standstill: going on the other way is acceleration, from the next interval on.
614        self.vel = if vel * self.vel < 0.0 { 0.0 } else { vel };
615        self.pos += self.vel * t;
616        if let Some(target) = m.target
617            && (target - self.pos).abs() < 1e-12
618        {
619            self.pos = target;
620        }
621        if self.vel == 0.0 && m.target.is_none_or(|target| self.pos == target) {
622            let k = m.fb;
623            self.motion = None;
624            if let Some(fb) = self.fbs.get_mut(k) {
625                (fb.busy, fb.done) = (false, true);
626            }
627            self.homed |= k == HOME;
628            self.stopping = k == STOP && self.fbs[k].execute;
629        }
630    }
631}
632
633/// `Execute` of block `k` of axis `i` written (`Axis::execute`), with MC_GearIn's and MC_CamIn's master found among
634/// `axes` by its id: not the slave itself, and no slave of an axis itself (`ERR_MASTER` else); an empty id is the
635/// machine's virtual cam master (MC_CamIn only).
636pub fn execute_in(axes: &mut [Axis], i: usize, k: usize, on: bool, setpoint: f64, busy: bool) {
637    let name = match k {
638        GEAR_IN => &axes[i].texts[0],
639        CAM_IN => &axes[i].texts[1],
640        _ => return axes[i].execute(k, on, setpoint, busy),
641    };
642    let master = match axes.iter().position(|a| a.info.id == name.trim()) {
643        _ if name.trim().is_empty() => {
644            if k == CAM_IN {
645                Ok(None)
646            } else {
647                Err(ERR_MASTER)
648            }
649        }
650        Some(j) if j != i && axes[j].master().is_none() => Ok(Some((j, axes[j].pos))),
651        _ => Err(ERR_MASTER),
652    };
653    axes[i].execute_with(k, on, setpoint, busy, master);
654}
655
656/// One setpoint interval `t` of every axis (`Axis::advance`, `setpoints` where the controller's setpoint stands for
657/// each): the axes that follow no axis first, then the slaves at their masters' new places.
658pub fn advance_all(axes: &mut [Axis], t: f64, setpoints: &[f64]) {
659    for (axis, at) in axes.iter_mut().zip(setpoints) {
660        if axis.master().is_none() {
661            axis.advance(t, *at);
662        }
663    }
664    for i in 0..axes.len() {
665        if let Some(j) = axes[i].master() {
666            let lost = matches!(axes[j].state(), State::ErrorStop | State::Disabled);
667            let master = (axes[j].pos, axes[j].vel);
668            axes[i].follow(t, master, lost);
669        }
670    }
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676
677    fn axis() -> Axis {
678        let info =
679            AxisInfo { id: "x", key: "", unit: "m", min: 0.0, max: 1.0, max_vel: 1.0, max_acc: 10.0, max_jerk: 100.0 };
680        let mut axis = Axis::new(&info, 0.1);
681        axis.power(true);
682        axis
683    }
684
685    /// Runs until the motion is over and returns the steps taken; checks speed and acceleration on the way.
686    fn run(axis: &mut Axis, vel: f64, acc: f64) -> usize {
687        let t = 0.01;
688        for n in 0..10_000 {
689            if !axis.moving() {
690                return n;
691            }
692            let (before, at) = (axis.vel, axis.pos);
693            axis.advance(t, 0.0);
694            assert!(axis.vel.abs() <= vel + 1e-12, "{}", axis.vel);
695            assert!((axis.vel - before).abs() <= acc * t + 1e-9, "{} after {before}", axis.vel);
696            assert!((axis.pos - at - axis.vel * t).abs() < 1e-12);
697        }
698        panic!("the motion did not end");
699    }
700
701    /// A move arrives exactly, from rest to rest, within the limits, in about the time a trapezoid takes.
702    #[test]
703    fn moves_arrive_exactly_within_the_limits() {
704        for target in [0.9, 0.1001, 0.5, 0.0] {
705            let mut a = axis();
706            a.set_param("MoveAbsolute.Position", target);
707            a.set_param("MoveAbsolute.Velocity", 0.5);
708            a.set_param("MoveAbsolute.Acceleration", 5.0);
709            a.set_param("MoveAbsolute.Deceleration", 2.0);
710            a.execute(MOVE_ABSOLUTE, true, 0.1, false);
711            assert_eq!(a.state(), State::DiscreteMotion);
712            let n = run(&mut a, 0.5, 5.0);
713            assert_eq!((a.pos, a.vel), (target, 0.0));
714            assert!(a.fbs[1].done && !a.fbs[1].busy && a.state() == State::Standstill);
715            // A trapezoid's time: with or without reaching 0.5 m/s.
716            let (d, r) = ((target - 0.1f64).abs(), 1.0 / 5.0 + 1.0 / 2.0);
717            let ideal = if d > 0.5 * 0.5 * r / 2.0 { d / 0.5 + 0.5 * r / 2.0 } else { (2.0 * d * r).sqrt() };
718            assert!((n as f64 * 0.01 - ideal).abs() < 0.05, "{target}: {n} steps, {ideal} s");
719        }
720    }
721
722    /// MC_Stop brakes a move with its deceleration and the move reports CommandAborted; the axis stays in Stopping
723    /// while Execute is held, and a move in Stopping is refused.
724    #[test]
725    fn stop_brakes_and_aborts_the_move() {
726        let mut a = axis();
727        a.set_param("MoveAbsolute.Position", 0.9);
728        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
729        for _ in 0..30 {
730            a.advance(0.01, 0.0);
731        }
732        let v = a.vel;
733        a.set_param("Stop.Deceleration", 4.0);
734        a.execute(STOP, true, 0.0, false);
735        assert!(a.fbs[1].aborted && !a.fbs[1].busy && a.fbs[STOP].busy);
736        let n = run(&mut a, 1.0, 4.0);
737        assert!((n as f64 * 0.01 - v / 4.0).abs() < 0.02, "{n} steps from {v} m/s");
738        assert!(a.fbs[STOP].done && a.state() == State::Stopping);
739        a.execute(MOVE_ABSOLUTE, false, 0.0, false);
740        a.execute(MOVE_ABSOLUTE, true, 0.0, false);
741        assert_eq!((a.fbs[1].error, a.fbs[1].error_id), (true, ERR_STATE));
742        a.execute(STOP, false, 0.0, false);
743        assert_eq!(a.state(), State::Standstill);
744    }
745
746    /// A new move takes over a move under way at its speed, also one that must turn round.
747    #[test]
748    fn a_new_move_takes_over_at_speed() {
749        let mut a = axis();
750        a.set_param("MoveAbsolute.Position", 0.9);
751        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
752        for _ in 0..30 {
753            a.advance(0.01, 0.0);
754        }
755        let (v, p) = (a.vel, a.pos);
756        a.set_param("MoveRelative.Distance", -0.2);
757        a.execute(2, true, 0.0, false);
758        assert_eq!((a.vel, a.pos), (v, p));
759        assert!(a.fbs[1].aborted && a.fbs[2].busy);
760        run(&mut a, 1.0, 10.0);
761        assert!((a.pos - (p - 0.2)).abs() < 1e-12 && a.fbs[2].done);
762    }
763
764    /// Execute starts on its rising edge only; a block that finished clears its outputs on the falling edge.
765    #[test]
766    fn execute_is_edge_triggered() {
767        let mut a = axis();
768        a.set_param("MoveRelative.Distance", 0.1);
769        a.execute(2, true, 0.1, false);
770        run(&mut a, 1.0, 10.0);
771        a.execute(2, true, a.pos, false);
772        assert!(!a.moving() && a.fbs[2].done, "held Execute started it again");
773        a.execute(2, false, a.pos, false);
774        assert!(!a.fbs[2].done);
775        a.execute(2, true, a.pos, false);
776        run(&mut a, 1.0, 10.0);
777        assert!((a.pos - 0.3).abs() < 1e-12);
778    }
779
780    /// Refusals: not powered, out of range, bad parameters; an axis error holds until MC_Reset.
781    #[test]
782    fn refusals_and_reset() {
783        let mut a = axis();
784        a.power(false);
785        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
786        assert_eq!(a.fbs[1].error_id, ERR_NOT_POWERED);
787        a.power(true);
788        a.execute(MOVE_ABSOLUTE, false, 0.1, false);
789        a.set_param("MoveAbsolute.Position", 2.0);
790        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
791        assert_eq!(a.fbs[1].error_id, ERR_RANGE);
792        a.execute(MOVE_ABSOLUTE, false, 0.1, false);
793        a.set_param("MoveAbsolute.Position", 0.5);
794        a.set_param("MoveAbsolute.Velocity", 0.0);
795        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
796        assert_eq!(a.fbs[1].error_id, ERR_PARAMETER);
797        a.fault(ERR_REFUSED);
798        assert_eq!(a.state(), State::ErrorStop);
799        a.execute(RESET, true, 0.1, false);
800        assert!(a.fbs[RESET].done && a.state() == State::Standstill);
801    }
802
803    /// NaN and infinite numeric inputs are refused, not cut to the axis limits.
804    #[test]
805    fn nan_and_infinite_inputs_are_refused() {
806        for (fb, name) in
807            [(MOVE_ABSOLUTE, "Velocity"), (MOVE_ABSOLUTE, "Acceleration"), (2, "Deceleration"), (STOP, "Deceleration")]
808        {
809            for bad in [f64::NAN, f64::INFINITY] {
810                let mut a = axis();
811                a.set_param("MoveAbsolute.Position", 0.5);
812                a.set_param(&format!("{}.{name}", FBS[fb]), bad);
813                a.execute(fb, true, 0.1, false);
814                assert_eq!((a.fbs[fb].error_id, a.moving()), (ERR_PARAMETER, false), "{}.{name} = {bad}", FBS[fb]);
815            }
816        }
817    }
818
819    /// Execute falling while busy and rising again restarts the block: it does not abort itself.
820    #[test]
821    fn a_block_started_again_does_not_abort_itself() {
822        let mut a = axis();
823        a.set_param("MoveRelative.Distance", 0.3);
824        a.execute(2, true, 0.1, false);
825        for _ in 0..10 {
826            a.advance(0.01, 0.0);
827        }
828        a.execute(2, false, 0.0, false);
829        assert!(a.fbs[2].busy);
830        let at = a.pos;
831        a.execute(2, true, 0.0, false);
832        assert!(a.fbs[2].busy && !a.fbs[2].aborted);
833        run(&mut a, 1.0, 10.0);
834        assert!(a.fbs[2].done && !a.fbs[2].aborted);
835        assert!((a.pos - at - 0.3).abs() < 1e-12);
836    }
837
838    /// A reversal from a speed residue near zero accelerates the other way with Acceleration, not Deceleration.
839    #[test]
840    fn a_reversal_through_zero_accelerates_with_acceleration() {
841        let mut a = axis();
842        a.set_param("MoveAbsolute.Position", 0.9);
843        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
844        a.set_param("MoveRelative.Distance", -0.1);
845        a.set_param("MoveRelative.Acceleration", 1.0);
846        a.set_param("MoveRelative.Deceleration", 10.0);
847        a.execute(2, true, 0.0, false);
848        a.vel = 1e-15;
849        a.advance(0.01, 0.0);
850        assert!(a.vel <= 0.0 && a.vel >= -0.01 - 1e-12, "{} m/s after one step", a.vel);
851    }
852
853    /// Takeover by another move, MC_Stop in the middle of a move, a block started again and a reversal, one after
854    /// the other: every step keeps the speed and acceleration of the motion under way, and each ends exactly.
855    #[test]
856    fn takeover_stop_restart_and_reversal_keep_the_limits() {
857        let t = 0.01;
858        let mut a = axis();
859        // Each step: the motion's velocity, acceleration and deceleration bound it; braking through zero is two parts.
860        let step = |a: &mut Axis, n: usize, (vel, acc, dec): (f64, f64, f64)| {
861            // Without a motion the axis would follow the setpoint 0 given here.
862            for _ in 0..n {
863                if !a.moving() {
864                    break;
865                }
866                let before = a.vel;
867                a.advance(t, 0.0);
868                assert!(a.vel.abs() <= vel + 1e-12, "{} m/s", a.vel);
869                let dv = a.vel - before;
870                let limit = if a.vel * before < 0.0 || a.vel.abs() > before.abs() { acc } else { dec };
871                assert!(dv.abs() <= limit * t + 1e-9, "{before} -> {} m/s", a.vel);
872            }
873        };
874        let params = |a: &mut Axis, fb: &str, v: f64, acc: f64, dec: f64| {
875            a.set_param(&format!("{fb}.Velocity"), v);
876            a.set_param(&format!("{fb}.Acceleration"), acc);
877            a.set_param(&format!("{fb}.Deceleration"), dec);
878        };
879        params(&mut a, "MoveAbsolute", 0.8, 4.0, 4.0);
880        a.set_param("MoveAbsolute.Position", 0.9);
881        a.execute(MOVE_ABSOLUTE, true, 0.1, false);
882        step(&mut a, 25, (0.8, 4.0, 4.0));
883        // Taken over by a relative move backwards: brakes with its deceleration, turns with its acceleration.
884        params(&mut a, "MoveRelative", 0.5, 1.0, 8.0);
885        a.set_param("MoveRelative.Distance", -0.2);
886        a.execute(2, true, 0.0, false);
887        assert!(a.fbs[1].aborted && a.fbs[2].busy);
888        step(&mut a, 20, (0.8, 1.0, 8.0));
889        assert!(a.vel < 0.0, "turned round");
890        // MC_Stop in the middle of it.
891        a.set_param("Stop.Deceleration", 2.0);
892        a.execute(STOP, true, 0.0, false);
893        assert!(a.fbs[2].aborted && a.state() == State::Stopping);
894        step(&mut a, 200, (0.5, 2.0, 2.0));
895        assert!(!a.moving() && a.vel == 0.0 && a.fbs[STOP].done);
896        a.execute(STOP, false, 0.0, false);
897        // Started again in the middle of its move, MoveRelative counts from where the axis is then.
898        a.execute(2, false, 0.0, false);
899        a.set_param("MoveRelative.Distance", 0.3);
900        a.execute(2, true, a.pos, false);
901        step(&mut a, 15, (0.5, 1.0, 8.0));
902        a.execute(2, false, 0.0, false);
903        let at = a.pos;
904        a.execute(2, true, 0.0, false);
905        assert!(a.fbs[2].busy && !a.fbs[2].aborted);
906        step(&mut a, 300, (0.5, 1.0, 8.0));
907        assert!(
908            !a.moving() && a.fbs[2].done && !a.fbs[2].aborted && (a.pos - at - 0.3).abs() < 1e-12,
909            "{} from {at}, {:?}",
910            a.pos,
911            a.fbs[2]
912        );
913    }
914
915    /// Two powered axes on a stroke of 0 to 10 m, up to 1 m/s and 100 m/s2: x the master at 1, y the slave at 2.
916    fn pair() -> Vec<Axis> {
917        let info =
918            |id| AxisInfo { id, key: "", unit: "m", min: 0.0, max: 10.0, max_vel: 1.0, max_acc: 100.0, max_jerk: 1e4 };
919        let mut axes = vec![Axis::new(&info("x"), 1.0), Axis::new(&info("y"), 2.0)];
920        axes.iter_mut().for_each(|a| a.power(true));
921        axes
922    }
923
924    /// The master x moving at `speed` (up to it within one interval of 10 ms), slave y standing.
925    fn master_at_speed(axes: &mut [Axis], speed: f64) {
926        axes[0].set_param("MoveAbsolute.Position", 9.0);
927        axes[0].set_param("MoveAbsolute.Velocity", speed);
928        execute_in(axes, 0, MOVE_ABSOLUTE, true, 1.0, false);
929        advance_all(axes, 0.01, &[1.0, 2.0]);
930        assert_eq!(axes[0].vel, speed);
931    }
932
933    /// MC_GearIn at ratio 2 (RatioNumerator 2, RatioDenominator 1) to a master running at 0.1 m/s, Acceleration 1 m/s2:
934    /// the slave's speed rises by 1 * 0.01 = 0.01 m/s per interval of 10 ms to 2 * 0.1 = 0.2 m/s, which it reaches in
935    /// the 20th interval, 0.2 s = 0.2 / 1 after the start: InGear then, Busy and Active on. On the way it has gone
936    /// 0.01 * (0.01 + 0.02 + ... + 0.2) = 0.021 m (a continuous ramp would go 0.2^2 / 2 = 0.02 m); geared, it goes
937    /// twice the master's travel, 0.1 m over the master's 0.05 m.
938    #[test]
939    fn gear_in_reaches_in_gear_at_ratio_2_after_its_acceleration() {
940        let mut axes = pair();
941        master_at_speed(&mut axes, 0.1);
942        axes[1].set_text("GearIn.Master", "x".into());
943        axes[1].set_param("GearIn.RatioNumerator", 2.0);
944        axes[1].set_param("GearIn.RatioDenominator", 1.0);
945        axes[1].set_param("GearIn.Acceleration", 1.0);
946        execute_in(&mut axes, 1, GEAR_IN, true, 2.0, false);
947        assert!(axes[1].fbs[GEAR_IN].busy && !axes[1].fbs[GEAR_IN].done);
948        assert_eq!((axes[1].state(), axes[1].master()), (State::SynchronizedMotion, Some(0)));
949        let mut intervals = 0;
950        while !axes[1].fbs[GEAR_IN].done {
951            advance_all(&mut axes, 0.01, &[0.0, 0.0]);
952            intervals += 1;
953            assert!(intervals < 100);
954        }
955        assert_eq!(intervals, 20);
956        assert!((axes[1].vel - 0.2).abs() < 1e-12 && axes[1].fbs[GEAR_IN].busy, "{}", axes[1].vel);
957        assert!((axes[1].pos - 2.021).abs() < 1e-12, "{}", axes[1].pos);
958        let (m, s) = (axes[0].pos, axes[1].pos);
959        for _ in 0..50 {
960            advance_all(&mut axes, 0.01, &[0.0, 0.0]);
961        }
962        assert!((axes[1].pos - s - 2.0 * (axes[0].pos - m)).abs() < 1e-12 && (axes[0].pos - m - 0.05).abs() < 1e-12);
963        let names: Vec<String> = axes[1].variables(true, (0.0, 0.0)).into_iter().map(|v| v.0).collect();
964        assert!(names.contains(&"GearIn.InGear".into()) && names.contains(&"GearIn.Master".into()));
965        assert!(!names.contains(&"GearIn.Done".into()) && names.contains(&"GearOut.Done".into()));
966
967        // MC_GearOut: the slave goes on at 0.2 m/s, ContinuousMotion, GearIn no longer busy and not aborted.
968        execute_in(&mut axes, 1, GEAR_OUT, true, 0.0, false);
969        assert!(axes[1].fbs[GEAR_OUT].done && !axes[1].fbs[GEAR_IN].busy && !axes[1].fbs[GEAR_IN].aborted);
970        assert_eq!(axes[1].state(), State::ContinuousMotion);
971        let at = axes[1].pos;
972        advance_all(&mut axes, 0.01, &[0.0, 0.0]);
973        assert!((axes[1].pos - at - 0.002).abs() < 1e-12);
974        // A GearOut with nothing geared is refused in that state; MC_Stop takes the slave over.
975        execute_in(&mut axes, 1, GEAR_OUT, false, 0.0, false);
976        execute_in(&mut axes, 1, GEAR_OUT, true, 0.0, false);
977        assert_eq!(axes[1].fbs[GEAR_OUT].error_id, ERR_STATE);
978        execute_in(&mut axes, 1, STOP, true, 0.0, false);
979        assert_eq!(axes[1].state(), State::Stopping);
980    }
981
982    /// MC_CamIn, relative, with the client's table of a 3-4-5 rise of 0.1 m over 0.5 m of master and the 3-4-5 back
983    /// over the next 0.5 m, the master at 0.2 m/s: InSync from the start; after 0.25 m of master (125 intervals of 10 ms)
984    /// the slave has risen by half, 0.05 m, at 1.875 * 0.1 / 0.5 * 0.2 = 0.075 m/s; after 0.5 m by 0.1 m, at rest; a
985    /// period on (1 m), back where it began. Started with a master that is no axis, or with a table that cannot be
986    /// read, it is refused with ErrorID 9 and 10.
987    #[test]
988    fn cam_in_follows_a_3_4_5_table_at_the_master_s_speed() {
989        let mut axes = pair();
990        master_at_speed(&mut axes, 0.2);
991        let m0 = axes[0].pos;
992        axes[1].set_text("CamIn.Master", "x".into());
993        axes[1].set_text("CamIn.Table", "span, rise, law\n0.5, 0.1, 3-4-5\n0.5, -0.1, 3-4-5\n".into());
994        execute_in(&mut axes, 1, CAM_IN, true, 2.0, false);
995        let fb = &axes[1].fbs[CAM_IN];
996        assert!(fb.busy && fb.done && !fb.error, "{fb:?}");
997        let ticks = |axes: &mut Vec<Axis>, n: usize| (0..n).for_each(|_| advance_all(axes, 0.01, &[0.0, 0.0]));
998        ticks(&mut axes, 125);
999        assert!((axes[0].pos - m0 - 0.25).abs() < 1e-12);
1000        let (pos, vel) = (axes[1].pos, axes[1].vel);
1001        assert!((pos - 2.05).abs() < 1e-12 && (vel - 0.075).abs() < 1e-12, "{pos} {vel}");
1002        ticks(&mut axes, 125);
1003        assert!((axes[1].pos - 2.1).abs() < 1e-12 && axes[1].vel.abs() < 1e-12);
1004        ticks(&mut axes, 250);
1005        assert!((axes[1].pos - 2.0).abs() < 1e-12);
1006        // MC_CamOut; then refusals.
1007        execute_in(&mut axes, 1, CAM_OUT, true, 0.0, false);
1008        assert!(axes[1].fbs[CAM_OUT].done && axes[1].state() == State::ContinuousMotion);
1009        let mut b = pair();
1010        b[1].set_text("CamIn.Master", "z".into());
1011        b[1].set_text("CamIn.Table", "0.5, 0.1, 3-4-5\n0.5, -0.1, 3-4-5".into());
1012        execute_in(&mut b, 1, CAM_IN, true, 2.0, false);
1013        assert_eq!(b[1].fbs[CAM_IN].error_id, ERR_MASTER);
1014        b[1].set_text("CamIn.Master", "x".into());
1015        b[1].set_text("CamIn.Table", "0.5, 0.1, three".into());
1016        execute_in(&mut b, 1, CAM_IN, false, 2.0, false);
1017        execute_in(&mut b, 1, CAM_IN, true, 2.0, false);
1018        assert_eq!(b[1].fbs[CAM_IN].error_id, ERR_TABLE);
1019    }
1020
1021    /// A master switched off while its slave is geared ends the coupling with ErrorID 9: the slave brakes with GearIn's
1022    /// Deceleration (5 m/s2, from 0.5 m/s by 0.05 m/s in the first interval of 10 ms) to a stop. A GearIn started again
1023    /// on the slave with a ratio of 0 is refused, reports Error alone and gives up its coupling: the slave brakes the
1024    /// same way, in DiscreteMotion, owned by no block.
1025    #[test]
1026    fn a_lost_master_and_a_refused_gear_in_end_the_coupling_with_an_error() {
1027        for lose in [true, false] {
1028            let mut axes = pair();
1029            master_at_speed(&mut axes, 0.5);
1030            axes[1].set_text("GearIn.Master", "x".into());
1031            axes[1].set_param("GearIn.Deceleration", 5.0);
1032            execute_in(&mut axes, 1, GEAR_IN, true, 2.0, false);
1033            (0..100).for_each(|_| advance_all(&mut axes, 0.01, &[0.0, 0.0]));
1034            assert!(axes[1].fbs[GEAR_IN].done && (axes[1].vel - 0.5).abs() < 1e-12);
1035            if lose {
1036                axes[0].power(false);
1037            } else {
1038                execute_in(&mut axes, 1, GEAR_IN, false, 0.0, false);
1039                axes[1].set_param("GearIn.RatioNumerator", 0.0);
1040                execute_in(&mut axes, 1, GEAR_IN, true, 0.0, false);
1041            }
1042            advance_all(&mut axes, 0.01, &[0.0, 0.0]);
1043            let fb = &axes[1].fbs[GEAR_IN];
1044            let id = if lose { ERR_MASTER } else { ERR_PARAMETER };
1045            assert!(fb.error && fb.error_id == id && !fb.busy && !fb.done && !fb.aborted, "{fb:?}");
1046            assert_eq!(axes[1].state(), State::DiscreteMotion);
1047            assert!((axes[1].vel - 0.45).abs() < 1e-12, "{}", axes[1].vel);
1048            (0..20).for_each(|_| advance_all(&mut axes, 0.01, &[0.0, 0.0]));
1049            assert!(!axes[1].moving() && axes[1].state() == State::Standstill);
1050        }
1051    }
1052
1053    /// MC_CamIn on the machine's own cam (CamTableID 1) with its virtual master (`CamIn.Master` empty): a slave that
1054    /// runs one to one with a master of 2 m/s, run up over 0.5 s by the sin^2 ramp. After 1.5 s the master has gone
1055    /// 2 * (1.5 - 0.5 / 2) = 2.5 m and the slave with it, at 2 m/s. Without a cam of its own the axis refuses it.
1056    #[test]
1057    fn cam_in_runs_the_machine_s_own_cam_on_its_virtual_master() {
1058        let mut axes = pair();
1059        let one_to_one = Cam::from_segments(&[Segment { master: 1.0, slave: 1.0, law: Law::Linear }]).unwrap();
1060        axes[1].set_param("CamIn.CamTableID", 1.0);
1061        execute_in(&mut axes, 1, CAM_IN, true, 2.0, false);
1062        assert_eq!(axes[1].fbs[CAM_IN].error_id, ERR_TABLE);
1063        execute_in(&mut axes, 1, CAM_IN, false, 2.0, false);
1064        axes[1].own_cam = Some((one_to_one, CamMaster { speed: 2.0, period: 1.0, ramp_s: 0.5 }));
1065        execute_in(&mut axes, 1, CAM_IN, true, 2.0, false);
1066        assert!(axes[1].fbs[CAM_IN].done && axes[1].master().is_none());
1067        assert_eq!(axes[1].state(), State::SynchronizedMotion);
1068        (0..150).for_each(|_| advance_all(&mut axes, 0.01, &[1.0, 2.0]));
1069        assert!((axes[1].pos - 4.5).abs() < 1e-9 && (axes[1].vel - 2.0).abs() < 1e-12, "{}", axes[1].pos);
1070    }
1071}