Search code examples
.net-coreopc-ua

C# OPCUA Client access node with Tag name to setup subscriptions


I have setup an OPCUA server using python as below and its working fine:

from opcua import Server
from opcua import ua

# Create an OPC UA server instance
server = Server()
server.set_endpoint("opc.tcp://127.0.0.1:4840/freeopcua/server/")

# Setup server namespace
uri = "http://example.org"
idx = server.register_namespace(uri)

print(f"ns= {idx} value={uri}.")

#root=server.nodes.base_object_type.add_object_type(idx, "MyDevice")

# Create a new object in the address space
root = server.nodes.objects.add_object(idx, "MyObject")


# Create multiple variable nodes under the object
variables = {
    "Tag1": root.add_variable(idx, "Tag1", 0.0),
    "Tag2": root.add_variable(idx, "Tag2", 0.0),
    "Tag3": root.add_variable(idx, "Tag3", 0.0),
}

for var in variables.values():
    var.set_writable()  # Allow write access
    var.set_modelling_rule(True)
    print(f"Variable '{var}' fully qualified name: {var.nodeid.to_string()}")

# Start the server
server.start()

Can some one please help me out with how to develop a OPC client using the c# with Opc.Ua.Client library to access a node and read its value.

I have tried many different option and only one that works is this:

var nodeId = NodeId.Parse($"ns=2;i=2");
var varNode = session.ReadNode(nodeId);

however I can only store name of the tag in the string format something like MyObject:Tag1 so if I modify the above code to use the following it breaks.

var nodeId = NodeId.Parse($"ns=2;s=MyObject:Tag1");
var varNode = session.ReadNode(nodeId);

Can someone please help me to find the Nodes using the tag name and setup subscriptions for the same.


Solution

  • Your sever should use string nodeids, if you want a better readable addressing. To do this change your code to this:

    root = server.nodes.objects.add_object(ua.NodeId("MyObject", idx), "MyObject")
    
    
    # Create multiple variable nodes under the object
    variables = {
        "Tag1": root.add_variable(ua.NodeId("MyObject:Tag1", idx), "Tag1", 0.0),
        "Tag2": root.add_variable(ua.NodeId("MyObject:Tag2", idx), "Tag2", 0.0),
        "Tag3": root.add_variable(ua.NodeId("MyObject:Tag3", idx), "Tag3", 0.0),
    }
    

    No you can read them in your C# Client as so:

    var nodeId = NodeId.Parse($"ns=2;s=MyObject:Tag1");
    var varNode = session.ReadNode(nodeId);