Connect / Disconnect
- Please review the construction parameters first Constructor.
- For encryption settings, see Security.
- For information on event subscriptions after connecting, see Events.
connect()
def connect(self): ...
Establish a connection to the endpoint. The connection establishment process is completed in the order specified in the specification OPC UA:
- Hello — Negotiate BufferSize / MaxMessageSize
- OpenSecureChannel — Negotiated Encryption Channel (NONE / Sign / SignAndEncrypt)
- GetEndpoints — Retrieve the list of server endpoints (for validation)
- CreateSession — Establish a session, negotiate SessionTimeout
- ActivateSession — Activate UserToken with
- Loading NamespaceArray to
namespaces - If
auto_publish_on_connect=True, letauto_publish = True - Start the KeepAlive heartbeat thread (thread name
DarraOpcUa-KeepAlive)
After successful completion:
is_connected == Truestate == SessionState.Connectedevents.connectedEvent Trigger
Failure throw OpcUaException (message is "Connect failed"), ex.status_code with specific details StatusCode (such as BadCertificateInvalid / BadIdentityTokenRejected / BadCommunicationError etc.).
Examples
from darra_opcua import OpcUaSession, OpcUaException
with OpcUaSession("opc.tcp://localhost:4840") as ua:
ua.events.connected.append(
lambda e: print(f"Connected to {e.endpoint_url}"))
ua.events.state_changed.append(
lambda e: print(f"{e.old_state.name} -> {e.new_state.name} ({e.reason.name})"))
try:
ua.connect()
except OpcUaException as ex:
print(f"Connect failed: {ex.status_code} ({ex})")
disconnect()
def disconnect(self): ...
Disconnect the connection proactively, but keep the OpcUaSession instance open for reconnection. When disconnecting:
- Stop the KeepAlive heartbeat thread
- If the previous value was
Connected, resend onceevents.state_changed+events.disconnected(message ="主动断开")
close() (with "exit") is not used disconnect(); instead, KeepAlive is stopped and session resources are released. Generally, this is sufficient with; there is no need to explicitly specify it disconnect().
Reconnect to the same instance
ua.disconnect()
# ... Waiting / Processing ...
ua.connect() # A single instance can be connected to multiple times
Automatic Reconnection (Built-in)
5 Safe variants (read_safe / write_safe / browse_safe / call_safe / read_history_safe) automatically reconnect and retry once when a session-level error code is encountered:
Connected
↓ (Safe variant hits BadSessionClosed / BadSessionIdInvalid / ...)
Reconnecting (events.reconnecting fires)
↓ (auto-reconnect: disconnect → connect, up to 1 time)
├── Success → Reconnected (events.reconnected fires) → subscriptions auto-restored (Transfer or MI rebuilt from cache)
└── Still failing → throws the original OpcUaException (Safe variant folds it into a StatusCode)
Disconnected / Failed The state is triggered by a SessionState migration; this is a separate process from whether the reconnection was successful.
Disable "Automatic SDK Reconnect" during construction:
OpcUaSession(..., auto_reconnect=False)
This parameter controls only automatic SDK reconnection; the "Safe" variant is fixed to retry 1 time only, regardless of this setting. For more details, see Automatic Reconnection.
Status Inquiry
@property
def state(self) -> SessionState: ...
@property
def is_connected(self) -> bool: ... # == (state == SessionState.Connected)
from darra_opcua import SessionState
s: SessionState = ua.state
# Disconnected / Connecting / Connected / Reconnecting / Closing / Failed
ok: bool = ua.is_connected # == (state == SessionState.Connected)
state Each read returns a real-time value; it is not cached.SessionState Enumeration (IntEnum):
| Value | Value | Note |
|---|---|---|
| Disconnected | 0 | Not connected / Disconnected |
| Connecting | 1 | Connection is being established |
| Connected | 2 | Connected, is_connected is True |
| Reconnecting | 3 | Reconnecting (triggered when this state is entered events.reconnecting) |
| Closing | 4 | Disconnecting / Shutting Down |
| Failed | 5 | Failure State |
Reconnecting A migration between Connected / and triggers events.reconnected; a migration from to Connected Disconnected / triggers Failed events.disconnected.