OPC UA에서 데이터 읽어 오기 ( feat. Python )

2024. 3. 22. 12:43it

반응형

 

Python은 다양한 라이브러리와 간결한 문법으로 인해 산업 자동화 시스템에서 OPC UA 클라이언트 개발에 널리 사용된다. opcua 라이브러리는 Python에서 OPC UA 서버와의 통신을 쉽게 구현할 수 있도록 해준다. 오늘은 관련 예제를 정리할 예정이다.

 

728x90

 

0. 설치

먼저, 필요한 라이브러리를 설치해야 한다.. opcua 라이브러리가 설치되어 있지 않다면, 다음 명령어를 사용하여 설치하면 된다. 

pip install opcua

 

 

1. 기본 데이터 읽기
opc 서버에서 하나의 값은 한번 가지고 오는 방법이다.

from opcua import Client

server_url = "opc.tcp://localhost:4840"
client = Client(server_url)

try:
    client.connect()
    print("클라이언트가 서버에 연결되었습니다.")

    temp_node = client.get_node("ns=3;s=Temperature")
    temperature = temp_node.get_value()
    print(f"현재 온도: {temperature}°C")

finally:
    client.disconnect()

 

 

 

2. 주기적을 데이터 읽기

주기적으로 값을 가지고 오는 방법이다. python opcua에는 해당 로직이 없어, 직접 쓰레드로 구현해야 한다.

 

반응형

 

import threading
from opcua import Client
import time

def read_temperatures():
    server_url = "opc.tcp://localhost:4840"
    client = Client(server_url)
    client.connect()

    # 여러 온도 노드의 식별자를 리스트에 저장
    temperature_nodes = [
        "ns=3;s=Temperature1",
        "ns=3;s=Temperature2",
        "ns=3;s=Temperature3"
        # 필요한 만큼 노드 식별자 추가
    ]
    
    while True:
        for node_id in temperature_nodes:
            temp_node = client.get_node(node_id)
            temperature = temp_node.get_value()
            print(f"{node_id} 현재 온도: {temperature}°C")
        time.sleep(10) # 10초마다 모든 온도 데이터를 읽음

# 백그라운드 스레드에서 주기적으로 여러 온도 읽기
thread = threading.Thread(target=read_temperatures)
thread.start()

 

 

 

3. 이벤트 구독 방법

값이 변경될 때마다 값을 가지고 오는 방법이다. 

from opcua import Client
from opcua import ua

# OPC UA 서버의 URL
server_url = "opc.tcp://localhost:4840"

# 클라이언트 인스턴스 생성 및 서버 연결
client = Client(server_url)
client.connect()

# 구독 객체 생성
subscription = client.create_subscription(1000, None)  # 1000ms의 간격으로 통지 받음

# 모니터링할 노드 지정
node_to_monitor = client.get_node("ns=2;s=Temperature1")

# 모니터링 항목 생성 및 구독에 추가
handler = subscription.subscribe_data_change(node_to_monitor)

# 이벤트 처리를 위한 핸들러 정의 (여기서는 단순히 변경된 값을 출력하는 예제)
class SubscriptionHandler:
    def datachange_notification(self, node, val, data):
        print(f"노드 {node}의 값이 변경되었습니다: {val}")

# 구독 핸들러 등록
client.create_subscription(500, SubscriptionHandler())

try:
    # 일정 시간(예: 30초) 동안 구독을 유지
    time.sleep(30)
finally:
    # 구독 삭제
    subscription.delete()
    # 클라이언트 연결 해제
    client.disconnect()

 

 

4. 결론

OPC UA는 산업 자동화를 위한 강력하고 유연한 통신 표준이다. Python과 같은 프로그래밍 언어를 사용하여 OPC UA 클라이언트를 개발함으로써, 산업 현장의 다양한 장비와 시스템 간의 데이터를 효과적으로 수집하고 관리할 수 있다. 특히, OPCUA에서 데이터를 읽어오는 방법은 자주 사용하는 방법이니 저장해 놓으면 효율적일 것이다. 

반응형