Skip to main content

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.

Java does not have a native keyword event; use List<Consumer<...>> (CopyOnWriteArrayList) instead — users can directly use / add(consumer) remove(consumer).

Distinguishing from Protocol OPC UA Events
  • ua.events.* — SDK Internal Events (This section is unrelated to the protocol)
  • ua.subscribeEvents(...) — OPC UA Agreement Events (Alarms & Conditions), see Event Subscription

Complete List of Events​

Session Lifecycle​

  • events.onConnected(ConnectionEventArgs) — First connection successful
  • events.onDisconnected(ConnectionEventArgs) — Active / Passive Disconnection
  • events.onReconnecting(ConnectionEventArgs) — Connection lost; automatic reconnection initiated
  • events.onReconnected(ConnectionEventArgs) — Automatic reconnection successful
  • events.onKeepAlive(KeepAliveEventArgs) — KeepAlive heartbeat successful
  • events.onStateChanged(SessionStateChangedEventArgs) — Any changes to SessionState

Exception​

  • events.onCommunicationError(CommunicationErrorEventArgs) — Communication failure (KeepAlive failure, Read exception, etc.)
  • events.onSubscriptionLost(SubscriptionLostEventArgs) — Subscription cleared by the server

Unified Channel​

  • events.onAny (OpcUaEventEntry) — All Events at a Glance (Connected / Disconnected / DataChange / Read / Write / Browse / Call / HistoryRead / Alarm / ...)

OpcUaEventEntry Fields: category (Enums.OpcUaEventCategory) + severity (Enums.OpcUaEventSeverity) + source + message + statusCode (Enums.StatusCode) + timestampUtc (Instant) + original (Object), and optional metadata nodeId (node-level event, nullable) + subscriptionId (long, 0 indicates not applicable) + monitoredItemId (long, 0 indicates not applicable).

OpcUaEventCategory Enumeration​

OpcUaEventEntry.category Fields, Complete List:

Unknown,

// 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,

// New Categories Added at the Node/Session Level (2026-04-25)
NodeRemoved // Delete a Node on the Server (BadNodeIdUnknown)
NodeAccessDenied // The current user does not have sufficient permissions for this node.
NodeTypeChanged // Node DataType has changed (BadTypeMismatch)
SessionLost // Session Expired (Warning Before Reconnection)
ServerStateChanged // Server status: Running → Failed/Shutdown , etc.

Java Enumeration ConstantsNo explicit value (The above is not an assignment = N ); the order corresponds to the order of declaration. Use a comma when a numeric value is needed category.ordinal(), but note that the ordinal will change depending on the order of declaration, so do not use it as a protocol code.

Typed Channels (Syntactic Sugar) — 6 New Events​

In addition to the Unified onAny Channel, the 6 high-frequency categories offer exclusive events:

EventCategoryTrigger Scenarios
events.onNodeRemovedNodeRemovedHit BadNodeIdUnknown
events.onNodeAccessDeniedNodeAccessDeniedHit: BadUserAccessDenied
events.onNodeTypeChangedNodeTypeChangedHit during a "Write" operation BadTypeMismatch
events.onSessionLostSessionLostSession Expiration Alert
events.onServerStateChangedServerStateChangedServer State Transition
events.onSubscriptionRestoredSubscriptionRestoredSubscription restored successfully

The signature of each typed event callback is Consumer<OpcUaEventEntry>.

ua.events.onNodeRemoved.add(e -> {
System.out.println("⚠ 节点已被服务端删除: " + e.source);
treeView.removeNode(e.source);
});

ua.events.onNodeAccessDenied.add(e ->
System.out.println("⛔ 权限不足: " + e.source));

ua.events.onSessionLost.add(e ->
statusBar.setText("⚠ 会话失效, 即将重连..."));

ua.events.onServerStateChanged.add(e ->
System.out.println("服务端状态: " + e.message));

ua.events.onSubscriptionRestored.add(e ->
System.out.println("订阅已恢复: " + e.source));

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)​

ua.events.onAny.add(e ->
System.out.printf("[%s] [%s] %s: %s (%s)%n",
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 (Swing)​

import javax.swing.SwingUtilities;

ua.events.onStateChanged.add(e -> {
SwingUtilities.invokeLater(() -> {
statusLabel.setText(e.newState.toString());
statusLabel.setForeground(e.newState == Enums.SessionState.Connected
? Color.GREEN : Color.RED);
});
});

Error Statistics​

java.util.concurrent.atomic.AtomicInteger errorCount = new java.util.concurrent.atomic.AtomicInteger();
ua.events.onCommunicationError.add(e -> errorCount.incrementAndGet());

Relationship with the onDataChanged Subscription​

Subscribe Receive events sub.onDataChanged only from this subscription; ua.events.onAny (Category=DataChange) Receive events from all subscriptions SDK under this category (unified channel). Both options coexist; the higher-level option is selected based on the scenario:

  • Single Subscription Business Logic → sub.onDataChanged.add(...)
  • Global Logs / Waveform Recording / Debugging → ua.events.onAny.add(...)

Thread Model​

Must switch back to the thread UI

The event callback is in C-layer Publish Thread Call from above, Not on the caller's thread. UI Operations must SwingUtilities.invokeLater (Swing) / Platform.runLater (JavaFX) switch back to UI the thread; otherwise, cross-thread UI operations will fail.

Do not perform long-running operations (>100 ms) within an event; doing so will block the publish queue.

Exceptions thrown within a callback are SDK swallowed (the try-catch block is ignored), so they do not propagate to the native code and do not cause the Stack to crash.

Next Step​