kazelee
7 天以前 2ca90a404fa1ab94eb6374f50c6ddd47a2b7f0e6
device/OpcUaHelper.cs
@@ -4,33 +4,25 @@
using Opc.Ua.Configuration;
using HH.WCS.Mobox3.DSZSH.util;
namespace HH.WCS.Mobox3.DSZSH.device
{
    internal class OpcUaHelper
    {
namespace HH.WCS.Mobox3.DSZSH.device {
    internal class OpcUaHelper {
        private static Opc.Ua.Client.Session session;
        static OpcUaHelper()
        {
        static OpcUaHelper() {
            CreateUpcSession();
        }
        /// <summary>
        /// 连接OPC服务
        /// </summary>
        internal static async void CreateUpcSession()
        {
            try
            {
        internal static async void CreateUpcSession() {
            try {
                // 创建一个应用配置对象,用于设置应用名称,唯一标识,类型,证书和安全策略
                var config = new ApplicationConfiguration()
                {
                var config = new ApplicationConfiguration() {
                    ApplicationName = "MyClient",
                    ApplicationUri = Utils.Format(@"urn:{0}:MyClient", System.Net.Dns.GetHostName()),
                    ApplicationType = ApplicationType.Client,
                    SecurityConfiguration = new SecurityConfiguration
                    {
                    SecurityConfiguration = new SecurityConfiguration {
                        ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "MyClientSubjectName" },
                        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" },
@@ -50,8 +42,7 @@
                await config.Validate(ApplicationType.Client);
                // 设置证书验证事件,用于自动接受不受信任的证书
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) {
                    config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
                }
@@ -65,19 +56,16 @@
                EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(config);
                ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
                session = await Session.Create(config, endpoint, false, false, "DataCollector", 60000, new UserIdentity(), null);
                if (session != null && session.Connected)
                {
                if (session != null && session.Connected) {
                    Console.WriteLine("The session is connected to the OPC UA server.");
                    LogHelper.Info($"创建OPC连接成功", "OPC");
                }
                else
                {
                else {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"创建OPC连接失败", "OPC");
                }
            }
            catch (Exception e)
            {
            catch (Exception e) {
                LogHelper.Info($"连接OPC服务异常" + e.Message, "OPC");
            }
        }
@@ -86,27 +74,22 @@
        /// 读取OPC节点数据
        /// </summary>
        /// <param name="nodeId"></param>
        internal static object ReadOpcValue(string nodeId)
        {
            try
            {
                if (session != null && session.Connected)
                {
        internal static object ReadOpcValue(string nodeId) {
            try {
                if (session != null && session.Connected) {
                    // 读取数据节点
                    DataValue item = session.ReadValue(nodeId: nodeId);
                    LogHelper.Info($"OPC读取:nodeid:{nodeId},value:{item.Value}", "OPC");
                    return item.Value;
                }
                else
                {
                else {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
            }
            catch (Exception e)
            {
            catch (Exception e) {
                LogHelper.Info($"读取OPC数据异常" + e.Message, "OPC");
            }
@@ -118,15 +101,11 @@
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="val"></param>
        internal static void WriteOpcValue(string nodeId,bool val)
        {
            try
            {
                if (session != null && session.Connected)
                {
        internal static void WriteOpcValue(string nodeId, bool val) {
            try {
                if (session != null && session.Connected) {
                    // 写入数据到节点
                    WriteValue writeValue = new WriteValue
                    {
                    WriteValue writeValue = new WriteValue {
                        NodeId = new NodeId(nodeId),
                        AttributeId = Attributes.Value,
                        Value = new DataValue(val)
@@ -138,16 +117,14 @@
                    Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
                    LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
                }
                else
                {
                else {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
            }
            catch (Exception e)
            {
            catch (Exception e) {
                LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
            }
        }
@@ -157,15 +134,11 @@
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="val"></param>
        internal static void WriteOpcValue(string nodeId, int val)
        {
            try
            {
                if (session != null && session.Connected)
                {
        internal static void WriteOpcValue(string nodeId, int val) {
            try {
                if (session != null && session.Connected) {
                    // 写入数据到节点
                    WriteValue writeValue = new WriteValue
                    {
                    WriteValue writeValue = new WriteValue {
                        NodeId = new NodeId(nodeId),
                        AttributeId = Attributes.Value,
                        Value = new DataValue(val)
@@ -177,16 +150,14 @@
                    Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
                    LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
                }
                else
                {
                else {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
            }
            catch (Exception e)
            {
            catch (Exception e) {
                LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
            }
        }