본문으로 건너뛰기

이벤트 구독

OPC UA 이벤트(Alarms & Conditions)는 구독을 subscribe_events 통해 확인할 수 있습니다. 이는 OPC UA 프로토콜 이벤트, 및 SDK 내부 ua.events.* 같은 말이 아닙니다.

차이점
  • ua.subscribe_events(...) — OPC UA 프로토콜 이벤트 (알람 / 조건, 서버 푸시, 본 절)
  • ua.events.* — SDK 내부 사건 (세션 / 구독 수명 주기, 프로토콜과 무관)

서명​

def subscribe_events(self,
node_id: Optional[str] = None,
existing_subscription: Optional[Subscription] = None
) -> EventSubscription: ...
매개변수기본값설명
node_idNone (Server, i=2253)이벤트 소스 노드; 전달하지 않으면 구독 Server (i=2253)
existing_subscriptionNone기존 구독을 재사용; 'None'인 경우 새로 생성 publishing_interval_ms=1000.0 컨테이너이며, EventSubscription이 라이프사이클을 관리합니다.

EventSubscription​

구성원설명
event_arrivedList[Callable[[EventArrivedEventArgs], None]] 이벤트가 콜백 목록에 추가됨
subscribe(node_id, event_filter=None)고급 사용법: 객체 생성 후 재구독 / 전송 EventFilter, 참조 EventFilter
attach_container_subscription(container, owns=True)Subscription 컨테이너를 연결하려면; subscribe 그 전에 반드시 먼저 연결해야 합니다.
dispose()해당 이벤트를 제거할 MI때 owns=True 컨테이너도 함께 파기합니다.

컨텍스트 with 매니저 (__enter__ / __exit__)를 지원합니다.close() 방법이 없다 —— 오직 만 해방된다 dispose().

dispose의 두 가지 동작

ua.subscribe_events() : 인수를 전달하지 않으면 existing_subscription 컨테이너는 EventSubscription에 귀속되며, 컨테이너 전체 구독이 dispose() 소멸됩니다. 인수를 전달하면 해당 Event만 existing_subscription 삭제하고 owns=False dispose() MI, 컨테이너는 호출자에게 남깁니다.

EventArrivedEventArgs​

@dataclass
class EventArrivedEventArgs:
severity: int = 0
message: Optional[str] = None
source_name: Optional[str] = None
time: Optional[datetime] = None
event_type: Optional[str] = None
필드유형설명
severityint심각도 (uint16)
messageOptional[str]사건 내용
source_nameOptional[str]이벤트 소스 이름
timeOptional[datetime]사건 발생 시간 (UTC; 유효한 시간을 가져올 수 없는 경우 None)
event_typeOptional[str]이벤트 유형 식별 문자열 (서버에서 지정)
5개의 필드가 고정되어 있으며, fields 목록은 없습니다.

콜백 매개변수는 이 5개의 필드로 고정되어 있습니다.없음 args.fields, 또한 EventId / ConditionId / 사용자 정의 필드도 없습니다 —— 추가 정보가 필요한 경우 콜백에서 ua.read(...) 직접 읽어와야 합니다.

사용법​

기본 구독 서버 노드​

import time

with ua.subscribe_events() as ev:
def on_event(e):
print(f"[{e.severity}] {e.source_name}: {e.message}")
print(f" EventType={e.event_type} Time={e.time}")
ev.event_arrived.append(on_event)

time.sleep(300) # 5분

지정된 노드의 이벤트 구독​

with ua.subscribe_events("ns=2;s=Line1") as ev:   # Line1 반드시 ~이어야 한다 EventNotifier
ev.event_arrived.append(lambda e: print(e.message))
time.sleep(60)

기존 구독 컨테이너 재사용​

with ua.create_subscription(500) as sub:
sub.add_node("ns=2;s=Counter") # 데이터 구독

# Event를 동일한 컨테이너에 MI 연결하기
with ua.subscribe_events("ns=2;s=Line1", existing_subscription=sub) as ev:
ev.event_arrived.append(lambda e: print(e.message))
time.sleep(60)
# ev.dispose는 Event만 제거하고 MI, sub는 소멸시키지 않습니다.

EventNotifier​

EventNotifier 속성(12)이 0이 아닌 노드만이 이벤트를 생성할 수 있습니다. 기본값인 Server(i=2253)는 EventNotifier입니다. 사용자 정의 노드가 이벤트 소스 기능을 갖는지 여부는 서버 구현에 따라 다릅니다.

EventFilter (고급)​

EventType / Severity 등의 조건으로 이벤트를 필터링하려면 EventSubscription.subscribe(node_id, event_filter)에 EventFilter를 전달합니다. 현재 버전에서는 filter가 서버로 내려가지 않습니다 — 이벤트는 항상 전체가 푸시되고 필드는 고정된 5개입니다. 자세한 내용은 EventFilter를 보십시오. 간편 진입점 ua.subscribe_events(...)는 filter 매개변수를 받지 않습니다.

알람 처리 (확인 / 승인)​

AlarmConditionType 이벤트를 수신한 후, 운영자는 일반적으로 Acknowledge(확인)를 수행해야 합니다. 이를 통해 call 알람 노드의 확인 방법(Acknowledge Method):

매개변수는 어디서 오는가

condition_id / event_id 이벤트 콜백의 5개 필드 중 하나에 포함되지 않음 (위 참조), 업무 측의 자체 알람 모델/서버 측 객체 트리에서 제공됩니다. 확인만 할 경우, 메모를 추가할 때는 직접 ua.acknowledge(condition_id, event_id, comment) / 를 사용합니다 ua.add_comment(...). 참조: 알람 및 조건; 아래의 작성 방식은 call 다른 알람 메서드를 호출하는 데 사용됩니다.

from darra_opcua import OpcUaVariant

# method_node_id 알람 노드에서 browse 빠져나와야 합니다 (BrowseName = "Acknowledge"),
# 문자열을 조합하는 방식이 아닙니다. f"{condition_id}.Acknowledge"
ack_node_id = next(
r.node_id for r in ua.browse(condition_id)
if r.browse_name == "Acknowledge")

results = ua.call(
object_node_id=condition_id,
method_node_id=ack_node_id,
inputs=[
OpcUaVariant().set_string(event_id), # 제1항은 EventId (ByteString)
OpcUaVariant().set_string("Operator confirmed"), # 2번째 매개변수는 Comment (LocalizedText)입니다.
])

# call 반환된 List[OpcUaVariant]는 각각 핸들을 보유하고 있으므로, 반드시 해제해야 합니다.
for v in results:
with v:
pass
매개변수 유형이 일치하지 않습니다.

Acknowledge의 입력 매개변수 시그니처는 입니다 (EventId: ByteString, Comment: LocalizedText). Python에는 OpcUaVariant,만 set_boolean / set_sbyte / set_byte / set_int16 / set_uint16 / set_int32 / set_uint32 / set_int64 / set_float / set_double / set_string / set_datetime 있습니다. 없음 set_bytestring / set_localized_text —— 위 예제에서 set_string 를 사용한 것은 매개변수를 String으로 형변환하여 전달한 것으로, 서버 측에서 이를 인식할지 여부는 서버 측의 구현 방식에 달려 있습니다. 엄격한 형식 일치가 필요한 경우, 먼저 서버 측이 String을 허용하는지 확인해야 합니다.

다음 단계​