Skip to main content

Automatic Reconnection

Overview​

OPC UA Server Sessions expire during maintenance restarts or network fluctuations. On the C++ sideNo Reconnect() methods — The reconnection ConnectionConfig of the three switches is determined during construction, and the disconnection and reconnection processes are reported to the service side as events.

Three switches directly determine the retry interval; there are no other configurable options. The disconnection/reconnection process is handled via the Session::Events()Field To expose it, simply assign a value directly.

API​

NameCategoryReading and WritingNote
ConnectionConfig::auto_reconnectConfigurationWriteDefault true; When disabled, the connection will not be reestablished if it is lost.
ConnectionConfig::reconnect_max_retriesConfigurationWriteDefault 3
ConnectionConfig::reconnect_delay_msConfigurationWriteDefault 2000
ConnectionConfig::connect_timeout_msConfigurationWriteBy default 10000,First Handshake Timeout (OPNHello//Create/Activate, 4 steps); not a reconnection timeout
SessionEvents::on_reconnectingEventReadEnter Reconnecting State
SessionEvents::on_reconnectedEventReadFrom Reconnecting Back to Connected
SessionEvents::on_disconnectedEventReadFrom Connected to Disconnected / Failed
SessionEvents::on_state_changedEventReadTriggered every time the state changes
Session::State()MethodsReadCurrently SessionState
Session::IsConnected()MethodsReadState() == SessionState::Connected
namespace darra::opcua {

struct ConnectionConfig {
// ...
uint32_t connect_timeout_ms = 10000; // First Handshake (Hello/OPN/Create/Activate 4 Steps)
bool auto_reconnect = true;
uint32_t reconnect_max_retries = 3;
uint32_t reconnect_delay_ms = 2000;
// ...
};

enum class SessionState : int {
Disconnected = 0, Connecting = 1, Connected = 2,
Reconnecting = 3, Closing = 4, Failed = 5
};

/// These are**Field**, Use the `operator=` for assignment, not a method OnXxx(callback) .
class SessionEvents {
public:
std::function<void(std::string const& endpoint)> on_connected;
std::function<void(std::string const& endpoint, Status reason)> on_disconnected;
std::function<void(std::string const& endpoint)> on_reconnecting;
std::function<void(std::string const& endpoint)> on_reconnected;
std::function<void(SessionState old_state, SessionState new_state, Status)> on_state_changed;
std::function<void(Status code, std::string const& cat, std::string const&)> on_communication_error;
// ...
};

SessionState Session::State() const;
bool Session::IsConnected() const;
}
Parameters / FieldsDefaultNote
auto_reconnecttrueCorresponding to Side C DarraUa_SessionConfig.auto_reconnect
reconnect_max_retries3Corresponding to Side C DarraUa_SessionConfig.reconnect_max_retries
reconnect_delay_ms2000Corresponding to Side C DarraUa_SessionConfig.reconnect_delay_ms
connect_timeout_ms10000First Handshake: 4-Step Timeout
on_reconnecting / on_reconnected—All the formal parameters are std::string const& endpoint
on_disconnected—Parameter Type (std::string const& endpoint, Status reason)
on_state_changed—Parameter Type (SessionState old, SessionState now, Status reason)

Event Trigger Rules:

  • Each state change is triggered first on_state_changed
  • Connected And if it wasn't before Connected: it was before Reconnecting →; on_reconnected otherwise → on_connected
  • Fell to Disconnected / Failed and was previously Connected → on_disconnected(endpoint, reason)
  • Enter Reconnecting → on_reconnecting

Code Example​

#include <darra/opcua/client.hpp>
#include <darra/opcua/safe_api.hpp>
#include <chrono>
#include <iostream>
#include <thread>

using namespace darra::opcua;

ConnectionConfig cfg;
cfg.endpoint_url = "opc.tcp://localhost:4840";
cfg.auto_reconnect = true;
cfg.reconnect_max_retries = 3;
cfg.reconnect_delay_ms = 2000;

Session s(cfg);

// Field assignment—not s.Events().OnReconnecting(...)
s.Events().on_reconnecting = [](std::string const& ep) {
std::cout << "重连中... " << ep << "\n";
};
s.Events().on_reconnected = [](std::string const& ep) {
std::cout << "已恢复 " << ep << "\n";
};
s.Events().on_disconnected = [](std::string const& ep, Status reason) {
std::cerr << "断开 " << ep << " reason="
<< Stack::StatusName(static_cast<uint32_t>(reason)) << "\n";
};

s.Connect();

while (running) {
auto r = ReadSafe(s, "ns=2;s=Temp"); // Free function; the first parameter is Session&
if (r) {
double d = 0;
if (r.value.Value().TryGetDouble(d)) Use(d);
} else {
std::cerr << "读失败 " << Stack::StatusName(static_cast<uint32_t>(r.status)) << "\n";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}

Reconnection Behavior​

  • Three switches directly determine the retry interval;SDK no additional retry wrapper is required.
  • SDK No Automatically reconnect and retry after each failure RPC .Session::Read / Write / Browse / Throw an exception on failure Call darra::opcua::Exception(use ex.status() to retrieve the status code); if you don't want to handle the exception, use Safe API, it folds the anomaly into Result::status
  • A complete failure is handled by the business side by on_disconnected prompting the user

Subscriptions and Auto-Renewal​

TransferSubscriptions isManual This method will not be automatically called after reconnection. To retain the subscription, the business logic must call it manually on_reconnected in s.TransferSubscriptions({旧订阅 id}, /*send_initial_values=*/true), and return the value for each item Status.

For more information, see Subscription Resumes Automatically。

Cross-Language Comparison​

No language exposes public Reconnect() methods—the comparison is withReconnection Configuration + Events:

ItemC#PythonJavaC++RustC
RecloserThe constructor does not expose (configuration fields auto_reconnect)OpcUaSession(auto_reconnect=)Configuration Fields auto_reconnectConnectionConfig::auto_reconnectConnectionConfig.auto_reconnectDarraUa_SessionConfig.auto_reconnect
Number of retriesThe constructor does not expose (configuration fields reconnect_max_retries)The constructor does not expose (configuration fields reconnect_max_retries)Configuration Fields reconnect_max_retriesConnectionConfig::reconnect_max_retriesConnectionConfig.reconnect_max_retriesDarraUa_SessionConfig.reconnect_max_retries
Retry IntervalThe constructor does not expose (configuration fields reconnect_delay_ms)The constructor does not expose (configuration fields reconnect_delay_ms)Configuration Fields reconnect_delay_msConnectionConfig::reconnect_delay_msConnectionConfig.reconnect_delay_msDarraUa_SessionConfig.reconnect_delay_ms
Reconnection Start EventEvents.Reconnectingevents.reconnectingonReconnectingSessionEvents::on_reconnectingon_reconnectingNone (only DarraUa_Session_SetStateCallback)
Reconnection Successful EventEvents.Reconnectedevents.reconnectedonReconnectedSessionEvents::on_reconnectedon_reconnectedNone (same as above)

In C++, the / on_reconnecting on_reconnected parameter is std::string const& an endpoint, while Python, Java, and Rust pass ConnectionEventArgs. There is no event callback on the C side; you can only use to listen DarraUa_Session_SetStateCallback for changes DarraUa_SessionState. Python’s public constructor exposes only auto_reconnect; the latter two can only modify the configuration structure fields.

Next Step​