-
Notifications
You must be signed in to change notification settings - Fork 6
/
OpcUaClient.cs
334 lines (252 loc) · 11 KB
/
OpcUaClient.cs
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using System.Threading;
using System.Diagnostics;
using System.Collections.ObjectModel;
using OPCUA2DTDL.Models;
namespace OPCUA2DTDL
{
public enum ExitCode : int
{
Ok = 0,
ErrorCreateApplication = 0x11,
ErrorDiscoverEndpoints = 0x12,
ErrorCreateSession = 0x13,
ErrorBrowseNamespace = 0x14,
ErrorCreateSubscription = 0x15,
ErrorMonitoredItem = 0x16,
ErrorAddSubscription = 0x17,
ErrorRunning = 0x18,
ErrorNoKeepAlive = 0x30,
ErrorInvalidCommandLine = 0x100
};
class OpcUaClient
{
private string _appName;
private static Session _session;
private string _endpointURL;
private int _clientRunTime = Timeout.Infinite;
private static bool _autoAccept = false;
private static ExitCode _exitCode;
private OpcUaNodeList _list = new OpcUaNodeList();
private static Dictionary<string, string> _map = new Dictionary<string, string>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="endpointURL"></param>
/// <param name="autoAccept"></param>
/// <param name="stopTimeout"></param>
/// <param name="appName"></param>
public OpcUaClient(string endpointURL, bool autoAccept, int stopTimeout, string appName)
{
_endpointURL = endpointURL;
_autoAccept = autoAccept;
_clientRunTime = stopTimeout <= 0 ? Timeout.Infinite : stopTimeout * 1000;
_appName = appName;
}
public static ExitCode ExitCode { get => _exitCode; }
/// <summary>
/// Connects to an OPC UA server endpoint URL
/// </summary>
/// <returns></returns>
public async Task<Session> Connect()
{
_exitCode = ExitCode.ErrorCreateApplication;
ApplicationInstance application = new ApplicationInstance
{
ApplicationName = _appName,
ApplicationType = ApplicationType.Client,
ConfigSectionName = Utils.IsRunningOnMono() ? "Opc.Ua.MonoSampleClient" : "Opc.Ua.SampleClient"
};
// Load the application configuration.
ApplicationConfiguration config = await application.LoadApplicationConfiguration(false);
// Check the application certificate.
bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0);
if (!haveAppCertificate)
{
throw new Exception("Application instance certificate invalid!");
}
if (haveAppCertificate)
{
config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate);
if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
// TODO - Fix this section.
_autoAccept = true;
}
config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
}
else
{
Debug.WriteLine("Missing application certificate, using unsecure connection.");
}
_exitCode = ExitCode.ErrorDiscoverEndpoints;
var selectedEndpoint = CoreClientUtils.SelectEndpoint(_endpointURL, haveAppCertificate, 15000);
_exitCode = ExitCode.ErrorCreateSession;
var endpointConfiguration = EndpointConfiguration.Create(config);
var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
return _session = await Session.Create(config, endpoint, false, _appName, 60000, new UserIdentity(new AnonymousIdentityToken()), null);
}
/// <summary>
/// Browse the top level OPC UA structure under \Root
/// </summary>
/// <returns></returns>
public async Task<OpcUaNodeList> Browse()
{
_exitCode = ExitCode.ErrorBrowseNamespace;
ReferenceDescriptionCollection references;
Byte[] continuationPoint;
//Browse root nodes
_session.Browse(
null,
null,
ObjectIds.RootFolder,
0u,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
(uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method | (uint)NodeClass.DataType | (uint)NodeClass.ObjectType | (uint)NodeClass.ReferenceType | (uint)NodeClass.VariableType,
out continuationPoint,
out references);
// Obtain details of each node in the root and add it to the list
foreach (var rd in references)
{
OpcUaNode item = new OpcUaNode();
item.DisplayName = rd.DisplayName.ToString();
item.BrowseName = rd.BrowseName.ToString();
item.NodeClass = rd.NodeClass.ToString();
item.NodeId = rd.NodeId.ToString();
item.ReferenceTypeId = rd.ReferenceTypeId.ToString();
item.TypeDefinition = rd.TypeDefinition.ToString();
item.DataType = GetDataType(_session, ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris));
item.Children = new ObservableCollection<OpcUaNode>();
// Add top level folders to list
_list.Add(item);
// For each top level folder, browse the next level down
BrowseNext(ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris), item);
}
return _list;
}
/// <summary>
/// Browse the next level OPC UA structure
/// </summary>
/// <param name="nodeid"></param>
/// <param name="item"></param>
public void BrowseNext(NodeId nodeid, OpcUaNode item)
{
_exitCode = ExitCode.ErrorBrowseNamespace;
ReferenceDescriptionCollection references;
Byte[] continuationPoint;
_session.Browse(
null,
null,
nodeid,
0u,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
(uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method | (uint)NodeClass.DataType | (uint)NodeClass.ObjectType | (uint)NodeClass.ReferenceType | (uint)NodeClass.VariableType,
out continuationPoint,
out references);
foreach (var rd in references)
{
try
{
OpcUaNode childItem = new OpcUaNode();
childItem.DisplayName = rd.DisplayName.ToString();
childItem.BrowseName = rd.BrowseName.ToString();
childItem.NodeClass = rd.NodeClass.ToString();
childItem.NodeId = rd.NodeId.ToString();
childItem.DataType = GetDataType(_session, ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris));
childItem.ReferenceTypeId = rd.ReferenceTypeId.ToString();
childItem.TypeDefinition = rd.TypeDefinition.ToString();
childItem.Children = new ObservableCollection<OpcUaNode>();
// Add it to the parent
item.Children.Add(childItem);
// Recursion
BrowseNext(ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris), childItem);
}
catch (Exception e)
{
//Debug.WriteLine(e.Message);
}
}
}
/// <summary>
/// Get the OPC UA data type
/// </summary>
/// <param name="session"></param>
/// <param name="nodeId"></param>
/// <returns></returns>
private string GetDataType(Session session, NodeId nodeId)
{
// Build list of attributes to read.
ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
foreach (uint attributeId in new uint[] { Attributes.DataType, Attributes.ValueRank })
{
ReadValueId nodeToRead = new ReadValueId();
nodeToRead.NodeId = nodeId;
nodeToRead.AttributeId = attributeId;
nodesToRead.Add(nodeToRead);
}
// Read the attributes.
DataValueCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
session.Read(
null,
0,
TimestampsToReturn.Neither,
nodesToRead,
out results,
out diagnosticInfos);
ClientBase.ValidateResponse(results, nodesToRead);
ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
// This call checks for error and checks the data type of the value.
// If an error or mismatch occurs the default value is returned.
NodeId dataTypeId = results[0].GetValue<NodeId>(null);
// Use the local type cache to look up the base type for the data type.
BuiltInType builtInType = DataTypes.GetBuiltInType(dataTypeId, session.NodeCache.TypeTree);
// The type info object is used in cast and compare functions.
return builtInType.ToString();
}
/// <summary>
/// Validate the cert
/// </summary>
/// <param name="validator"></param>
/// <param name="e"></param>
private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e)
{
if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
{
e.Accept = _autoAccept;
if (_autoAccept)
{
Debug.WriteLine("Accepted Certificate: {0}", e.Certificate.Subject);
}
else
{
Debug.WriteLine("Rejected Certificate: {0}", e.Certificate.Subject);
}
}
}
/// <summary>
/// Get the type definition for a node id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static string GetTypeDefinition(NodeId id)
{
string name = "Unknown";
var typeDefinition = _session.NodeCache.Find(ExpandedNodeId.ToNodeId(id, _session.NamespaceUris)) as Node;
if (typeDefinition != null)
{
name = typeDefinition.ToString();
}
return name;
}
}
}