创建一个可以访问节点的 opc-ua 方法。我的主要目标是通过一次服务器调用返回节点列表(例如,一个文件夹或特定文件夹中的所有节点),而不是每个节点一个。
我发现这个 opc-ua 方法的示例对我有用: https://github.com/ifak-prototypes/opcua_examples/tree/main/src/MethodsServerSimple
但是那个人不访问节点。
我创建了一个最小的非工作服务器示例,它公开两个节点(Node1、Node2)和方法 sum()。
from opcua import ua, Server
def sum_method(parent):
val1 = node1.get_value()
val2 = node2.get_value()
return [ua.Variant(val1 + val2, ua.VariantType.Double)]
if __name__ == "__main__":
server = Server()
server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
uri = "http://example.opcua.server"
idx = server.register_namespace(uri)
objects = server.get_objects_node()
# Add two nodes with initial values
node1 = objects.add_variable(idx, "Node1", 5.5)
node2 = objects.add_variable(idx, "Node2", 10.5)
node1.set_writable()
node2.set_writable()
# Add a method to sum the two nodes
objects.add_method(idx, "sum", sum_method, [], [ua.VariantType.Double])
# Start the server
server.start()
try:
input("Server is running. Press Enter to stop...")
finally:
server.stop()
以及调用该方法的客户端代码:
from opcua import Client
if __name__ == "__main__":
client = Client("opc.tcp://localhost:4840/freeopcua/server/")
try:
# Connect to the server
client.connect()
print("Client connected")
# Access the root node and browse to the Objects node
objects_node = client.get_objects_node()
# Find the method node by browsing or by known ID/path
sum_method = objects_node.get_child(["0:MyObject", "0:sum"])
# Call the method, no input arguments
result = sum_method.call()
print(f"The sum of the two node values is: {result}")
finally:
# Close the connection
client.disconnect()
print("Client disconnected")
和错误:
opcua.ua.uaerrors._auto.BadNoMatch: "The requested operation has no match to return."(BadNoMatch)