/
UAClient.cs
363 lines (299 loc) · 13.6 KB
/
UAClient.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
namespace Opc.Ua.Cloud.Commander
{
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes;
using Serilog;
using System;
public class UAClient
{
public void ExecuteUACommand(ApplicationConfiguration appConfiguration, string payload)
{
Session session = null;
try
{
JsonDecoder decoder = new JsonDecoder(payload, new ServiceMessageContext());
string serverEndpoint = decoder.ReadString("Endpoint");
session = CreateSession(appConfiguration, serverEndpoint);
string expandedNodeID = decoder.ReadString("MethodNodeId");
if (string.IsNullOrEmpty(expandedNodeID))
{
Log.Logger.Error("Expanded node ID is not specified!");
throw new ArgumentException("Expanded node ID is not specified!");
}
ExpandedNodeId nodeID = ExpandedNodeId.Parse(expandedNodeID);
string expandedParentNodeID = decoder.ReadString("ParentNodeId");
if (string.IsNullOrEmpty(expandedParentNodeID))
{
Log.Logger.Error("Expanded parent node ID is not specified!");
throw new ArgumentException("Expanded parent node ID is not specified!");
}
ExpandedNodeId parentNodeID = ExpandedNodeId.Parse(expandedParentNodeID);
CallMethodRequest request = new CallMethodRequest
{
ObjectId = new NodeId(parentNodeID.Identifier, parentNodeID.NamespaceIndex),
MethodId = new NodeId(nodeID.Identifier, nodeID.NamespaceIndex),
};
request.InputArguments = decoder.ReadVariantArray("Arguments");
CallMethodRequestCollection requests = new CallMethodRequestCollection
{
request
};
CallMethodResultCollection results;
DiagnosticInfoCollection diagnosticInfos;
ResponseHeader responseHeader = session.Call(
null,
requests,
out results,
out diagnosticInfos);
if (StatusCode.IsBad(results[0].StatusCode))
{
throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable));
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Executing OPC UA command failed!");
throw;
}
finally
{
if (session != null)
{
if (session.Connected)
{
session.Close();
}
session.Dispose();
}
}
}
public string ReadUAVariable(ApplicationConfiguration appConfiguration, string payload)
{
Session session = null;
try
{
JsonDecoder decoder = new JsonDecoder(payload, new ServiceMessageContext());
string serverEndpoint = decoder.ReadString("Endpoint");
session = CreateSession(appConfiguration, serverEndpoint);
string expandedNodeID = decoder.ReadString("NodeId");
if (string.IsNullOrEmpty(expandedNodeID))
{
Log.Logger.Error("Expanded node ID is not specified!");
throw new ArgumentException("Expanded node ID is not specified!");
}
ExpandedNodeId nodeID = ExpandedNodeId.Parse(expandedNodeID);
// read a variable node from the OPC UA server
VariableNode node = (VariableNode)session.ReadNode(ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris));
// load complex type system
ComplexTypeSystem complexTypeSystem = new ComplexTypeSystem(session);
ExpandedNodeId nodeTypeId = node.DataType;
complexTypeSystem.LoadType(nodeTypeId).GetAwaiter().GetResult();
// now that we have loaded the (potentionally) complex type, we can read the value
DataValue value = session.ReadValue(ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris));
if (StatusCode.IsBad(value.StatusCode))
{
throw ServiceResultException.Create(value.StatusCode.Code, "Reading OPC UA node failed!");
}
return value.WrappedValue.ToString();
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Reading OPC UA node failed!");
throw;
}
finally
{
if (session != null)
{
if (session.Connected)
{
session.Close();
}
session.Dispose();
}
}
}
public string ReadUAHistory(ApplicationConfiguration appConfiguration, string payload)
{
Session session = null;
try
{
JsonDecoder decoder = new JsonDecoder(payload, new ServiceMessageContext());
string serverEndpoint = decoder.ReadString("Endpoint");
session = CreateSession(appConfiguration, serverEndpoint);
string expandedNodeID = decoder.ReadString("NodeId");
DateTime startTime = decoder.ReadDateTime("StartTime");
DateTime endTime = decoder.ReadDateTime("EndTime");
if (string.IsNullOrEmpty(expandedNodeID))
{
Log.Logger.Error("Expanded node ID is not specified!");
throw new ArgumentException("Expanded node ID is not specified!");
}
ExpandedNodeId nodeID = ExpandedNodeId.Parse(expandedNodeID);
// read a variable node from the OPC UA server
VariableNode node = (VariableNode)session.ReadNode(ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris));
// load complex type system
ComplexTypeSystem complexTypeSystem = new(session);
ExpandedNodeId nodeTypeId = node.DataType;
complexTypeSystem.LoadType(nodeTypeId).GetAwaiter().GetResult();
// now that we have loaded the (potentionally) complex type, we can read the history
ReadRawModifiedDetails details = new()
{
StartTime = startTime,
EndTime = endTime,
NumValuesPerNode = 0,
IsReadModified = false,
ReturnBounds = false
};
HistoryReadValueIdCollection nodesToRead = new();
HistoryReadValueId nodeToRead = new()
{
NodeId = ExpandedNodeId.ToNodeId(nodeID, session.NamespaceUris)
};
nodesToRead.Add(nodeToRead);
session.HistoryRead(
null,
new ExtensionObject(details),
TimestampsToReturn.Both,
false,
nodesToRead,
out HistoryReadResultCollection results,
out DiagnosticInfoCollection diagnosticInfos);
if (StatusCode.IsBad(results[0].StatusCode))
{
throw ServiceResultException.Create(results[0].StatusCode.Code, "Reading OPC UA node failed!");
}
HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
// release continuation points
if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0)
{
nodeToRead.ContinuationPoint = results[0].ContinuationPoint;
session.HistoryRead(
null,
new ExtensionObject(details),
TimestampsToReturn.Neither,
true,
nodesToRead,
out results,
out diagnosticInfos);
}
string result = string.Empty;
foreach(DataValue value in values.DataValues)
{
result += (value.ToString() + ',');
}
return result.TrimEnd(',');
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Reading OPC UA node failed!");
throw;
}
finally
{
if (session != null)
{
if (session.Connected)
{
session.Close();
}
session.Dispose();
}
}
}
public void WriteUAVariable(ApplicationConfiguration appConfiguration, string payload)
{
Session session = null;
try
{
JsonDecoder decoder = new JsonDecoder(payload, new ServiceMessageContext());
string serverEndpoint = decoder.ReadString("Endpoint");
session = CreateSession(appConfiguration, serverEndpoint);
string expandedNodeID = decoder.ReadString("NodeId");
if (string.IsNullOrEmpty(expandedNodeID))
{
Log.Logger.Error("Expanded node ID is not specified!");
throw new ArgumentException("Expanded node ID is not specified!");
}
ExpandedNodeId nodeID = ExpandedNodeId.Parse(expandedNodeID);
WriteValue nodeToWrite = new WriteValue()
{
NodeId = new NodeId(nodeID.Identifier, nodeID.NamespaceIndex),
AttributeId = Attributes.Value,
Value = new DataValue()
};
nodeToWrite.Value.WrappedValue = decoder.ReadVariant("ValueToWrite");
WriteValueCollection nodesToWrite = new WriteValueCollection() {
nodeToWrite
};
StatusCodeCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
ResponseHeader responseHeader = session.Write(
null,
nodesToWrite,
out results,
out diagnosticInfos);
ClientBase.ValidateResponse(results, nodesToWrite);
ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite);
if (StatusCode.IsBad(results[0]))
{
throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable);
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Writing OPC UA node failed!");
throw;
}
finally
{
if (session != null)
{
if (session.Connected)
{
session.Close();
}
session.Dispose();
}
}
}
private Session CreateSession(ApplicationConfiguration appConfiguration, string serverEndpoint)
{
if (string.IsNullOrEmpty(serverEndpoint))
{
Log.Logger.Error("Server endpoint is not specified!");
throw new ArgumentException("Server endpoint is not specified!");
}
// find endpoint on a local OPC UA server
EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverEndpoint, true);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, EndpointConfiguration.Create());
// check which identity to use
UserIdentity userIdentity = new UserIdentity(new AnonymousIdentityToken());
if ((Environment.GetEnvironmentVariable("UA_USERNAME") != null) && (Environment.GetEnvironmentVariable("UA_PASSWORD") != null))
{
userIdentity = new UserIdentity(Environment.GetEnvironmentVariable("UA_USERNAME"), Environment.GetEnvironmentVariable("UA_PASSWORD"));
}
Log.Logger.Information("Creating secure session for endpoint {endpointUrl}.", endpoint.EndpointUrl);
Session session = Session.Create(
appConfiguration,
endpoint,
true,
false,
appConfiguration.ApplicationName,
(uint)appConfiguration.ClientConfiguration.DefaultSessionTimeout,
userIdentity,
null)
.GetAwaiter().GetResult();
if (!session.Connected)
{
Log.Logger.Error("Connection to OPC UA server failed!");
return null;
}
else
{
return session;
}
}
}
}