import time
import opcua
from opcua import ua
from opcua.ua import uatypes
class SubHandler(object):
"""
Subscription Handler. To receive events from server for a subscription
data_change and event methods are called directly from receiving thread.
Do not do expensive, slow or network operation there. Create another
thread if you need to do such a thing
"""
# 当有数据发生变化时会执行该方法
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
url = 'opc.tcp://192.168.1.39:4840'
client = opcua.Client(url)
client.connect()
# test_node节点是PLC里的一个bool数组,长度为20
test_node = client.get_node('ns=4;s=CIP数据BOOL')
# test_node节点是PLC里的一个String
test_node1 = client.get_node('ns=4;s=ABC')
handler = SubHandler()
# 创建订阅
sub = client.create_subscription(500, handler)
print(sub.is_ready())
# 数据变化时,可监视多个节点组成的列表
handle = sub.subscribe_data_change([test_node1, test_node])
time.sleep(2)
# 取消handle的订阅,执行后数据变化时不会再执行handle
# sub.unsubscribe(handle)
# 删除服务器上的订阅。这是由客户端和服务器类在退出时自动完成的
# sub.delete()
# client.disconnect()
输出:
Python: New data change event ns=4;s=ABC 888
Python: New data change event ns=4;s=CIP数据BOOL [True, True, True, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False]
如果执行client.disconnect()
会报错opcua.ua.uaerrors._auto.BadSessionClosed: "The session was closed by the client."(BadSessionClosed)