Skip to main content

Automatic Reconnection

Overview​

Sessions expire on the OPC UA Server during maintenance restarts or network jitter. The Rust SDK has no ua.reconnect() method and no RPC-level auto-retry wrapper such as retry_on_session_fault — every RPC failure returns Err(OpcUaError) immediately.

The observability of session-level failures isEvent: The state transitions at the lower level are derived via state callbacks as on_reconnecting / on_reconnected / on_disconnected / on_state_changed; on the business side, a decision is made on_reconnecting within as to whether to wait or to rebuild the session on its own.

Manual Reconnect = Keep the instance Session, then call again connect().disconnect() This means "disconnect but retain the session handle; reconnection is possible."

API​

Methods / EventsCategoryReading and WritingNote
(None ua.reconnect())——Manually reconnect and try again ua.connect()
cfg.auto_reconnectConfigurationWritebool, passed to the underlying layer (default: true)
cfg.reconnect_max_retriesConfigurationWriteu32 (default 3)
cfg.reconnect_delay_msConfigurationWriteu32 (default 2000)
events.on_reconnectingEventReadReconnection in progress
events.on_reconnectedEventReadReconnection Successful
events.on_disconnectedEventReadDisconnect (parameter ConnectionEventArgs)
events.on_session_lostEventReadSession Expiration Alert (Parameters OpcUaEventEntry)
events.on_state_changedEventReadAny State Change (Parameter: SessionStateChangedEventArgs, containing old_state/new_state/reason)

Event registration uses the Session.events: Arc<Mutex<OpcUaEvents>> public Vec field .push(Box::new(...)); see Events。

Code Example​

use darra_opcua::{AttributeId, Session};
use std::time::Duration;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut ua = Session::new("opc.tcp://localhost:4840")?;

{
let mut ev = ua.events.lock().unwrap();
ev.on_reconnecting.push(Box::new(|e| {
println!("重连中... {}", e.endpoint_url);
}));
ev.on_reconnected.push(Box::new(|_| {
println!("已恢复");
}));
ev.on_disconnected.push(Box::new(|e| {
// ConnectionEventArgs: endpoint_url / status_code / message / timestamp_utc
eprintln!("断开: {} ({:?})", e.endpoint_url, e.status_code);
}));
} // Timely Release MutexGuard

ua.connect()?;

loop {
// RPC No automatic retries: A failure results directly in an `Err` exception; the business logic determines whether to retry or trigger an alert.
match ua.read_attr("ns=2;s=Temp", AttributeId::Value) {
Ok(dv) => println!("{:?}", dv.variant().as_f64()),
Err(e) => {
eprintln!("读失败: {:?} — 再试一次 connect()", e.status);
// disconnect (retains the handle); you can also call connect() directly
let _ = ua.disconnect();
let _ = ua.connect();
}
}
std::thread::sleep(Duration::from_secs(1));
}
}

Reconnection Policy​

  • Session-level reconnection is reconnect_delay_ms handled by the underlying layer via auto_reconnect / reconnect_max_retries /; these three values are written to the underlying configuration (ConnectionConfig → native cfg) during construction.
  • Reconnect timeout = connect_timeout_ms (default 10 000 ms)
  • Reconnection progress is pushed to the business layer through events; the RPC layer does not retry transparently
  • A complete failure is on_state_changed indicated to the user by the business side via on_disconnected /

Subscriptions and Auto-Renewal​

After a session reconnection, the business logic must handle the subscription itself:

  1. ua.transfer_subscriptions(&[sub_id], true) Transfer the server-side list Subscription Id to the current session. The first parameter is a slice &[u32]; the second parameter is send_initial_values: bool required—true = push the current value immediately after the transfer is complete; false = wait until the next change to push it.
  2. Transfer Failed → Reconstruct Everything Using the Cached MonitoredItemSpec MI

For more information, see Subscription Resumes Automatically。

Cross-Language Comparison​

C#PythonJavaC++RustC
ua.Reconnect()ua.reconnect()ua.reconnect()ua.Reconnect()None (using connect())None (Configure Driver + DarraUa_Session_SetStateCallback)

Side CNoneDarraUa_Session_Reconnect This function; reconnection is reconnect_delay_ms automatically driven by the session configuration auto_reconnect / reconnect_max_retries /, and the state is managed using DarraUa_Session_SetStateCallback subscription andDarraUa_Session_GetState polling.

Next Step​