Events — ua.Events.*
DarraOpcUa.Events It is a unified channel for SDK lifecycle events, consolidating session lifecycle, subscription lifecycle, data changes, and communication exceptions into a single object, making it easier for upper-level components to UI handle logging, status bars, and debugging.
ua.Events.*— SDK Life Cycle Events (This section is protocol-independent)ua.SubscribeEvents(...)— OPC UA protocol events (Alarms & Conditions); see Event Subscription
There are only 15 event members
OpcUaEvents only declares the 15 events below; all are of the event EventHandler<T> style and are subscribed with +=:
| Event | The EventArgs Type | Trigger Conditions |
|---|---|---|
StateChanged | SessionStateChangedEventArgs | Any SessionState change |
Connected | ConnectionEventArgs | First connection successful (CreateSession + ActivateSession OK) |
Disconnected | ConnectionEventArgs | Active / Passive Disconnection |
Reconnecting | ConnectionEventArgs | Enter State Reconnecting |
Reconnected | ConnectionEventArgs | From Reconnecting Restore to Connected |
KeepAlive | KeepAliveEventArgs | Read once per heartbeat cycle ServerStatus.CurrentTime after |
CommunicationError | CommunicationErrorEventArgs | Non-fatal communication errors, such as KeepAlive read failures |
SubscriptionLost | SubscriptionLostEventArgs | Server-Side Unsubscription |
Any | OpcUaEventEntry | A unified channel for all category events |
NodeRemoved | OpcUaEventEntry | See the table below |
NodeAccessDenied | OpcUaEventEntry | See the table below |
NodeTypeChanged | OpcUaEventEntry | See the table below |
SessionLost | OpcUaEventEntry | See the table below |
ServerStateChanged | OpcUaEventEntry | See the table below |
SubscriptionRestored | OpcUaEventEntry | See the table below |
NoneDataChange / ServerEvent / SecurityError / Event members Alarm like these — they are simply OpcUaEventCategory 'sCategory Value, When arriving from the channel Any, apply the filter e.Category.
EventArgs Actual Fields
public sealed class SessionStateChangedEventArgs : EventArgs
{ public SessionState OldState { get; init; }
public SessionState NewState { get; init; }
public StatusCode Reason { get; init; }
public DateTime TimestampUtc { get; init; } }
public sealed class ConnectionEventArgs : EventArgs
{ public string EndpointUrl { get; init; }
public StatusCode StatusCode { get; init; }
public string Message { get; init; }
public DateTime TimestampUtc { get; init; } }
public sealed class KeepAliveEventArgs : EventArgs
{ public DateTime ServerTimeUtc { get; init; }
public StatusCode ServerStatus { get; init; }
public DateTime TimestampUtc { get; init; } }
public sealed class CommunicationErrorEventArgs : EventArgs
{ public StatusCode StatusCode { get; init; }
public string Category { get; init; } // Such as "keepalive"
public string Message { get; init; }
public DateTime TimestampUtc { get; init; } }
public sealed class SubscriptionLostEventArgs : EventArgs
{ public uint SubscriptionId { get; init; }
public StatusCode Reason { get; init; }
public bool WillReconnect { get; init; }
public DateTime TimestampUtc { get; init; } }
OpcUaEventEntry The fields (for "Walk" and Any the 6 typed channels) are in PascalCase { get; init; }:
Category / Severity / Source / Message / StatusCode / TimestampUtc / Original / NodeId / SubscriptionId / MonitoredItemId.
Note that the field name is StatusCode No Status; events StatusCode not covered are treated as default StatusCode.Good.
OpcUaEventCategory Enumeration
Any The full e.Category range of values for the channel:
Unknown = 0,
// Connection / Session Lifecycle
Connected, Disconnected, Reconnecting, Reconnected, KeepAlive, StateChanged,
// Subscription Lifecycle
SubscriptionCreated, SubscriptionLost, SubscriptionRestored,
MonitoredItemAdded, MonitoredItemRemoved, SubscriptionCleared,
// Data / Server Events
DataChange, ServerEvent, Alarm,
// Read / Write / View / Call / History
Read, Write, Browse, Call, HistoryRead,
// Exception
CommunicationError, SecurityError, ProtocolError,
// Other
Info, Diagnostic,
// Node / Session-Level Classification
NodeRemoved = 30, // The server deleted a node (received BadNodeIdUnknown / BadNodeIdInvalid)
NodeAccessDenied = 31,
NodeTypeChanged = 32,
SessionLost = 33, // Session Expired (BadSessionClosed / BadSessionIdInvalid)
ServerStateChanged = 34
Categories actually reported by the SDK: Connected / Disconnected / Reconnecting / Reconnected / KeepAlive / StateChanged / CommunicationError / SubscriptionLost / SubscriptionCreated / SubscriptionRestored / MonitoredItemAdded / MonitoredItemRemoved / DataChange / Read / Write / Browse / Call / HistoryRead / NodeRemoved / SessionLost / SecurityError / ProtocolError / Alarm / ServerEvent / Diagnostic.
Typed Channels (Syntactic Sugar) — 6 Events
In addition to the unified Any channel, the 6 high-frequency categories provide dedicated events, UI eliminating the need to filter if Category==X each event first. The distribution rule is: "e.Category Whichever event is matched triggers the corresponding typed event."
| Event | Trigger Category | Trigger Conditions |
|---|---|---|
NodeRemoved | NodeRemoved | When any operation returns BadNodeIdUnknown / BadNodeIdInvalid (the node has been deleted by the server); the monitoring item in the subscription also reports this when it receives BadNodeIdUnknown. |
SessionLost | SessionLost | When a session-level error occurs (the session has expired, such as BadSessionClosed / BadSessionIdInvalid) |
SubscriptionRestored | SubscriptionRestored | When subscription reconstruction is successful (reports for both data subscriptions and event subscriptions) |
NodeAccessDenied | NodeAccessDenied | Currently, this category will not SDK be reported. — Since the "insufficient permissions" error is actually attributed to SecurityError, this event will not be triggered. |
NodeTypeChanged | NodeTypeChanged | Currently, this category will not SDK be reported. — It is actually BadTypeMismatch assigned to ProtocolError, so this event will not be triggered |
ServerStateChanged | ServerStateChanged | Currently, this category will not SDK be reported. — For server-side status changes, please refer to the field ServerStatus in KeepAlive. |
To monitor "Insufficient Permissions / Type Mismatch / Server Status," please subscribe Any and filter e.Category by:
ua.Events.Any += (s, e) =>
{
if (e.Category == OpcUaEventCategory.SecurityError) { /* Insufficient permissions */ }
if (e.Category == OpcUaEventCategory.ProtocolError) { /* Type mismatch */ }
};
The callback signature for each typed event is EventHandler<OpcUaEventEntry>, and the parameters are NodeId / StatusCode / Source / Message.
ua.Events.NodeRemoved += (s, e) =>
{
Console.WriteLine($"节点已被服务端删除: {e.NodeId ?? e.Source} ({e.StatusCode})");
};
ua.Events.SessionLost += (s, e) =>
{
Console.WriteLine($"会话失效: {e.Message} ({e.StatusCode})");
};
ua.Events.SubscriptionRestored += (s, e) =>
{
Console.WriteLine($"订阅已恢复: {e.Message} (sub={e.SubscriptionId})");
};
For more information, see Automatic Reconnection and Subscription Resumes Automatically。
OpcUaEventSeverity Enumeration
Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Fatal = 5
Log levels in use today: KeepAlive at Trace, successful reads and writes at Debug/Info, failing paths at Warn, and CommunicationError / SubscriptionLost at Error.
Examples of Usage
General Log Hook (Prints all events SDK in a single line)
ua.Events.Any += (s, e) =>
{
Console.WriteLine($"[{e.Severity}] [{e.Category}] {e.Source}: {e.Message} ({e.StatusCode})");
};
Debugging is a breeze—no need to subscribe to specific events; just one hook covers everything.
Status Bar Binding (WPF)
using System.Windows.Media; // Brushes
ua.Events.StateChanged += (s, e) =>
{
Dispatcher.Invoke(() =>
{
statusText.Text = e.NewState.ToString(); // WPF TextBlock
statusText.Foreground = e.NewState == SessionState.Connected
? Brushes.Green : Brushes.Red;
});
};
Error Statistics
int errorCount = 0;
ua.Events.CommunicationError += (s, e) => Interlocked.Increment(ref errorCount);
Relationship with the DataChanged Subscription
Subscribe sub.DataChanged (EventHandler<DataChangeEventArgs>) Receives only events from this subscription; the subscription also pushes Events a Category = DataChange to OpcUaEventEntry. Both exist simultaneously, and the upper layer selects the appropriate one based on the scenario:
- Single-subscription business logic →
sub.DataChanged(can be obtainedDataChangeEventArgs) - Global Logs / Waveform Recording / Debugging →
ua.Events.AnyFilterCategory == DataChange
DataChange That line's OpcUaEventEntry Source = NodeId, Message = value string, StatusCode = the current state.
Thread Model
Events are dispatched synchronously on the SDK's own thread, not on the caller's thread. UI operations must be marshalled back to the UI thread with Dispatcher.Invoke / this.Invoke; otherwise a cross-thread UI operation throws InvalidOperationException.
- Exceptions are isolated per subscriber during dispatch: one subscriber throwing does not affect the others — so an exception raised inside an event callback is never handed back to the caller and is never logged; it is swallowed silently. To surface an error from a callback, wrap it in try/catch and log it yourself inside the callback.
- Do not perform time-consuming operations in event callbacks, as this will slow down the triggering process (KeepAlive thread / Publish callback).