From bf8e2c947a78a0bb999d54c14259930a39f857d6 Mon Sep 17 00:00:00 2001 From: Jan-Niklas Burfeind Date: Tue, 30 Jul 2024 10:20:55 +0200 Subject: [PATCH] feat: Implement an 'example' rapid-clock which is basically a utility to spawn rapid OPC UA variable changes on a subscribable server. It might better reside in the upstream OPC UA crate eventually. --- Cargo.toml | 4 +++ examples/opc_ua/rapid-clock.rs | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 examples/opc_ua/rapid-clock.rs diff --git a/Cargo.toml b/Cargo.toml index 94846a6..b5f0190 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,10 @@ opcua = { version = "0.12.0", features = ["server", "console-logging"] } socket2 = "0.5.7" tokio = "1.38.0" +[[example]] +name = "rapid-clock" +path = "examples/opc_ua/rapid-clock.rs" + [[example]] name = "simple-publisher" path = "examples/ros2/simple-publisher.rs" diff --git a/examples/opc_ua/rapid-clock.rs b/examples/opc_ua/rapid-clock.rs new file mode 100644 index 0000000..90a2cc4 --- /dev/null +++ b/examples/opc_ua/rapid-clock.rs @@ -0,0 +1,63 @@ +use opcua::server::prelude::{Config, DateTime, NodeId, Server, ServerConfig, Variable}; +use std::path::PathBuf; + +fn main() { + rapid_clock(); +} + +fn rapid_clock() { + opcua::console_logging::init(); + + let mut server = + Server::new(ServerConfig::load(&PathBuf::from("tests/resources/clock.conf")).unwrap()); + + let namespace = { + let address_space = server.address_space(); + let mut address_space = address_space.write(); + address_space.register_namespace("urn:rapid-clock").unwrap() + }; + + add_timed_variable(&mut server, namespace); + + server.run(); +} + +fn add_timed_variable(server: &mut Server, namespace: u16) { + // These will be the node ids of the new variables + let ticks_since_launch_node_id = NodeId::new(namespace, "ticks_since_launch"); + + let address_space = server.address_space(); + + // The address space is guarded so obtain a lock to change it + { + let mut address_space = address_space.write(); + + let rapid_folder_id = address_space + .add_folder("Rapid", "Rapid", &NodeId::objects_folder_id()) + .unwrap(); + + let _ = address_space.add_variables( + vec![Variable::new( + &ticks_since_launch_node_id, + "ticks_since_launch", + "ticks_since_launch", + 0i32, + )], + &rapid_folder_id, + ); + } + + { + server.add_polling_action(10, move || { + let mut address_space = address_space.write(); + let now = DateTime::now(); + let ticks_in_100_ns = now.ticks(); + let _ = address_space.set_variable_value( + ticks_since_launch_node_id.clone(), + ticks_in_100_ns as i32, + &now, + &now, + ); + }); + } +}