-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpcUaClient.cs
314 lines (253 loc) · 12.1 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
using System;
namespace Fraunhofer.IPA.MSB.Clients.OPCUA
{
public class OpcUaClient
{
private Opc.Ua.Configuration.ApplicationInstance application;
private Opc.Ua.EndpointDescription selectedEndpoint;
public OpcUaClient(string server, string name)
{
application = new Opc.Ua.Configuration.ApplicationInstance
{
ApplicationName = name,
ApplicationType = Opc.Ua.ApplicationType.Client
};
application.ApplicationConfiguration = new Opc.Ua.ApplicationConfiguration(){
ApplicationName = name,
ApplicationType = Opc.Ua.ApplicationType.Client,
ApplicationUri = "urn:localhost:071:MsbClient",
SecurityConfiguration = new Opc.Ua.SecurityConfiguration {
ApplicationCertificate = new Opc.Ua.CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\071\CertificateStores\MachineDefault", SubjectName="MsbClient" },
TrustedIssuerCertificates = new Opc.Ua.CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\071\CertificateStores\UA Certificate Authorities" },
TrustedPeerCertificates = new Opc.Ua.CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\071\CertificateStores\UA Applications" },
RejectedCertificateStore = new Opc.Ua.CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\071\CertificateStores\RejectedCertificates" },
AutoAcceptUntrustedCertificates = true
},
TransportConfigurations = new Opc.Ua.TransportConfigurationCollection(),
TransportQuotas = new Opc.Ua.TransportQuotas { OperationTimeout = 15000 },
ClientConfiguration = new Opc.Ua.ClientConfiguration { DefaultSessionTimeout = 60000 },
TraceConfiguration = new Opc.Ua.TraceConfiguration()
};
//application.ApplicationConfiguration.Validate(Opc.Ua.ApplicationType.Client).GetAwaiter().GetResult();
if (application.ApplicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
application.ApplicationConfiguration.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == Opc.Ua.StatusCodes.BadCertificateUntrusted); };
}
selectedEndpoint = Opc.Ua.Client.CoreClientUtils.SelectEndpoint(server, false);
}
public void CreateSession(string user, string password)
{
var endpointConfiguration = Opc.Ua.EndpointConfiguration.Create(application.ApplicationConfiguration);
var endpoint = new Opc.Ua.ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
Opc.Ua.UserIdentity userIdentity;
if (user != "")
{
userIdentity = new Opc.Ua.UserIdentity(user, password);
} else {
userIdentity = new Opc.Ua.UserIdentity(new Opc.Ua.AnonymousIdentityToken());
}
session = Opc.Ua.Client.Session.Create(application.ApplicationConfiguration, endpoint, false, application.ApplicationName, 60000, userIdentity, null).Result;
session.KeepAlive += Callback_KeepAlive;
}
public void EndSession()
{
session.Close();
session.Dispose();
}
public static Type TranslateNodeIdtoDatatype(Opc.Ua.NodeId nodeId)
{
if (nodeId.NamespaceIndex != 0 || nodeId.IdType != Opc.Ua.IdType.Numeric) return null;
switch((uint)nodeId.Identifier)
{
case 1: return typeof(Boolean);
case 10: return typeof(float);
case 11: return typeof(Double);
case 12: return typeof(string);
case 3: return typeof(byte);
case 5: return typeof(UInt16);
case 7: return typeof(UInt32);
case 9: return typeof(UInt64);
case 2: return typeof(sbyte);
case 4: return typeof(Int16);
case 6: return typeof(Int32);
case 8: return typeof(Int64);
}
return null;
}
public event EventHandler<EventArgs> Connected;
public event EventHandler<EventArgs> Disconnected;
Opc.Ua.Client.SessionReconnectHandler reconnectHandler;
Opc.Ua.Client.Session session;
Opc.Ua.Client.Subscription subscription;
public void generateSubscription(int publishingInterval)
{
subscription = new Opc.Ua.Client.Subscription(session.DefaultSubscription) { PublishingInterval = publishingInterval };
session.AddSubscription(subscription);
subscription.Create();
}
public void applySubcription()
{
subscription.ApplyChanges();
}
public void monitorItem(string nodeId, int samplingInterval, uint queueSize, Opc.Ua.Client.MonitoredItemNotificationEventHandler handler)
{
var item = new Opc.Ua.Client.MonitoredItem(subscription.DefaultItem)
{
RelativePath = "",
StartNodeId = Opc.Ua.NodeId.Parse(nodeId),
SamplingInterval = samplingInterval,
QueueSize = queueSize
};
item.Notification += handler;
subscription.AddItem(item);
}
public bool getSubNodes(string nodeId, out Opc.Ua.ReferenceDescriptionCollection refCollection)
{
refCollection = null;
if (!session.Connected)
{
return false;
}
var nodeId_ = Opc.Ua.NodeId.Parse(nodeId);
var browser = new Opc.Ua.Client.Browser(session);
var refType = new Opc.Ua.NodeId(46, 0);
browser.BrowseDirection = Opc.Ua.BrowseDirection.Forward;
browser.NodeClassMask = (int)Opc.Ua.NodeClass.Variable;
browser.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HierarchicalReferences;
refCollection = browser.Browse(nodeId_);
return refCollection.Count > 0;
}
public bool getInputOutputParameters(string nodeId, out Type inputObjekt, out Type outputObjekt)
{
inputObjekt = null;
outputObjekt = null;
if (!session.Connected)
{
return false;
}
Opc.Ua.ReferenceDescriptionCollection refCollection;
if (!getSubNodes(nodeId, out refCollection)) return false;
foreach (var reference in refCollection)
{
if (reference.BrowseName.NamespaceIndex != 0) continue;
if (reference.BrowseName.Name == "InputArguments")
{
var nodeId_ = new Opc.Ua.NodeId(reference.NodeId.Identifier, reference.NodeId.NamespaceIndex);
var val = session.ReadValue(nodeId_);
var dic = new System.Collections.Generic.Dictionary<string, Type>();
foreach (var l in (Opc.Ua.ExtensionObject[])(val.Value))
{
var b = (Opc.Ua.Argument)l.Body;
var typ = TranslateNodeIdtoDatatype(b.DataType);
dic.Add(b.Name, typ);
}
inputObjekt = Helper.CompileResultType(dic);
} else if (reference.BrowseName.Name == "OutputArguments") {
var nodeId_ = new Opc.Ua.NodeId(reference.NodeId.Identifier, reference.NodeId.NamespaceIndex);
var val = session.ReadValue(nodeId_);
var dic = new System.Collections.Generic.Dictionary<string, Type>();
foreach (var l in (Opc.Ua.ExtensionObject[])(val.Value))
{
var b = (Opc.Ua.Argument)l.Body;
var typ = TranslateNodeIdtoDatatype(b.DataType);
dic.Add(b.Name, typ);
}
outputObjekt = Helper.CompileResultType(dic);
}
}
return inputObjekt != null|| outputObjekt != null;
}
public bool readToNode(string nodeId, out Opc.Ua.Node node)
{
node = null;
if (!session.Connected)
{
return false;
}
try {
var nodeId_ = Opc.Ua.NodeId.Parse(nodeId);
node = session.ReadNode(nodeId_);
} catch (System.Exception e) {
Serilog.Log.Error(e.Message);
}
return node != null;
}
public bool readToObject(string nodeId, out object value)
{
if (!session.Connected)
{
value = null;
return false;
}
var nodeId_ = Opc.Ua.NodeId.Parse(nodeId);
Opc.Ua.DataValue val = null;
try
{
val = session.ReadValue(nodeId_);
if (Opc.Ua.StatusCode.IsGood(val.StatusCode))
{
value = val.Value;
return true;
}
} catch (Exception e) {
Serilog.Log.Error(e.Message);
}
value = null;
return false;
}
public bool writeNode(string nodeId, object value)
{
if (!session.Connected) return false;
var nodeId_ = Opc.Ua.NodeId.Parse(nodeId);
var coll = new Opc.Ua.WriteValueCollection() {
new Opc.Ua.WriteValue() {
NodeId = nodeId_,
Value = new Opc.Ua.DataValue()
{
Value = value
}
}
};
var stat = new Opc.Ua.StatusCodeCollection();
var diag = new Opc.Ua.DiagnosticInfoCollection();
var rsp = session.Write(null, coll, out stat, out diag);
return rsp.ServiceResult == Opc.Ua.StatusCodes.Good;
}
public System.Collections.Generic.IList<object> callMethod(Opc.Ua.NodeId objectNodeId, string methodNodeId, params object[] args)
{
if (!session.Connected) return null;
/*var m = new Opc.Ua.CallMethodRequest() {
InputArguments = new Opc.Ua.VariantCollection(inputArguments),
ObjectId = Opc.Ua.NodeId.Parse(objectNodeId),
MethodId = Opc.Ua.NodeId.Parse(methodNodeId)
};
var v = new Opc.Ua.CallMethodRequestCollection(){ m };
var res = new Opc.Ua.CallMethodResultCollection() {
new Opc.Ua.CallMethodResult()
};
session.GetType().GetMethod("Call").Invoke()*/
return session.Call(objectNodeId, Opc.Ua.NodeId.Parse(methodNodeId), args);
}
private void Callback_KeepAlive(Opc.Ua.Client.Session sender, Opc.Ua.Client.KeepAliveEventArgs e)
{
if (e.Status != null && Opc.Ua.ServiceResult.IsNotGood(e.Status))
{
if (Disconnected != null) Disconnected.Invoke(sender, e);
if (reconnectHandler == null)
{
reconnectHandler = new Opc.Ua.Client.SessionReconnectHandler();
reconnectHandler.BeginReconnect(sender, 5000, Callback_Reconnect);
}
}
}
private void Callback_Reconnect(object sender, EventArgs e)
{
// ignore callbacks from discarded objects.
if (!Object.ReferenceEquals(sender, reconnectHandler)) return;
session = reconnectHandler.Session;
reconnectHandler.Dispose();
reconnectHandler = null;
if (Connected != null) Connected.Invoke(sender, e);
}
}
}