1pub 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
111pub static I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
113
114#[derive(Debug)]
116pub struct LinkError(pub &'static str, pub String);
117
118enum 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 AxisFlag(usize, String, bool),
132 AxisNumber(usize, String, f64),
133 AxisText(usize, String, String),
135 ResetPacing,
136 Trajectory(Vec<(f64, Vec<f64>)>),
138}
139
140#[derive(Debug, Clone, Default)]
142pub struct Pacing {
143 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 pub overruns: u64,
152 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#[derive(Debug, Clone, Default)]
184pub struct Intervals {
185 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 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 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#[derive(Debug, Clone, Default)]
219pub struct ClientTiming {
220 pub reads: Intervals,
221 pub writes: Intervals,
222}
223
224pub 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 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 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
292pub const POLICIES: [(&str, SecurityPolicy); 3] = [
295 ("basic256sha256", SecurityPolicy::Basic256Sha256),
296 ("aes128_sha256_rsaoaep", SecurityPolicy::Aes128Sha256RsaOaep),
297 ("aes256_sha256_rsapss", SecurityPolicy::Aes256Sha256RsaPss),
298];
299
300#[derive(Debug, Clone, Default)]
305pub struct Security {
306 pub trust_all: bool,
309 pub user: Option<(String, String)>,
311 pub user_certs: Vec<PathBuf>,
314}
315
316impl Security {
317 pub fn logins(&self) -> bool {
320 self.user.is_some() || !self.user_certs.is_empty()
321 }
322}
323
324fn own_certificate(pki_dir: &Path) -> PathBuf {
326 pki_dir.join("own").join("cert.der")
327}
328
329pub 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
338pub 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
352pub 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 pub namespace: u16,
386 pub pacing: Arc<Mutex<Pacing>>,
387 pub clients: Arc<Mutex<ClientTiming>>,
388 inputs: Sender<Input>,
389}
390
391impl Link {
392 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
404pub fn number(value: &DataValue) -> Option<f64> {
407 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
432pub 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
446pub 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 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 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 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 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 .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 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 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 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 stream_steps: u64,
740 interval: f64,
741 cycle: Duration,
742 pacing: Arc<Mutex<Pacing>>,
743 clients: Arc<Mutex<ClientTiming>>,
744}
745
746impl SimLoop {
747 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 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
766async 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 let mut target_written = vec![false; target.len()];
775 let mut refused: Option<(std::mem::Discriminant<Command>, &'static str)> = None;
777 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 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 next += s.cycle;
805 let now = Instant::now();
806 if next > now {
807 tokio::time::sleep(next - now).await;
808 } else {
809 tokio::task::yield_now().await;
813 if now - next > s.cycle {
814 next = now;
815 }
816 }
817 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 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 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 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 Ok(()) if refused.is_some_and(|(refused_kind, _)| refused_kind == kind) => refused = None,
893 Ok(()) => {}
894 }
895 }
896 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 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 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 #[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 #[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}