Constructor
OpcUaSession A single constructor, with all parameters passed by keyword; the default values cover most common use cases.
- For encryption parameters (security_mode / security_policy_uri / certificate), see Security Encryption.
- See "Server-Side Pre-Scan" Discovery.
- For instructions on what to do after connecting, see Connection Management.
Signature
class OpcUaSession:
def __init__(self,
endpoint_url: str,
security_mode: MessageSecurityMode = MessageSecurityMode.NONE,
username: Optional[str] = None,
password: Optional[str] = None,
session_timeout_ms: int = 60_000,
request_timeout_ms: int = 5_000,
connect_timeout_ms: int = 10_000,
keepalive_interval_ms: int = 10_000,
auto_reconnect: bool = True,
auto_publish_on_connect: bool = True,
client_cert_path: Optional[str] = None,
client_key_path: Optional[str] = None,
server_cert_path: Optional[str] = None,
security_policy_uri: Optional[str] = None):
...
Parameters
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Required | endpoint_url | str | in | OPC UA endpoint, in the form of opc.tcp://host:port |
| Security | security_mode | MessageSecurityMode | in | NONE / Sign / SignAndEncrypt, default NONE (Python uses uppercase NONE to avoid the keyword None) |
security_policy_uri | Optional[str] | in | If not provided, the mode is selected automatically (NONE → #None, others → #Basic256Sha256) | |
client_cert_path | Optional[str] | in | Client PFX path (Sign / SignAndEncrypt Required), containing the private key | |
client_key_path | Optional[str] | in | The password for the client_cert_path PFX; leave blank if there is no password (the private key is already inside the PFX, so there is no need to provide a separate private key file) | |
server_cert_path | Optional[str] | in | ⚠ Optional server certificate **PFX (PKCS#12) Path** (No DER, and it must be passwordless); if None is passed, it defaults to Secure and automatically upgrades. If loading fails, only a WARN is logged and the process silently reverts to auto-discovery without reporting an error | |
| Login | username | Optional[str] | in | None = Anonymous, non-empty = UsernameIdentityToken |
password | Optional[str] | in | Used with username | |
| Timeout (milliseconds) | session_timeout_ms | int | in | Server-side session keep-alive timeout; default is 60 000 ms (60 seconds) |
request_timeout_ms | int | in | Single RPC timeout, default 5 000 ms (includes large Read/Write/Browse requests) | |
connect_timeout_ms | int | in | Initial handshake timeout (Hello/OPN/Create/Activate), default 10 000 ms | |
keepalive_interval_ms | int | in | KeepAlive heartbeat interval; default is 10 000 ms (<= 0 disables the heartbeat thread) | |
| Behavior | auto_reconnect | bool | in | SDK Auto-reconnect toggle; default is True. The Safe variant ignores this setting; see the Auto-Reconnect page |
auto_publish_on_connect | bool | in | Sets auto_publish to True after a successful connect() call; default is True |
Examples
Anonymous + Plaintext (Development Phase)
from darra_opcua import OpcUaSession
with OpcUaSession("opc.tcp://localhost:4840") as ua:
ua.connect()
# ...
Anonymous + Sign Encryption
from darra_opcua import OpcUaSession, MessageSecurityMode
with OpcUaSession(
"opc.tcp://server:4840",
security_mode=MessageSecurityMode.Sign,
client_cert_path=r"C:\certs\client.pfx") as ua:
ua.connect()
Username + SignAndEncrypt (Typical Production)
with OpcUaSession(
"opc.tcp://server:4840",
security_mode=MessageSecurityMode.SignAndEncrypt,
username="operator",
password="secret",
client_cert_path=r"C:\certs\client.pfx") as ua:
ua.connect()
Structure by Result GetEndpoints Factory
from darra_opcua import OpcUaSession, OpcUaDiscovery, MessageSecurityMode
eps = OpcUaDiscovery.get_endpoints("opc.tcp://server:4840")
ep = next(e for e in eps if e.security_mode == MessageSecurityMode.SignAndEncrypt)
with OpcUaSession(
endpoint_url=ep.endpoint_url,
security_mode=ep.security_mode,
security_policy_uri=ep.security_policy_uri,
username="operator",
password="secret",
client_cert_path=r"C:\certs\client.pfx") as ua:
ua.connect()
Exception
The constructor throws exceptions in only two places:
| Exception | Reason |
|---|---|
ValueError("endpoint_url is required") | endpoint_url Empty |
OpcUaException("Session_Create failed", rc) | Session creation failed (initialization/configuration failed) |
Certificate loading failures are not exposed during the construction phase—the construction phase only logs client_cert_path / client_key_path, while the certificate is actually used by connect().
OpcUaException.status_code is a StatusCode enumeration; however, if the code returned by the server is not in the StatusCode enumeration, it keeps the original int. ex.status is a compatible alias for it.
from darra_opcua import OpcUaException, StatusCode
ua = OpcUaSession("opc.tcp://bad-host:4840", connect_timeout_ms=1000)
try:
ua.connect()
except OpcUaException as ex:
if ex.status_code == StatusCode.BadCommunicationError:
print("Network down")
else:
print(f"Connect failed: {ex}")
finally:
ua.close()
Resource Management
OpcUaSession Implement a context manager that automatically releases session resources upon exit. Highly recommended for use with with:
# Recommended: with automatic close
with OpcUaSession(...) as ua:
ua.connect()
# ...
# or explicitly
ua = OpcUaSession(...)
try:
ua.connect()
# ...
finally:
ua.close()
dispose() directly calls close(). close() stops the KeepAlive heartbeat and releases session resources. It does not call disconnect(). To "disconnect and still reconnect with the same instance", follow the disconnect() then connect() procedure; close() is teardown, not part of the disconnect-and-reconnect procedure. Usually with is sufficient.