Events — ua.events.*
OpcUaSession.events Yes SDK Internal A unified event channel that consolidates session lifecycles, subscription lifecycles, data changes, and communication exceptions into a single object, making it easier for upper-level layers to UI handle logging, status bar updates, and debugging.
ua.events.*— SDK Internal Events (This section is unrelated to the agreement)ua.subscribe_events(...)— OPC UA Agreement Events (Alarms & Conditions), see Event Subscription
Python Event Mechanism
Python does not have C#'s strong EventHandler<T> typing mechanism; SDK use List[Callable] Simulation:
ua.events.connected.append(callback) # Register
ua.events.connected.remove(callback) # Cancel
ua.events.connected.clear() # Clear
Each event is a list; when triggered, it iterates through the list and calls all callables. If a single callback throws an exception, it is internally SDK try/except caught and does not affect other callbacks or the main thread.
Complete List of Events
Session Lifecycle
connected(ConnectionEventArgs: endpoint_url, status_code, message, timestamp_utc)— First connection successfuldisconnected(ConnectionEventArgs: 同上)— Active / Passive Disconnectionreconnecting(ConnectionEventArgs: 同上)— Disconnection detected; automatic reconnection initiatedreconnected(ConnectionEventArgs: 同上)— Automatic reconnection successfulkeep_alive(KeepAliveEventArgs: server_time_utc, server_status, timestamp_utc)— KeepAlive heartbeat successfulstate_changed(SessionStateChangedEventArgs: old_state, new_state, reason, timestamp_utc)— Any changes to SessionState
Exception
communication_error(CommunicationErrorEventArgs: status_code, category, message, timestamp_utc)— Communication failure (KeepAlive failure, read exception, etc.).categoryisstr(e.g.,"keepalive"), not an enumeration.subscription_lost(SubscriptionLostEventArgs: subscription_id, reason, will_reconnect, timestamp_utc)— Subscription cleared by the server
Unified Channel events.any
Events of all types will trigger this channel simultaneously. The callback parameters are OpcUaEventEntry:
category(OpcUaEventCategory)— Category Enumerationseverity(OpcUaEventSeverity)— Severity (Trace/Debug/Info/Warn/Error/Fatal)source(str)— Event Source (NodeId / Child Component Name)message(str)— Event Textstatus_code(StatusCode)— Related Status Codestimestamp_utc(datetime)— Trigger Time (UTC)original(Any)— Strongly typed EventArgs (e.g., Connected → ConnectionEventArgs), nullablenode_id(Optional[str])— ID of the affected node (provided when NodeRemoved, NodeAccessDenied, or NodeTypeChanged occurs)subscription_id(int)— Specified when subscribing to related eventsmonitored_item_id(int)— Provided when there is a data change or a level MI event
OpcUaEventCategory Enumeration
events.any Complete OpcUaEventEntry.category list of received values (IntEnum; values are shown in parentheses):
Unknown = 0
# Connection / Session Lifecycle
Connected = 1
Disconnected = 2
Reconnecting = 3
Reconnected = 4
KeepAlive = 5
StateChanged = 6
# Subscription Lifecycle
SubscriptionCreated = 7
SubscriptionLost = 8
SubscriptionRestored = 9
MonitoredItemAdded = 10
MonitoredItemRemoved = 11
SubscriptionCleared = 12
# Data / Server Events
DataChange = 13
ServerEvent = 14
Alarm = 15
# Read / Write / View / Call / History
Read = 16
Write = 17
Browse = 18
Call = 19
HistoryRead = 20
# Exception
CommunicationError = 21
SecurityError = 22
ProtocolError = 23
# Other
Info = 24
Diagnostic = 25
# Node / Session / Server Extension
NodeRemoved = 26 # The node has been deleted by the server (BadNodeIdUnknown)
NodeAccessDenied = 27 # The current user does not have sufficient permissions for this node.
NodeTypeChanged = 28 # Node DataType has changed (BadTypeMismatch)
SessionLost = 29 # Session Expired (BadSessionClosed/BadSessionIdInvalid etc.)
ServerStateChanged = 30 # Server status: Running → Failed/Shutdown , etc.
Typed Channels (Syntax Sugar) — 6 New Events
In addition to the Unified any Channel, the 6 high-frequency categories offer exclusive events.Note: Their callback parameters are not OpcUaEventEntry, each of which is a dedicated dataclass:
| Event | Callback Parameter Types | Field | Trigger Scenarios |
|---|---|---|---|
| node_removed | NodeAffectedEventArgs | node_id, status_code, detail, timestamp_utc | Hit BadNodeIdUnknown |
| node_access_denied | NodeAffectedEventArgs | Ibid. | Hit: BadUserAccessDenied |
| node_type_changed | NodeAffectedEventArgs | Ibid. | Hit during a "Write" operation BadTypeMismatch |
| session_lost | ConnectionEventArgs | endpoint_url, status_code, message, timestamp_utc | Session has expired; warning before reconnecting |
| server_state_changed | ServerStateChangedEventArgs | old_state_value, new_state_value, detail, timestamp_utc | Server-side state transition. The two state fields are int, not an enumeration |
| subscription_restored | SubscriptionRestoredEventArgs | subscription_id, monitored_item_count, detail, timestamp_utc | Subscription restored successfully |
def on_node_removed(e): # e is 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 is ConnectionEventArgs
lambda e: status_bar.setText("⚠ 会话失效, 即将重连..."))
ua.events.server_state_changed.append( # e is ServerStateChangedEventArgs
lambda e: print(f"服务端状态: {e.old_state_value} -> {e.new_state_value} {e.detail}"))
ua.events.subscription_restored.append( # e is SubscriptionRestoredEventArgs
lambda e: print(f"订阅已恢复: sub={e.subscription_id}, MI={e.monitored_item_count}"))
For more information, see Automatic Reconnection and Subscription Resumes Automatically。
OpcUaEventSeverity Enumeration
Trace, Debug, Info, Warn, Error, Fatal
Examples of Usage
General Log Hook (Prints all events SDK in a single line)
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)
Debugging is a breeze—no need to subscribe to specific events; just one hook covers everything.
Status Bar Binding (PyQt / Tk)
from darra_opcua import SessionState
def on_state_changed(e):
# The callback is not in the thread GUI ; it PyQt must be switched back to the thread 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)
Error Statistics
import threading
lock = threading.Lock()
counter = {"err": 0}
def on_err(e):
with lock:
counter["err"] += 1
ua.events.communication_error.append(on_err)
Relationship with the data_changed subscription
Subscribe: Receive sub.data_changed only events from this subscription; ua.events.any In the channel: Receive events category == DataChange SDK from all subscriptions (unified channel). Both coexist:
- Single Subscription Business Logic →
sub.data_changed - Global Logs / Waveform Recording / Debugging →
ua.events.any
Thread Model
Events are dispatched on an SDK internal trigger thread, not on your main thread (native status callback thread / data and event callback thread / DarraOpcUa-KeepAlive heartbeat thread, etc.). UI operations must be marshalled to the main thread yourself (PyQt: QMetaObject.invokeMethod / Tk: root.after / asyncio: loop.call_soon_threadsafe).
Avoid performing time-consuming operations (writing to disk, accessing the database, or performing inferences) in callbacks, as this will block the triggering thread and cause subsequent events to be delayed. Instead, place the data in a queue and let another thread consume it:
import queue, threading
q = queue.Queue()
ua.events.any.append(lambda e: q.put(e)) # Short-term pullback
def consumer():
while True:
e = q.get()
# Slow operations (writing to files / databases / DNN inference)
threading.Thread(target=consumer, daemon=True).start()
If a single callback throws an exception, it is " SDK swallowed" (without affecting other callbacks), but this also means you won't receive a failure notification—you'll need to handle it yourself with a try/except block and log the error within the callback.