Connect / Disconnect
- 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:
- TCP + Hello/Ack — Negotiate BufferSize / MaxMessageSize, timeout =
connect_timeout_ms - OpenSecureChannel — Opens the channel. When
security_mode != Noneandserver_cert_pathwas 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; ifserver_cert_pathwas already given, it opens the secure channel directly in one step. - 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)
- CreateSession — Establish a session, negotiate SessionTimeout
- ActivateSession — Activate UserToken with
- Loading NamespaceArray To
s.NamespacesRef()(Failures are logged as warnings only; connections are not blocked) - Enable AutoPublish (Controlled
auto_publish_on_connect, default true) - Enable KeepAlive (Controlled
keepalive_interval_ms > 0) - Enable Link Monitoring and Automatic Reconnection (
auto_reconnectControlled)
After successful completion:
s.IsConnected() == trues.State() == SessionState::Connected- The callback
Disconnectedis triggeredConnectedwhen enterings.Events().on_connected
Failure: throws an Exception carrying the specific StatusCode (Status::BadCommunicationError / BadConnectionRejected / BadSecurityModeRejected / ...) and lands State() on Failed.
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:
- Stop KeepAlive Heartbeat
- Disable automatic reconnection and set the "User Disconnected" flag; a link disconnection will no longer trigger a reconnection.
- Stop AutoPublish
- Status →
Closing - CloseSession + CloseSecureChannel, Release the channel and certificate
- Status →
Disconnected
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:
| Value | Meaning |
|---|---|
| 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 |