跟随上一篇文章
直接上代码
# encoding=utf-8
from opcua import Client
from datetime import datetime
from opcua import ua
def set_value_to_OPC(tagID,value,time_str = None):
# tagID: 指对应OPCUA server中点对应的ID号
# value:需要写入的值
# time_str:写入值对应的UTC时间,格式为'%Y-%m-%d %H:%M:%S'
# client = Client("opc.tcp://127.0.0.1:48408/freeopcua/server/")
# client = Client("opc.tcp://172.16.102.105:48408/freeopcua/server/") #AWS 服务上地址
#通过tagID找到对应的tag,并写入值
# try:
# client.connect()
# tagID = tagID
# value = value
# tag = client.get_node("ns=2;i={}".format(tagID))
# if time_str == None:
# datavalue = value
# else:
# datavalue = ua.DataValue(value)
# date_time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
# datavalue.SourceTimestamp = date_time
# tag.set_value(datavalue)
# # v.set_value(i)
# client.disconnect()
# except enumerate as e:
# print(e)
client = Client("opc.tcp://192.168.70.134:62551/DataAccessServer")
try:
print(client.connect())
tagID = tagID
value = value
# tag = client.get_node("ns=2;i={}".format(tagID))
tag = client.get_node("ns=2;s=1:IN7?Value")
print(tag.get_value())
# datavalue = ua.DataValue(56)
# tag.set_value(datavalue)
# print(tag.get_value())
dv = ua.DataValue(ua.Variant(125, ua.VariantType.Float))
#设置值,与数据类型
dv.ServerTimestamp = None
dv.SourceTimestamp = None
tag.set_value(dv)
# if time_str == None:
# datavalue = value
# else:
# datavalue = ua.DataValue(value)
# date_time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
# datavalue.SourceTimestamp = date_time
# tag.set_value(datavalue)
client.disconnect()
except enumerate as e:
print(e)
#默认写入值
# set_value_to_OPC(410,5.6,'2021-10-12 08:06:00')
#指定数据类型写入值
set_value_to_OPC("1:IN7?Value",34)
网友评论