跳到主要内容

Events — ua.events.*

OpcUaSession.events 是 SDK 内部事件统一通道, 把会话生命周期 / 订阅生命周期 / 数据变化 / 通讯异常都汇集到一个对象上, 方便上层 UI 做日志 / 状态栏 / 调试.

与 OPC UA 协议事件区分
  • ua.events.* — SDK 内部事件 (本节, 与协议无关)
  • ua.subscribe_events(...) — OPC UA 协议事件 (Alarms & Conditions), 见 事件订阅

Python 事件机制​

Python 没有 C# EventHandler<T> 强类型机制, SDK 用 List[Callable] 模拟:

ua.events.connected.append(callback)        # 注册
ua.events.connected.remove(callback) # 取消
ua.events.connected.clear() # 清空

每个事件就是一个 list, 触发时遍历调用所有 callable. 单个回调抛异常被 SDK 内部 try/except 吞掉, 不影响其他回调和主线程.

完整事件清单​

会话生命周期​

  • connected (ConnectionEventArgs: endpoint_url, status_code, message, timestamp_utc) — 首次连接成功
  • disconnected (ConnectionEventArgs: 同上) — 主动 / 被动断开
  • reconnecting (ConnectionEventArgs: 同上) — 检测到断线, 启动自动重连
  • reconnected (ConnectionEventArgs: 同上) — 自动重连成功
  • keep_alive (KeepAliveEventArgs: server_time_utc, server_status, timestamp_utc) — KeepAlive 心跳成功
  • state_changed (SessionStateChangedEventArgs: old_state, new_state, reason, timestamp_utc) — 任何 SessionState 变化

异常​

  • communication_error (CommunicationErrorEventArgs: status_code, category, message, timestamp_utc) — 通讯失败 (KeepAlive 失败 / read 异常等)。category 是 str (如 "keepalive"), 不是枚举。
  • subscription_lost (SubscriptionLostEventArgs: subscription_id, reason, will_reconnect, timestamp_utc) — 订阅被服务端清理

统一通道 events.any​

所有类别事件都会同步触发此通道, 回调参数是 OpcUaEventEntry:

  • category (OpcUaEventCategory) — 类别枚举
  • severity (OpcUaEventSeverity) — 严重度 (Trace/Debug/Info/Warn/Error/Fatal)
  • source (str) — 事件源 (NodeId / 子组件名)
  • message (str) — 事件文本
  • status_code (StatusCode) — 关联状态码
  • timestamp_utc (datetime) — 触发时刻 (UTC)
  • original (Any) — 强类型 EventArgs (Connected → ConnectionEventArgs 等), 可空
  • node_id (Optional[str]) — 受影响节点 ID (NodeRemoved / NodeAccessDenied / NodeTypeChanged 时给出)
  • subscription_id (int) — 订阅相关事件时给出
  • monitored_item_id (int) — 数据变更 / MI 级事件时给出

OpcUaEventCategory 枚举​

events.any 接收的 OpcUaEventEntry.category 完整清单 (IntEnum, 括号内是数值):

Unknown              = 0

# 连接 / 会话生命周期
Connected = 1
Disconnected = 2
Reconnecting = 3
Reconnected = 4
KeepAlive = 5
StateChanged = 6

# 订阅生命周期
SubscriptionCreated = 7
SubscriptionLost = 8
SubscriptionRestored = 9
MonitoredItemAdded = 10
MonitoredItemRemoved = 11
SubscriptionCleared = 12

# 数据 / 服务器事件
DataChange = 13
ServerEvent = 14
Alarm = 15

# 读 / 写 / 浏览 / 调用 / 历史
Read = 16
Write = 17
Browse = 18
Call = 19
HistoryRead = 20

# 异常
CommunicationError = 21
SecurityError = 22
ProtocolError = 23

# 其他
Info = 24
Diagnostic = 25

# 节点 / 会话 / 服务器扩展
NodeRemoved = 26 # 节点已被服务端删除 (BadNodeIdUnknown)
NodeAccessDenied = 27 # 当前用户对该节点权限不足
NodeTypeChanged = 28 # 节点 DataType 变了 (BadTypeMismatch)
SessionLost = 29 # Session 失效 (BadSessionClosed/BadSessionIdInvalid 等)
ServerStateChanged = 30 # 服务端 Running → Failed/Shutdown 等

Typed 通道 (语法糖) — 6 个新事件​

除了 any 统一通道, 6 个高频 Category 提供专属事件。注意: 它们的回调参数不是 OpcUaEventEntry, 各自是专用 dataclass:

事件回调参数类型字段触发场景
node_removedNodeAffectedEventArgsnode_id, status_code, detail, timestamp_utc命中 BadNodeIdUnknown
node_access_deniedNodeAffectedEventArgs同上命中 BadUserAccessDenied
node_type_changedNodeAffectedEventArgs同上Write 时命中 BadTypeMismatch
session_lostConnectionEventArgsendpoint_url, status_code, message, timestamp_utcSession 失效, 重连前预警
server_state_changedServerStateChangedEventArgsold_state_value, new_state_value, detail, timestamp_utc服务端状态切换。两个 state 字段是 int, 不是枚举
subscription_restoredSubscriptionRestoredEventArgssubscription_id, monitored_item_count, detail, timestamp_utc订阅恢复成功
def on_node_removed(e):                      # e 是 NodeAffectedEventArgs
print(f"⚠ 节点已被服务端删除: {e.node_id} ({e.status_code.name}) {e.detail}")
tree_view.remove_node(e.node_id)

ua.events.node_removed.append(on_node_removed)

ua.events.node_access_denied.append(
lambda e: print(f"⛔ 权限不足: {e.node_id}"))

ua.events.session_lost.append( # e 是 ConnectionEventArgs
lambda e: status_bar.setText("⚠ 会话失效, 即将重连..."))

ua.events.server_state_changed.append( # e 是 ServerStateChangedEventArgs
lambda e: print(f"服务端状态: {e.old_state_value} -> {e.new_state_value} {e.detail}"))

ua.events.subscription_restored.append( # e 是 SubscriptionRestoredEventArgs
lambda e: print(f"订阅已恢复: sub={e.subscription_id}, MI={e.monitored_item_count}"))

详见 自动重连 与 订阅自恢复。

OpcUaEventSeverity 枚举​

Trace, Debug, Info, Warn, Error, Fatal

用法示例​

通用日志钩子 (一行打印 SDK 内所有事件)​

def on_any(e):
print(f"[{e.severity.name}] [{e.category.name}] {e.source}: {e.message} ({e.status_code.name})")

ua.events.any.append(on_any)

调试期非常省事 — 不订阅具体事件, 一行 hook 看全部.

状态栏绑定 (PyQt / Tk)​

from darra_opcua import SessionState

def on_state_changed(e):
# 回调不在 GUI 线程, PyQt 必须切回 GUI 线程: QMetaObject.invokeMethod / signal-slot
label.setText(e.new_state.name)
color = "green" if e.new_state == SessionState.Connected else "red"
label.setStyleSheet(f"color: {color}")

ua.events.state_changed.append(on_state_changed)

错误统计​

import threading
lock = threading.Lock()
counter = {"err": 0}

def on_err(e):
with lock:
counter["err"] += 1

ua.events.communication_error.append(on_err)

与订阅 data_changed 的关系​

订阅 sub.data_changed 仅收到该订阅的事件; ua.events.any 通道里 category == DataChange 的项收到 SDK 下所有订阅的事件 (统一通道). 两者并存:

  • 单订阅业务逻辑 → sub.data_changed
  • 全局日志 / 录波 / 调试 → ua.events.any

线程模型​

不在 UI 线程

事件在 SDK 内部触发线程上派发, 不是你的主线程 (原生状态回调线程 / 数据与事件回调线程 / DarraOpcUa-KeepAlive 心跳线程等)。UI 操作必须自行 marshal 到主线程 (PyQt: QMetaObject.invokeMethod / Tk: root.after / asyncio: loop.call_soon_threadsafe)。

回调里不要做长操作 (写盘 / 数据库 / 推理), 否则会拖住触发线程, 后续事件被压后。把数据放队列, 让另一个线程消费:

import queue, threading
q = queue.Queue()

ua.events.any.append(lambda e: q.put(e)) # 短回调

def consumer():
while True:
e = q.get()
# 慢处理 (写文件 / 数据库 / DNN 推理)

threading.Thread(target=consumer, daemon=True).start()

单个回调抛异常由 SDK 吞掉 (不影响其它回调), 但也意味着你不会收到失败通知 —— 回调体内自己 try/except 并记日志。

下一步​