kazelee
2025-05-21 5ad394cf1708a4629f90f40bfd9b48d9a9f6f0c8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
using Opc.Ua.Client;
using Opc.Ua;
using System;
using Opc.Ua.Configuration;
 
 
namespace HH.WCS.Mobox3.DSZSH.device
{
    internal class OpcUaHelper
    {
        private static Opc.Ua.Client.Session session;
 
        static OpcUaHelper()
        {
            CreateUpcSession();
        }
 
        /// <summary>
        /// 连接OPC服务
        /// </summary>
        internal static async void CreateUpcSession()
        {
            try
            {
                // 创建一个应用配置对象,用于设置应用名称、唯一标识、类型、证书和安全策略
                var config = new ApplicationConfiguration()
                {
                    ApplicationName = "MyClient",
                    ApplicationUri = Utils.Format(@"urn:{0}:MyClient", System.Net.Dns.GetHostName()),
                    ApplicationType = ApplicationType.Client,
                    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" },
                        RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" },
                        AutoAcceptUntrustedCertificates = true,
                        RejectSHA1SignedCertificates = false,
                        MinimumCertificateKeySize = 1024,
                        NonceLength = 32,
                    },
                    TransportConfigurations = new TransportConfigurationCollection(),
                    TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
                    ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
                    TraceConfiguration = new TraceConfiguration()
                };
 
                // 验证应用配置对象
                await config.Validate(ApplicationType.Client);
 
                // 设置证书验证事件,用于自动接受不受信任的证书
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
                }
 
                // 创建一个应用实例对象,用于检查证书
                var application = new ApplicationInstance(config);
 
                // 检查应用实例对象的证书
                bool check = await application.CheckApplicationInstanceCertificate(false, 2048);
                // 创建一个会话对象,用于连接到 OPC UA 服务器
                EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint("opc.tcp://172.16.57.41:4840", true);
                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)
                {
                    Console.WriteLine("The session is connected to the OPC UA server.");
                    LogHelper.Info($"创建OPC连接成功", "OPC");
                }
                else
                {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"创建OPC连接失败", "OPC");
                }
            }
            catch (Exception e)
            {
                LogHelper.Info($"连接OPC服务异常" + e.Message, "OPC");
            }
        }
 
        /// <summary>
        /// 读取OPC节点数据
        /// </summary>
        /// <param name="nodeId"></param>
        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
                {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
               
            }
            catch (Exception e)
            {
 
                LogHelper.Info($"读取OPC数据异常" + e.Message, "OPC");
            }
            return null;
        }
 
        /// <summary>
        /// 写OPC节点数据
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="val"></param>
        internal static void WriteOpcValue(string nodeId,bool val)
        {
            try
            {
                if (session != null && session.Connected)
                {
                    // 写入数据到节点
                    WriteValue writeValue = new WriteValue
                    {
                        NodeId = new NodeId(nodeId),
                        AttributeId = Attributes.Value,
                        Value = new DataValue(val)
                    };
 
                    StatusCodeCollection results;
                    DiagnosticInfoCollection diagnosticInfos;
                    session.Write(null, new WriteValueCollection { writeValue }, out results, out diagnosticInfos);
                    Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
                    LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
                }
                else
                {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
 
            }
            catch (Exception e)
            {
                LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
            }
        }
 
        /// <summary>
        /// 写OPC节点数据
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="val"></param>
        internal static void WriteOpcValue(string nodeId, int val)
        {
            try
            {
                if (session != null && session.Connected)
                {
                    // 写入数据到节点
                    WriteValue writeValue = new WriteValue
                    {
                        NodeId = new NodeId(nodeId),
                        AttributeId = Attributes.Value,
                        Value = new DataValue(val)
                    };
 
                    StatusCodeCollection results;
                    DiagnosticInfoCollection diagnosticInfos;
                    session.Write(null, new WriteValueCollection { writeValue }, out results, out diagnosticInfos);
                    Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
                    LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
                }
                else
                {
                    Console.WriteLine("The session is not connected to the OPC UA server.");
                    LogHelper.Info($"OPC连接失败", "OPC");
                    CreateUpcSession();
                }
 
            }
            catch (Exception e)
            {
                LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
            }
        }
    }
}