-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathUASampleClient.cs
More file actions
231 lines (199 loc) · 8.65 KB
/
Copy pathUASampleClient.cs
File metadata and controls
231 lines (199 loc) · 8.65 KB
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
/* Copyright (c) 1996-2016, OPC Foundation. All rights reserved.
The source code in this file is covered under a dual-license scenario:
- RCL: for OPC Foundation members in good-standing
- GPL V2: everybody else
RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/
GNU General Public License as published by the Free Software Foundation;
version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using AdminShellNS;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
namespace SampleClient
{
public class UASampleClient
{
const int ReconnectPeriod = 10;
public Session session;
SessionReconnectHandler reconnectHandler;
string endpointURL;
int clientRunTime = Timeout.Infinite;
static bool autoAccept = true;
static ExitCode exitCode;
string userName;
string password;
public UASampleClient(string _endpointURL, bool _autoAccept, int _stopTimeout, string _userName, string _password)
{
endpointURL = _endpointURL;
autoAccept = _autoAccept;
clientRunTime = _stopTimeout <= 0 ? Timeout.Infinite : _stopTimeout * 1000;
userName = _userName;
password = _password;
}
public void Run()
{
try
{
ConsoleSampleClient().Wait();
}
catch (Exception ex)
{
Utils.Trace("ServiceResultException:" + ex.Message);
Console.WriteLine("Exception: {0}", ex.Message);
Console.WriteLine("press any key to continue");
return;
}
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
{
Console.CancelKeyPress += (sender, eArgs) =>
{
quitEvent.Set();
eArgs.Cancel = true;
};
}
catch
{
}
// wait for timeout or Ctrl-C
quitEvent.WaitOne(clientRunTime);
// return error conditions
if (session.KeepAliveStopped)
{
exitCode = ExitCode.ErrorNoKeepAlive;
return;
}
exitCode = ExitCode.Ok;
}
public static ExitCode ExitCode { get => exitCode; }
public async Task ConsoleSampleClient()
{
exitCode = ExitCode.ErrorCreateApplication;
ApplicationInstance application = new ApplicationInstance
{
ApplicationName = "UA Core Sample Client",
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);
config.ApplicationUri = X509Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate);
if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
autoAccept = true;
}
config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
}
else
{
}
exitCode = ExitCode.ErrorDiscoverEndpoints;
var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, haveAppCertificate, 15000);
// Console.WriteLine(" Selected endpoint uses: {0}",
selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1);
exitCode = ExitCode.ErrorCreateSession;
var endpointConfiguration = EndpointConfiguration.Create(config);
var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
if ((userName == "" || userName == null) && (password == "" || password == null))
{
session = await Session.Create(config, endpoint, false, "OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null);
}
else
{
session = await Session.Create(config, endpoint, false, "OPC UA Console Client", 60000, new UserIdentity(userName, password), null);
}
// register keep alive handler
session.KeepAlive += Client_KeepAlive;
}
private void Client_KeepAlive(Session sender, KeepAliveEventArgs e)
{
if (e.Status != null && ServiceResult.IsNotGood(e.Status))
{
Console.WriteLine("{0} {1}/{2}", e.Status, sender.OutstandingRequestCount, sender.DefunctRequestCount);
if (reconnectHandler == null)
{
Console.WriteLine("--- RECONNECTING ---");
reconnectHandler = new SessionReconnectHandler();
reconnectHandler.BeginReconnect(sender, ReconnectPeriod * 1000, Client_ReconnectComplete);
}
}
}
private void Client_ReconnectComplete(object sender, EventArgs e)
{
// ignore callbacks from discarded objects.
if (!Object.ReferenceEquals(sender, reconnectHandler))
{
return;
}
session = reconnectHandler.Session;
reconnectHandler.Dispose();
reconnectHandler = null;
Console.WriteLine("--- RECONNECTED ---");
}
private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
{
foreach (var value in item.DequeueValues())
{
Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value, value.SourceTimestamp, value.StatusCode);
}
}
private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e)
{
if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
{
e.Accept = autoAccept;
}
}
public string ReadSubmodelElementValue(string nodeName, int index)
{
NodeId node = new NodeId(nodeName, (ushort)index);
return (session.ReadValue(node).ToString());
}
public string ReadSubmodelElementValue(NodeId nodeId)
{
return (session.ReadValue(nodeId).ToString(null, CultureInfo.InvariantCulture));
}
public void WriteSubmodelElementValue(NodeId nodeId, object value)
{
WriteValue nodeToWrite = new WriteValue();
nodeToWrite.NodeId = nodeId;
nodeToWrite.AttributeId = Attributes.Value;
nodeToWrite.Value = new DataValue();
nodeToWrite.Value.WrappedValue = new Variant(value);
WriteValueCollection nodesToWrite = new WriteValueCollection();
nodesToWrite.Add(nodeToWrite);
// read the attributes.
StatusCodeCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
ResponseHeader responseHeader = session.Write(
null,
nodesToWrite,
out results,
out diagnosticInfos);
ClientBase.ValidateResponse(results, nodesToWrite);
ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite);
// check for error.
if (StatusCode.IsBad(results[0]))
{
throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable);
}
}
}
}