OPC UAUse C# to read OPC UA electro-hydraulic control data

C# read OPC UA electro-hydraulic control data

  • foreword
  • 1. Confirmation items before reading data
  • 2. Specific steps
    • 1. Connect to the server
    • 2. Read all nodes
    • Get references under the specified node
    • read data
  • Summarize

Foreword

OPC UA and OPC DA protocols are commonly used in industrial production, such as the electro-hydraulic control system of fully mechanized mining supports in coal mines. OPC UA is the successor standard of OPC, but UA is added later, which means “Unified Architecture”. Its main purpose is to get rid of windows! To achieve platform-independent OPC. From OPC to OPC UA, its purpose It has not changed, it is still to realize the distributed object technology in the distributed control system. But its method has become independent of the platform. It is oriented to the open system. This means that we can implement it on an Arm /linux platform OPC server, or implement the Client program on the cloud linux platform.

1. Confirmation items before reading data

At present, most OPC UA protocols use Kepserver EX6 as the server side. When we read the data from the server side as the client side, we must ensure that the configuration of the server and the client side match.
1: The server and client must keep the network unobstructed, which is the most basic requirement.
2: Confirm the IP address of the server and the open port number.
3: Confirm the server-side security policy, whether a password is required, etc.

2. Specific steps

1. Connect to the server

The code is as follows (C# as an example):

try
            {<!-- -->
                //Create the configuration.
                ApplicationConfiguration configuration = Helpers. CreateClientConfiguration();
                // Create the endpoint configuration (use the application configuration to provide default values).
                EndpointConfiguration endpointConfiguration = EndpointConfiguration. Create(configuration);
                // The default timeout for a requests sent using the channel.
                endpointConfiguration. OperationTimeout = 300000;
                // Use the pure binary encoding on the wire.
                endpointConfiguration. UseBinaryEncoding = true;
                // Create the endpoint.
                ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
                //Create the binding factory.
                BindingFactory bindingFactory = BindingFactory. Create(configuration);
                X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find();
                // Set up a callback to handle certificate validation errors.
                configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
                // Initialize the channel which will be created with the server.
                SessionChannel channel = SessionChannel. Create(
                    configuration,
                    endpointDescription,
                    endpointConfiguration,
                    bindingFactory,
                    client Certificate,
                    null);
                // Wrap the channel with the session object.
                // This call will fail if the server does not trust the client certificate.
                m_Session = new Session(channel, configuration, endpoint);
                m_Session.ReturnDiagnostics = DiagnosticsMasks.All;
                // Register keep alive callback.
                m_Session.KeepAlive + = new KeepAliveEventHandler(Session_KeepAlive);
                UserIdentity identity = new UserIdentity();
                // Create the session. This actually connects to the server.
                // Passing null for the user identity will create an anonymous session.
                m_Session.Open("OPC UA client", identity);
                return m_Session;
            }
            catch (Exception e)
            {<!-- -->
                throw e;
            }

2. Read all nodes

The code is as follows (example):

public ReferenceDescriptionCollection BrowseNodes(NodeId sourceId)
        {<!-- -->
            m_Session = this. MySession;
            if (m_Session == null){<!-- -->return null;}
            // fetch references from the server.
            // find all of the components of the node.
            BrowseDescription nodeToBrowse1 = new BrowseDescription();

            nodeToBrowse1.NodeId = sourceId;
            nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
            //nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates;
            nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasChild;
            nodeToBrowse1.IncludeSubtypes = false;
            //nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable);
            nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Variable);
            nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
            Browser bro = new Browser(m_Session);
            ReferenceDescriptionCollection references = bro.Browse(sourceId);
            return references;
        }

Get references under the specified node

private ReferenceDescriptionCollection getTargetItemList(ReferenceDescriptionCollection references, string targetStr)
        {<!-- -->
            ReferenceDescriptionCollection returnRef = new ReferenceDescriptionCollection();
            foreach (ReferenceDescription rf in references)
            {<!-- -->
                if (!targetStr.Equals("item"))
                {<!-- -->
                    if (!rf.DisplayName.ToString().StartsWith(@"_") & amp; & amp; targetStr.Equals(rf.DisplayName.ToString()) & amp; & amp; rf.BrowseName.ToString() ! = "FolderType")
                    {<!-- -->
                        returnRef = BrowseNodes((NodeId)rf.NodeId);
                        break;
                    }
                }
                else
                {<!-- -->
                    if (!rf.DisplayName.ToString().StartsWith(@"_") & amp; & amp; rf.DisplayName.ToString() != "FolderType")
                    {<!-- -->
                        returnRef.Add(rf);
                    }
                }
            }
            return returnRef;
        }

Read data

public ResponseHeader ReadValues(
            NodeIdCollection nodesToRead,
            out DataValueCollection results)
        {<!-- -->
            ResponseHeader response = null;
            results = null;
            DiagnosticInfoCollection diagnosticInfos;
            // build list of attributes to read.
            ReadValueIdCollection valueIdsToRead = new ReadValueIdCollection();
            try
            {<!-- -->
                for (int i = 0; i < nodesToRead. Count; i ++ )
                {<!-- -->
                    ReadValueId attributeToRead = new ReadValueId();
                    attributeToRead.NodeId = nodesToRead[i];
                    attributeToRead.AttributeId = Attributes.Value;
                    attributeToRead.Handle = attributeIdToString(Attributes.Value);
                    valueIdsToRead. Add(attributeToRead);
                }
                response = m_Session. Read(
                        null,
                        0,
                        TimestampsToReturn.Both,
                        valueIdsToRead,
                        out results,
                        out diagnosticInfos);
            }
            catch (Exception e)
            {<!-- -->
                throw e;
            }
            return response;
        }

Summary

When we read data from the server as a client, we still need to follow the configuration structure of the server, such as the relationship between the structures of server, channel, group, and item. Using the above key methods, the OPC UA data of each interface can be read smoothly.