Skip to main content

Connect / Disconnect

Prerequisite Reading
  • 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:

  1. Hello — Negotiate BufferSize / MaxMessageSize
  2. OpenSecureChannel — Negotiated Encryption Channel (NONE / Sign / SignAndEncrypt)
  3. GetEndpoints — Retrieve the list of server endpoints (for validation)
  4. CreateSession — Establish a session, negotiate SessionTimeout
  5. ActivateSession — Activate UserToken with
  6. Loading NamespaceArray to namespaces
  7. If auto_publish_on_connect=True, let auto_publish = True
  8. Start the KeepAlive heartbeat thread (thread name DarraOpcUa-KeepAlive)

After successful completion:

  • is_connected == True
  • state == SessionState.Connected
  • events.connected Event 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:

  1. Stop the KeepAlive heartbeat thread
  2. If the previous value was Connected, resend once events.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):

ValueValueNote
Disconnected0Not connected / Disconnected
Connecting1Connection is being established
Connected2Connected, is_connected is True
Reconnecting3Reconnecting (triggered when this state is entered events.reconnecting)
Closing4Disconnecting / Shutting Down
Failed5Failure State
note

Reconnecting A migration between Connected / and triggers events.reconnected; a migration from to Connected Disconnected / triggers Failed events.disconnected.

Next Step​