在OPCUA服务器端,当数据或者变化时,要做一些处理。例如:在聚合服务器或者网关程序中,当客户端修改某一个变量时,需要将修改值传递给底层服务器或者现场总线设备(比如modbus设备。
这是一种中继方式。SubHanlder 相当于AfterWriteCallback 程序。
演示代码
import sys
sys.path.insert(0, "..")
import time
from opcua import Server
class SubHandler(object):
def datachange_notification(self, node, val, data):
print(node.get_browse_name().Name+" DataChanged")
pass
if __name__ == "__main__":
# setup our server
server = Server()
server.set_endpoint("opc.tcp://127.0.0.1:48400/freeopcua/server/")
uri = "http://examples.freeopcua.github.io"
idx = server.register_namespace(uri)
# get Objects node, this is where we should put our nodes
objects = server.get_objects_node()
# populating our address space
myobj = objects.add_object(idx, "MyObject")
myvar = myobj.add_variable(idx, "MyVariable", 6.7)
myvar.set_writable() # Set MyVariable to be writable by clients
# starting!
server.start()
handler = SubHandler()
sub = server.create_subscription(100, handler)
sub.subscribe_data_change(myvar)
try:
count = 0
while True:
time.sleep(1)
count += 0.1
myvar.set_value(count)
finally:
#close connection, remove subcsriptions, etc
server.stop()
在上面的程序中,使用下列函数实现订阅
subscribe_data_change
(nodes, attr=<AttributeIds.Value: 13>, queuesize=0)
nodes可以为一个node 也可以为以节点的数组,例如
sub.subscribe_data_change([myvar1,myvar2])