连接 / 断开
connect()
def connect(self): ...
建立到 endpoint 的连接. 建立过程按 OPC UA 规范顺序完成:
- Hello — 协商 BufferSize / MaxMessageSize
- OpenSecureChannel — 协商加密通道 (NONE / Sign / SignAndEncrypt)
- GetEndpoints — 拉取服务端 Endpoint 列表 (用于校验)
- CreateSession — 创建会话, 协商 SessionTimeout
- ActivateSession — 用 UserToken 激活
- 加载 NamespaceArray 到
namespaces - 若
auto_publish_on_connect=True, 置auto_publish = True - 启动 KeepAlive 心跳线程 (线程名
DarraOpcUa-KeepAlive)
成功后:
is_connected == Truestate == SessionState.Connectedevents.connected事件触发
失败抛 OpcUaException (message 为 "Connect failed"), ex.status_code 携带具体 StatusCode (如 BadCertificateInvalid / BadIdentityTokenRejected / BadCommunicationError 等).
例子
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): ...
主动断开连接, 但保留 OpcUaSession 实例可重连. 断开时:
- 停 KeepAlive 心跳线程
- 若此前是
Connected, 补发一次events.state_changed+events.disconnected(message ="主动断开")
close() (with 退出) 不调 disconnect(), 而是停 KeepAlive 并释放会话资源。一般 with 即可, 不需要显式 disconnect()。
重连同一实例
ua.disconnect()
# ... 等待 / 业务处理 ...
ua.connect() # 同一实例可以多次 connect
自动重连 (内置)
5 个 Safe 变体 (read_safe / write_safe / browse_safe / call_safe / read_history_safe) 命中 session 级故障状态码时自动重连 + 重试一次:
Connected
↓ (Safe 变体命中 BadSessionClosed / BadSessionIdInvalid / ...)
Reconnecting (events.reconnecting 触发)
↓ (自动重连: disconnect → connect, 最多 1 次)
├── 成功 → Reconnected (events.reconnected 触发) → 订阅自动恢复 (Transfer 或按缓存重建 MI)
└── 仍失败 → 抛原始 OpcUaException (Safe 版折叠为 StatusCode)
Disconnected / Failed 状态由 SessionState 迁移触发, 与重连是否成功不是同一条路径。
构造时关掉 SDK 自动重连:
OpcUaSession(..., auto_reconnect=False)
该参数只控制 SDK 自动重连; Safe 变体固定只重试 1 次, 不看这个开关。详见 自动重连。
状态查询
@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 每次读都返回实时值, 不是缓存。SessionState 枚举 (IntEnum):
| 值 | 数值 | 说明 |
|---|---|---|
| Disconnected | 0 | 未连接 / 已断开 |
| Connecting | 1 | 连接建立过程中 |
| Connected | 2 | 已连接, is_connected 为 True |
| Reconnecting | 3 | 重连中 (此状态进入时触发 events.reconnecting) |
| Closing | 4 | 断开 / 关闭过程中 |
| Failed | 5 | 失败态 |
备注
Reconnecting / Connected 之间的迁移会触发 events.reconnected; 从 Connected 迁到 Disconnected / Failed 触发 events.disconnected。