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:
Callhit session-level error code (BadSessionClosed/BadSessionIdInvalid/BadServerNotConnected/BadConnectionClosed/BadSecureChannelClosed)- Push
session_lostEvent (with "attempt reconnect" details) - Automatically disconnect and reconnect (disconnect → connect) to reestablish the connection
- 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.
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 / Events | Category | Reading and Writing | Note |
|---|---|---|---|
| ua.read_safe / write_safe / browse_safe / call_safe / read_history_safe | Methods | Reading and Writing | Internal Automatic Reconnection + One Retry |
| ua.events.reconnecting.append(cb) | Event | Read | Reconnection in progress |
| ua.events.reconnected.append(cb) | Event | Read | Reconnection Successful |
| ua.events.disconnected.append(cb) | Event | Read | Connection Lost |
| ua.events.session_lost.append(cb) | Event | Read | Session Expiration Alert |
Python None The reconnect public method named — reconnection is automatically triggered by the Safe variant.
| Item | Default | Note |
|---|---|---|
| Number of RPC Reconnections per Session | 1 | A 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) | True | Automatic 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
disconnectedThe event was caused by a SessionState migration (Disconnected/Failedand was previouslyConnected), 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:
- Try
transfer_subscriptions([old_sub_id], send_initial_values=True)to migrate the old server-side subscriptions - Transfer failed → Create a new subscription container and rebuild everything using the original subscription parameters MI
- If any step succeeds → Push
subscription_restoredevent; If reconstruction fails → PushSubscriptionLost(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
reconnectnamed ). To force a reconnection, you mustdisconnect()and thenconnect(). - If there are no
OPCUA_RECONNECT_MAX/ environment variablesOPCUA_RECONNECT_INTERVAL_MSof 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# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
(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"。