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 / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| (None ua.reconnect()) | — | — | Manually reconnect and try again ua.connect() |
| cfg.auto_reconnect | Configuration | Write | bool, passed to the underlying layer (default: true) |
| cfg.reconnect_max_retries | Configuration | Write | u32 (default 3) |
| cfg.reconnect_delay_ms | Configuration | Write | u32 (default 2000) |
| events.on_reconnecting | Event | Read | Reconnection in progress |
| events.on_reconnected | Event | Read | Reconnection Successful |
| events.on_disconnected | Event | Read | Disconnect (parameter ConnectionEventArgs) |
| events.on_session_lost | Event | Read | Session Expiration Alert (Parameters OpcUaEventEntry) |
| events.on_state_changed | Event | Read | Any 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_mshandled by the underlying layer viaauto_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_changedindicated to the user by the business side viaon_disconnected/
Subscriptions and Auto-Renewal
After a session reconnection, the business logic must handle the subscription itself:
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 issend_initial_values: boolrequired—true = push the current value immediately after the transfer is complete; false = wait until the next change to push it.- Transfer Failed → Reconstruct Everything Using the Cached MonitoredItemSpec MI
For more information, see Subscription Resumes Automatically。
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| 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.