OPC UA数据采集(二)Python 写一个 OPC UA 客户端

一、安装库opcua

pip install opcua

 

二、新建文件opcua_server.py

# -*- coding: utf-8 -*-

from opcua import Client
import time

# 配置客户端
server_url = "opc.tcp://localhost:4840"  # 服务器地址(与服务器代码一致)
node_address = "ns=2;i=2"     # 节点地址(根据服务器输出调整)

def read_temperature():
    client = Client(server_url)
    try:
        # 连接服务器
        client.connect()
        print("成功连接到OPC UA服务器")

        # 获取节点
        temp_node = client.get_node(node_address)
        print(f"已找到节点: {node_address}")

        # 持续读取温度数据
        while True:
            temperature = temp_node.get_value()
            print(f"当前温度: {temperature:.2f} °C")
            time.sleep(1)  # 每秒读取一次

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        client.disconnect()
        print("已断开与服务器的连接")

if __name__ == "__main__":
    # 先等待2秒确保服务器启动完成
    print("等待服务器初始化...")
    time.sleep(2)
    
    read_temperature()

三、运行,输出采集到的数据

posted @ 2025-07-08 10:21  daviyoung  阅读(192)  评论(0)    收藏  举报