Skip to main content

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:

  1. Hello — Negotiate BufferSize / MaxMessageSize
  2. OpenSecureChannel — Negotiated Encryption Channel (None / Sign / SignAndEncrypt)
  3. GetEndpoints — Retrieve the list of server endpoints (for validation)
  4. CreateSession — Establish a session, negotiate SessionTimeout
  5. ActivateSession — Activate UserToken with
  6. Loading NamespaceArray to namespaces()
  7. Automatically start a auto_publish = true background thread (as auto_publish_on_connect configured)
  8. Automatically start the KeepAlive heartbeat thread

After successful completion:

  • is_connected() == true
  • state() == SessionState::Connected
  • events.lock().unwrap().on_connected The 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:

  1. Stop the KeepAlive thread
  2. Stop AutoPublish
  3. Close the native session (CloseSession + CloseSecureChannel)
  4. 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:

ValueMeaning
DisconnectedNot connected / Disconnected
ConnectingConnecting (Hello / OpenSecureChannel)
ConnectedConnected; read, write, and subscribe operations are working normally.
ReconnectingA disconnection has been detected; automatically reconnecting
ClosingDisconnecting / Dropping
FailedFinal state: Reconnection failed; a new instance must be created

Explanation of the Borrowing Model​

MethodsBorrowReason
connect&mut selfEnable the KeepAlive thread; modify the keep_alive_thread field
disconnect&mut selfStop the thread; modify the keep_alive_thread field
state / is_connected&selfRead-Only Atomic Mass
read / write / browse&selfLet'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),
}
}

Next Step​