Skip to main content

Events — s.events.lock().unwrap().*

Session.events: Arc<Mutex<OpcUaEvents>> Yes SDK Internal A unified event channel that consolidates session lifecycle / subscription lifecycle / data changes / communication exceptions into a single object, making it easier for upper-level components to UI handle logging, status bar updates, and debugging.

When the registration callback passes, obtain lock() a mutable reference and push Box<dyn Fn(...)> it into the corresponding field:

s.events.lock().unwrap().on_connected.push(Box::new(|e| {
println!("connected to {}", e.endpoint_url);
}));
Distinguishing from Protocol OPC UA Events
  • s.events.* — SDK Internal Events (This section is unrelated to the protocol)
  • s.subscribe_events(...) — OPC UA Agreement Events (Alarms & Conditions), see Event Subscription

Complete List of Events​

Session Lifecycle​

  • on_connected(ConnectionEventArgs { endpoint_url, status_code, message, timestamp_utc }) — First connection successful
  • on_disconnected(同上) — Active / Passive Disconnection
  • on_reconnecting(同上) — Connection lost; automatic reconnection initiated
  • on_reconnected(同上) — Automatic reconnection successful
  • on_keep_alive(KeepAliveEventArgs { server_time_utc, server_status, timestamp_utc }) — KeepAlive heartbeat successful
  • on_state_changed(SessionStateChangedEventArgs { old_state, new_state, reason, timestamp_utc }) — Any changes to SessionState

Communication Error​

  • on_communication_error(CommunicationErrorEventArgs { status_code, category, message, timestamp_utc }) — Communication failure (KeepAlive / Read exceptions, etc.)
  • on_subscription_lost(SubscriptionLostEventArgs { subscription_id, reason, will_reconnect, timestamp_utc }) — Subscription cleared by the server

Unified Channel (Any)​

on_any Receive all internal events (including DataChange / Read / Write / Browse / Call / HistoryRead / subscription lifecycle), represented OpcUaEventEntry by:

pub struct OpcUaEventEntry {
pub category: OpcUaEventCategory,
pub severity: OpcUaEventSeverity,
pub source: String,
pub message: String,
pub status_code: StatusCode,
pub timestamp_utc: SystemTime,
// Targets for Node-Level Events (NodeRemoved / NodeAccessDenied / NodeTypeChanged) NodeId
pub node_id: Option<String>,
// Subscription ID for the subscription-level event (SubscriptionLost / SubscriptionRestored); 0 = not applicable
pub subscription_id: u32,
// MonitoredItem Event Level ID MI , 0 = Not Applicable
pub monitored_item_id: u32,
}

OpcUaEventCategory Enumeration​

pub enum OpcUaEventCategory {
Unknown,
Connected, Disconnected, Reconnecting, Reconnected, KeepAlive, StateChanged,
SubscriptionCreated, SubscriptionLost, SubscriptionRestored,
MonitoredItemAdded, MonitoredItemRemoved, SubscriptionCleared,
DataChange, ServerEvent, Alarm,
Read, Write, Browse, Call, HistoryRead,
CommunicationError, SecurityError, ProtocolError,
Info, Diagnostic,

// New Categories Added at the Node/Session Level (2026-04-25)
NodeRemoved = 30, // Delete a Node on the Server (BadNodeIdUnknown)
NodeAccessDenied = 31, // The current user does not have sufficient permissions for this node.
NodeTypeChanged = 32, // Node DataType has changed (BadTypeMismatch)
SessionLost = 33, // Session Expired (Warning Before Reconnection)
ServerStateChanged = 34, // Server status: Running → Failed/Shutdown , etc.
}

Typed Channels (Syntax Sugar) — 6 New Events​

In addition to the Unified on_any Channel, the 6 high-frequency categories offer exclusive events:

FieldCategoryTrigger Scenarios
events.on_node_removedNodeRemovedHit BadNodeIdUnknown
events.on_node_access_deniedNodeAccessDeniedHit: BadUserAccessDenied
events.on_node_type_changedNodeTypeChangedHit during a "Write" operation BadTypeMismatch
events.on_session_lostSessionLostSession Expiration Alert
events.on_server_state_changedServerStateChangedServer State Transition
events.on_subscription_restoredSubscriptionRestoredSubscription restored successfully

All 6 of these fields are Vec<AnyListener>, and the registration method is .push(Box::new(...)), not call-based. The callback signature is uniformly Box<dyn Fn(&OpcUaEventEntry) + Send + Sync>。

use darra_opcua::Session;

let mut s = Session::new("opc.tcp://localhost:4840")?;
{
let mut ev = s.events.lock().unwrap();

ev.on_node_removed.push(Box::new(|e| {
println!("⚠ 节点已被服务端删除: {}", e.source);
}));

ev.on_node_access_denied.push(Box::new(|e| {
println!("⛔ 权限不足: {}", e.source);
}));

ev.on_session_lost.push(Box::new(|e| {
println!("⚠ 会话失效, 即将重连: {}", e.message);
}));

ev.on_server_state_changed.push(Box::new(|e| {
println!("服务端状态: {}", e.message);
}));

ev.on_subscription_restored.push(Box::new(|e| {
println!("订阅已恢复: sub={} mi={}", e.subscription_id, e.monitored_item_id);
}));
} // Timely Release MutexGuard

For more information, see Automatic Reconnection and Subscription Resumes Automatically。

OpcUaEventSeverity Enumeration​

pub enum OpcUaEventSeverity { Trace, Debug, Info, Warn, Error, Fatal }

Examples of Usage​

General Log Hook (Prints all events SDK in a single line)​

s.events.lock().unwrap().on_any.push(Box::new(|e| {
println!("[{:?}] [{:?}] {}: {} ({})",
e.severity, e.category, e.source, e.message, e.status_code);
}));

Debugging is a breeze—no need to subscribe to specific events; just one hook covers everything.

State Machine Callbacks + Cross-Thread Communication​

use std::sync::mpsc;

let (tx, rx) = mpsc::channel::<bool>();
let tx2 = tx.clone();

s.events.lock().unwrap().on_state_changed.push(Box::new(move |e| {
let connected = matches!(e.new_state, darra_opcua::SessionState::Connected);
let _ = tx2.send(connected);
}));

s.connect()?;
while let Ok(connected) = rx.recv() {
if connected { println!("UI 上更新连接状态"); break; }
}

Error Statistics​

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

let count = Arc::new(AtomicU32::new(0));
let count2 = count.clone();
s.events.lock().unwrap().on_communication_error.push(Box::new(move |_e| {
count2.fetch_add(1, Ordering::SeqCst);
}));

Relationship with Subscription Callbacks​

Subscribe callback (sub.add_node(..., callback)) receives only events for that subscription; on_any receives events DataChange SDK from all subscriptions (unified channel). Both exist, and the higher-level layer selects the appropriate one based on the scenario:

  • Single Subscription Business Logic → sub.add_node(..., cb)
  • Global Logs / Waveform Recording / Debugging → on_any

Closure Requirements​

All listeners are Box<dyn Fn(...) + Send + Sync>:

  • Fn (No FnMut): Closures cannot directly modify captured variables; use Mutex / Atomic* / mpsc::channel to move mutability outside the closure.
  • Send + Sync: A closure cannot hold non-thread-safe references.
  • Actual lifetime required 'static (owned by Vec after a push)

If you need a variable state, use Mutex<T>:

use std::sync::{Arc, Mutex};

let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let log2 = log.clone();
s.events.lock().unwrap().on_state_changed.push(Box::new(move |e| {
let line = format!("{:?} -> {:?}", e.old_state, e.new_state);
if let Ok(mut g) = log2.lock() { g.push(line); }
}));

Thread Model​

Callback Thread

Event callbacks occur in Layer C Publish Thread / KeepAlive Thread Call up, Not on the caller's thread. In the callback:

  • Do not perform long-running operations (>100 ms), as this will block the publish queue.
  • A panic will be SDK caught and will not interrupt other callbacks.
  • Cross-thread access requires you to add it yourself, Mutex use it, or Atomic* mpsc::channel pass it through

UI libraries (egui / iced / Tauri, etc.) normally require updates on the main thread, with the data handed to that thread through mpsc::Sender for rendering.

Complete Example​

use darra_opcua::{Session, SessionState};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut s = Session::new("opc.tcp://localhost:4840")?;
{
let mut ev = s.events.lock().unwrap();
ev.on_connected.push(Box::new(|e| {
println!("CONNECTED: {} ({})", e.endpoint_url, e.status_code);
}));
ev.on_disconnected.push(Box::new(|e| {
println!("DISCONNECTED: {} ({})", e.endpoint_url, e.status_code);
}));
ev.on_reconnecting.push(Box::new(|e| {
println!("RECONNECTING: {}", e.endpoint_url);
}));
ev.on_state_changed.push(Box::new(|e| {
println!("STATE: {:?} -> {:?}", e.old_state, e.new_state);
}));
} // Release it promptly MutexGuardto avoid deadlocks caused by locking again in the callback.
s.connect()?;
let _ = SessionState::Connected;
Ok(())
}

Next Step​