Skip to main content

Add MonitoredItem

Prerequisite Reading

sub.add_node​

pub fn add_node<F>(&self, node_id: &str, callback: F) -> Result<u32, OpcUaError>
where F: FnMut(&DataChangeEventArgs) + Send + 'static;

Monitor the property Value and sample at the subscription's publishing interval.

let h: u32 = sub.add_node("ns=2;s=Temperature", |args| {
println!("{:?} = {:?}", args.node_id, args.value_string);
})?;

Returns u32 MonitoredItem handle (local handle, used for subsequent modify_item / remove).

sub.add_node_with​

Full Parameter Version.

pub fn add_node_with<F>(
&self,
node_id: &str,
attr: AttributeId,
sampling_ms: f64,
callback: F,
) -> Result<u32, OpcUaError>
where F: FnMut(&DataChangeEventArgs) + Send + 'static;
ParametersDefaultNote
node_id—Monitored NodeId
attrAttributeId::ValueMonitored Attributes
sampling_ms-1.0 (Subscribe)Server sampling interval. 0.0 = As soon as possible
use darra_opcua::AttributeId;

let h = sub.add_node_with(
"ns=2;s=Pressure",
AttributeId::Value,
100.0, // 100 ms Sampling
|args| println!("press = {:?}", args.value_string),
)?;

Error: StatusCode::BAD_NODE_ID_UNKNOWN Wait for Result::Err to return, then OpcUaError.status read the status code from.

sub.add_many​

Add multiple items in bulk MIand share a single callback:

pub fn add_many<F>(
&self,
node_ids: &[&str],
attr: AttributeId,
callback: F,
) -> Result<Vec<(u32, StatusCode)>, OpcUaError>
where F: FnMut(&DataChangeEventArgs) + Send + 'static;

Returns Vec<(handle, status)>, in the same node_ids order as, and any failed items handle == 0.

let nodes: Vec<String> = (1..=100).map(|i| format!("ns=2;s=T{}", i)).collect();
let nodes_ref: Vec<&str> = nodes.iter().map(String::as_str).collect();

let results = sub.add_many(&nodes_ref, AttributeId::Value, |args| {
println!("{:?} = {:?}", args.node_id, args.value_string);
})?;

for (i, (h, st)) in results.iter().enumerate() {
if st.is_good() {
println!(" {} -> handle={}", nodes[i], h);
} else {
println!(" {} FAILED: {}", nodes[i], st);
}
}
Design Trade-offs

Client-side: AddNodes API Accepts a single callback + no context; the trampoline cannot look up each one MI NodeId. Therefore, the implementation takes the iterative add_node_with path (N times RPC), with each having an independent MI context and a shared user callback Arc<Mutex<F>> wrapper. Performance is slightly worse, but it is semantically and memory-wise reliable.

DataChangeEventArgs​

pub struct DataChangeEventArgs {
pub monitored_item_handle: u32,
pub node_id: Option<String>,
/// String representation of the value (pre-extracted by the callback thread). If the value is null or decoding fails, this field is None.
pub value_string: Option<String>,
/// Built-in data type enumeration names (such as "Double" / "Int32"). None = Variant null.
pub data_type_name: Option<String>,
pub status: StatusCode,
pub source_timestamp: Option<SystemTime>,
pub server_timestamp: Option<SystemTime>,
}
Safety Design

value_string / Thread Published data_type_name at the C LayerSynchronous Extraction, Thread-safe. No longer expose the original pointer DataValue, to prevent use-after-free crashes.

For more information, see DataChange Callback.

Remove​

sub.remove(h);                                    // Single -> StatusCode
sub.remove_by_node_id("ns=2;s=Temperature"); // Click NodeId Remove All Corresponding -> usize (number of items removed)

Monitoring Different Attributes​

In addition to the default monitoring Value, you can also monitor other properties Description such as:

use darra_opcua::AttributeId;

sub.add_node_with("ns=2;s=T1", AttributeId::Value, -1.0, |a| {
println!("value = {:?}", a.value_string);
})?;
sub.add_node_with("ns=2;s=T1", AttributeId::Description, -1.0, |a| {
println!("desc = {:?}", a.value_string);
})?;
AttributeId No StatusCode variants

AttributeId There are 22 variants in Part 4, Section §5.6.2 (NodeId=1 … UserExecutable=22), insideNone StatusCode. WorthStatus Code The "walk back" field args.status (DataChangeEventArgs.status: StatusCode ) is not a standalone attribute. Other writable values include AttributeId::NodeId / BrowseName / DisplayName /, etc EventNotifier . For a complete list of variants, see SDK AttributeId Enumerations (Part 4 §5.6.2 ).

Closure Requirements​

ConstraintsReason
FnMutClosures can modify captured variables (using move and Mutex)
SendC Publish The thread calls the callback; it does not create a thread.
'staticItems Map: Long-Term Holdings

To share mutable state within a closure, use Arc<Mutex<T>>:

use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0u64));
let counter2 = counter.clone();
sub.add_node("ns=2;s=X", move |_args| {
let mut g = counter2.lock().unwrap();
*g += 1;
})?;

Next Step​