C#使用UA-.NETStandard开发OPC UA客户端

OpcUa作为客户端测试代码

1、打开服务端,使用开源代码GitHub - OPCFoundation/UA-.NETStandard: OPC Unified Architecture .NET Standard中Quickstarts.ReferenceServer启动服务端

2、运行打印结果如下

测试标准OPC UA
Session_KeepAlive
2023/9/27 21:09:39Connected, loading complex type system.
ReadNode查询到这个Node的属性
data value : 55

3、测试启动

MyOpcUaServer myOpcUaServer = new MyOpcUaServer();

4、连接服务端测试类,引用NuGet:OPCFoundation.NetStandard.Opc.Ua

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Configuration;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes;
using Org.BouncyCastle.Asn1.X509;

namespace 标准OPC_UA
{
    internal class MyOpcUaClient
    {
        public string OpcUaName = "My Opc ua";

        private ApplicationConfiguration m_configuration;
        private Session m_session;
        private SessionReconnectHandler m_reconnectHandler;
        private CertificateValidationEventHandler m_CertificateValidation;
        //private Dictionary<Uri, EndpointDescription> m_endpoints;


        public MyOpcUaClient(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000) {
            InitConfiguration();

            // 连接测试
            Connect(uri, useSecurity, sessionTimeout);
            //Read();

            ConfiguredEndpointCollection configuredEndpoints = new ConfiguredEndpointCollection();
            List<ConfiguredEndpoint> list = configuredEndpoints.GetEndpoints("opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");

            if (m_session != null)
            {
                // 读取属性和值
                Node node = m_session.ReadNode("ns=7;s=Alarms.AnalogSource");
                if (node != null)
                {
                    Console.WriteLine("ReadNode查询到这个Node的属性");
                }

                WriteValueCollection nodesToWrite = new WriteValueCollection();
                WriteValue writeValue = new WriteValue();
                writeValue.NodeId = "ns=7;s=Alarms.AnalogSource";           // 看下属性是否是可写
                writeValue.AttributeId = 13u;                               // 不定义无法正常设置
                writeValue.Value = new DataValue(new Variant(55));          // 设置值
                nodesToWrite.Add(writeValue);
                StatusCodeCollection statusCodes = new StatusCodeCollection();
                DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
                ResponseHeader rep = m_session.Write(null, nodesToWrite, out statusCodes, out diagnosticInfos);

                DataValue value = m_session.ReadValue("ns=7;s=Alarms.AnalogSource");
                if(value != null)
                {
                    Console.WriteLine("data value : " + value.ToString());
                }
            }

            //TranslateBrowsePathsToNodeIds();
        }
        void InitConfiguration()
        {
            var certificateValidator = new CertificateValidator();
            certificateValidator.CertificateValidation += (sender, eventArgs) =>
            {
                if (ServiceResult.IsGood(eventArgs.Error))
                    eventArgs.Accept = true;
                else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)
                    eventArgs.Accept = true;
                else
                    throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo));
            };

            SecurityConfiguration securityConfigurationcv = new SecurityConfiguration
            {
                AutoAcceptUntrustedCertificates = true,
                RejectSHA1SignedCertificates = false,
                MinimumCertificateKeySize = 1024,
            };
            certificateValidator.Update(securityConfigurationcv);

            // Build the application configuration
            var configuration = new ApplicationConfiguration
            {
                ApplicationName = OpcUaName,
                ApplicationType = ApplicationType.Client,
                CertificateValidator = certificateValidator,
                ApplicationUri = "urn:MyClient", //Kepp this syntax
                ProductUri = "OpcUaClient",

                ServerConfiguration = new ServerConfiguration
                {
                    MaxSubscriptionCount = 100000,
                    MaxMessageQueueSize = 1000000,
                    MaxNotificationQueueSize = 1000000,
                    MaxPublishRequestCount = 10000000,
                },

                SecurityConfiguration = new SecurityConfiguration
                {
                    AutoAcceptUntrustedCertificates = true,
                    RejectSHA1SignedCertificates = false,
                    MinimumCertificateKeySize = 1024,
                    SuppressNonceValidationErrors = true,

                    ApplicationCertificate = new CertificateIdentifier
                    {
                        StoreType = CertificateStoreType.X509Store,
                        StorePath = "CurrentUser\\My",
                        SubjectName = OpcUaName,
                    },
                    TrustedIssuerCertificates = new CertificateTrustList
                    {
                        StoreType = CertificateStoreType.X509Store,
                        StorePath = "CurrentUser\\Root",
                    },
                    TrustedPeerCertificates = new CertificateTrustList
                    {
                        StoreType = CertificateStoreType.X509Store,
                        StorePath = "CurrentUser\\Root",
                    }
                },

                TransportQuotas = new TransportQuotas
                {
                    OperationTimeout = 6000000,
                    MaxStringLength = int.MaxValue,
                    MaxByteStringLength = int.MaxValue,
                    MaxArrayLength = 65535,
                    MaxMessageSize = 419430400,
                    MaxBufferSize = 65535,
                    ChannelLifetime = -1,
                    SecurityTokenLifetime = -1
                },
                ClientConfiguration = new ClientConfiguration
                {
                    DefaultSessionTimeout = -1,
                    MinSubscriptionLifetime = -1,
                },
                DisableHiResClock = true
            };

            configuration.Validate(ApplicationType.Client);
            m_configuration = configuration;
        }

        async void Connect(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000)
        {
            if (m_session != null)
            {
                m_session.KeepAlive -= Session_KeepAlive;
                m_session.Close(10000);
                m_session = null;
            }
            // select the best endpoint.
            var endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, uri, useSecurity, sessionTimeout);
            var endpointConfiguration = EndpointConfiguration.Create(m_configuration);
            var endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);

            m_session = await Session.Create(
                m_configuration,
                //connection,
                endpoint,
                false,
                //true,        //DisableDomainCheck
                "Quickstart Reference Client", //(String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName,
                (uint)sessionTimeout,
                null,       //UserIdentity,
                null);      //PreferredLocales

            // set up keep alive callback.
            m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);

            // set up reconnect handler.
            m_reconnectHandler = new SessionReconnectHandler(true, 10 * 1000);

            try
            {
                Console.WriteLine(DateTime.Now + "Connected, loading complex type system.");
                var typeSystemLoader = new ComplexTypeSystem(m_session);
                await typeSystemLoader.Load();
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now + "Connected, failed to load complex type system.");
                Utils.LogError(e, "Failed to load complex type system.");
            }
        }

        bool Read()
        {
            DataValueCollection dataValues = new DataValueCollection();
            DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
            ResponseHeader resp = m_session.Read(null, 0, TimestampsToReturn.Both, null, out dataValues, out diagnosticInfos);
            return true;
        }
        void TranslateBrowsePathsToNodeIds()
            //RequestHeader requestHeader,
            //BrowsePathCollection browsePaths)
            //out BrowsePathResultCollection results,
            //out DiagnosticInfoCollection diagnosticInfos)
        {
            //m_session.TranslateBrowsePathsToNodeIds(null, "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");
            BrowsePathResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;
            var startNodeId = new NodeId(Objects.ObjectsFolder);
            var browsePaths1 = new BrowsePathCollection
            {
                new BrowsePath
                {
                    RelativePath = RelativePath.Parse("Objects", m_session.TypeTree, m_session.NamespaceUris, m_session.NamespaceUris),
                    StartingNode = startNodeId
                }
            };
            ResponseHeader resp = m_session.TranslateBrowsePathsToNodeIds(null, browsePaths1, out results, out diagnosticInfos);

        }

        private void ChangeSession(Session session, bool refresh)
        {
            //m_session = session;

            //if (AttributesControl != null)
            //{
            //    AttributesControl.ChangeSession(session);
            //}

            //BrowseTV.Nodes.Clear();

            //if (m_session != null)
            //{
            //    INode node = m_session.NodeCache.Find(m_rootId);

            //    if (node != null)
            //    {
            //        TreeNode root = new TreeNode(node.ToString());
            //        root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false);
            //        root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true);

            //        ReferenceDescription reference = new ReferenceDescription();
            //        reference.NodeId = node.NodeId;
            //        reference.NodeClass = node.NodeClass;
            //        reference.BrowseName = node.BrowseName;
            //        reference.DisplayName = node.DisplayName;
            //        reference.TypeDefinition = node.TypeDefinitionId;
            //        root.Tag = reference;

            //        root.Nodes.Add(new TreeNode());
            //        BrowseTV.Nodes.Add(root);
            //        root.Expand();
            //        BrowseTV.SelectedNode = root;
            //    }
            //}
        }

        private void Session_KeepAlive(ISession session, KeepAliveEventArgs e)
        {
            Console.WriteLine("Session_KeepAlive");
        }

    }
}
相关推荐
捕鲸叉9 分钟前
MVC(Model-View-Controller)模式概述
开发语言·c++·设计模式
wrx繁星点点25 分钟前
享元模式:高效管理共享对象的设计模式
java·开发语言·spring·设计模式·maven·intellij-idea·享元模式
真的想不出名儿28 分钟前
Java基础——反射
java·开发语言
努力编程的阿伟1 小时前
【Java SE语法】抽象类(abstract class)和接口(interface)有什么异同?
java·开发语言
包饭厅咸鱼1 小时前
QML----复制指定下标的ListModel数据
开发语言·数据库
bryant_meng1 小时前
【python】Distribution
开发语言·python·分布函数·常用分布
红黑色的圣西罗1 小时前
Lua 怎么解决闭包内存泄漏问题
开发语言·lua
yanlou2331 小时前
KMP算法,next数组详解(c++)
开发语言·c++·kmp算法
小林熬夜学编程1 小时前
【Linux系统编程】第四十一弹---线程深度解析:从地址空间到多线程实践
linux·c语言·开发语言·c++·算法
墨墨祺2 小时前
嵌入式之C语言(基础篇)
c语言·开发语言