Skip to main content

Automatic Reconnection

Overview​

Sessions expire on the OPC UA Server during maintenance restarts or network jitter. The SDK's 5 "Safe" variants (read_safe / write_safe / browse_safe / call_safe / read_history_safe) all reconnect automatically on session-level failures:

  1. Call hit session-level error code (BadSessionClosed / BadSessionIdInvalid / BadServerNotConnected / BadConnectionClosed / BadSecureChannelClosed)
  2. Push session_lost Event (with "attempt reconnect" details)
  3. Automatically disconnect and reconnect (disconnect → connect) to reestablish the connection
  4. Retry once after reconnecting; if it still fails → throw the original exception OpcUaException (The Safe version is collapsed to StatusCode)

No action is required on the business side. The reconnection process is handled via ua.events channel push reconnecting / reconnected / disconnected.

Only the "Safe" variant automatically retries

Naked read / write / browse / call / read_history None Automatic reconnection; session-level failures are immediately thrown OpcUaException. To ensure "transparent operation," you must go through the entry *_safe point.

API​

Methods / EventsCategoryReading and WritingNote
ua.read_safe / write_safe / browse_safe / call_safe / read_history_safeMethodsReading and WritingInternal Automatic Reconnection + One Retry
ua.events.reconnecting.append(cb)EventReadReconnection in progress
ua.events.reconnected.append(cb)EventReadReconnection Successful
ua.events.disconnected.append(cb)EventReadConnection Lost
ua.events.session_lost.append(cb)EventReadSession Expiration Alert

Python None The reconnect public method named — reconnection is automatically triggered by the Safe variant.

ItemDefaultNote
Number of RPC Reconnections per Session1A single call may reconnect a maximum of 1 time; if the call still fails after the retry, let the original exception be thrown.
Reconnection Implementation—DarraUa_Session_Disconnect + DarraUa_Session_Connect
auto_reconnect (constructor parameter)TrueAutomatic reconnection that affects only the underlying connection; Retry attempts for Python-side Safe variants do not check this flag

Code Example​

import time
from darra_opcua import DarraOpcUa

with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.events.reconnecting.append(
lambda args: print(f"重连中... {args.endpoint_url}"))

ua.events.reconnected.append(
lambda args: print("已恢复"))

ua.events.session_lost.append( # args is ConnectionEventArgs
lambda args: print(f"Session 失效: {args.message}"))

ua.connect()

# The business logic does not require any `try/except` statements at all.
while running:
st, dv = ua.read_safe("ns=2;s=Temp") # Even if the server restarts midway, it will automatically reconnect and retry.
time.sleep(1)

Reconnection Policy​

  • Per session RPC Maximum number of reconnections 1 time, If the retry still fails, let the original exception be thrown
  • Reconnection itself does not have a separate timeout parameter—it uses the value set during construction connect_timeout_ms (default: 10 000 ms).
  • Exceptions that occur during the reconnection process are not thrown; instead, the original operation is retried. If it still fails, an exception is thrown.That initial exception
  • When multiple Safe calls are triggered concurrentlyNot serialized —— Each follows its own reconnection path independently
  • disconnected The event was caused by a SessionState migration (Disconnected / Failed and was previously Connected), not a dedicated exit due to a reconnection failure.

Subscriptions and Auto-Renewal​

After a successful session reconnection (events.reconnected), each session is Subscription automatically restored in a background thread:

  1. Try transfer_subscriptions([old_sub_id], send_initial_values=True) to migrate the old server-side subscriptions
  2. Transfer failed → Create a new subscription container and rebuild everything using the original subscription parameters MI
  3. If any step succeeds → Push subscription_restored event; If reconstruction fails → Push SubscriptionLost (Error level)

For more information, see Subscription Resumes Automatically.

Implementation Constraints​

  • There is no publicly documented method for manually reconnecting (there is no publicly documented method reconnect named ). To force a reconnection, you must disconnect() and then connect().
  • If there are no OPCUA_RECONNECT_MAX / environment variables OPCUA_RECONNECT_INTERVAL_MS of this type, the number of retries is set to 1.
  • Only the "Safe" variant automatically retries; the "Naked" variant does not RPC retry.
  • Reconnection means "disconnecting and then reconnecting"; it creates a new SecureChannel /Session, and the old session on the server side is recycled when it times out.

Cross-Language Comparison​

C#PythonJavaC++RustC
(No public reconnection API; only " Disconnect() +" is allowed. Connect())(No public reconnection API; only "+ disconnect() " is allowed connect())———(No manual reconnection API; only "+ DarraUa_Session_Disconnect " is allowed DarraUa_Session_Connect)

Side CNone DarraUa_Session_Reconnect, Reconnection is driven reconnect_delay_ms by DarraUa_SessionConfig 's auto_reconnect / reconnect_max_retries /; status notifications are sent via DarraUa_Session_SetStateCallback(DarraUa_Session_GetState check current status).

The scope of automatic reconnection differs between the two sides: On the C# side, it wraps the main Call method at Read / Write / Browse / ReadHistory /, Python includes only 5 variants of "Safe"。

Next Step​