-
Notifications
You must be signed in to change notification settings - Fork 7
/
UAClient.cs
289 lines (246 loc) · 10.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
namespace Opc.Ua.Edge.Translator
{
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes;
using Opc.Ua.Edge.Translator.Interfaces;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
public class UAClient : IAsset
{
private ISession _session = null;
private string _endpoint = string.Empty;
private List<SessionReconnectHandler> _reconnectHandlers = new List<SessionReconnectHandler>();
private object _reconnectHandlersLock = new object();
private Dictionary<string, uint> _missedKeepAlives = new Dictionary<string, uint>();
private object _missedKeepAlivesLock = new object();
private readonly Dictionary<ISession, ComplexTypeSystem> _complexTypeList = new Dictionary<ISession, ComplexTypeSystem>();
public void Connect(string ipAddress, int port)
{
string url = "opc.tcp://" + ipAddress + ":" + port;
string username = Environment.GetEnvironmentVariable("OPCUA_CLIENT_USERNAME");
string password = Environment.GetEnvironmentVariable("OPCUA_CLIENT_PASSWORD");
ConnectSessionAsync(url, username, password).GetAwaiter().GetResult();
}
public void Disconnect()
{
if (_session != null)
{
_session.Close();
_session = null;
}
}
public string GetRemoteEndpoint()
{
return _endpoint;
}
public Task<byte[]> Read(string addressWithinAsset, byte unitID, string function, ushort count)
{
if (_session != null)
{
NodeId nodeId = ExpandedNodeId.ToNodeId(new ExpandedNodeId(addressWithinAsset), _session.NamespaceUris);
DataValue value = _session.ReadValue(nodeId);
#pragma warning disable SYSLIB0011
BinaryFormatter bf = new();
using (MemoryStream ms = new())
{
bf.Serialize(ms, value.Value);
#pragma warning restore SYSLIB0011
return Task.FromResult(ms.ToArray());
}
}
else
{
return Task.FromResult(new byte[0]);
}
}
public Task Write(string addressWithinAsset, byte unitID, string function, byte[] values, bool singleBitOnly)
{
using (MemoryStream memStream = new(values))
{
#pragma warning disable SYSLIB0011
BinaryFormatter binForm = new();
object value = binForm.Deserialize(memStream);
#pragma warning restore SYSLIB0011
WriteValue nodeToWrite = new()
{
NodeId = new NodeId(addressWithinAsset),
Value = new DataValue(new Variant(value))
};
WriteValueCollection nodesToWrite = new(){ nodeToWrite };
RequestHeader requestHeader = new()
{
ReturnDiagnostics = (uint)DiagnosticsMasks.All
};
StatusCodeCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
ResponseHeader responseHeader = _session.Write(
requestHeader,
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);
}
return Task.CompletedTask;
}
}
private async Task ConnectSessionAsync(string endpointUrl, string username, string password)
{
_endpoint = endpointUrl;
// check if the required session is already available
if ((_session != null) && (_session.Endpoint.EndpointUrl == endpointUrl))
{
return;
}
EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, true);
ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(Program.App.ApplicationConfiguration));
uint timeout = (uint)Program.App.ApplicationConfiguration.ClientConfiguration.DefaultSessionTimeout;
UserIdentity userIdentity = null;
if (username == null)
{
userIdentity = new UserIdentity(new AnonymousIdentityToken());
}
else
{
userIdentity = new UserIdentity(username, password);
}
try
{
_session = await Session.Create(
Program.App.ApplicationConfiguration,
configuredEndpoint,
true,
false,
Program.App.ApplicationConfiguration.ApplicationName,
timeout,
userIdentity,
null
).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
return;
}
// enable diagnostics
_session.ReturnDiagnostics = DiagnosticsMasks.All;
// register keep alive callback
_session.KeepAlive += KeepAliveHandler;
// enable subscriptions transfer
_session.DeleteSubscriptionsOnClose = false;
_session.TransferSubscriptionsOnReconnect = true;
// load complex type system
try
{
if (!_complexTypeList.ContainsKey(_session))
{
_complexTypeList.Add(_session, new ComplexTypeSystem(_session));
}
await _complexTypeList[_session].Load().ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
}
}
private void KeepAliveHandler(ISession session, KeepAliveEventArgs eventArgs)
{
if (eventArgs != null && session != null && session.ConfiguredEndpoint != null)
{
try
{
string endpoint = session.ConfiguredEndpoint.EndpointUrl.AbsoluteUri;
lock (_missedKeepAlivesLock)
{
if (!ServiceResult.IsGood(eventArgs.Status))
{
if (session.Connected)
{
// add a new entry, if required
if (!_missedKeepAlives.ContainsKey(endpoint))
{
_missedKeepAlives.Add(endpoint, 0);
}
_missedKeepAlives[endpoint]++;
}
// start reconnect if there are 3 missed keep alives
if (_missedKeepAlives[endpoint] >= 3)
{
// check if a reconnection is already in progress
bool reconnectInProgress = false;
lock (_reconnectHandlersLock)
{
foreach (SessionReconnectHandler handler in _reconnectHandlers)
{
if (ReferenceEquals(handler.Session, session))
{
reconnectInProgress = true;
break;
}
}
}
if (!reconnectInProgress)
{
SessionReconnectHandler reconnectHandler = new SessionReconnectHandler();
lock (_reconnectHandlersLock)
{
_reconnectHandlers.Add(reconnectHandler);
}
reconnectHandler.BeginReconnect(session, 10000, ReconnectCompleteHandler);
}
}
}
else
{
if (_missedKeepAlives.ContainsKey(endpoint) && (_missedKeepAlives[endpoint] != 0))
{
// Reset missed keep alive count
_missedKeepAlives[endpoint] = 0;
}
}
}
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
}
}
}
private void ReconnectCompleteHandler(object sender, EventArgs e)
{
// find our reconnect handler
SessionReconnectHandler reconnectHandler = null;
lock (_reconnectHandlersLock)
{
foreach (SessionReconnectHandler handler in _reconnectHandlers)
{
if (ReferenceEquals(sender, handler))
{
reconnectHandler = handler;
break;
}
}
}
// ignore callbacks from discarded objects
if (reconnectHandler == null || reconnectHandler.Session == null)
{
return;
}
// update the session
_session = reconnectHandler.Session;
lock (_reconnectHandlersLock)
{
_reconnectHandlers.Remove(reconnectHandler);
}
reconnectHandler.Dispose();
}
}
}