/
GdsDiscoverServersDlg.cs
538 lines (456 loc) · 17.6 KB
/
GdsDiscoverServersDlg.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/* ========================================================================
* Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Opc.Ua.Client;
using Opc.Ua.Client.Controls;
using System.Threading.Tasks;
namespace Opc.Ua.Client.Controls
{
/// <summary>
/// Searches for the servers in a GDS.
/// </summary>
public partial class GdsDiscoverServersDlg : Form
{
#region Constructors
/// <summary>
/// Constructs the form.
/// </summary>
public GdsDiscoverServersDlg()
{
InitializeComponent();
this.Icon = ClientUtils.GetAppIcon();
ServersLV.SmallImageList = new ClientUtils().ImageList;
List<object> items = new List<object>();
foreach (object value in Enum.GetValues(typeof(Match)))
{
items.Add(value);
}
ApplicationNameCB.Items.AddRange(items.ToArray());
MachineNameCB.Items.AddRange(items.ToArray());
ApplicationUriCB.Items.AddRange(items.ToArray());
ProductUriCB.Items.AddRange(items.ToArray());
ApplicationNameCB.SelectedIndex = 0;
MachineNameCB.SelectedIndex = 0;
ApplicationUriCB.SelectedIndex = 0;
ProductUriCB.SelectedIndex = 0;
}
#endregion
#region Match Enumeration
private enum Match
{
StartsWith,
IsExactly,
EndsWith,
Contains
}
#endregion
#region Private Fields
private ApplicationDescription m_application;
#endregion
#region Private Constants
/// <summary>
/// The identifier for the Directory Object.
/// </summary>
private const uint GdsId_Directory = 584;
/// <summary>
/// The identifier for the Directory_Applications Object.
/// </summary>
private const uint GdsId_Directory_Applications = 586;
/// <summary>
/// The identifier for the RootDirectoryEntryType_QueryServers Method.
/// </summary>
private const uint GdsId_RootDirectoryEntryType_QueryServers = 550;
/// <summary>
/// The identifier for the ApplicationElementType ObjectType.
/// </summary>
public const uint GdsId_ApplicationElementType = 572;
#endregion
#region Public Interface
/// <summary>
/// Shows the dialog.
/// </summary>
public async Task<ApplicationDescription> ShowDialog(ApplicationConfiguration configuration, bool showSearchPanel)
{
List<string> urls = new List<string>();
foreach (EndpointDescription endpoint in configuration.ClientConfiguration.DiscoveryServers)
{
urls.Add(endpoint.EndpointUrl);
}
if (urls.Count == 0)
{
// TODO find servers with LDS
urls.Add("opc.tcp://localhost:58800/GlobalDiscoveryServer");
}
ServerCTRL.Configuration = configuration;
ServerCTRL.SetAvailableUrls(urls);
try
{
await ServerCTRL.Connect();
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
OkBTN.Visible = true;
CancelBTN.Visible = true;
BrowseCK.Checked = showSearchPanel;
BrowseCK.Checked = !showSearchPanel;
if (base.ShowDialog() != DialogResult.OK)
{
return null;
}
return m_application;
}
#endregion
#region Private Methods
/// <summary>
/// Adds the results to the control.
/// </summary>
private void UpdateResults(ApplicationDescription[] descriptions)
{
ServersLV.Items.Clear();
if (descriptions == null)
{
return;
}
for (int ii = 0; ii < descriptions.Length; ii++)
{
ApplicationDescription description = descriptions[ii];
if (description == null)
{
continue;
}
ListViewItem item = new ListViewItem();
item.Text = Utils.Format("{0}", description.ApplicationName);
item.ImageIndex = ClientUtils.GetImageIndex(ServerCTRL.Session, NodeClass.Object, null, false);
item.SubItems.Add(new ListViewItem.ListViewSubItem());
item.SubItems.Add(new ListViewItem.ListViewSubItem());
item.SubItems.Add(new ListViewItem.ListViewSubItem());
item.Tag = description;
ServersLV.Items.Add(item);
item.SubItems[1].Text = description.ApplicationType.ToString();
if (description.DiscoveryUrls == null)
{
continue;
}
// collect the domains and protocols.
List<string> domains = new List<string>();
List<string> protocols = new List<string>();
foreach (string discoveryUrl in description.DiscoveryUrls)
{
Uri url = Utils.ParseUri(discoveryUrl);
if (url != null)
{
if (!domains.Contains(url.DnsSafeHost))
{
domains.Add(url.DnsSafeHost);
}
if (!protocols.Contains(url.Scheme))
{
protocols.Add(url.Scheme);
}
}
}
// format the domains.
StringBuilder buffer = new StringBuilder();
foreach (string domain in domains)
{
if (buffer.Length > 0)
{
buffer.Append(", ");
}
buffer.Append(domain);
}
item.SubItems[2].Text = buffer.ToString();
// format the protocols.
buffer = new StringBuilder();
foreach (string protocol in protocols)
{
if (buffer.Length > 0)
{
buffer.Append(", ");
}
buffer.Append(protocol);
}
item.SubItems[3].Text = buffer.ToString();
}
// adjust column widths.
for (int ii = 0; ii < ServersLV.Columns.Count; ii++)
{
ServersLV.Columns[ii].Width = -2;
}
}
/// <summary>
/// Adds wildcards to the filter.
/// </summary>
private string ProcessFilter(ComboBox selection, TextBox filter)
{
if (String.IsNullOrEmpty(filter.Text))
{
return String.Empty;
}
string text = filter.Text;
Match match = (Match)selection.SelectedItem;
if (match == Match.Contains || match == Match.StartsWith)
{
if (!text.EndsWith("%"))
{
text = text + "%";
}
}
if (match == Match.Contains || match == Match.EndsWith)
{
if (!text.StartsWith("%"))
{
text = "%" + text;
}
}
return text;
}
/// <summary>
/// Searches the server for servers.
/// </summary>
private void Search()
{
Session session = ServerCTRL.Session;
if (session == null)
{
return;
}
NodeId elementId = null;
ReferenceDescription reference = SystemElementBTN.SelectedReference;
if (reference != null && !reference.NodeId.IsAbsolute)
{
elementId = (NodeId)reference.NodeId;
}
ushort namespaceIndex = (ushort)session.NamespaceUris.GetIndex(Namespaces.OpcUaGds);
IList<object> outputArguments = session.Call(
new NodeId(GdsId_Directory, namespaceIndex),
new NodeId(GdsId_RootDirectoryEntryType_QueryServers, namespaceIndex),
elementId,
ProcessFilter(ApplicationNameCB, ApplicationNameTB),
ProcessFilter(MachineNameCB, MachineNameTB),
ProcessFilter(ApplicationUriCB, ApplicationUriTB),
ProcessFilter(ProductUriCB, ProductUriTB));
if (outputArguments != null && outputArguments.Count == 1)
{
ExtensionObject[] extensions = outputArguments[0] as ExtensionObject[];
ApplicationDescription[] descriptions = (ApplicationDescription[])ExtensionObject.ToArray(extensions, typeof(ApplicationDescription));
UpdateResults(descriptions);
}
}
/// <summary>
/// Reads the application description from the GDS.
/// </summary>
private ApplicationDescription Read(NodeId nodeId)
{
NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);
string[] browsePaths = new string[]
{
"1:ApplicationName",
"1:ApplicationType",
"1:ApplicationUri",
"1:ProductUri",
"1:GatewayServerUri",
"1:DiscoveryUrls"
};
List<NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
ServerCTRL.Session,
nodeId,
wellKnownNamespaceUris,
browsePaths);
ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
foreach (NodeId propertyId in propertyIds)
{
ReadValueId nodeToRead = new ReadValueId();
nodeToRead.NodeId = propertyId;
nodeToRead.AttributeId = Attributes.Value;
nodesToRead.Add(nodeToRead);
}
DataValueCollection results = null;
DiagnosticInfoCollection diagnosticInfos = null;
ServerCTRL.Session.Read(
null,
0,
TimestampsToReturn.Neither,
nodesToRead,
out results,
out diagnosticInfos);
ClientBase.ValidateResponse(results, nodesToRead);
ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
ApplicationDescription application = new ApplicationDescription();
application.ApplicationName = results[0].GetValue<LocalizedText>(null);
application.ApplicationType = (ApplicationType)results[1].GetValue<int>((int)ApplicationType.Server);
application.ApplicationUri = results[2].GetValue<string>(null);
application.ProductUri = results[3].GetValue<string>(null);
application.GatewayServerUri = results[4].GetValue<string>(null);
string[] discoveryUrls = results[5].GetValue<string[]>(null);
if (discoveryUrls != null)
{
application.DiscoveryUrls = new StringCollection(discoveryUrls);
}
return application;
}
#endregion
#region Event Handlers
private void SearchBTN_Click(object sender, EventArgs e)
{
try
{
Search();
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void CloseBTN_Click(object sender, EventArgs e)
{
try
{
Close();
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void ServerCTRL_ConnectComplete(object sender, EventArgs e)
{
try
{
Session session = ServerCTRL.Session;
if (session != null)
{
ushort namespaceIndex = (ushort)session.NamespaceUris.GetIndex(Opc.Ua.Namespaces.OpcUaGds);
NodeId rootId = new NodeId(GdsId_Directory_Applications, namespaceIndex);
NodeId[] referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.Organizes, Opc.Ua.ReferenceTypeIds.HasChild };
BrowseCTRL.Initialize(session, rootId, referenceTypeIds);
SystemElementBTN.Session = session;
SystemElementBTN.RootId = rootId;
SystemElementBTN.ReferenceTypeIds = referenceTypeIds;
}
else
{
BrowseCTRL.ChangeSession(session);
SystemElementBTN.Session = session;
}
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void ServerCTRL_ReconnectComplete(object sender, EventArgs e)
{
try
{
Session session = ServerCTRL.Session;
BrowseCTRL.ChangeSession(session);
SystemElementBTN.Session = session;
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void BrowseCK_CheckedChanged(object sender, EventArgs e)
{
try
{
SearchPN.Visible = !BrowseCK.Checked;
SearchBTN.Enabled = !BrowseCK.Checked;
BrowseCTRL.Visible = BrowseCK.Checked;
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void ServersLV_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ServerCTRL.Session == null)
{
return;
}
foreach (ListViewItem item in ServersLV.SelectedItems)
{
m_application = item.Tag as ApplicationDescription;
OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server || m_application.ApplicationType == ApplicationType.ClientAndServer;
return;
}
m_application = null;
OkBTN.Enabled = false;
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
private void BrowseCTRL_AfterSelect(object sender, EventArgs e)
{
try
{
if (ServerCTRL.Session == null)
{
return;
}
ushort namespaceIndex = (ushort)ServerCTRL.Session.NamespaceUris.GetIndex(Opc.Ua.Namespaces.OpcUaGds);
NodeId typeId = new NodeId(GdsId_ApplicationElementType, namespaceIndex);
ReferenceDescription reference = BrowseCTRL.SelectedNode;
if (reference != null)
{
if (reference.TypeDefinition == typeId)
{
m_application = Read((NodeId)reference.NodeId);
OkBTN.Enabled = m_application.ApplicationType == ApplicationType.Server || m_application.ApplicationType == ApplicationType.ClientAndServer;
return;
}
}
m_application = null;
OkBTN.Enabled = false;
}
catch (Exception exception)
{
ClientUtils.HandleException(this.Text, exception);
}
}
#endregion
}
}