Skip to main content

Constructor

Session Two associated functions are provided: Session::new Simplified Construction (default derivation) and Session::with_config Full Configuration Construction.

Prerequisite Reading
pub fn new(endpoint_url: &str) -> Result<Self, OpcUaError>;

Default parameters: MessageSecurityMode::None + Anonymous login + Default timeout (session_timeout_ms 60 seconds, request_timeout_ms 5 seconds).

use darra_opcua::Session;

darra_opcua::initialize()?;
let mut s = Session::new("opc.tcp://localhost:4840")?;
s.connect()?;

Full Configuration with_config​

pub fn with_config(cfg: ConnectionConfig) -> Result<Self, OpcUaError>;

Pass all fields via the structure ConnectionConfig.

ConnectionConfig Field​

CategoryPropertyTypeAccessDescription
Requiredendpoint_urlStringinOPC UA endpoint, in the form of opc.tcp://host:port
Securitysecurity_modeMessageSecurityModeinNone / Sign / SignAndEncrypt, Default: None
security_policy_uriOption<String>inIf 'None' is specified, the mode is selected automatically (None → #None, others → #Basic256Sha256)
client_cert_pathOption<String>inClient PFX path (Sign / SignAndEncrypt required)
client_key_pathOption<String>inPrivate key path (PFX included; field alignment preserved in Stack)
server_cert_pathOption<String>inOptional: server certificate DER path; None goes through the None→Secure automatic upgrade (the server certificate is retrieved from GetEndpoints)
LoginusernameOption<String>inNone = Anonymous, Some = UsernameIdentityToken
passwordOption<String>inUsed with username
Timeoutsession_timeout_msu32inServer-side session timeout; default is 60 000 ms (60 seconds)
request_timeout_msu32inSingle RPC timeout, default 5 000 ms (5 seconds)
connect_timeout_msu32inConnection establishment timeout; default 10 000 ms (10 seconds)
keepalive_interval_msu32inKeepAlive heartbeat interval, default 10 000 ms
Reconnectauto_reconnectboolinEnable automatic reconnection; default is true
reconnect_max_retriesu32inMaximum number of reconnection attempts; default is 3
reconnect_delay_msu32inReconnection interval (ms), default 2000
auto_publish_on_connectboolinAutomatically starts AutoPublish after connect; default is true

ConnectionConfig::new(url) All default values have been filled in; simply modify the fields you need to:

use darra_opcua::{Session, ConnectionConfig};

let mut cfg = ConnectionConfig::new("opc.tcp://localhost:4840");
cfg.session_timeout_ms = 1_800_000; // 30 minutes
cfg.request_timeout_ms = 30_000; // 30 seconds
let mut s = Session::with_config(cfg)?;

Examples​

Anonymous + Plaintext (Development Phase)​

let mut s = Session::new("opc.tcp://localhost:4840")?;
s.connect()?;

Anonymous + Sign Encryption​

use darra_opcua::{Session, ConnectionConfig, MessageSecurityMode};

let mut cfg = ConnectionConfig::new("opc.tcp://server:4840");
cfg.security_mode = MessageSecurityMode::Sign;
cfg.client_cert_path = Some("C:/certs/client.pfx".into());
let mut s = Session::with_config(cfg)?;
s.connect()?;

Username + SignAndEncrypt (Typical Production)​

let mut cfg = ConnectionConfig::new("opc.tcp://server:4840");
cfg.security_mode = MessageSecurityMode::SignAndEncrypt;
cfg.username = Some("operator".into());
cfg.password = Some("secret".into());
cfg.client_cert_path = Some("C:/certs/client.pfx".into());
let mut s = Session::with_config(cfg)?;
s.connect()?;

Structure by Result GetEndpoints Factory​

use darra_opcua::{Discovery, Session, ConnectionConfig, MessageSecurityMode};

let endpoints = Discovery::get_endpoints("opc.tcp://server:4840", 10_000)?;
let ep = endpoints.iter()
.find(|e| e.security_mode == MessageSecurityMode::SignAndEncrypt)
.ok_or("no SignAndEncrypt endpoint")?;

let mut cfg = ConnectionConfig::new(&ep.endpoint_url);
cfg.security_mode = ep.security_mode;
cfg.security_policy_uri = Some(ep.security_policy_uri.clone());
cfg.client_cert_path = Some("C:/certs/client.pfx".into());
cfg.username = Some("operator".into());
cfg.password = Some("secret".into());
let mut s = Session::with_config(cfg)?;
s.connect()?;

Error​

Possible returns during construction OpcUaError:

statusReason
StatusCode::INVALID_ARGUMENTendpoint_url is empty / contains NUL
StatusCode::BAD_CERTIFICATE_INVALIDClient certificate loading failed
Other Bad*Stack: Failed to create a native session

Resource Management (Drop)​

Session Implementation Drop — Automatically when leaving the scope:

  1. Stop the KeepAlive thread
  2. Unset state callback
  3. Adjust DarraUa_Session_Close() Release native handle
{
let mut s = Session::new("opc.tcp://localhost:4840")?;
s.connect()?;
// ... using s ...
} // <- Here, s Drop; all native resources are released

No manual action is required ( disconnect() but an explicit call is clearer and also allows the event callback to receive a notification when the connection is actively terminated).

Global init / shutdown​

You must set the process-level once before construction initialize():

darra_opcua::initialize()?;        // Called once at the process entry point
{
let mut s = Session::new("opc.tcp://localhost:4840")?;
s.connect()?;
// ...
}
darra_opcua::shutdown()?; // Called once before the process exits

initialize() / shutdown() Internal reference counting; safe for multiple calls.

Next Step​