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()​

void Connect();

Establish a connection to the endpoint. Follow these steps:

  1. TCP + Hello/Ack — Negotiate BufferSize / MaxMessageSize, timeout = connect_timeout_ms
  2. OpenSecureChannel — Opens the channel. When security_mode != None and server_cert_path was not given, it first runs a None channel discovery: open a None channel → GetEndpoints to fetch the server certificate DER → close the channel and reconnect TCP → then open the real channel with Sign / SignAndEncrypt; if server_cert_path was already given, it opens the secure channel directly in one step.
  3. GetEndpoints — Detect UserTokenPolicy the PolicyId on the session channel (ActivateSession to be used; if detection fails, it simply reverts to an empty PolicyId without terminating the connection)
  4. CreateSession — Establish a session, negotiate SessionTimeout
  5. ActivateSession — Activate UserToken with
  6. Loading NamespaceArray To s.NamespacesRef() (Failures are logged as warnings only; connections are not blocked)
  7. Enable AutoPublish (Controlled auto_publish_on_connect, default true)
  8. Enable KeepAlive (Controlled keepalive_interval_ms > 0 )
  9. Enable Link Monitoring and Automatic Reconnection ( auto_reconnect Controlled)

After successful completion:

  • s.IsConnected() == true
  • s.State() == SessionState::Connected
  • The callback Disconnected is triggered Connected when entering s.Events().on_connected

Failure: throws an Exception carrying the specific StatusCode (Status::BadCommunicationError / BadConnectionRejected / BadSecurityModeRejected / ...) and lands State() on Failed.

Callback Trigger Conditions

on_disconnected Only atold_state == Connected This is triggered Disconnected when the new state is Failed /. A normal disconnect via Closing does not follow this branch; to capture every state transition, use on_state_changed.

Examples​

#include <darra/opcua/client.hpp>
#include <iostream>

using namespace darra::opcua;

int main() {
Stack::Init();

{
Session s("opc.tcp://localhost:4840");

s.Events().on_connected = [](std::string const& url) {
std::cout << "Connected to " << url << "\n";
};
s.Events().on_state_changed = [](SessionState old_s, SessionState new_s, Status reason) {
std::cout << static_cast<int>(old_s) << " -> "
<< static_cast<int>(new_s)
<< " (reason=0x" << std::hex << static_cast<uint32_t>(reason) << ")\n";
};

try {
s.Connect();
} catch (Exception const& ex) {
std::cerr << "Connect failed: " << ex.what() << "\n";
return 1;
}
// ... Business ...
} // ← First, perform a destruct (Disconnect + release the handle), then Shutdown

Stack::Shutdown();
return 0;
}

Disconnect()​

void Disconnect();

The sequence for Session actively disconnecting while allowing the instance Session::Disconnect() to reconnect is:

  1. Stop KeepAlive Heartbeat
  2. Disable automatic reconnection and set the "User Disconnected" flag; a link disconnection will no longer trigger a reconnection.
  3. Stop AutoPublish
  4. Status → Closing
  5. CloseSession + CloseSecureChannel, Release the channel and certificate
  6. Status → Disconnected
This path does not trigger the transition.

on_disconnected The state transition is Connected → Closing → Disconnected, but on_disconnected requires old_state == Connected to occur, soCannot obtain after an active disconnect on_disconnected. To receive disconnection notifications, please subscribe on_state_changed.

Session Automatically disconnects and releases resources upon destruction, No need to do it manually, Just click here RAII:

{
Session s("opc.tcp://localhost:4840");
s.Connect();
// ...
} // ← Automatically disconnect and release the handle when leaving the scope

Reconnect to the same instance​

s.Disconnect();
// ... Waiting / Processing ...
s.Connect(); // A single instance can be connected to multiple times

Each time a connection is successfully Connect() established, the "User Disconnected" flag is cleared, and the connection is automatically reestablished and restored to an active state.

Automatic Reconnection (Built-in)​

Link Disconnection Detected SDK Automatically: A link disconnection is detected as soon as an error occurs on the receiving end, triggering an automatic reconnection.

Connected
↓ (link disconnected)
Reconnecting (on_reconnecting fires)
↓ (waits reconnect_delay_ms each time, retries up to reconnect_max_retries times)
├── Success → on_reconnected fires → best-effort subscription restore → AutoPublish restored → Connected
└── Retries exhausted → Failed (on_disconnected does not fire; only on_state_changed reports Failed)

The subscription has not been restored Republish .: After successfully reconnecting, do your best TransferSubscriptions to move the subscriptions to the new session.Subscriptions are discarded immediately when a transfer fails., Handle cleared — The business side must re-establish the subscription; it cannot be expected to resume on its own.

auto_reconnect = false Do not retry; proceed directly Failed.

Reconnection parameters are passed via ConnectionConfig:

ConnectionConfig cfg;
cfg.endpoint_url = "opc.tcp://server:4840";
cfg.auto_reconnect = true; // Default: true
cfg.reconnect_max_retries = 5; // Default 3
cfg.reconnect_delay_ms = 1500; // Default 2000 (wait time before each attempt)
Session s(cfg);
s.Connect();

Status Inquiry​

SessionState st = s.State();
// Disconnected / Connecting / Connected / Reconnecting / Closing / Failed

bool ok = s.IsConnected(); // == (State() == Connected)

SessionState Enumeration:

ValueMeaning
Disconnected (0)Not connected / Disconnected
Connecting (1)Currently on Connect (Hello / OpenSecureChannel)
Connected (2)Connected; Read, Write, and Subscribe functions are working normally.
Reconnecting (3)A disconnection has been detected; automatically reconnecting
Closing (4)Disconnecting / Destructor
Failed (5)Reconnection and retry attempts have been exhausted, or the connection was lost auto_reconnect=false at this point

Next Step​