Events — s.Events().*
Session::Events() 는 SessionEvents& 를 반환, 는 SDK 내부이벤트 통합 채널을 통해 세션 수명 주기, 하트비트, 통신 오류 등을 하나의 콜백 std::function 필드에 통합하여, 상위 계층에서 로그 기록, 상태 표시줄, 디버깅을 편리하게 UI 수행할 수 있도록 합니다.
s.Events().on_*— SDK 내부이벤트 (본 절, 프로토콜과 무관함)s.SubscribeEvents(...)— OPC UA 협정이벤트 (Alarms & Conditions), 참조 이벤트 구독
SessionEvents 필드
필드형 std::function 콜백, 직접 값을 할당하면 됩니다:
| 필드 | 서명 | 발동 조건 |
|---|---|---|
| on_connected | void(std::string const& url) | Connected 게다가 이전에는 Connected~도 아니었고, ~에서 온 Reconnecting 것도 아니었다 |
| on_disconnected | void(std::string const& url, Status reason) | Disconnected/로Failed 떨어졌다 게다가 이전에는 Connected(능동적 Disconnect() 경로: Connected→Closing→Disconnected,발동되지 않음) |
| on_reconnecting | void(std::string const& url) | 들어가기 Reconnecting |
| on_reconnected | void(std::string const& url) | Connected 게다가 이전에는 Reconnecting |
| on_keepalive | void(int64_t server_time_ft, Status server_status) | 매번 하트비트 감지모두 실행됨, 성공 여부는 두 번째 매개변수를 통해 반환됩니다. |
| on_state_changed | void(SessionState old, SessionState new, Status reason) | 모든 SessionState 변경 사항 (가장 먼저 발생한 것부터) |
| on_communication_error | void(Status code, std::string const& cat, std::string const& msg) | 하트비트 감지 과정에서 예외가 발생할 때 (cat 항상 "keepalive") |
| on_any | void(OpcUaEventEntry const&) | 통합 이벤트 채널 (현재는 두 StateChanged 가지 유형만 자동으로 KeepAlive 푸시됨) |
이벤트 트리거 순서: 먼저 하나를 발동한 다음 on_state_changed, 위의 조건에 따라 나머지를 발동합니다.구독 기반 콜백이 없습니다.(OnSubscriptionLost 그와 같은 것은 존재하지 않는다), 참조 구독 자동 복원.
OpcUaEventCategory 열거형
OpcUaEventEntry::category 필드에 사용되는원본열거:
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 그중 두 가지 유형만 자동으로 추천합니다:StateChanged(상태가 변경될 때) 및 KeepAlive(하트비트 감지 시). 나머지 카테고리는 상위 계층에서 직접 사용하도록 되어 있으며 PushEvent ,SDK 자동으로 전송되지는 않습니다.
노드/세션 수준에서 새로 추가된 분류는 다음과 같습니다.또 다른 열거형 ExtEventCategory, 위와 같은 것이 아닙니다:
enum class ExtEventCategory : int {
NodeRemoved = 30, // 서버에서 특정 노드 삭제 (BadNodeIdUnknown)
NodeAccessDenied = 31, // 현재 사용자의 해당 노드에 대한 권한이 부족합니다.
NodeTypeChanged = 32, // 노드 DataType 변경됨 (BadTypeMismatch)
SessionLost = 33, // 세션 만료 (재연결 전 경고)
ServerStateChanged = 34 // 서버 Running → Failed/Shutdown 등
};
이러한 분류에는 해당 자동 배부 지점이 없습니다. 비즈니스 측에서 직접 비즈니스 로직 내에서 PushExtEvent(...)를 사용하여 데이터를 전송하고, 다시 EventBus::Subscribe(...)를 사용하여 데이터를 수신해야 합니다.
OpcUaEventSeverity 열거형
enum class OpcUaEventSeverity : int {
Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Fatal = 5
};
OpcUaEventEntry 구조
struct OpcUaEventEntry {
OpcUaEventCategory category = OpcUaEventCategory::Unknown;
OpcUaEventSeverity severity = OpcUaEventSeverity::Info;
std::string source;
std::string message;
Status status = Status::Good;
};
푸위안 데이터 버전은 OpcUaEventEntryEx, 다중 node_id / subscription_id / monitored_item_id / timestamp, 경로를 EventBus 통해 전송됩니다.
사용 예시
일반 로그 훅 (한 줄에 SDK 모든 이벤트 출력)
#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";
};
디버깅 단계에서 매우 간편합니다. 특정 이벤트를 구독할 필요 없이, 하나의 람다 함수로 모든 이벤트를 처리할 수 있습니다(현재는 StateChanged / KeepAlive 두 가지 유형의 이벤트를 수신합니다).
상태 표시줄 바인딩 (Qt 예제)
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");
});
};
오류 통계
#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 하트비트 출력 서버 시간
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 ‘예’ FileTime(UTC 100ns since 1601)이며, ‘아니오’가 아닙니다 system_clock::time_point.
스레드 모델
콜백은 C 계층 발행 스레드또는 KeepAlive 스레드상위 호출, 호출자 스레드가 아님. UI 작업은 반드시 해당 UI 스레드(Qt QMetaObject::invokeMethod 등 WPF Dispatcher )로 되돌아가야 하며, 그렇지 않으면 스레드 간 작업으로 인해 프로그램이 UI 충돌합니다.
이벤트 콜백은 동기식으로 실행되며, 콜백 내의 긴 작업은 해당 세션의 후속 알림 전달을 지연시킬 수 있습니다. —— 재시도는 작업 스레드나 큐에 맡기십시오.
콜백 내의 예외는 SDK try-catch에 의해 처리됩니다(프로세스 충돌 방지). 직접 try-catch를 추가하여 구체적인 예외를 확인해 보세요.