DataChange Callback
Subscription::add_node / add_many Accepts a closure as a callback, triggered by the server whenever the data MI changes.
pub fn add_node<F>(&self, node_id: &str, callback: F) -> Result<u32, OpcUaError>
where F: FnMut(&DataChangeEventArgs) + Send + 'static;
- See the Global Unified Channel
s.events.on_any. - For OPC UA alarms / conditional events (protocol events), see Event Subscription.
DataChangeEventArgs
pub struct DataChangeEventArgs {
pub monitored_item_handle: u32,
pub node_id: Option<String>,
/// String representation of a value (thread-safe)
pub value_string: Option<String>,
/// Names of built-in data type enumerations (e.g., "Double", "Int32")
pub data_type_name: Option<String>,
pub status: StatusCode,
pub source_timestamp: Option<SystemTime>,
pub server_timestamp: Option<SystemTime>,
}
| Field | Type | Note |
|---|---|---|
| monitored_item_handle | u32 | Triggered MI Local Handle |
| node_id | Option<String> | It's about time MI NodeId |
| value_string | Option<String> | String representation of a value (thread-safe) |
| data_type_name | Option<String> | Names of built-in data type enumerations (e.g., Double, Int32) |
| status | StatusCode | DataValue Status |
| source_timestamp | Option<SystemTime> | Data Source Timestamp |
| server_timestamp | Option<SystemTime> | Server Timestamp |
Design Trade-offs
The callback parameter is a flat field snapshot (Option<String> + StatusCode + Option<SystemTime>), which is completely safe for cross-thread use,
but you cannot access the original value to perform Variant advanced operations.
If you need the original data ( Variant e.g., for complex parsing ExtensionObject), use s.read(&node_id)
to re-read it synchronously within the callback. Note: Re-reading the data RPC will block the next notification; this is not recommended in high-frequency scenarios.
Examples
Simple Log
sub.add_node("ns=2;s=Temperature", |args| {
println!("{:?} = {:?} ({:?}) @ {:?}",
args.node_id, args.value_string, args.data_type_name, args.source_timestamp);
})?;
Write a document
use std::sync::{Arc, Mutex};
use std::fs::OpenOptions;
use std::io::Write;
let log_file = Arc::new(Mutex::new(
OpenOptions::new().create(true).append(true).open("data.csv")?
));
let f = log_file.clone();
sub.add_node("ns=2;s=Temperature", move |args| {
if let Ok(mut g) = f.lock() {
let _ = writeln!(g, "{:?},{:?},{:?}",
args.source_timestamp,
args.node_id,
args.value_string);
}
})?;
Inter-thread Communication (mpsc)
use std::sync::mpsc;
let (tx, rx) = mpsc::channel::<f64>();
sub.add_node("ns=2;s=Temperature", move |args| {
if let Some(s) = &args.value_string {
if let Ok(v) = s.parse::<f64>() {
let _ = tx.send(v);
}
}
})?;
// Main thread receives data + updates UI
while let Ok(v) = rx.recv() {
println!("UI temp = {}", v);
}
Counter (FnMut + Mutex)
use std::sync::{Arc, Mutex};
let count = Arc::new(Mutex::new(0u64));
let count2 = count.clone();
sub.add_node("ns=2;s=Counter", move |_args| {
let mut g = count2.lock().unwrap();
*g += 1;
})?;
Thread Model
- Callbacks run in a background thread and are single-threaded and serial (there is no concurrency within the same subscription).
- In the callbackDo not perform long operations (>100 ms), otherwise subsequent events will be blocked
- In the callback, it
panic!will be captured, It will not be passed outside the callback - Cross-subscription callbacks may run concurrently — lock shared data yourself / use
Atomic*
A Detailed Explanation of Closure Requirements
| Constraints | Note |
|---|---|
| FnMut | Closures can modify captured variables, but the lock can only be held in one place at a time. |
| Send | Closures are cross-thread; closures cannot hold non-Send references (such as Rc) internally. |
| 'static | Items are stored in a map for long-term retention; closures cannot borrow short-term data from the stack. |
If a closure needs to hold non-Send types, such as handles GUI, use mpsc::channel to pass the data out, and let the thread GUI consume it.
Relationship with s.events.on_any
// Method A: Single-Subscription-Level Callback
sub.add_node("ns=2;s=X", |args| { /* ... */ })?;
// Method B: Global Unified Channel (All Subscriptions Consolidated)
s.events.lock().unwrap().on_any.push(Box::new(|e| {
if e.category == darra_opcua::OpcUaEventCategory::DataChange {
println!("any: {} = {} ({})", e.source, e.message, e.status_code);
}
}));
Both events will be triggered for the same data point; just choose one to use.