Skip to main content

Events — s.Events().*

Session::Events() Returns SessionEvents&, is SDK Internal A unified event channel that consolidates session lifecycle, heartbeats, and communication exceptions into a set of callback std::function fields, making it easier for upper-level layers to UI handle logging, status bar updates, and debugging.

Distinguishing from Protocol OPC UA Events
  • s.Events().on_* — SDK Internal Events (This section is unrelated to the agreement)
  • s.SubscribeEvents(...) — OPC UA Agreement Events (Alarms & Conditions), see Event Subscription

SessionEvents Field​

Field-style callback std::function —simply assign the value directly:

FieldSignatureTrigger Conditions
on_connectedvoid(std::string const& url)Connected And it wasn't before Connected, nor did it Reconnecting come from.
on_disconnectedvoid(std::string const& url, Status reason)Fall into Disconnected/Failed And before that, it was Connected(Active Disconnect(): Connected → Closing → Disconnected,Does not trigger)
on_reconnectingvoid(std::string const& url)Enter Reconnecting
on_reconnectedvoid(std::string const& url)Connected And before that, it was Reconnecting
on_keepalivevoid(int64_t server_time_ft, Status server_status)Heartbeat Detection Each TimeAll triggered, the success or failure is reported in the second parameter
on_state_changedvoid(SessionState old, SessionState new, Status reason)Any SessionState change (the first one to occur)
on_communication_errorvoid(Status code, std::string const& cat, std::string const& msg)When an exception is thrown during the heartbeat detection process (cat always set to "keepalive")
on_anyvoid(OpcUaEventEntry const&)Unified Event Channel (Currently only automatically pushes StateChanged / KeepAlive two types)

Event trigger sequence: Trigger the first one first on_state_changed, then trigger the rest according to the conditions listed above.No subscription-level callback(OnSubscriptionLost such things do not exist), see Subscription Resumes Automatically。

OpcUaEventCategory Enumeration​

OpcUaEventEntry::category Used for fieldsOriginal Version Enumeration:

enum class OpcUaEventCategory : int {
Unknown = 0,
Connected, Disconnected, Reconnecting, Reconnected,
KeepAlive, StateChanged,
SubscriptionCreated, SubscriptionLost, SubscriptionRestored,
MonitoredItemAdded, MonitoredItemRemoved, SubscriptionCleared,
DataChange, ServerEvent, Alarm,
Read, Write, Browse, Call, HistoryRead,
CommunicationError, SecurityError, ProtocolError,
Info, Diagnostic,
};

SDK Only automatically recommend two of these categories:StateChanged(when the state changes) and KeepAlive(when a heartbeat is detected). The remaining categories are reserved for PushEvent use by higher-level layers andSDK will not be sent automatically.

New categories at the node/session level areAnother enumeration ExtEventCategory, not the one above this:

enum class ExtEventCategory : int {
NodeRemoved = 30, // Delete a Node on the Server (BadNodeIdUnknown)
NodeAccessDenied = 31, // The current user does not have sufficient permissions for this node.
NodeTypeChanged = 32, // Node DataType has changed (BadTypeMismatch)
SessionLost = 33, // Session Expired (Warning Before Reconnection)
ServerStateChanged = 34 // Server status: Running → Failed/Shutdown , etc.
};

These CategoriesThere is no corresponding automatic distribution point....the business side needs to use PushExtEvent(...) push and then EventBus::Subscribe(...) pull within its own business logic.

OpcUaEventSeverity Enumeration​

enum class OpcUaEventSeverity : int {
Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Fatal = 5
};

OpcUaEventEntry Structure​

struct OpcUaEventEntry {
OpcUaEventCategory category = OpcUaEventCategory::Unknown;
OpcUaEventSeverity severity = OpcUaEventSeverity::Info;
std::string source;
std::string message;
Status status = Status::Good;
};

The Fuyuan Data Edition is OpcUaEventEntryEx, multiple node_id / subscription_id / monitored_item_id / timestamp, and uses the channel EventBus.

Examples of Usage​

General Log Hook (Prints all events SDK in a single line)​

#include <darra/opcua/client.hpp>
#include <iomanip>
#include <iostream>

using namespace darra::opcua;

s.Events().on_any = [](OpcUaEventEntry const& e) {
std::cout << "[" << static_cast<int>(e.severity) << "] "
<< "[" << static_cast<int>(e.category) << "] "
<< e.source << ": " << e.message
<< " (0x" << std::hex << static_cast<uint32_t>(e.status) << ")\n";
};

The debugging phase is very straightforward—no need to subscribe to specific events; a single Lambda function handles them all (currently, it receives KeepAlive two types: StateChanged /).

Status Bar Binding (Qt Example)​

s.Events().on_state_changed = [&](SessionState old_s, SessionState new_s, Status reason) {
QMetaObject::invokeMethod(qApp, [&, new_s]() {
statusLabel->setText(QString("State=%1").arg(static_cast<int>(new_s)));
statusLabel->setStyleSheet(new_s == SessionState::Connected
? "color:green" : "color:red");
});
};

Error Statistics​

#include <atomic>

std::atomic<int> error_count{0};
s.Events().on_communication_error = [&](Status, std::string const&, std::string const&) {
error_count.fetch_add(1);
};

KeepAlive Heartbeat Output Server Time​

constexpr int64_t WIN_EPOCH_OFFSET = 116444736000000000LL;
s.Events().on_keepalive = [](int64_t ft, Status status) {
time_t t = (ft - WIN_EPOCH_OFFSET) / 10000000;
std::cout << "KeepAlive @ " << t
<< " status=0x" << std::hex << static_cast<uint32_t>(status) << "\n";
};

server_time_ft Yes FileTime(UTC since 100ns 1601), not system_clock::time_point.

Thread Model​

Must switch back to the thread UI

The callback is in C-layer Publish Thread or KeepAlive Thread Call from above, Not on the caller's thread. UI Operations must be performed within the same thread UI (Qt QMetaObject::invokeMethod, etc WPF Dispatcher .), otherwise cross-thread UI operations will cause a crash.

Event callbacks are executed synchronously; long-running operations within a callback can slow down the delivery of subsequent notifications in the current session—delegate these tasks to worker threads or a queue.

Exceptions in callbacks are caught by the SDK try-catch block (to prevent the process from crashing); add your own try-catch block to handle specific exceptions.

Next Step​