Events — s.events.lock().unwrap().*
Session.events: Arc<Mutex<OpcUaEvents>> 네 SDK 내부이벤트 통합 채널로, 세션 수명 주기 /
구독 수명 주기 / 데이터 변경 / 통신 오류를 모두 하나의 객체에 통합하여, 상위 계층에서 로그 / 상태 표시줄 / 디버깅을 편리하게 UI 수행할 수 있도록 합니다.
등록 콜백이 성공하면 가변 참조를 lock() 가져와 해당 필드에 Box<dyn Fn(...)> push합니다:
s.events.lock().unwrap().on_connected.push(Box::new(|e| {
println!("connected to {}", e.endpoint_url);
}));
s.events.*— SDK 내부이벤트 (본 절, 프로토콜과 무관함)s.subscribe_events(...)— OPC UA 협정이벤트 (Alarms & Conditions), 참조 이벤트 구독
전체 사건 목록
세션 수명 주기
on_connected(ConnectionEventArgs { endpoint_url, status_code, message, timestamp_utc })— 첫 연결 성공on_disconnected(同上)— 능동적 / 수동적 연결 해제on_reconnecting(同上)— 연결 끊김 감지, 자동 재연결 시작on_reconnected(同上)— 자동 재연결에 성공했습니다on_keep_alive(KeepAliveEventArgs { server_time_utc, server_status, timestamp_utc })— KeepAlive 하트비트 성공on_state_changed(SessionStateChangedEventArgs { old_state, new_state, reason, timestamp_utc })— SessionState의 모든 변경 사항
통신 오류
on_communication_error(CommunicationErrorEventArgs { status_code, category, message, timestamp_utc })— 통신 실패 (KeepAlive / Read 예외 등)on_subscription_lost(SubscriptionLostEventArgs { subscription_id, reason, will_reconnect, timestamp_utc })— 구독이 서버 측에서 삭제됨
통합 채널 (Any)
on_any 모든 내부 이벤트( DataChange / Read / Write / Browse / /
Call HistoryRead / 구독 수명 주기 포함)를 수신하며, 이를 로 OpcUaEventEntry 표시합니다:
pub struct OpcUaEventEntry {
pub category: OpcUaEventCategory,
pub severity: OpcUaEventSeverity,
pub source: String,
pub message: String,
pub status_code: StatusCode,
pub timestamp_utc: SystemTime,
// 노드 수준 이벤트 (NodeRemoved / NodeAccessDenied / NodeTypeChanged)의 목표 NodeId
pub node_id: Option<String>,
// 구독 수준 이벤트 (SubscriptionLost / SubscriptionRestored)의 구독 ID, 0 = 해당 없음
pub subscription_id: u32,
// MonitoredItem 레벨 이벤트의 ID MI , 0 = 해당 없음
pub monitored_item_id: u32,
}
OpcUaEventCategory 열거형
pub enum OpcUaEventCategory {
Unknown,
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,
// 노드 / 세션 수준에 새로운 분류 추가 (2026-04-25)
NodeRemoved = 30, // 서버에서 특정 노드 삭제 (BadNodeIdUnknown)
NodeAccessDenied = 31, // 현재 사용자의 해당 노드에 대한 권한이 부족합니다.
NodeTypeChanged = 32, // 노드 DataType 변경됨 (BadTypeMismatch)
SessionLost = 33, // 세션 만료 (재연결 전 경고)
ServerStateChanged = 34, // 서버 Running → Failed/Shutdown 등
}
유형 지정 채널 (구문 단축) — 6가지 새로운 이벤트
통합 on_any 채널 외에도, 6개의 고주파 카테고리에서는 전용 이벤트를 제공합니다:
| 필드 | Category | 트리거 시나리오 |
|---|---|---|
| events.on_node_removed | NodeRemoved | 명중 BadNodeIdUnknown |
| events.on_node_access_denied | NodeAccessDenied | BadUserAccessDenied 오류 발생 |
| events.on_node_type_changed | NodeTypeChanged | Write 시 적중 BadTypeMismatch |
| events.on_session_lost | SessionLost | 세션 만료 경고 |
| events.on_server_state_changed | ServerStateChanged | 서버 측 상태 전환 |
| events.on_subscription_restored | SubscriptionRestored | 구독 복원이 성공했습니다. |
이 6개의 필드는 모두 Vec<AnyListener>, 등록 방식은 .push(Box::new(...)), 호출 방식이 아닙니다. 콜백 서명은 모두 Box<dyn Fn(&OpcUaEventEntry) + Send + Sync>.
use darra_opcua::Session;
let mut s = Session::new("opc.tcp://localhost:4840")?;
{
let mut ev = s.events.lock().unwrap();
ev.on_node_removed.push(Box::new(|e| {
println!("⚠ 节点已被服务端删除: {}", e.source);
}));
ev.on_node_access_denied.push(Box::new(|e| {
println!("⛔ 权限不足: {}", e.source);
}));
ev.on_session_lost.push(Box::new(|e| {
println!("⚠ 会话失效, 即将重连: {}", e.message);
}));
ev.on_server_state_changed.push(Box::new(|e| {
println!("服务端状态: {}", e.message);
}));
ev.on_subscription_restored.push(Box::new(|e| {
println!("订阅已恢复: sub={} mi={}", e.subscription_id, e.monitored_item_id);
}));
} // 적시에 해제 MutexGuard
OpcUaEventSeverity 열거형
pub enum OpcUaEventSeverity { Trace, Debug, Info, Warn, Error, Fatal }
사용 예시
일반 로그 훅 (한 줄에 SDK 모든 이벤트 출력)
s.events.lock().unwrap().on_any.push(Box::new(|e| {
println!("[{:?}] [{:?}] {}: {} ({})",
e.severity, e.category, e.source, e.message, e.status_code);
}));
디버깅 단계에서 매우 간편합니다 — 특정 이벤트를 구독할 필요 없이, 한 줄의 훅으로 모든 것을 확인할 수 있습니다.
상태 머신 콜백 + 스레드 간 통신
use std::sync::mpsc;
let (tx, rx) = mpsc::channel::<bool>();
let tx2 = tx.clone();
s.events.lock().unwrap().on_state_changed.push(Box::new(move |e| {
let connected = matches!(e.new_state, darra_opcua::SessionState::Connected);
let _ = tx2.send(connected);
}));
s.connect()?;
while let Ok(connected) = rx.recv() {
if connected { println!("UI 上更新连接状态"); break; }
}
오류 통계
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
let count = Arc::new(AtomicU32::new(0));
let count2 = count.clone();
s.events.lock().unwrap().on_communication_error.push(Box::new(move |_e| {
count2.fetch_add(1, Ordering::SeqCst);
}));
구독 콜백과의 관계
구독 콜백 (sub.add_node(..., callback))은 해당 구독의 이벤트만 수신하며, on_any 는
SDK 모든 구독의 DataChange 이벤트를 수신합니다 (통합 채널). 두 가지가 공존하며, 상위 계층에서 상황에 따라 선택하여 사용합니다:
- 단일 구독 비즈니스 로직 →
sub.add_node(..., cb) - 전역 로그 / 기록 / 디버깅 →
on_any
클로저 요구 사항
모든 리스너는 다음과 같습니다 Box<dyn Fn(...) + Send + Sync>:
Fn(아님FnMut): 클로저는 캡처된 변수를 직접 수정할 수 없으며,Mutex/Atomic*/ 를 사용하여 가변성을 외부로mpsc::channel이동시킵니다.Send + Sync: 클로저 내부에서는 스레드 안전하지 않은 참조를 보유할 수 없습니다.- 실제 수명 주기 필요 (
'staticpush 후 Vec이 소유)
가변 상태가 필요한 경우, 다음을 사용하십시오 Mutex<T>:
use std::sync::{Arc, Mutex};
let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let log2 = log.clone();
s.events.lock().unwrap().on_state_changed.push(Box::new(move |e| {
let line = format!("{:?} -> {:?}", e.old_state, e.new_state);
if let Ok(mut g) = log2.lock() { g.push(line); }
}));
스레드 모델
이벤트 콜백은 C 계층 Publish 스레드 / KeepAlive 스레드 상위 호출, 호출자 스레드가 아님. 콜백 내에서:
- 길이 연산(>100 ms)을 수행할 수 없습니다. 그렇지 않으면 Publish 큐가 차단됩니다.
- panic은 SDK 처리되며, 다른 콜백을 중단시키지 않습니다.
- 스레드 간 액세스 시 직접 추가 /
Mutex사용Atomic*/mpsc::channel전달해야 함
UI 라이브러리(egui, iced, Tauri 등)는 일반적으로 메인 스레드에서 업데이트를 수행하고, 데이터를 mpsc::Sender로 메인 스레드에 전달한 후 렌더링하도록 요구합니다.
전체 예시
use darra_opcua::{Session, SessionState};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut s = Session::new("opc.tcp://localhost:4840")?;
{
let mut ev = s.events.lock().unwrap();
ev.on_connected.push(Box::new(|e| {
println!("CONNECTED: {} ({})", e.endpoint_url, e.status_code);
}));
ev.on_disconnected.push(Box::new(|e| {
println!("DISCONNECTED: {} ({})", e.endpoint_url, e.status_code);
}));
ev.on_reconnecting.push(Box::new(|e| {
println!("RECONNECTING: {}", e.endpoint_url);
}));
ev.on_state_changed.push(Box::new(|e| {
println!("STATE: {:?} -> {:?}", e.old_state, e.new_state);
}));
} // 적시에 잠금을 해제하여 MutexGuard, 콜백 내에서 다시 잠금을 걸어 데드락이 발생하는 것을 방지합니다.
s.connect()?;
let _ = SessionState::Connected;
Ok(())
}