Session 세션 — OpcUaSession
OpcUaSession Client의 기본 클래스로, 하나의 인스턴스가 하나의 에 해당합니다 OPC UA Session. 모든 액세스(읽기 / 쓰기 / browse / 구독 / call / 기록)는 이 객체를 통해 이루어집니다.
DarraOpcUa이는OpcUaSession의 호환 별칭 (DarraOpcUa = OpcUaSession)이며, 둘은 동일합니다.
하위 페이지 이동
- 구조 및 연결 매개변수는 다음을 참조하십시오. 생성자.
- 연결/해제 방법은 다음을 참조하십시오. 연결 관리.
- 단일 항목 / 일괄 읽기/쓰기에 대해서는 다음을 참조하십시오. read / write.
- 내부 사건 통합 채널에 대해서는 다음을 참조하십시오. Events.
- 네임스페이스 역조회에 대해서는 다음을 참조하십시오. Namespaces.
- 하트비트 및 세션 유지에 대해서는 다음을 참조하십시오. KeepAlive.
공용 속성
| 분류 | 속성 | 유형 | 접근 | 설명 |
|---|---|---|---|---|
| 연결 | endpoint_url | str | R | 생성 시 지정된 엔드포인트 URL |
security_mode | MessageSecurityMode | R | 보안 모드 (NONE / Sign / SignAndEncrypt) | |
| 상태 | state | SessionState | R | 현재 세션 상태 (Disconnected / Connecting / Connected / Reconnecting / Closing / Failed) |
is_connected | bool | R | 연결되어 있는지 여부 (= state == SessionState.Connected) | |
handle | int | R | C 계층 네이티브 세션 핸들 (내부) | |
| 자식 객체 | nodes | NodeCollection | R | Lazy Load 노드 액세서 |
namespaces | NamespaceCollection | R | 네임스페이스 URI ↔ 인덱스 상호 변환 | |
| 이벤트 | events | OpcUaEvents | R | 세션 수준 이벤트 집합: state_changed / connected / disconnected / reconnecting / reconnected / keep_alive / communication_error / subscription_lost / node_removed / node_access_denied / node_type_changed / session_lost / server_state_changed / subscription_restored / any (각각은 List[Callable]이며, .append을 사용하여 등록) |
| 구성 | keep_alive_interval_ms | int | RW | KeepAlive 하트비트 주기 (기본값 10000 ms, <= 0 = 비활성화) |
auto_publish | bool | RW | 백그라운드 Publish 스레드 시작/중지 (속성 초기값: False; 생성자 매개변수 auto_publish_on_connect의 기본값은 True이며, connect() 내에서 자동으로 True로 설정됨) |
공용 메서드
연결 관리
connect()— 연결 설정 (Hello → SecureChannel → Session → Activate)disconnect()— 수동으로 연결 끊기, 인스턴스 재연결 가능dispose() / close()— 하트비트 중지 + 네이티브 세션 종료 + 스택 참조 해제 (with종료 시 자동으로 호출됨dispose)
하트비트와 발행
publish(timeout_ms = 2000)— Publish를 수동으로 한 번 실행하면 반환됩니다StatusCode(일반적으로 호출할 필요가 없음)
읽기 / 쓰기
read(node_id, attribute = AttributeId.Value)— 단일 노드에서 속성 지정 읽기read_many(node_ids, attribute)— 일괄 읽기 (단일 속성)write(node_id, value, attribute = AttributeId.Value)— 주문 작성 노드
열람
browse(node_id, filter = NodeClass.Unspecified)— 단일 레이어 보기browse_many(node_ids, filter)— 일괄 보기browse_with_paging(node_id, filter)— 페이지 ContinuationPoint 넘기기 기능 지원browse_next(continuation_point, release = False)— 다음 페이지로 넘어가기translate_browse_paths(paths)— 경로를 일괄적으로 다음과 같이 해석합니다. NodeIdresolve(path, start_node_id = None)— 단일 경로 분석register_nodes(node_ids)— 임시 등록, 높은 효율 NodeIdunregister_nodes(registered_node_ids)— 임시 계정 해지 NodeId
구독하기
create_subscription(publishing_interval_ms = 500.0)— 데이터 구독 생성subscribe_events(node_id = None, existing_subscription = None)— 이벤트 구독 (알람 / 조건)transfer_subscriptions(subscription_ids, send_initial_values = True)— 세션 간 구독 이전
메서드 호출
call(object_node_id, method_node_id, inputs = None)— 노드 OPC UA Method 호출
이력
read_history(node_id, start_utc, end_utc, max_values = 0)— 원시 이력 읽기 (간편 접속)read_history_modified(...)— 수정 내역이 포함된 이력을 읽기read_history_at_time(...)— 지정된 시점의 보간값 읽기read_history_processed(...)— 집계 (평균 / 최소 / 최대 / TimeAverage / ...)read_history_events(...)— 이력 이벤트 읽기update_history(...)— 삽입 / 교체 / 업데이트 내역delete_history_range(...)— 시간대별로 기록 삭제
제어
cancel(request_handle)— 세션에서 처리되지 않은 요청을 취소하고, 서버 측에서 실제로 취소된 요청 수를 반환합니다 (int)
Safe 변형 (예외를 절대 발생시키지 않음)
read_safe(node_id, attribute)→(StatusCode, Optional[OpcUaDataValue])write_safe(node_id, value, attribute)→StatusCodebrowse_safe(node_id, filter)→(StatusCode, List[Reference])call_safe(object_node_id, method_node_id, inputs=None)→(StatusCode, List[OpcUaVariant])read_history_safe(node_id, start_utc, end_utc, max_values = 0)→(StatusCode, List[OpcUaDataValue])
고급 검색 / 하위 구간
browse_filtered(nid, node_class_filter, direction, reference_type_id, include_subtypes)— 방향성 + 참조 유형 필터링 (현재는browse+ 클라이언트 측 NodeClass 필터링으로 축소됨)read_range(node_id, range_, attribute)/write_range(node_id, range_, value, attribute)— 부분 배열 읽기/쓰기 (NumericRange); 전체 범위일 경우 전달read/write, 전체 범위가 아닐 경우 현재 예외 발생NotImplementedError
이력 스트림
read_history_stream(node_id, start_utc, end_utc, batch_size = 1000)— 비동기 생성자, 하나씩 yieldOpcUaDataValue(취소 매개변수 없음)
서버 정보
read_server_status()—ServerStatus반환 (포함:build/state/ 타임스탬프)read_server_state()—ServerState열거형 반환read_current_time()—Optional[datetime]반환
알람 및 조건
acknowledge/confirm/add_comment/enable_condition/disable_condition/condition_refresh/condition_refresh2/one_shot_shelve/timed_shelve/unshelve— 참조 알람 및 확인
전체 예시
from darra_opcua import OpcUaSession, OpcUaVariant # 모듈명 darra_opcua
import time
with OpcUaSession("opc.tcp://localhost:4840") as ua:
ua.events.connected.append(
lambda e: print(f"Connected to {e.endpoint_url}"))
ua.events.disconnected.append(
lambda e: print(f"Disconnected: {e.message}"))
ua.connect()
# 읽기
with ua.read("ns=2;s=Temperature") as dv:
print(f"T = {dv.value} °C")
# 쓰기
st = ua.write("ns=2;s=Setpoint", OpcUaVariant().set_double(42.0))
print(f"Write status = {st.name}")
# 구독하기
with ua.create_subscription(500) as sub:
sub.data_changed.append(
lambda e: print(f"{e.node_id} = {e.value_string} ({e.status.name})"))
sub.add_node("ns=2;s=Counter")
# 방법
outputs = ua.call(
"ns=2;s=Calc", "ns=2;s=Calc.Add",
[OpcUaVariant().set_int32(3), OpcUaVariant().set_int32(4)])
for v in outputs:
with v:
print(f"sum = {v.as_int32}")
time.sleep(60)