Connect / Disconnect
Prerequisite Reading
- Please review the construction parameters first Constructor.
- For encryption settings, see Security.
- For information on event subscriptions after connecting, see Events.
connect()
pub fn connect(&mut self) -> Result<(), OpcUaError>;
Establish a connection to the endpoint. Internal serial execution:
- Hello — Negotiate BufferSize / MaxMessageSize
- OpenSecureChannel — Negotiated Encryption Channel (None / Sign / SignAndEncrypt)
- GetEndpoints — Retrieve the list of server endpoints (for validation)
- CreateSession — Establish a session, negotiate SessionTimeout
- ActivateSession — Activate UserToken with
- Loading NamespaceArray to
namespaces() - Automatically start a
auto_publish = truebackground thread (asauto_publish_on_connectconfigured) - Automatically start the KeepAlive heartbeat thread
After successful completion:
is_connected() == truestate() == SessionState::Connectedevents.lock().unwrap().on_connectedThe callbacks in the list were triggered
Returns on failure Err(OpcUaError)
; the field status
contains specific values StatusCode
(BAD_CERTIFICATE_INVALID
/ BAD_IDENTITY_TOKEN_REJECTED
/ BAD_COMMUNICATION_ERROR
/ ...).
Examples
use darra_opcua::Session;
let mut s = Session::new("opc.tcp://localhost:4840")?;
s.events.lock().unwrap().on_connected.push(Box::new(|e| {
println!("Connected to {}", e.endpoint_url);
}));
s.events.lock().unwrap().on_state_changed.push(Box::new(|e| {
println!("{:?} -> {:?} (reason={})", e.old_state, e.new_state, e.reason);
}));
match s.connect() {
Ok(()) => println!("connected"),
Err(e) => eprintln!("Connect failed: {} (status={})", e.message, e.status),
}
disconnect()
pub fn disconnect(&mut self) -> Result<(), OpcUaError>;
Disconnect the connection proactively, but keep the instance Session open for reconnection. Internally:
- Stop the KeepAlive thread
- Stop AutoPublish
- Close the native session (CloseSession + CloseSecureChannel)
- Trigger Event
on_disconnected(ConnectionEventArgs.message= "Active Disconnection")
Drop Automatic "Disconnect + Close": This generally relies on scope and does not require an explicit statement disconnect().
Reconnect to the same instance
s.disconnect()?;
// ... Waiting / Processing ...
s.connect()?; // A single instance can be connected to multiple times
Automatic Reconnection (Built-in)
When the SDK detects a communication anomaly at the lower layer, it reconnects automatically:
Connected
↓ (communication error)
Reconnecting (on_reconnecting fires)
↓ (retries up to reconnect_max_retries times, default 3)
├── Success → Reconnected (on_reconnected fires) → auto Republish of subscriptions
└── Failure → Disconnected (on_disconnected fires)
Reconnection parameters are configured ConnectionConfig via:
use darra_opcua::{Session, ConnectionConfig};
let mut cfg = ConnectionConfig::new("opc.tcp://server:4840");
cfg.auto_reconnect = true;
cfg.reconnect_max_retries = 5;
cfg.reconnect_delay_ms = 3000;
let mut s = Session::with_config(cfg)?;
Status Inquiry
use darra_opcua::SessionState;
let st: SessionState = s.state();
// Disconnected / Connecting / Connected / Reconnecting / Closing / Failed
let ok: bool = s.is_connected(); // == (state() == Connected)
SessionState Enumeration:
| Value | Meaning |
|---|---|
| Disconnected | Not connected / Disconnected |
| Connecting | Connecting (Hello / OpenSecureChannel) |
| Connected | Connected; read, write, and subscribe operations are working normally. |
| Reconnecting | A disconnection has been detected; automatically reconnecting |
| Closing | Disconnecting / Dropping |
| Failed | Final state: Reconnection failed; a new instance must be created |
Explanation of the Borrowing Model
| Methods | Borrow | Reason |
|---|---|---|
| connect | &mut self | Enable the KeepAlive thread; modify the keep_alive_thread field |
| disconnect | &mut self | Stop the thread; modify the keep_alive_thread field |
| state / is_connected | &self | Read-Only Atomic Mass |
| read / write / browse | &self | Let's go RPC—without changing the local configuration. |
Examples of Invalid Paths
match s.connect() {
Ok(()) => println!("connected"),
Err(e) => match e.status {
darra_opcua::StatusCode::BAD_CERTIFICATE_INVALID
=> eprintln!("证书校验失败"),
darra_opcua::StatusCode::BAD_IDENTITY_TOKEN_REJECTED
=> eprintln!("用户名/密码错误"),
darra_opcua::StatusCode::BAD_COMMUNICATION_ERROR
=> eprintln!("网络不通"),
_ => eprintln!("其他错误: {}", e),
}
}