Skip to main content

sim_opcua/
lib.rs

1//! PLC link: the simulator as an OPC UA server. A PLC (or any client) sends targets and setpoints
2//! and reads back every signal. The servo loops stay inside the simulator; OPC UA is far too slow
3//! to close them.
4//!
5//! The variables are generated from the simulation's signal list, never written per machine:
6//!
7//! | node (string id in the simulator's namespace) | type    | access | meaning                                   |
8//! | --------------------------------------------- | ------- | ------ | ----------------------------------------- |
9//! | `signal.<signal id>`                          | Double  | read   | every signal of the simulation            |
10//! | `command.target.<axis id>`                    | Double  | write  | target of the next point-to-point move    |
11//! | `command.move`                                | Boolean | write  | true starts the move to the targets       |
12//! | `command.setpoint.<axis id>`                  | Double  | write  | streamed position setpoint, interpolated  |
13//! | `command.cycle`                               | Boolean | write  | true starts the cycle, false stops it     |
14//! | `command.disable`                             | Boolean | write  | true switches the drives off (brakes on)  |
15//! | `command.enable`                              | Boolean | write  | true switches the drives on again         |
16//! | `command.stop_category`                       | Int32   | write  | 0, 1 or 2 stops the machine in that stop category (`Command::Halt`) |
17//! | `command.path`                                | String  | write  | a path, in the text of a path file        |
18//! | `command.path_time_optimal`                   | Boolean | write  | plan the path as fast as the motors allow |
19//! | `command.run_path`                            | Boolean | write  | true plans `command.path` and runs it     |
20//! | `status.busy`                                 | Boolean | read   | a move, path or the cycle is under way    |
21//! | `status.refused`                              | String  | read   | key of the last refused command, or empty |
22//!
23//! An axis the PLC does not write stays where it is: `command.target.<axis id>` reads the planned position
24//! until it is written, and again after the move it was written for; `command.setpoint.<axis id>` reads the
25//! setpoint the controller follows, which is the planned position whenever no setpoint is on its way. So a
26//! write to one axis never carries an old value for the others.
27//!
28//! The path is planned from where the machine stands when `command.run_path` arrives, as
29//! `Sim::plan_path` plans it (format: see `sim_components::path`). A path that cannot be read is refused with
30//! `opcua-error-path-line`; one that cannot be planned or run with the key the planner or the controller gives.
31//!
32//! `status.refused` keeps a refusal until a command of the same kind (move, setpoint, cycle start, ...) is
33//! accepted. Accepted commands of another kind, such as a stream of setpoints, do not wipe it.
34//!
35//! Next to these, every axis has PLCopen motion function blocks as handshake variables (see `plcopen` and
36//! docs/plc.md), in the folder `axis.<axis id>`:
37//!
38//! | node                                     | type    | access | meaning                                           |
39//! | ---------------------------------------- | ------- | ------ | ------------------------------------------------- |
40//! | `axis.<id>.Power.Enable`                 | Boolean | write  | MC_Power: true powers the axis                    |
41//! | `axis.<id>.Power.Status`, `.Valid`       | Boolean | read   | drives on; on and without error                   |
42//! | `axis.<id>.Power.Error`, `.ErrorID`      | Boolean, UInt16 | read | the axis error (ErrorStop), also unpowered |
43//! | `axis.<id>.<FB>.Execute`                 | Boolean | write  | rising edge starts FB = Home, MoveAbsolute, MoveRelative, Stop, Reset, GearIn, GearOut, CamIn, CamOut |
44//! | `axis.<id>.GearIn.Master`, `.CamIn.Master`, `.CamIn.Table` | String | write | the master's axis id; the client's cam table |
45//! | `axis.<id>.GearIn.RatioNumerator`, ..., `.CamIn.CamTableID` | Double | write | inputs of GearIn and CamIn, taken on the rising edge |
46//! | `axis.<id>.MoveAbsolute.Position`, `.Velocity`, `.Acceleration`, `.Deceleration`, `.Jerk` | Double | write | inputs, taken on the rising edge |
47//! | `axis.<id>.MoveRelative.Distance`, ...   | Double  | write  | as for MoveAbsolute                               |
48//! | `axis.<id>.Stop.Deceleration`            | Double  | write  | braking deceleration of MC_Stop                   |
49//! | `axis.<id>.<FB>.Done`, `.Busy`, `.Active`, `.CommandAborted`, `.Error` | Boolean | read | outputs (`InGear`, `InSync` for GearIn, CamIn) |
50//! | `axis.<id>.<FB>.ErrorID`                 | UInt16  | read   | why the block failed, 0 without error             |
51//! | `axis.<id>.State`, `.StateID`            | String, Int32 | read | PLCopen state (Disabled 1, Standstill 2, ErrorStop 3, Stopping 4, Homing 5, DiscreteMotion 6, ContinuousMotion 7, SynchronizedMotion 8) |
52//! | `axis.<id>.ActualPosition`, `.ActualVelocity` | Double | read | from the simulated axis                      |
53//! | `axis.<id>.IsHomed`, `.Error`, `.ErrorID` | Boolean, Boolean, UInt16 | read | homed; the axis error (ErrorStop) |
54//!
55//! The loop's real-time pacing is measured from the wall-clock times of its ticks, since the start or the last
56//! `command.reset_pacing`:
57//!
58//! | node                         | type    | access | meaning                                                   |
59//! | ---------------------------- | ------- | ------ | --------------------------------------------------------- |
60//! | `status.cycle_s`             | Double  | read   | the loop's nominal cycle                                  |
61//! | `status.cycle_period_s`      | Double  | read   | mean measured time between ticks                          |
62//! | `status.jitter_max_s`        | Double  | read   | largest deviation of a tick period from the cycle         |
63//! | `status.jitter_rms_s`        | Double  | read   | root mean square of that deviation                        |
64//! | `status.overruns`            | UInt64  | read   | ticks that came more than a whole cycle late              |
65//! | `status.cycles`              | UInt64  | read   | ticks measured                                            |
66//! | `status.realtime_factor`     | Double  | read   | simulated time over wall-clock time                       |
67//! | `status.steps`               | UInt64  | read   | simulation steps since the start                          |
68//! | `command.reset_pacing`       | Boolean | write  | true starts the measurement anew                          |
69//!
70//! The clients' cycle, from the arrival times of their Read and Write requests (`ClientTiming`), reset with the pacing:
71//!
72//! | node                                                   | type    | access | meaning                                |
73//! | ------------------------------------------------------ | ------- | ------ | -------------------------------------- |
74//! | `status.client_writes`, `status.client_reads`          | UInt64  | read   | intervals measured                     |
75//! | `status.client_write_mean_s`, `status.client_read_mean_s` | Double | read  | mean interval                          |
76//! | `status.client_write_std_s`, `status.client_read_std_s`   | Double | read  | standard deviation of the intervals    |
77//! | `status.client_write_max_s`, `status.client_read_max_s`   | Double | read  | largest interval                       |
78//!
79//! Endpoints, certificates and users: see `Security`. docs/plc.md has the IEC 61131-3 type of every node.
80
81pub mod plcopen;
82
83use opcua::crypto::SecurityPolicy;
84use opcua::server::address_space::{AccessLevel, AddressSpace, VariableBuilder};
85use opcua::server::diagnostics::NamespaceMetadata;
86use opcua::server::node_manager::memory::{
87    InMemoryNodeManager, InMemoryNodeManagerBuilder, InMemoryNodeManagerImpl, InMemoryNodeManagerImplBuilder,
88    SimpleNodeManagerBuilder, SimpleNodeManagerImpl,
89};
90use opcua::server::node_manager::{
91    MonitoredItemRef, MonitoredItemUpdateRef, ParsedReadValueId, RequestContext, ServerContext, WriteNode,
92};
93use opcua::server::{ANONYMOUS_USER_TOKEN_ID, CreateMonitoredItem, ServerBuilder, ServerHandle, ServerUserToken};
94use opcua::sync::RwLock;
95use opcua::types::{
96    DataTypeId, DataValue, MessageSecurityMode, MonitoringMode, NodeId, ObjectId, StatusCode, TimestampsToReturn,
97    Variant,
98};
99use plcopen::{Axis, ERR_CRASH, ERR_DRIVES_OFF, ERR_REFUSED, FBS};
100use sim_components::cam::Cam;
101use sim_components::{Command, Sim};
102use sim_core::{Config, MachineEntry, Translations};
103use std::path::{Path, PathBuf};
104use std::sync::mpsc::{Receiver, Sender, channel};
105use std::sync::{Arc, Mutex};
106use std::time::{Duration, Instant};
107use tokio::net::TcpListener;
108
109pub const NAMESPACE: &str = "urn:kinematics-simulation";
110
111/// (language code, translation file contents) for the link's own messages.
112pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
113
114/// A failure to start, as a translation key and a detail.
115#[derive(Debug)]
116pub struct LinkError(pub &'static str, pub String);
117
118/// What a client wrote.
119enum Input {
120    Target(usize, f64),
121    Move,
122    Setpoint(usize, f64),
123    Cycle(bool),
124    Disable,
125    Enable,
126    Halt(sim_components::StopCategory),
127    Path(String),
128    PathTimeOptimal(bool),
129    RunPath,
130    /// A PLCopen input of an axis: `Power.Enable`, `<FB>.Execute`, or a number such as `MoveAbsolute.Position`.
131    AxisFlag(usize, String, bool),
132    AxisNumber(usize, String, f64),
133    /// A text input of an axis: a master's axis id or a cam table (`plcopen::TEXTS`).
134    AxisText(usize, String, String),
135    ResetPacing,
136    /// `Link::run_trajectory`.
137    Trajectory(Vec<(f64, Vec<f64>)>),
138}
139
140/// The loop's real-time pacing, measured from the wall-clock times of its ticks since the last reset.
141#[derive(Debug, Clone, Default)]
142pub struct Pacing {
143    /// The nominal cycle.
144    pub cycle_s: f64,
145    pub cycles: u64,
146    pub wall_s: f64,
147    pub sim_s: f64,
148    jitter_square_sum: f64,
149    pub jitter_max_s: f64,
150    /// Ticks that came more than a whole cycle late.
151    pub overruns: u64,
152    /// Wall-clock time the loop did not simulate: what a tick came later than the most it makes up for (`simulate`).
153    /// `sim_s + lost_s` is `wall_s` to within a step on any host; `lost_s` is 0 on a host that keeps up.
154    pub lost_s: f64,
155}
156
157impl Pacing {
158    fn record(&mut self, period: f64, simulated: f64, lost: f64) {
159        let jitter = period - self.cycle_s;
160        self.cycles += 1;
161        self.wall_s += period;
162        self.sim_s += simulated;
163        self.lost_s += lost;
164        self.jitter_square_sum += jitter * jitter;
165        self.jitter_max_s = self.jitter_max_s.max(jitter.abs());
166        self.overruns += u64::from(period > 2.0 * self.cycle_s);
167    }
168
169    pub fn period_s(&self) -> f64 {
170        self.wall_s / self.cycles.max(1) as f64
171    }
172
173    pub fn jitter_rms_s(&self) -> f64 {
174        (self.jitter_square_sum / self.cycles.max(1) as f64).sqrt()
175    }
176
177    pub fn realtime_factor(&self) -> f64 {
178        if self.wall_s > 0.0 { self.sim_s / self.wall_s } else { 0.0 }
179    }
180}
181
182/// The time between consecutive requests of one kind (Read or Write) from the clients, since the last reset.
183#[derive(Debug, Clone, Default)]
184pub struct Intervals {
185    /// Intervals measured: one fewer than the requests.
186    pub count: u64,
187    sum_s: f64,
188    square_sum_s2: f64,
189    pub max_s: f64,
190    last: Option<Instant>,
191}
192
193impl Intervals {
194    /// A request arrived at `at`.
195    pub fn record(&mut self, at: Instant) {
196        if let Some(last) = self.last.replace(at) {
197            let interval = at.saturating_duration_since(last).as_secs_f64();
198            self.count += 1;
199            self.sum_s += interval;
200            self.square_sum_s2 += interval * interval;
201            self.max_s = self.max_s.max(interval);
202        }
203    }
204
205    pub fn mean_s(&self) -> f64 {
206        self.sum_s / self.count.max(1) as f64
207    }
208
209    /// Standard deviation of the intervals around their mean (of the population: divided by the count).
210    pub fn std_s(&self) -> f64 {
211        (self.square_sum_s2 / self.count.max(1) as f64 - self.mean_s().powi(2)).max(0.0).sqrt()
212    }
213}
214
215/// How regularly the clients read and write the simulator's variables: a PLC that reads and writes once a task cycle
216/// shows its cycle and jitter here. One Read or Write request counts once, however many variables it holds; reads of
217/// other attributes than the value (browsing) and subscriptions do not count.
218#[derive(Debug, Clone, Default)]
219pub struct ClientTiming {
220    pub reads: Intervals,
221    pub writes: Intervals,
222}
223
224/// The simple in-memory node manager, with the arrival of every Read and Write request timed.
225pub struct Timed {
226    simple: SimpleNodeManagerImpl,
227    clients: Arc<Mutex<ClientTiming>>,
228}
229
230#[async_trait::async_trait]
231impl InMemoryNodeManagerImpl for Timed {
232    async fn init(&self, address_space: &mut AddressSpace, context: ServerContext) {
233        self.simple.init(address_space, context).await
234    }
235
236    fn name(&self) -> &str {
237        self.simple.name()
238    }
239
240    fn namespaces(&self) -> Vec<NamespaceMetadata> {
241        self.simple.namespaces()
242    }
243
244    async fn read_values(
245        &self,
246        context: &RequestContext,
247        address_space: &RwLock<AddressSpace>,
248        nodes: &[&ParsedReadValueId],
249        max_age: f64,
250        timestamps_to_return: TimestampsToReturn,
251    ) -> Vec<DataValue> {
252        let arrived = Instant::now();
253        let values = self.simple.read_values(context, address_space, nodes, max_age, timestamps_to_return).await;
254        // Counted once answered: a read of the measurement is not in its own answer.
255        self.clients.lock().unwrap().reads.record(arrived);
256        values
257    }
258
259    async fn write(
260        &self,
261        context: &RequestContext,
262        address_space: &RwLock<AddressSpace>,
263        nodes_to_write: &mut [&mut WriteNode],
264    ) -> Result<(), StatusCode> {
265        // Before the write is carried out: `command.reset_pacing` clears what it is counted in.
266        self.clients.lock().unwrap().writes.record(Instant::now());
267        self.simple.write(context, address_space, nodes_to_write).await
268    }
269
270    async fn create_value_monitored_items(
271        &self,
272        context: &RequestContext,
273        address_space: &RwLock<AddressSpace>,
274        items: &mut [&mut &mut CreateMonitoredItem],
275    ) {
276        self.simple.create_value_monitored_items(context, address_space, items).await
277    }
278
279    async fn set_monitoring_mode(&self, context: &RequestContext, mode: MonitoringMode, items: &[&MonitoredItemRef]) {
280        self.simple.set_monitoring_mode(context, mode, items).await
281    }
282
283    async fn modify_monitored_items(&self, context: &RequestContext, items: &[&MonitoredItemUpdateRef]) {
284        self.simple.modify_monitored_items(context, items).await
285    }
286
287    async fn delete_monitored_items(&self, context: &RequestContext, items: &[&MonitoredItemRef]) {
288        self.simple.delete_monitored_items(context, items).await
289    }
290}
291
292/// The secured endpoints, each offered with `Sign` and with `SignAndEncrypt`: every policy async-opcua has that OPC UA
293/// does not deprecate (Basic128Rsa15 and Basic256 are, and are left out).
294pub const POLICIES: [(&str, SecurityPolicy); 3] = [
295    ("basic256sha256", SecurityPolicy::Basic256Sha256),
296    ("aes128_sha256_rsaoaep", SecurityPolicy::Aes128Sha256RsaOaep),
297    ("aes256_sha256_rsapss", SecurityPolicy::Aes256Sha256RsaPss),
298];
299
300/// How the server lets clients in. It offers at the same URL the security policy `None` and every policy of `POLICIES`
301/// with `Sign` and with `SignAndEncrypt`. Its application instance certificate (self-signed, valid for 365 days) is
302/// created in the pki folder on the first start: `own/cert.der` and `private/private.pem` (`certificate_days_left`,
303/// `renew_certificate`).
304#[derive(Debug, Clone, Default)]
305pub struct Security {
306    /// Accept every client certificate and store it in `<pki>/trusted` (for commissioning). Off, a client certificate
307    /// that is not in `<pki>/trusted` is refused and stored in `<pki>/rejected`, to be moved to `trusted` by hand.
308    pub trust_all: bool,
309    /// The user name and password a client may log in with.
310    pub user: Option<(String, String)>,
311    /// User certificates (X.509 user tokens, `.der` or `.pem`): a client that signs with the private key of one of them
312    /// logs in as that user, named after the file.
313    pub user_certs: Vec<PathBuf>,
314}
315
316impl Security {
317    /// Whether a client must log in. Then no client gets in anonymously and the endpoint without security is not
318    /// offered, so that a password never travels in clear.
319    pub fn logins(&self) -> bool {
320        self.user.is_some() || !self.user_certs.is_empty()
321    }
322}
323
324/// The server's application instance certificate in `pki_dir`, where async-opcua stores it.
325fn own_certificate(pki_dir: &Path) -> PathBuf {
326    pki_dir.join("own").join("cert.der")
327}
328
329/// Days until the server's certificate in `pki_dir` expires (negative once it has); `None` without one (the next start
330/// creates it).
331pub fn certificate_days_left(pki_dir: &Path) -> Option<f64> {
332    let cert = opcua::crypto::CertificateStore::read_cert(&own_certificate(pki_dir)).ok()?;
333    let end = cert.not_after().ok()?.timestamp() as f64;
334    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs_f64();
335    Some((end - now) / 86_400.0)
336}
337
338/// Sets the server's certificate and private key in `pki_dir` aside (`.old` beside them, replacing an older one), so
339/// that the next start creates new ones, valid for 365 days. Clients that trusted the old certificate must trust the
340/// new one. Nothing to do without one.
341pub fn renew_certificate(pki_dir: &Path) -> std::io::Result<()> {
342    for file in [own_certificate(pki_dir), pki_dir.join("private").join("private.pem")] {
343        if file.exists() {
344            let mut old = file.clone().into_os_string();
345            old.push(".old");
346            std::fs::rename(&file, old)?;
347        }
348    }
349    Ok(())
350}
351
352/// The config of `--config FILE` (or else the machine's default) with every `--set path=value` on top, read as sim-cli
353/// reads them; and the trajectory of `--trajectory FILE` (`sim_components::path::parse_trajectory`), to run at the start
354/// (`Link::run_trajectory`).
355pub fn configured(
356    entry: &MachineEntry,
357    config: Option<&Path>,
358    sets: &[String],
359    trajectory: Option<&Path>,
360) -> Result<(Config, Option<Vec<(f64, Vec<f64>)>>), LinkError> {
361    let read = |path: &Path| {
362        std::fs::read_to_string(path).map_err(|e| LinkError("opcua-error-file", format!("{}: {e}", path.display())))
363    };
364    let config_error = |e: sim_core::ConfigError| LinkError(e.key(), e.detail().into());
365    let mut cfg = match config {
366        Some(path) => sim_components::load_config(entry, &read(path)?).map_err(config_error)?,
367        None => entry.config(),
368    };
369    for assignment in sets {
370        sim_components::set_config_text(entry, &mut cfg, assignment).map_err(config_error)?;
371    }
372    let points = match trajectory {
373        Some(path) => Some(
374            sim_components::path::parse_trajectory(&read(path)?)
375                .map_err(|line| LinkError("opcua-error-file", format!("{}: {line}", path.display())))?,
376        ),
377        None => None,
378    };
379    Ok((cfg, points))
380}
381
382pub struct Link {
383    pub handle: ServerHandle,
384    /// Index of the simulator's namespace on this server.
385    pub namespace: u16,
386    pub pacing: Arc<Mutex<Pacing>>,
387    pub clients: Arc<Mutex<ClientTiming>>,
388    inputs: Sender<Input>,
389}
390
391impl Link {
392    /// Runs the poses at times `points` (`Command::Trajectory`) at the next tick; a refusal shows in `status.refused`.
393    pub fn run_trajectory(&self, points: Vec<(f64, Vec<f64>)>) {
394        let _ = self.inputs.send(Input::Trajectory(points));
395    }
396}
397
398impl Drop for Link {
399    fn drop(&mut self) {
400        self.handle.cancel();
401    }
402}
403
404/// A number a client wrote, of any IEC 61131-3 numeric type: LREAL, REAL, SINT, INT, DINT, LINT, USINT, UINT, UDINT,
405/// ULINT. A 64-bit integer beyond 2^53 is refused: a double would not hold it exactly.
406pub fn number(value: &DataValue) -> Option<f64> {
407    // Compared as integers: 2^53 + 1 as a double is already 2^53.
408    const EXACT: u64 = 1 << 53;
409    match value.value.as_ref()? {
410        Variant::Double(v) => Some(*v),
411        Variant::Float(v) => Some(*v as f64),
412        Variant::SByte(v) => Some(*v as f64),
413        Variant::Byte(v) => Some(*v as f64),
414        Variant::Int16(v) => Some(*v as f64),
415        Variant::UInt16(v) => Some(*v as f64),
416        Variant::Int32(v) => Some(*v as f64),
417        Variant::UInt32(v) => Some(*v as f64),
418        Variant::Int64(v) => (v.unsigned_abs() <= EXACT).then_some(*v as f64),
419        Variant::UInt64(v) => (*v <= EXACT).then_some(*v as f64),
420        _ => None,
421    }
422}
423
424fn text(value: &DataValue) -> Option<String> {
425    if let Some(Variant::String(s)) = &value.value { Some(s.as_ref().to_string()) } else { None }
426}
427
428fn flag(value: &DataValue) -> Option<bool> {
429    if let Some(Variant::Boolean(on)) = value.value { Some(on) } else { None }
430}
431
432/// Starts the server on `listener` and the simulation behind it, in real time, in ticks of `cycle`.
433/// `labels` names the variables for people browsing the server; `pki_dir` holds the server's keys.
434/// Anonymous clients, and only client certificates already trusted: `Security::default()`.
435pub async fn serve(
436    entry: &'static MachineEntry,
437    cfg: &Config,
438    labels: &Translations,
439    listener: TcpListener,
440    pki_dir: &Path,
441    cycle: Duration,
442) -> Result<Link, LinkError> {
443    serve_secured(entry, cfg, labels, listener, pki_dir, cycle, &Security::default()).await
444}
445
446/// `serve`, letting clients in as `security` says.
447pub async fn serve_secured(
448    entry: &'static MachineEntry,
449    cfg: &Config,
450    labels: &Translations,
451    listener: TcpListener,
452    pki_dir: &Path,
453    cycle: Duration,
454    security: &Security,
455) -> Result<Link, LinkError> {
456    let sim = Sim::new(entry, cfg).map_err(|e| LinkError(e.key(), e.detail().into()))?;
457    // The PLCopen axes stream one setpoint per setpoint interval, counted in simulation steps.
458    let interval = cfg.f64("profile.setpoint_interval_s").map_err(|e| LinkError(e.key(), e.detail().into()))?;
459    let stream_steps = ((interval / sim.dt).round() as u64).max(1);
460    let mut plc: Vec<Axis> =
461        sim.machine.axes().iter().zip(&sim.control.set_pos).map(|(info, home)| Axis::new(info, *home)).collect();
462    // The machine's own electronic cam, for MC_CamIn's CamTableID 1: each slave's table through 1440 points of the
463    // master's period with their slopes.
464    if let Some(run) = sim.machine.cam() {
465        let n = 1440;
466        let mut at = vec![[0.0; 4]; plc.len()];
467        let mut rows = vec![Vec::with_capacity(n + 1); plc.len()];
468        for k in 0..=n {
469            let m = run.period * k as f64 / n as f64;
470            sim.machine.cam_at(m, &mut at);
471            for (row, s) in rows.iter_mut().zip(&at) {
472                row.push((m, s[0], Some(s[1])));
473            }
474        }
475        for (axis, row) in plc.iter_mut().zip(&rows) {
476            axis.own_cam = Cam::from_table(row).ok().map(|cam| (cam, run));
477        }
478    }
479    let address = listener.local_addr().map_err(|e| LinkError("opcua-error-start", e.to_string()))?;
480    let clients = Arc::new(Mutex::new(ClientTiming::default()));
481    let timed = {
482        let clients = clients.clone();
483        move |context: ServerContext, space: &mut AddressSpace| Timed {
484            simple: SimpleNodeManagerBuilder::new(
485                NamespaceMetadata { namespace_uri: NAMESPACE.to_owned(), ..Default::default() },
486                "simulator",
487            )
488            .build(context, space),
489            clients,
490        }
491    };
492    let mut builder = ServerBuilder::new();
493    let mut user_tokens: Vec<String> = Vec::new();
494    if let Some((user, password)) = &security.user {
495        builder = builder.add_user_token("user", ServerUserToken::user_pass(user.as_str(), password.as_str()));
496        user_tokens.push("user".into());
497    }
498    for (i, path) in security.user_certs.iter().enumerate() {
499        // Read here: async-opcua passes over a certificate it cannot read without a word, and nobody could log in.
500        opcua::crypto::CertificateStore::read_cert(path)
501            .map_err(|_| LinkError("opcua-error-user-cert", path.display().to_string()))?;
502        let user = path.file_stem().map_or(String::new(), |s| s.to_string_lossy().into_owned());
503        let id = format!("x509-{i}");
504        builder = builder.add_user_token(id.clone(), ServerUserToken::x509(user, path));
505        user_tokens.push(id);
506    }
507    if user_tokens.is_empty() {
508        user_tokens.push(ANONYMOUS_USER_TOKEN_ID.into());
509    }
510    let user_tokens: Vec<&str> = user_tokens.iter().map(String::as_str).collect();
511    // With a login, no endpoint without security: async-opcua takes a password sent in clear (an empty encryption
512    // algorithm) even where the policy asks for it encrypted.
513    if !security.logins() {
514        builder =
515            builder.add_endpoint("none", ("/", SecurityPolicy::None, MessageSecurityMode::None, &user_tokens[..]));
516    }
517    for (name, policy) in POLICIES {
518        for (suffix, mode) in
519            [("sign", MessageSecurityMode::Sign), ("sign_encrypt", MessageSecurityMode::SignAndEncrypt)]
520        {
521            builder = builder.add_endpoint(format!("{name}_{suffix}"), ("/", policy, mode, &user_tokens[..]));
522        }
523    }
524    let (server, handle) = builder
525        .application_name("sim-opcua")
526        // Not the namespace URI: the application URI becomes namespace 1, and the same URI twice
527        // would make the variables' namespace index ambiguous.
528        .application_uri(format!("{NAMESPACE}:server"))
529        .product_uri(format!("{NAMESPACE}:server"))
530        .create_sample_keypair(true)
531        .pki_dir(pki_dir)
532        .trust_client_certs(security.trust_all)
533        .host(address.ip().to_string())
534        .port(address.port())
535        .discovery_urls(vec![format!("opc.tcp://{address}/")])
536        .default_endpoint(if security.logins() { "basic256sha256_sign_encrypt" } else { "none" })
537        .with_node_manager(InMemoryNodeManagerBuilder::new(timed))
538        .build()
539        .map_err(|e| LinkError("opcua-error-start", e.to_string()))?;
540    let manager = handle
541        .node_managers()
542        .get_of_type::<InMemoryNodeManager<Timed>>()
543        .ok_or(LinkError("opcua-error-start", String::new()))?;
544    let namespace = handle.get_namespace_index(NAMESPACE).ok_or(LinkError("opcua-error-start", String::new()))?;
545    let node = |name: String| NodeId::new(namespace, name);
546
547    // The address space, generated from the signal list and the machine's axes.
548    let signals = sim.signal_infos();
549    let axes: Vec<&'static str> = sim.machine.axes().iter().map(|a| a.id).collect();
550    let axis_keys: Vec<&'static str> = sim.machine.axes().iter().map(|a| a.key).collect();
551    let (inputs, inbox) = channel::<Input>();
552    {
553        let mut space = manager.address_space().write();
554        let folder = node("simulator".into());
555        space.add_folder(&folder, "simulator", labels.tr(entry.key), &NodeId::from(ObjectId::ObjectsFolder));
556        let add_to = |space: &mut opcua::server::address_space::AddressSpace,
557                      parent: &NodeId,
558                      id: &NodeId,
559                      name: &str,
560                      label: String,
561                      kind: DataTypeId,
562                      start: Variant,
563                      writable: bool| {
564            let variable = VariableBuilder::new(id, name, label).data_type(kind).value(start).organized_by(parent);
565            let access = if writable {
566                AccessLevel::CURRENT_READ | AccessLevel::CURRENT_WRITE
567            } else {
568                AccessLevel::CURRENT_READ
569            };
570            variable.access_level(access).user_access_level(access).insert(space);
571        };
572        for (i, axis) in plc.iter().enumerate() {
573            let parent = node(format!("axis.{}", axes[i]));
574            space.add_folder(
575                &parent,
576                format!("axis.{}", axes[i]).as_str(),
577                format!("{} · {}", labels.tr(axis_keys[i]), labels.tr("opcua-plcopen-axis")),
578                &folder,
579            );
580            for (name, start, writable) in axis.variables(true, (0.0, 0.0)) {
581                let kind = match start {
582                    Variant::Boolean(_) => DataTypeId::Boolean,
583                    Variant::UInt16(_) => DataTypeId::UInt16,
584                    Variant::Int32(_) => DataTypeId::Int32,
585                    Variant::String(_) => DataTypeId::String,
586                    _ => DataTypeId::Double,
587                };
588                let label = format!("{} · {name}", labels.tr(axis_keys[i]));
589                add_to(
590                    &mut space,
591                    &parent,
592                    &node(format!("axis.{}.{name}", axes[i])),
593                    &name,
594                    label,
595                    kind,
596                    start,
597                    writable,
598                );
599            }
600        }
601        let mut add = |id: &NodeId, name: &str, label: String, kind: DataTypeId, start: Variant, writable: bool| {
602            add_to(&mut space, &folder, id, name, label, kind, start, writable)
603        };
604        for signal in &signals {
605            let label =
606                format!("{} · {} [{}]", labels.tr(&signal.owner_key), labels.tr(&signal.quantity_key), signal.unit);
607            add(&node(format!("signal.{}", signal.id)), &signal.id, label, DataTypeId::Double, 0.0.into(), false);
608        }
609        for (i, axis) in axes.iter().enumerate() {
610            for (kind, key) in [("target", "opcua-target"), ("setpoint", "opcua-setpoint")] {
611                let name = format!("command.{kind}.{axis}");
612                let label = format!("{} · {}", labels.tr(axis_keys[i]), labels.tr(key));
613                add(&node(name.clone()), &name, label, DataTypeId::Double, sim.control.set_pos[i].into(), true);
614            }
615        }
616        for (name, key, kind, start, writable) in [
617            ("command.move", "opcua-move", DataTypeId::Boolean, Variant::from(false), true),
618            ("command.cycle", "opcua-cycle", DataTypeId::Boolean, Variant::from(false), true),
619            ("command.disable", "opcua-disable", DataTypeId::Boolean, Variant::from(false), true),
620            ("command.enable", "opcua-enable", DataTypeId::Boolean, Variant::from(false), true),
621            ("command.stop_category", "opcua-stop-category", DataTypeId::Int32, Variant::from(-1i32), true),
622            ("command.path", "opcua-path", DataTypeId::String, Variant::from(""), true),
623            ("command.path_time_optimal", "opcua-path-time-optimal", DataTypeId::Boolean, Variant::from(false), true),
624            ("command.run_path", "opcua-run-path", DataTypeId::Boolean, Variant::from(false), true),
625            ("status.busy", "opcua-busy", DataTypeId::Boolean, Variant::from(false), false),
626            ("status.refused", "opcua-refused", DataTypeId::String, Variant::from(""), false),
627            ("status.cycle_s", "opcua-cycle-s", DataTypeId::Double, Variant::from(cycle.as_secs_f64()), false),
628            ("status.cycle_period_s", "opcua-cycle-period", DataTypeId::Double, Variant::from(0.0), false),
629            ("status.jitter_max_s", "opcua-jitter-max", DataTypeId::Double, Variant::from(0.0), false),
630            ("status.jitter_rms_s", "opcua-jitter-rms", DataTypeId::Double, Variant::from(0.0), false),
631            ("status.overruns", "opcua-overruns", DataTypeId::UInt64, Variant::from(0u64), false),
632            ("status.cycles", "opcua-cycles", DataTypeId::UInt64, Variant::from(0u64), false),
633            ("status.realtime_factor", "opcua-realtime-factor", DataTypeId::Double, Variant::from(0.0), false),
634            ("status.steps", "opcua-steps", DataTypeId::UInt64, Variant::from(0u64), false),
635            ("command.reset_pacing", "opcua-reset-pacing", DataTypeId::Boolean, Variant::from(false), true),
636            ("status.client_writes", "opcua-client-writes", DataTypeId::UInt64, Variant::from(0u64), false),
637            ("status.client_write_mean_s", "opcua-client-write-mean", DataTypeId::Double, Variant::from(0.0), false),
638            ("status.client_write_std_s", "opcua-client-write-std", DataTypeId::Double, Variant::from(0.0), false),
639            ("status.client_write_max_s", "opcua-client-write-max", DataTypeId::Double, Variant::from(0.0), false),
640            ("status.client_reads", "opcua-client-reads", DataTypeId::UInt64, Variant::from(0u64), false),
641            ("status.client_read_mean_s", "opcua-client-read-mean", DataTypeId::Double, Variant::from(0.0), false),
642            ("status.client_read_std_s", "opcua-client-read-std", DataTypeId::Double, Variant::from(0.0), false),
643            ("status.client_read_max_s", "opcua-client-read-max", DataTypeId::Double, Variant::from(0.0), false),
644        ] {
645            add(&node(name.into()), name, labels.tr(key).into(), kind, start, writable);
646        }
647    }
648    // Writes arrive on the server's tasks; they are queued for the simulation loop.
649    let on_write =
650        |name: String, convert: fn(&DataValue, usize) -> Option<Input>, index: usize, inputs: Sender<Input>| {
651            manager.inner().simple.add_write_callback(node(name), move |value, _| match convert(&value, index) {
652                Some(input) => inputs.send(input).map_or(StatusCode::BadShutdown, |_| StatusCode::Good),
653                None => StatusCode::BadTypeMismatch,
654            });
655        };
656    for (i, axis) in axes.iter().enumerate() {
657        on_write(format!("command.target.{axis}"), |v, i| Some(Input::Target(i, number(v)?)), i, inputs.clone());
658        on_write(format!("command.setpoint.{axis}"), |v, i| Some(Input::Setpoint(i, number(v)?)), i, inputs.clone());
659    }
660    on_write("command.move".into(), |v, _| flag(v)?.then_some(Input::Move), 0, inputs.clone());
661    on_write("command.cycle".into(), |v, _| Some(Input::Cycle(flag(v)?)), 0, inputs.clone());
662    on_write("command.disable".into(), |v, _| flag(v)?.then_some(Input::Disable), 0, inputs.clone());
663    on_write("command.enable".into(), |v, _| flag(v)?.then_some(Input::Enable), 0, inputs.clone());
664    on_write(
665        "command.stop_category".into(),
666        |v, _| {
667            let n = number(v).filter(|n| n.fract() == 0.0 && (0.0..=2.0).contains(n))?;
668            sim_components::StopCategory::from_number(n as u8).map(Input::Halt)
669        },
670        0,
671        inputs.clone(),
672    );
673    on_write("command.path".into(), |v, _| Some(Input::Path(text(v)?)), 0, inputs.clone());
674    on_write("command.path_time_optimal".into(), |v, _| Some(Input::PathTimeOptimal(flag(v)?)), 0, inputs.clone());
675    on_write("command.run_path".into(), |v, _| flag(v)?.then_some(Input::RunPath), 0, inputs.clone());
676    // The client timing starts anew at once, in this write: the loop would count the writes that come before its tick.
677    let (reset, timing) = (inputs.clone(), clients.clone());
678    manager.inner().simple.add_write_callback(node("command.reset_pacing".into()), move |value, _| {
679        match flag(&value) {
680            Some(on) => {
681                if on {
682                    *timing.lock().unwrap() = ClientTiming::default();
683                    return reset.send(Input::ResetPacing).map_or(StatusCode::BadShutdown, |_| StatusCode::Good);
684                }
685                StatusCode::Good
686            }
687            None => StatusCode::BadTypeMismatch,
688        }
689    });
690    for (i, axis) in plc.iter().enumerate() {
691        for (name, start, writable) in axis.variables(true, (0.0, 0.0)) {
692            if !writable {
693                continue;
694            }
695            let inputs = inputs.clone();
696            let (is_flag, is_text) = (matches!(start, Variant::Boolean(_)), matches!(start, Variant::String(_)));
697            manager.inner().simple.add_write_callback(node(format!("axis.{}.{name}", axes[i])), move |value, _| {
698                let input = if is_flag {
699                    flag(&value).map(|on| Input::AxisFlag(i, name.clone(), on))
700                } else if is_text {
701                    text(&value).map(|t| Input::AxisText(i, name.clone(), t))
702                } else {
703                    number(&value).map(|v| Input::AxisNumber(i, name.clone(), v))
704                };
705                match input {
706                    Some(input) => inputs.send(input).map_or(StatusCode::BadShutdown, |_| StatusCode::Good),
707                    None => StatusCode::BadTypeMismatch,
708                }
709            });
710        }
711    }
712
713    let pacing = Arc::new(Mutex::new(Pacing { cycle_s: cycle.as_secs_f64(), ..Default::default() }));
714    tokio::spawn(server.run_with(listener));
715    tokio::spawn(simulate(SimLoop {
716        sim,
717        inbox,
718        handle: handle.clone(),
719        namespace,
720        axes,
721        plc,
722        stream_steps,
723        interval,
724        cycle,
725        pacing: pacing.clone(),
726        clients: clients.clone(),
727    }));
728    Ok(Link { handle, namespace, pacing, clients, inputs })
729}
730
731struct SimLoop {
732    sim: Sim,
733    inbox: Receiver<Input>,
734    handle: ServerHandle,
735    namespace: u16,
736    axes: Vec<&'static str>,
737    plc: Vec<Axis>,
738    /// Simulation steps per setpoint interval, and the interval in seconds.
739    stream_steps: u64,
740    interval: f64,
741    cycle: Duration,
742    pacing: Arc<Mutex<Pacing>>,
743    clients: Arc<Mutex<ClientTiming>>,
744}
745
746impl SimLoop {
747    /// One setpoint interval of the PLCopen axes: each runs its profile, and the positions of those that moved go to
748    /// the controller as one setpoint. A setpoint the controller refuses is an axis error for each of them.
749    fn stream(&mut self) -> Option<&'static str> {
750        let setpoint = self.sim.control.external_setpoint().to_vec();
751        let moving: Vec<bool> = self.plc.iter().map(Axis::moving).collect();
752        plcopen::advance_all(&mut self.plc, self.interval, &setpoint);
753        // Drives that went off in this tick (a trip, a crash), or that stop on their fault reaction until they are off,
754        // are the axes' error, ErrorID 7 or 8 once off, not the setpoint the stopping controller refuses.
755        if !moving.contains(&true) || !self.sim.control.enabled() || self.sim.control.reacting() {
756            return None;
757        }
758        let err = self.sim.command(Command::Setpoint(self.plc.iter().map(|a| a.pos).collect())).err()?;
759        for (axis, _) in self.plc.iter_mut().zip(&moving).filter(|(_, m)| **m) {
760            axis.fault(ERR_REFUSED);
761        }
762        Some(err.key)
763    }
764}
765
766/// Steps the simulation in real time and publishes every signal once a cycle (a hundred times a second by default).
767async fn simulate(mut s: SimLoop) {
768    let Some(manager) = s.handle.node_managers().get_of_type::<InMemoryNodeManager<Timed>>() else { return };
769    let namespace = s.namespace;
770    let node = |name: String| NodeId::new(namespace, name);
771    let signal_nodes: Vec<NodeId> = s.sim.signal_infos().iter().map(|i| node(format!("signal.{}", i.id))).collect();
772    let (mut target, mut setpoint) = (s.sim.control.set_pos.clone(), s.sim.control.set_pos.clone());
773    // Targets the PLC has written for the move to come.
774    let mut target_written = vec![false; target.len()];
775    // The last refusal: the kind of command and why.
776    let mut refused: Option<(std::mem::Discriminant<Command>, &'static str)> = None;
777    // The path the PLC has written, and whether to plan it as fast as the motors allow.
778    let (mut path, mut time_optimal) = (String::new(), false);
779    let mut sample = Vec::new();
780    let actual: Vec<(Option<usize>, Option<usize>)> = s
781        .axes
782        .iter()
783        .map(|id| {
784            (s.sim.signal_index(&format!("axis.{id}.position")), s.sim.signal_index(&format!("axis.{id}.velocity")))
785        })
786        .collect();
787    let axis_nodes: Vec<Vec<NodeId>> = s
788        .plc
789        .iter()
790        .zip(&s.axes)
791        .map(|(axis, id)| {
792            axis.variables(true, (0.0, 0.0)).into_iter().map(|(name, _, _)| node(format!("axis.{id}.{name}"))).collect()
793        })
794        .collect();
795    // Whether a PLCopen axis was powered at the last tick: switched off all together, the drives go off.
796    let mut was_powered = false;
797    let mut last = Instant::now();
798    let mut next = last;
799    let mut owed = 0.0;
800    while !s.handle.token().is_cancelled() {
801        // Ticks on a fixed grid of deadlines, so that the mean period is the cycle. A tick more than a cycle late is not
802        // made up for with a burst of ticks: the steps owed are counted from the wall clock anyway. (A dedicated thread
803        // with `std::thread::sleep` was tried: on a loaded Windows host it came late more often than the runtime's timer.)
804        next += s.cycle;
805        let now = Instant::now();
806        if next > now {
807            tokio::time::sleep(next - now).await;
808        } else {
809            // Behind (a machine the simulator runs slower than real time, such as a six-legged platform, or a loaded host): no
810            // sleep, but the runtime's other tasks get their turn. Without an await the loop held its worker for good
811            // and starved the tasks queued on it, the server's answers among them: no client got one, and tests hung.
812            tokio::task::yield_now().await;
813            if now - next > s.cycle {
814                next = now;
815            }
816        }
817        // In the order they arrived; `None` is a path to run, planned when its turn comes.
818        let mut commands = Vec::new();
819        let mut new_setpoint = false;
820        for input in s.inbox.try_iter() {
821            match input {
822                Input::Target(i, v) => (target[i], target_written[i]) = (v, true),
823                Input::Setpoint(i, v) => {
824                    setpoint[i] = v;
825                    new_setpoint = true;
826                }
827                Input::Move => {
828                    commands.push(Some(Command::MoveTo(target.clone())));
829                    target_written.fill(false);
830                }
831                Input::Cycle(on) => commands.push(Some(if on { Command::StartCycle } else { Command::Stop })),
832                Input::Disable => commands.push(Some(Command::Disable)),
833                Input::Enable => commands.push(Some(Command::Enable)),
834                Input::Halt(category) => commands.push(Some(Command::Halt(category))),
835                Input::Path(text) => path = text,
836                Input::PathTimeOptimal(on) => time_optimal = on,
837                Input::RunPath => commands.push(None),
838                Input::AxisFlag(i, name, on) if name == "Power.Enable" => s.plc[i].power(on),
839                Input::AxisFlag(i, name, on) => {
840                    if let Some(k) = FBS.iter().position(|fb| name.strip_suffix(".Execute") == Some(*fb)) {
841                        let (setpoint, busy) = (s.sim.control.external_setpoint()[i], s.sim.control.busy());
842                        plcopen::execute_in(&mut s.plc, i, k, on, setpoint, busy);
843                    }
844                }
845                Input::AxisNumber(i, name, v) => _ = s.plc[i].set_param(&name, v),
846                Input::AxisText(i, name, t) => _ = s.plc[i].set_text(&name, t),
847                Input::ResetPacing => {
848                    let mut pacing = s.pacing.lock().unwrap();
849                    *pacing = Pacing { cycle_s: pacing.cycle_s, ..Default::default() };
850                }
851                Input::Trajectory(points) => commands.push(Some(Command::Trajectory(points))),
852            }
853        }
854        // The controller's drives are on while a PLCopen axis is powered and not in ErrorStop (also after MC_Reset),
855        // and go off when the last axis is switched off. Without PLCopen axes they are left to the commands above.
856        let powered = s.plc.iter().any(|a| a.enable);
857        if s.plc.iter().any(|a| a.enable && a.error_id == 0) && !s.sim.control.enabled() {
858            commands.push(Some(Command::Enable));
859        } else if was_powered && !powered {
860            commands.push(Some(Command::Disable));
861        }
862        was_powered = powered;
863        // Axes written together arrive together: one setpoint command per tick.
864        if new_setpoint {
865            commands.push(Some(Command::Setpoint(setpoint.clone())));
866        }
867        let trajectory = std::mem::discriminant(&Command::Trajectory(Vec::new()));
868        for command in commands {
869            // The path written last, also later in the same write, planned from where the commands before
870            // left the machine; refused like the trajectory it would become.
871            let command = match command {
872                Some(command) => command,
873                None => match sim_components::path::parse(&path) {
874                    Err(_) => {
875                        refused = Some((trajectory, "opcua-error-path-line"));
876                        continue;
877                    }
878                    Ok(pieces) => match s.sim.plan_path(&pieces, time_optimal) {
879                        Ok(points) => Command::Trajectory(points),
880                        Err(e) => {
881                            refused = Some((trajectory, e.key));
882                            continue;
883                        }
884                    },
885                },
886            };
887            let kind = std::mem::discriminant(&command);
888            match s.sim.command(command) {
889                Err(e) => refused = Some((kind, e.key)),
890                // Only a command of the same kind settles a refusal: a refused move stays to be read while
891                // setpoints stream on.
892                Ok(()) if refused.is_some_and(|(refused_kind, _)| refused_kind == kind) => refused = None,
893                Ok(()) => {}
894            }
895        }
896        // The wall clock only decides how many steps are due. A slow host falls behind instead of
897        // piling up work; only lag beyond two cycles counts as falling behind, so that long cycles keep real time.
898        let now = Instant::now();
899        let period = (now - last).as_secs_f64();
900        let due = owed + period;
901        owed = f64::min(due, f64::max(0.1, 2.0 * s.cycle.as_secs_f64()));
902        let lost = due - owed;
903        last = now;
904        let steps_before = s.sim.step;
905        while owed >= s.sim.dt {
906            if s.sim.step.is_multiple_of(s.stream_steps)
907                && let Some(key) = s.stream()
908            {
909                refused = Some((std::mem::discriminant(&Command::Setpoint(Vec::new())), key));
910            }
911            s.sim.step();
912            owed -= s.sim.dt;
913        }
914        s.pacing.lock().unwrap().record(period, (s.sim.step - steps_before) as f64 * s.sim.dt, lost);
915        // Drives switched off by `command.disable`, a trip or a crash: an error for every powered axis.
916        if !s.sim.control.enabled() {
917            for axis in s.plc.iter_mut().filter(|a| a.enable && a.error_id == 0) {
918                axis.fault(if s.sim.crashed { ERR_CRASH } else { ERR_DRIVES_OFF });
919            }
920        }
921
922        // The mirrors follow the controller where the PLC has not written: after a move the axes stand
923        // elsewhere, and a write to one axis would send the others back to a value from before it.
924        for (i, planned) in s.sim.control.planned_pos().iter().enumerate() {
925            if !target_written[i] {
926                target[i] = *planned;
927            }
928        }
929        setpoint.copy_from_slice(s.sim.control.external_setpoint());
930
931        s.sim.sample(&mut sample);
932        let mut values: Vec<(NodeId, DataValue)> =
933            signal_nodes.iter().cloned().zip(sample.iter().map(|v| DataValue::new_now(*v))).collect();
934        for (i, axis) in s.axes.iter().enumerate() {
935            values.push((node(format!("command.target.{axis}")), DataValue::new_now(target[i])));
936            values.push((node(format!("command.setpoint.{axis}")), DataValue::new_now(setpoint[i])));
937        }
938        values.push((node("command.path".into()), DataValue::new_now(path.as_str())));
939        values.push((node("command.path_time_optimal".into()), DataValue::new_now(time_optimal)));
940        values.push((node("status.busy".into()), DataValue::new_now(s.sim.control.busy())));
941        values.push((node("status.refused".into()), DataValue::new_now(refused.map_or("", |(_, key)| key))));
942        let pacing = s.pacing.lock().unwrap().clone();
943        for (name, value) in [
944            ("status.cycle_period_s", Variant::from(pacing.period_s())),
945            ("status.jitter_max_s", pacing.jitter_max_s.into()),
946            ("status.jitter_rms_s", pacing.jitter_rms_s().into()),
947            ("status.overruns", pacing.overruns.into()),
948            ("status.cycles", pacing.cycles.into()),
949            ("status.realtime_factor", pacing.realtime_factor().into()),
950            ("status.steps", s.sim.step.into()),
951        ] {
952            values.push((node(name.into()), DataValue::new_now(value)));
953        }
954        let clients = s.clients.lock().unwrap().clone();
955        for (name, value) in [
956            ("status.client_writes", Variant::from(clients.writes.count)),
957            ("status.client_write_mean_s", clients.writes.mean_s().into()),
958            ("status.client_write_std_s", clients.writes.std_s().into()),
959            ("status.client_write_max_s", clients.writes.max_s.into()),
960            ("status.client_reads", clients.reads.count.into()),
961            ("status.client_read_mean_s", clients.reads.mean_s().into()),
962            ("status.client_read_std_s", clients.reads.std_s().into()),
963            ("status.client_read_max_s", clients.reads.max_s.into()),
964        ] {
965            values.push((node(name.into()), DataValue::new_now(value)));
966        }
967        let drives_on = s.sim.control.enabled();
968        for ((axis, nodes), (position, velocity)) in s.plc.iter().zip(&axis_nodes).zip(&actual) {
969            let at = |index: &Option<usize>| index.map_or(f64::NAN, |k| sample[k]);
970            for (id, (_, value, _)) in nodes.iter().zip(axis.variables(drives_on, (at(position), at(velocity)))) {
971                values.push((id.clone(), DataValue::new_now(value)));
972            }
973        }
974        let _ =
975            manager.set_values(s.handle.subscriptions(), values.iter().map(|(id, value)| (id, None, value.clone())));
976    }
977}
978
979#[cfg(test)]
980mod tests {
981    use super::Intervals;
982    use std::time::{Duration, Instant};
983
984    /// Requests at intervals of 10, 10, 10 and 30 ms: four intervals, mean (30 + 30) / 4 = 15 ms, largest 30 ms;
985    /// deviations −5, −5, −5 and +15 ms, so the standard deviation is √((3 · 25 + 225) / 4) = √75 = 8.660 ms. The
986    /// first request starts the series and is no interval itself.
987    #[test]
988    fn intervals_give_count_mean_standard_deviation_and_largest() {
989        let mut intervals = Intervals::default();
990        let mut at = Instant::now();
991        intervals.record(at);
992        assert_eq!((intervals.count, intervals.mean_s(), intervals.std_s()), (0, 0.0, 0.0));
993        for ms in [10, 10, 10, 30] {
994            at += Duration::from_millis(ms);
995            intervals.record(at);
996        }
997        assert_eq!(intervals.count, 4);
998        assert!((intervals.mean_s() - 0.015).abs() < 1e-12, "{}", intervals.mean_s());
999        assert!((intervals.max_s - 0.030).abs() < 1e-12, "{}", intervals.max_s);
1000        assert!((intervals.std_s() - 75f64.sqrt() * 1e-3).abs() < 1e-9, "{}", intervals.std_s());
1001    }
1002
1003    /// Every key the link shows has a German and an English entry.
1004    #[test]
1005    fn every_link_message_exists_in_every_language() {
1006        let sources = [include_str!("lib.rs"), include_str!("main.rs")].concat();
1007        let keys: Vec<&str> = sources
1008            .split('"')
1009            .filter(|s| s.starts_with("opcua-") && s.len() > 6 && s.chars().all(|c| c.is_ascii_lowercase() || c == '-'))
1010            .collect();
1011        assert!(keys.len() >= 10, "{keys:?}");
1012        for (lang, text) in super::I18N {
1013            let tr = sim_core::Translations::parse(text);
1014            for key in &keys {
1015                assert!(tr.has(key), "no '{lang}' entry for '{key}'");
1016            }
1017        }
1018    }
1019}