Python OPC UA订阅节点的Value,当Value变化时执行执行的Handle

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

M_qsqsqsq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值