我正在try 创建我自己的OPC UA客户端.我正在使用Nuget包OPCFoundation.NetStandard.Opc.Ua.为此,我使用了以下代码示例:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

using Opc.Ua;   // Install-Package OPCFoundation.NetStandard.Opc.Ua
using Opc.Ua.Client;
using Opc.Ua.Configuration;

using System.Threading;

namespace Test_OPC_UA
{
    public partial class Form1 : Form
    {
        //creating a object that encapsulates the netire OPC UA Server related work
        OPCUAClass myOPCUAServer;

        //creating a dictionary of Tags that would be captured from the OPC UA Server
        Dictionary<String, Form1.OPCUAClass.TagClass> TagList = new Dictionary<String, Form1.OPCUAClass.TagClass>();


        public Form1()
        {
            InitializeComponent();


            //Add tags to the Tag List, For each tag, you have to define the name of the tag and its address
            //the address can typically be found by browsing the OPC UA Server's tree. In the example below
            // The OPC Server had the following hierarchy: M0401 -> CPU945 -> IBatchOutput
            //i used TBC0401 as a name of the tag, you can use any name
            //add as many tags as you want to capture
            TagList.Add("TBC0401", new Form1.OPCUAClass.TagClass("TBC0401", "M0401.CPU945.iBatchOutput"));

            //to initialize the OPC UA Server, provide the IP Address, Port Number, the list of tags you want to capture
            //in some OPC UA servers and kepware aswell the session can be closed by the OPC UA Server, so its better to 
            //allow the class to reinitiate session periodically, before renewing current sessions are closed
            myOPCUAServer = new OPCUAClass("127.0.0.1", "49320", TagList, true, 1, "2");


            //once the OPC Server has been initialized, you can easily read Tag values and even see when they were
            // updated last time
            //as an example i could read the TBC0401 tag by:

            var tagCurrentValue = TagList["TBC0401"].CurrentValue;
            var tagLastGoodValue = TagList["TBC0401"].LastGoodValue;
            var lastTimeTagupdated = TagList["TBC0401"].LastUpdatedTime;

        }



        public class OPCUAClass
        {
            public string ServerAddress { get; set; }
            public string ServerPortNumber { get; set; }
            public bool SecurityEnabled { get; set; }
            public string MyApplicationName { get; set; }
            public Session OPCSession { get; set; }
            public string OPCNameSpace { get; set; }
            public Dictionary<string, TagClass> TagList { get; set; }

            public bool SessionRenewalRequired { get; set; }
            public double SessionRenewalPeriodMins { get; set; }
            public DateTime LastTimeSessionRenewed { get; set; }
            public DateTime LastTimeOPCServerFoundAlive { get; set; }
            public bool ClassDisposing { get; set; }
            public bool InitialisationCompleted { get; set; }
            private Thread RenewerTHread { get; set; }
            public OPCUAClass(string serverAddres, string serverport, Dictionary<string, TagClass> taglist, bool sessionrenewalRequired, double sessionRenewalMinutes, string nameSpace)
            {
                ServerAddress = serverAddres;
                ServerPortNumber = serverport;
                MyApplicationName = "MyApplication";
                TagList = taglist;
                SessionRenewalRequired = sessionrenewalRequired;
                SessionRenewalPeriodMins = sessionRenewalMinutes;
                OPCNameSpace = nameSpace;
                LastTimeOPCServerFoundAlive = DateTime.Now;
                InitializeOPCUAClient();

                if (SessionRenewalRequired)
                {
                    LastTimeSessionRenewed = DateTime.Now;
                    RenewerTHread = new Thread(renewSessionThread);
                    RenewerTHread.Start();
                }
            }

            //class destructor
            ~OPCUAClass()
            {

                ClassDisposing = true;
                try
                {

                    OPCSession.Close();
                    OPCSession.Dispose();
                    OPCSession = null;
                    RenewerTHread.Abort();
                }
                catch { }

            }

            private void renewSessionThread()
            {
                while (!ClassDisposing)
                {
                    if ((DateTime.Now - LastTimeSessionRenewed).TotalMinutes > SessionRenewalPeriodMins
                        || (DateTime.Now - LastTimeOPCServerFoundAlive).TotalSeconds > 60)
                    {
                        Console.WriteLine("Renewing Session");
                        try
                        {
                            OPCSession.Close();
                            OPCSession.Dispose();
                        }
                        catch { }
                        InitializeOPCUAClient();
                        LastTimeSessionRenewed = DateTime.Now;

                    }
                    Thread.Sleep(2000);

                }

            }



            public void InitializeOPCUAClient()
            {
                //Console.WriteLine("Step 1 - Create application configuration and certificate.");
                var config = new ApplicationConfiguration()
                {
                    ApplicationName = MyApplicationName,
                    ApplicationUri = Utils.Format(@"urn:{0}:" + MyApplicationName + "", ServerAddress),
                    ApplicationType = ApplicationType.Client,
                    SecurityConfiguration = new SecurityConfiguration
                    {
                        ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", MyApplicationName, ServerAddress) },
                        TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
                        TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" },
                        RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" },
                        AutoAcceptUntrustedCertificates = true,
                        AddAppCertToTrustedStore = true
                    },
                    TransportConfigurations = new TransportConfigurationCollection(),
                    TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
                    ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
                    TraceConfiguration = new TraceConfiguration()
                };
                config.Validate(ApplicationType.Client).GetAwaiter().GetResult();
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
                }

                var application = new ApplicationInstance
                {
                    ApplicationName = MyApplicationName,
                    ApplicationType = ApplicationType.Client,
                    ApplicationConfiguration = config
                };
                application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();


                //string serverAddress = Dns.GetHostName();
                string serverAddress = ServerAddress; ;
                var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "", useSecurity: SecurityEnabled, operationTimeout: 15000);

                // Console.WriteLine($"Step 2 - Create a session with your server: {selectedEndpoint.EndpointUrl} ");
                OPCSession = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult();
                {


                    //Console.WriteLine("Step 4 - Create a subscription. Set a faster publishing interval if you wish.");
                    var subscription = new Subscription(OPCSession.DefaultSubscription) { PublishingInterval = 1000 };

                    //Console.WriteLine("Step 5 - Add a list of items you wish to monitor to the subscription.");
                    var list = new List<MonitoredItem> { };
                    //list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = "M0404.CPU945.iBatchOutput", StartNodeId = "ns=2;s=M0404.CPU945.iBatchOutput" });

                    list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=2258" });

                    foreach (KeyValuePair<string, TagClass> td in TagList)
                    {
                        list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = td.Value.DisplayName, StartNodeId = "ns=" + OPCNameSpace + ";s=" + td.Value.NodeID + "" });

                    }


                    list.ForEach(i => i.Notification += OnTagValueChange);
                    subscription.AddItems(list);

                    //Console.WriteLine("Step 6 - Add the subscription to the session.");
                    OPCSession.AddSubscription(subscription);
                    subscription.Create();



                }




            }


            public class TagClass
            {

                public TagClass(string displayName, string nodeID)
                {
                    DisplayName = displayName;
                    NodeID = nodeID;

                }

                public DateTime LastUpdatedTime { get; set; }

                public DateTime LastSourceTimeStamp { get; set; }


                public string StatusCode { get; set; }

                public string LastGoodValue { get; set; }
                public string CurrentValue { get; set; }
                public string NodeID { get; set; }

                public string DisplayName { get; set; }


            }


            public void OnTagValueChange(MonitoredItem item, MonitoredItemNotificationEventArgs e)
            {

                foreach (var value in item.DequeueValues())
                {

                    if (item.DisplayName == "ServerStatusCurrentTime")
                    {
                        LastTimeOPCServerFoundAlive = value.SourceTimestamp.ToLocalTime();

                    }
                    else
                    {
                        if (value.Value != null)
                            Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value.ToString(), value.SourceTimestamp.ToLocalTime(), value.StatusCode);
                        else
                            Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, "Null Value", value.SourceTimestamp, value.StatusCode);

                        if (TagList.ContainsKey(item.DisplayName))
                        {
                            if (value.Value != null)
                            {
                                TagList[item.DisplayName].LastGoodValue = value.Value.ToString();
                                TagList[item.DisplayName].CurrentValue = value.Value.ToString();
                                TagList[item.DisplayName].LastUpdatedTime = DateTime.Now;
                                TagList[item.DisplayName].LastSourceTimeStamp = value.SourceTimestamp.ToLocalTime();
                                TagList[item.DisplayName].StatusCode = value.StatusCode.ToString();

                            }
                            else
                            {
                                TagList[item.DisplayName].StatusCode = value.StatusCode.ToString();
                                TagList[item.DisplayName].CurrentValue = null;

                            }

                        }

                    }

                }
                InitialisationCompleted = true;
            }

        }

    }
}

它起作用了.但我需要连接到另一台OPC UA服务器,我开始收到一条错误消息:无法找到Application证书. 它在一行中发生:OPCSession=Session.Create(... 我很确定问题在于没有正确创建应用程序证书.我说的是这句话:

ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", MyApplicationName, ServerAddress) },

如何才能正确地为特定的OPC UA服务器创建证书?或者,问题可能出在其他地方?

更新:如果重要的话,客户端在Debian虚拟机上,而服务器在真正的Windows10机器上.

推荐答案

在Linux上,建议使用LocalApplicationData而不是CommonApplicationData解释100

确保您的服务器自动接受(仅在开发期间)客户端证书或在服务器中手动输入.

使用CertificateIdentifier将搜索带有"MySubjectName"的证书:

ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%LocalApplicationData%/OPCFoundation/CertificateStores/MachineDefault", SubjectName = "MySubjectName" },

并根据上面的代码在运行时创建证书:

application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();

小编辑:用这个代替Utils.Format(@"CN={0}, DC={1}", MyApplicationName, ServerAddress)

ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "CN=OPCUA Client, C=US, S=Arizona, O=OPC Foundation, DC=localhost" },

如果不存在,则会创建一个.从LocalApplicationData开始的文件夹路径为:

ENM: System.Environment.SpecialFolder.LocalApplicationData
WIN: C:\Users\USER\AppData\Local
LIN: /home/USER/.local/share
OSX: /Users/USER/.local/share

要确保您位于OPCFoundation文件夹的位置,您可以执行以下操作:

Console.WriteLine("My LocalApplicationData folder: " + Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData));

这就是它保存的位置.因此,在user/.local/share/OPCFoundation/CertificateStores/MachineDefault/certs中是.der证书,在/private文件夹中是.pfx

location

确保每个文件夹位置都具有读/写权限.我相信您可以使用下面的命令做到这一点:sudo chmod -R 777 /home

如果这不起作用,它应该会起作用.您可以try 使用以下命令获取证书(.p12):

var appCertificate = new X509Certificate2(@".folderpath/certs/CertificateName.p12", "password");
application.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate = new(appCertificate);

我不推荐这样做.

If you want disable certificates at all:

确保您可以在没有安全保护的情况下连接到服务器.然后在SelectEndpoint中禁用useSecurity

public bool SecurityEnabled { get; set; }
SecurityEnabled = false;
var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "", useSecurity: SecurityEnabled, operationTimeout: 15000);

我在这篇文章中举了一个没有证书和凭据的小例子:100

Csharp相关问答推荐

.请求()不适用于Azure AD B2C的C#

在C#c/await中,延迟长度是否会影响控制返回调用者?

如何将两个查询结果组合在C#ASP.NET MHC控制器中

Blazor:用参数创建根路径

为什么在GuardationRule的收件箱函数中,decode.TryParse(valueString,out valueParsed)在给出1.0.1时返回true?

我无法在Ubuntu下编译使用microsoft.extension.configurationbuilder jsonapi和mono mcs的c#应用程序

. NET Core DB vs JSON模型设计

如何模拟耐久任务客户端在统一测试和获取错误在调度NewsListationInstanceAsync模拟设置

System.Net.Http.HttpClient.SendAsync(request)在docker容器内的POST方法30秒后停止

MS Graph v5.42.0:在寻呼消息时更改页面大小

HttpClient 415不支持的媒体类型错误

如何将DotNet Watch与发布配置和传递给应用程序的参数一起使用?

Swagger没有显示int?可以为空

如何将端点(或с匹配请求并判断其路径)添加到BCL?

EFR32BG22 BLE在SPP模式下与PC(Windows 10)不连接

CRL已过期,但ChainStatus告诉我RevocationStatus未知

.NET8->;并发词典总是比普通词典快...怎么回事?[包含基准结果和代码]

如何在mediatr命令中访问HttpContext而不安装弃用的nuget包

我的命名管道在第一次连接后工作正常,但后来我得到了System.ObjectDisposedException:无法访问关闭的管道

C#System.Commandline:如何向命令添加参数以便向其传递值?