OPC UA-.net标准C#简单控制台客户端

5
我正在尝试使用OPC UA基金会的GitHub页面上的SampleApplication NetCoreConsoleClientOPC-UA.net Standard,与此同时我遇到了几个问题。
我想用这个库来简单读取服务器发送的数据(我正在使用Prosys OPC UA Server)并在控制台中将其写出。我一直在努力获取我通过服务器发送的实际数据变量。我设法连接并订阅,但我无法使用onNotification方法将所需的MonitoredItem值写出。
Console.WriteLine("6 - Add a list of items (server current time and status) to the subscription.");
exitCode = ExitCode.ErrorMonitoredItem;
var list = new List<MonitoredItem> 
{
    new MonitoredItem(subscription.DefaultItem)
    {
        DisplayName = "ServerStatusCurrentTime", StartNodeId = "i="+Variables.Server_ServerStatus_CurrentTime.ToString()
    }
};
list.ForEach(i => i.Notification += OnNotification);
subscription.AddItems(list);

这里的示例将一个新的MonitoredItem添加到列表中。当我尝试添加自己的项时,即使服务器一直发送更改的值,它也从未收到任何响应,因此应该触发onNotification方法。

我从这部分获取所需值的DisplayName和StartNodeId:

foreach (var rd in references)
{
    Console.WriteLine(" {0}, {1}, {2}", rd.DisplayName, rd.BrowseName, rd.NodeClass);
    ReferenceDescriptionCollection nextRefs;
    byte[] nextCp;
    session.Browse(
    null,
    null,
    ExpandedNodeId.ToNodeId(rd.NodeId, session.NamespaceUris),
                0u,
                BrowseDirection.Forward,
                ReferenceTypeIds.HierarchicalReferences,
                true,
                (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method,
                out nextCp,
                out nextRefs);

    foreach (var nextRd in nextRefs)
    {
        Console.WriteLine("   + {0}, {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass);
    }
}

因此:

var list = new List<MonitoredItem>
{
    new MonitoredItem(subscription.DefaultItem)
    {
        DisplayName = "Simulation", StartNodeId = "ns=2;s=85\:Simulation"
    } 
};

我从来没有收到任何返回值。我对OPC UA标准及其数据打包方式感到有些困惑。


2
欢迎来到stackoverflow。请花一分钟时间参观[tour],特别是关注[ask]和[edit],并根据需要编辑你的问题。 - jazb
请参观[tour]并阅读[ask]和相关的帮助主题。寻求调试帮助的问题应包括一个[mcve],以及对期望行为的描述,以及您当前的代码在提供该行为方面存在的不足之处。 - ProgrammingLlama
订阅中没有“ApplyChanges”。 - astrowalker
2个回答

12

我曾经遇到和这个问题非常相似的困境,因为在网上找到的OPCFoundation的例子不是很易懂。下面的解决方案使用了OPCFoundation库来从标准OPC UA服务器中读取数据。

我已经试过使用Kepware ServerEX OPC UA服务器来测试下面的解决方案,完全稳定运行,但我相信同样的方法可能适用于Prosys或任何标准的OPC UA服务器,只需要稍作修改即可。

安装以下Nuget包:OPCFoundation.NetStandard.Opc.Ua

参考资料:此答案是多个答案的改编,以及StackOverflow上其他人的好工作。


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;
            }

        }

    }
}





你救了我的一天。通常当你需要阅读像ns=2;s=Tag11这样的东西时,数字"2"已经在OPCUAClass构造函数的最后一个参数中指定了,所以你的标签看起来像这样TagList.Add("Tag11", new Form1.OPCUAClass.TagClass("Tag11","Tag11"));。如果你有不同的子URL,CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "" + suburl, useSecurity: SecurityEnabled, discoverTimeout : 15000);在上面的代码中,'operationTimeout'参数在新库中被更改为'discoverTimeout'。 - undefined

3

我也曾遇到从Prosys OPC UA模拟服务器读取节点的困难。关于C#和OPC UA的SO问题并不多,如果有人发现这个旧帖子,我希望这篇文章能够提供帮助。

相较于示例存储库提供的代码,我发现ConsoleReferenceClient更加有用。

该代码更加清晰,文档描述完善且易于理解。它具有一个ReadNodes方法,可以读取节点的当前值。

在此处找到:https://github.com/OPCFoundation/UA-.NETStandard/blob/master/Applications/ConsoleReferenceClient/UAClient.cs


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接