-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathClientSamples.cs
More file actions
1628 lines (1462 loc) · 66.4 KB
/
ClientSamples.cs
File metadata and controls
1628 lines (1462 loc) · 66.4 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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ========================================================================
* Copyright (c) 2005-2021 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes;
namespace Quickstarts
{
/// <summary>
/// A client interface which holds an active session.
/// The client handler may reconnect and the Session
/// property may be updated during operation.
/// </summary>
public interface IUAClient
{
/// <summary>
/// The session to use.
/// </summary>
ISession Session { get; }
}
/// <summary>
/// Sample Session calls based on the reference server node model.
/// </summary>
public class ClientSamples
{
private const int kMaxSearchDepth = 128;
public ClientSamples(
ITelemetryContext telemetry,
Action<IList, IList> validateResponse,
ManualResetEvent quitEvent = null,
bool verbose = false)
{
m_telemetry = telemetry;
m_logger = telemetry.CreateLogger<ClientSamples>();
m_validateResponse = validateResponse ?? ClientBase.ValidateResponse;
m_quitEvent = quitEvent;
m_verbose = verbose;
m_desiredEventFields = [];
int eventIndexCounter = 0;
m_desiredEventFields.Add(
eventIndexCounter++,
[.. new QualifiedName[] { BrowseNames.Time }]);
m_desiredEventFields.Add(
eventIndexCounter++,
[.. new QualifiedName[] { BrowseNames.ActiveState }]);
m_desiredEventFields.Add(
eventIndexCounter++,
[.. new QualifiedName[] { BrowseNames.Message }]);
m_desiredEventFields.Add(
eventIndexCounter++,
[.. new QualifiedName[] { BrowseNames.LimitState, BrowseNames.CurrentState }]);
m_desiredEventFields.Add(
eventIndexCounter++,
[.. new QualifiedName[] { BrowseNames.LimitState, BrowseNames.LastTransition }]);
}
/// <summary>
/// Read a list of nodes from Server
/// </summary>
public async Task ReadNodesAsync(ISession session, CancellationToken ct = default)
{
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return;
}
try
{
// build a list of nodes to be read
var nodesToRead = new ReadValueIdCollection
{
// Value of ServerStatus
new ReadValueId {
NodeId = Variables.Server_ServerStatus,
AttributeId = Attributes.Value },
// BrowseName of ServerStatus_StartTime
new ReadValueId
{
NodeId = Variables.Server_ServerStatus_StartTime,
AttributeId = Attributes.BrowseName
},
// Value of ServerStatus_StartTime
new ReadValueId
{
NodeId = Variables.Server_ServerStatus_StartTime,
AttributeId = Attributes.Value
}
};
// Read the node attributes
m_logger.LogInformation("Reading nodes...");
// Call Read Service
ReadResponse response = await session.ReadAsync(
null,
0,
TimestampsToReturn.Both,
nodesToRead,
ct).ConfigureAwait(false);
DataValueCollection resultsValues = response.Results;
DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos;
// Validate the results
m_validateResponse(resultsValues, nodesToRead);
// Display the results.
foreach (DataValue result in resultsValues)
{
m_logger.LogInformation(
"Read Value = {Value} , StatusCode = {StatusCode}",
result.Value,
result.StatusCode);
}
// Read Server NamespaceArray
m_logger.LogInformation("Reading Value of NamespaceArray node...");
DataValue namespaceArray = await session.ReadValueAsync(Variables.Server_NamespaceArray, ct)
.ConfigureAwait(false);
// Display the result
m_logger.LogInformation("NamespaceArray Value = {NamespaceArray}", namespaceArray);
}
catch (Exception ex)
{
// Log Error
m_logger.LogError(ex, "Read Nodes Error.");
}
}
/// <summary>
/// Write a list of nodes to the Server.
/// </summary>
public async Task WriteNodesAsync(ISession session, CancellationToken ct = default)
{
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return;
}
try
{
// Write the configured nodes
var nodesToWrite = new WriteValueCollection();
// Int32 Node - Objects\CTT\Scalar\Scalar_Static\Int32
var intWriteVal = new WriteValue
{
NodeId = new NodeId("ns=2;s=Scalar_Static_Int32"),
AttributeId = Attributes.Value,
Value = new DataValue { Value = 100 }
};
nodesToWrite.Add(intWriteVal);
// Float Node - Objects\CTT\Scalar\Scalar_Static\Float
var floatWriteVal = new WriteValue
{
NodeId = new NodeId("ns=2;s=Scalar_Static_Float"),
AttributeId = Attributes.Value,
Value = new DataValue { Value = (float)100.5 }
};
nodesToWrite.Add(floatWriteVal);
// String Node - Objects\CTT\Scalar\Scalar_Static\String
var stringWriteVal = new WriteValue
{
NodeId = new NodeId("ns=2;s=Scalar_Static_String"),
AttributeId = Attributes.Value,
Value = new DataValue { Value = "String Test" }
};
nodesToWrite.Add(stringWriteVal);
// Write the node attributes
m_logger.LogInformation("Writing nodes...");
// Call Write Service
WriteResponse response = await session.WriteAsync(
null,
nodesToWrite,
ct).ConfigureAwait(false);
StatusCodeCollection results = response.Results;
DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos;
// Validate the response
m_validateResponse(results, nodesToWrite);
// Display the results.
m_logger.LogInformation("Write Results :");
foreach (StatusCode writeResult in results)
{
m_logger.LogInformation(" {Result}", writeResult);
}
}
catch (Exception ex)
{
// Log Error
m_logger.LogInformation(ex, "Write Nodes Error.");
}
}
/// <summary>
/// Browse Server nodes
/// </summary>
public async Task BrowseAsync(ISession session, CancellationToken ct = default)
{
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return;
}
try
{
// Create a Browser object
var browser = new Browser(session)
{
// Set browse parameters
BrowseDirection = BrowseDirection.Forward,
NodeClassMask = (int)NodeClass.Object | (int)NodeClass.Variable,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true
};
NodeId nodeToBrowse = ObjectIds.Server;
// Call Browse service
m_logger.LogInformation("Browsing {Count} node...", nodeToBrowse);
ReferenceDescriptionCollection browseResults =
await browser.BrowseAsync(nodeToBrowse, ct).ConfigureAwait(false);
// Display the results
m_logger.LogInformation("Browse returned {Count} results:", browseResults.Count);
foreach (ReferenceDescription result in browseResults)
{
m_logger.LogInformation(
" DisplayName = {DisplayName}, NodeClass = {NodeClass}",
result.DisplayName.Text,
result.NodeClass);
}
}
catch (Exception ex)
{
// Log Error
m_logger.LogError(ex, "Browse Error.");
}
}
/// <summary>
/// Call UA method
/// </summary>
public async Task CallMethodAsync(ISession session, CancellationToken ct = default)
{
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return;
}
try
{
// Define the UA Method to call
// Parent node - Objects\CTT\Methods
// Method node - Objects\CTT\Methods\Add
var objectId = new NodeId("ns=2;s=Methods");
var methodId = new NodeId("ns=2;s=Methods_Add");
// Define the method parameters
// Input argument requires a Float and an UInt32 value
object[] inputArguments = [(float)10.5, (uint)10];
IList<object> outputArguments = null;
// Invoke Call service
m_logger.LogInformation("Calling UAMethod for method node id {NodeId} ...", methodId);
outputArguments = await session.CallAsync(
objectId,
methodId,
ct,
inputArguments).ConfigureAwait(false);
// Display results
m_logger.LogInformation(
"Method call returned {Count} output argument(s):",
outputArguments.Count);
foreach (object outputArgument in outputArguments)
{
m_logger.LogInformation(" OutputValue = {Value}", outputArgument);
}
}
catch (Exception ex)
{
m_logger.LogError(ex, "Method call error");
}
}
/// <summary>
/// Call the Start method for Alarming to enable events
/// </summary>
public async Task EnableEventsAsync(
ISession session,
uint timeToRun,
CancellationToken ct = default)
{
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return;
}
try
{
// Define the UA Method to call
// Parent node - Objects\CTT\Alarms
// Method node - Objects\CTT\Alarms\Start
var objectId = new NodeId("ns=7;s=Alarms");
var methodId = new NodeId("ns=7;s=Alarms.Start");
// Define the method parameters
// Input argument requires a Float and an UInt32 value
object[] inputArguments = [timeToRun];
IList<object> outputArguments = null;
// Invoke Call service
m_logger.LogInformation("Calling UAMethod for method node id {NodeId} ...", methodId);
outputArguments = await session.CallAsync(
objectId,
methodId,
ct,
inputArguments).ConfigureAwait(false);
// Display results
m_logger.LogInformation(
"Method call returned {Count} output argument(s):",
outputArguments.Count);
foreach (object outputArgument in outputArguments)
{
m_logger.LogInformation(" OutputValue = {Value}", outputArgument);
}
}
catch (Exception ex)
{
m_logger.LogError(ex, "Method call error");
}
}
/// <summary>
/// Create Subscription and MonitoredItems for DataChanges
/// </summary>
public async Task<bool> SubscribeToDataChangesAsync(
ISession session,
uint minLifeTime,
bool enableDurableSubscriptions,
CancellationToken ct = default)
{
bool isDurable = false;
if (session == null || !session.Connected)
{
m_logger.LogInformation("Session not connected!");
return isDurable;
}
try
{
// Create a subscription for receiving data change notifications
const int subscriptionPublishingInterval = 1000;
const int itemSamplingInterval = 1000;
uint queueSize = 10;
uint lifetime = minLifeTime;
if (enableDurableSubscriptions)
{
queueSize = 100;
lifetime = 20;
}
// Define Subscription parameters
var subscription = new Subscription(session.DefaultSubscription)
{
DisplayName = "Console ReferenceClient Subscription",
PublishingEnabled = true,
PublishingInterval = subscriptionPublishingInterval,
LifetimeCount = 0,
MinLifetimeInterval = lifetime,
KeepAliveCount = 5
};
session.AddSubscription(subscription);
// Create the subscription on Server side
await subscription.CreateAsync(ct).ConfigureAwait(false);
m_logger.LogInformation(
"New Subscription created with SubscriptionId = {Id}, Sampling Interval {SamplingInterval}, Publishing Interval {PublishingInterval}.",
subscription.Id,
itemSamplingInterval,
subscriptionPublishingInterval);
if (enableDurableSubscriptions)
{
(bool success, uint revisedLifetimeInHours) =
await subscription.SetSubscriptionDurableAsync(1, ct).ConfigureAwait(false);
if (success)
{
isDurable = true;
m_logger.LogInformation(
"Subscription {SubscriptionId} is now durable, Revised Lifetime {Lifetime} in hours.",
subscription.Id,
revisedLifetimeInHours);
}
else
{
m_logger.LogInformation("Subscription {SubscriptionId} failed durable call", subscription.Id);
}
}
// Create MonitoredItems for data changes (Reference Server)
var intMonitoredItem = new MonitoredItem(subscription.DefaultItem)
{
// Int32 Node - Objects\CTT\Scalar\Simulation\Int32
StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_Int32"),
AttributeId = Attributes.Value,
DisplayName = "Int32 Variable",
SamplingInterval = itemSamplingInterval,
QueueSize = queueSize,
DiscardOldest = true
};
intMonitoredItem.Notification += OnMonitoredItemNotification;
subscription.AddItem(intMonitoredItem);
var floatMonitoredItem = new MonitoredItem(subscription.DefaultItem)
{
// Float Node - Objects\CTT\Scalar\Simulation\Float
StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_Float"),
AttributeId = Attributes.Value,
DisplayName = "Float Variable",
SamplingInterval = itemSamplingInterval,
QueueSize = queueSize
};
floatMonitoredItem.Notification += OnMonitoredItemNotification;
subscription.AddItem(floatMonitoredItem);
var stringMonitoredItem = new MonitoredItem(subscription.DefaultItem)
{
// String Node - Objects\CTT\Scalar\Simulation\String
StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_String"),
AttributeId = Attributes.Value,
DisplayName = "String Variable",
SamplingInterval = itemSamplingInterval,
QueueSize = queueSize
};
stringMonitoredItem.Notification += OnMonitoredItemNotification;
subscription.AddItem(stringMonitoredItem);
var eventMonitoredItem = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = new NodeId(ObjectIds.Server),
AttributeId = Attributes.EventNotifier,
DisplayName = "Event Variable",
SamplingInterval = itemSamplingInterval,
QueueSize = queueSize
};
eventMonitoredItem.Notification += OnMonitoredItemEventNotification;
var filter = new EventFilter();
var simpleAttributeOperands = new SimpleAttributeOperandCollection();
foreach (QualifiedNameCollection desiredEventField in m_desiredEventFields.Values)
{
simpleAttributeOperands.Add(
new SimpleAttributeOperand
{
AttributeId = Attributes.Value,
TypeDefinitionId = ObjectTypeIds.BaseEventType,
BrowsePath = desiredEventField
});
}
filter.SelectClauses = simpleAttributeOperands;
var whereClause = new ContentFilter();
var existingEventType = new SimpleAttributeOperand
{
AttributeId = Attributes.Value,
TypeDefinitionId = ObjectTypeIds.ExclusiveLevelAlarmType,
BrowsePath = new QualifiedNameCollection(["EventType"])
};
var desiredEventType = new LiteralOperand
{
Value = new Variant(new NodeId(ObjectTypeIds.ExclusiveLevelAlarmType))
};
whereClause.Push(FilterOperator.Equals, [existingEventType, desiredEventType]);
filter.WhereClause = whereClause;
eventMonitoredItem.Filter = filter;
eventMonitoredItem.NodeClass = NodeClass.Object;
subscription.AddItem(eventMonitoredItem);
// Create the monitored items on Server side
await subscription.ApplyChangesAsync(ct).ConfigureAwait(false);
m_logger.LogInformation(
"MonitoredItems created for SubscriptionId = {SubscriptionId}.",
subscription.Id);
}
catch (Exception ex)
{
m_logger.LogError(ex, "Subscribe error");
}
return isDurable;
}
/// <summary>
/// Fetch all references and nodes with attributes except values from the server.
/// </summary>
/// <param name="uaClient">The UAClient with a session to use.</param>
/// <param name="startingNode">The node from which the hierarchical nodes are fetched.</param>
/// <param name="fetchTree">Iterate to fetch all nodes in the tree.</param>
/// <param name="addRootNode">Adds the root node to the result.</param>
/// <param name="filterUATypes">Filters nodes from namespace 0 from the result.</param>
/// <returns>The list of nodes on the server.</returns>
public async Task<IList<INode>> FetchAllNodesNodeCacheAsync(
IUAClient uaClient,
NodeId startingNode,
bool fetchTree = false,
bool addRootNode = false,
bool filterUATypes = true,
bool clearNodeCache = true,
CancellationToken ct = default)
{
var stopwatch = new Stopwatch();
var nodeDictionary = new Dictionary<ExpandedNodeId, INode>();
var references = new NodeIdCollection { ReferenceTypeIds.HierarchicalReferences };
var nodesToBrowse = new ExpandedNodeIdCollection { startingNode };
// start
stopwatch.Start();
if (clearNodeCache)
{
// clear NodeCache to fetch all nodes from server
uaClient.Session.NodeCache.Clear();
await FetchReferenceIdTypesAsync(uaClient.Session, ct).ConfigureAwait(false);
}
// add root node
if (addRootNode)
{
INode rootNode = await uaClient.Session.NodeCache.FindAsync(startingNode, ct)
.ConfigureAwait(false);
nodeDictionary[rootNode.NodeId] = rootNode;
}
int searchDepth = 0;
while (nodesToBrowse.Count > 0 && searchDepth < kMaxSearchDepth)
{
if (m_quitEvent?.WaitOne(0) == true)
{
m_logger.LogInformation("Browse aborted.");
break;
}
searchDepth++;
m_logger.LogInformation(
"{Depth}: Find {Count} references after {Duration}ms",
searchDepth,
nodesToBrowse.Count,
stopwatch.ElapsedMilliseconds);
IList<INode> response = await uaClient
.Session.NodeCache.FindReferencesAsync(nodesToBrowse, references, false, true, ct)
.ConfigureAwait(false);
var nextNodesToBrowse = new ExpandedNodeIdCollection();
int duplicates = 0;
int leafNodes = 0;
foreach (INode node in response)
{
if (!nodeDictionary.ContainsKey(node.NodeId))
{
if (fetchTree)
{
bool leafNode = false;
// no need to browse property types
if (node is VariableNode variableNode)
{
IReference hasTypeDefinition = variableNode.ReferenceTable
.FirstOrDefault(r =>
r.ReferenceTypeId
.Equals(ReferenceTypeIds.HasTypeDefinition));
if (hasTypeDefinition != null)
{
leafNode = hasTypeDefinition.TargetId == VariableTypeIds
.PropertyType;
}
}
if (!leafNode)
{
nextNodesToBrowse.Add(node.NodeId);
}
else
{
leafNodes++;
}
}
if (filterUATypes)
{
if (node.NodeId.NamespaceIndex != 0)
{
// filter out default namespace
nodeDictionary[node.NodeId] = node;
}
}
else
{
nodeDictionary[node.NodeId] = node;
}
}
else
{
duplicates++;
}
}
if (duplicates > 0)
{
m_logger.LogInformation("Find References {Count} duplicate nodes were ignored", duplicates);
}
if (leafNodes > 0)
{
m_logger.LogInformation("Find References {Count} leaf nodes were ignored", leafNodes);
}
nodesToBrowse = nextNodesToBrowse;
}
stopwatch.Stop();
m_logger.LogInformation(
"FetchAllNodesNodeCache found {Count} nodes in {Duration}ms",
nodeDictionary.Count,
stopwatch.ElapsedMilliseconds);
var result = nodeDictionary.Values.ToList();
result.Sort((x, y) => x.NodeId.CompareTo(y.NodeId));
if (m_verbose)
{
foreach (INode node in result)
{
m_logger.LogInformation(
"NodeId {NodeId} {NodeClass} {BrowseName}",
node.NodeId,
node.NodeClass,
node.BrowseName);
}
}
return result;
}
/// <summary>
/// Browse full address space using the ManagedBrowseMethod, which
/// will take care of not sending to many nodes to the server,
/// calling BrowseNext and dealing with the status codes
/// BadNoContinuationPoint and BadInvalidContinuationPoint.
/// </summary>
/// <param name="uaClient">The UAClient with a session to use.</param>
/// <param name="startingNode">The node where the browse operation starts.</param>
/// <param name="browseDescription">An optional BrowseDescription to use.</param>
public async Task<ReferenceDescriptionCollection> ManagedBrowseFullAddressSpaceAsync(
IUAClient uaClient,
NodeId startingNode = null,
BrowseDescription browseDescription = null,
CancellationToken ct = default)
{
ContinuationPointPolicy policyBackup = uaClient.Session.ContinuationPointPolicy;
uaClient.Session.ContinuationPointPolicy = ContinuationPointPolicy.Default;
var stopWatch = new Stopwatch();
stopWatch.Start();
BrowseDirection browseDirection = BrowseDirection.Forward;
NodeId referenceTypeId = ReferenceTypeIds.HierarchicalReferences;
bool includeSubtypes = true;
uint nodeClassMask = 0;
if (browseDescription != null)
{
startingNode = browseDescription.NodeId;
browseDirection = browseDescription.BrowseDirection;
referenceTypeId = browseDescription.ReferenceTypeId;
includeSubtypes = browseDescription.IncludeSubtypes;
nodeClassMask = browseDescription.NodeClassMask;
if (browseDescription.ResultMask != (uint)BrowseResultMask.All)
{
m_logger.LogWarning(
"Setting the BrowseResultMask is not supported by the " +
"ManagedBrowse method. Using '{BrowseResultMask}' instead of " +
"the mask {BrowseDescriptionResultMask} for the result mask",
BrowseResultMask.All,
browseDescription.ResultMask);
}
}
var nodesToBrowse = new List<NodeId> { startingNode ?? ObjectIds.RootFolder };
const int kMaxReferencesPerNode = 1000;
// Browse
var referenceDescriptions = new Dictionary<ExpandedNodeId, ReferenceDescription>();
int searchDepth = 0;
uint maxNodesPerBrowse = uaClient.Session.OperationLimits.MaxNodesPerBrowse;
var allReferenceDescriptions = new List<ReferenceDescriptionCollection>();
var newReferenceDescriptions = new List<ReferenceDescriptionCollection>();
var allServiceResults = new List<ServiceResult>();
while (nodesToBrowse.Count != 0 && searchDepth < kMaxSearchDepth)
{
searchDepth++;
m_logger.LogInformation(
"{Depth}: Browse {Count} nodes after {Duration}ms",
searchDepth,
nodesToBrowse.Count,
stopWatch.ElapsedMilliseconds);
const bool repeatBrowse = false;
do
{
if (m_quitEvent?.WaitOne(0) == true)
{
m_logger.LogInformation("Browse aborted.");
break;
}
try
{
// the resultMask defaults to "all"
// maybe the API should be extended to
// support it. But that will then also be
// necessary for BrowseAsync
(IList<ReferenceDescriptionCollection> descriptions, IList<ServiceResult> errors) =
await uaClient
.Session.ManagedBrowseAsync(
null,
null,
nodesToBrowse,
kMaxReferencesPerNode,
browseDirection,
referenceTypeId,
true,
nodeClassMask,
ct)
.ConfigureAwait(false);
allReferenceDescriptions.AddRange(descriptions);
newReferenceDescriptions.AddRange(descriptions);
allServiceResults.AddRange(errors);
}
catch (ServiceResultException sre)
{
// the maximum number of nodes per browse is
// set in the ManagedBrowse from the configuration
// and cannot be influenced from the outside.
// if that's desired it would be necessary to provide
// an additional parameter to the method.
m_logger.LogError(sre, "Browse error");
throw;
}
} while (repeatBrowse);
// Build browse request for next level
var nodesForNextManagedBrowse = new List<NodeId>();
int duplicates = 0;
foreach (ReferenceDescriptionCollection referenceCollection in newReferenceDescriptions)
{
foreach (ReferenceDescription reference in referenceCollection)
{
if (!referenceDescriptions.ContainsKey(reference.NodeId))
{
referenceDescriptions[reference.NodeId] = reference;
if (!reference.ReferenceTypeId.Equals(ReferenceTypeIds.HasProperty))
{
nodesForNextManagedBrowse.Add(
ExpandedNodeId.ToNodeId(
reference.NodeId,
uaClient.Session.NamespaceUris));
}
}
else
{
duplicates++;
}
}
}
newReferenceDescriptions.Clear();
nodesToBrowse = nodesForNextManagedBrowse;
if (duplicates > 0)
{
m_logger.LogInformation(
"Managed Browse Result {Count} duplicate nodes were ignored.",
duplicates);
}
}
stopWatch.Stop();
var result = new ReferenceDescriptionCollection(referenceDescriptions.Values);
result.Sort((x, y) => x.NodeId.CompareTo(y.NodeId));
m_logger.LogInformation(
"ManagedBrowseFullAddressSpace found {Count} references on server in {Duration}ms.",
result.Count,
stopWatch.ElapsedMilliseconds);
if (m_verbose)
{
foreach (ReferenceDescription reference in result)
{
m_logger.LogInformation(
"NodeId {NodeId} {NodeClass} {BrowseName}",
reference.NodeId,
reference.NodeClass,
reference.BrowseName);
}
}
uaClient.Session.ContinuationPointPolicy = policyBackup;
return result;
}
/// <summary>
/// Browse full address space.
/// </summary>
/// <param name="uaClient">The UAClient with a session to use.</param>
/// <param name="startingNode">The node where the browse operation starts.</param>
/// <param name="browseDescription">An optional BrowseDescription to use.</param>
public async Task<ReferenceDescriptionCollection> BrowseFullAddressSpaceAsync(
IUAClient uaClient,
NodeId startingNode = null,
BrowseDescription browseDescription = null,
CancellationToken ct = default)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
// Browse template
const int kMaxReferencesPerNode = 1000;
BrowseDescription browseTemplate =
browseDescription
?? new BrowseDescription
{
NodeId = startingNode ?? ObjectIds.RootFolder,
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true,
NodeClassMask = 0,
ResultMask = (uint)BrowseResultMask.All
};
BrowseDescriptionCollection browseDescriptionCollection
= CreateBrowseDescriptionCollectionFromNodeId(
[.. new NodeId[] { startingNode ?? ObjectIds.RootFolder }],
browseTemplate);
// Browse
var referenceDescriptions = new Dictionary<ExpandedNodeId, ReferenceDescription>();
int searchDepth = 0;
uint maxNodesPerBrowse = uaClient.Session.OperationLimits.MaxNodesPerBrowse;
while (browseDescriptionCollection.Count > 0 && searchDepth < kMaxSearchDepth)
{
searchDepth++;
m_logger.LogInformation(
"{Depth}: Browse {Count} nodes after {Duration}ms",
searchDepth,
browseDescriptionCollection.Count,
stopWatch.ElapsedMilliseconds);
var allBrowseResults = new BrowseResultCollection();
bool repeatBrowse;
var browseResultCollection = new BrowseResultCollection();
var unprocessedOperations = new BrowseDescriptionCollection();
DiagnosticInfoCollection diagnosticsInfoCollection;
do
{
if (m_quitEvent?.WaitOne(0) == true)
{
m_logger.LogInformation("Browse aborted.");
break;
}
BrowseDescriptionCollection browseCollection =
maxNodesPerBrowse == 0
? browseDescriptionCollection
: browseDescriptionCollection.Take((int)maxNodesPerBrowse).ToArray();
repeatBrowse = false;
try
{
BrowseResponse browseResponse = await uaClient
.Session.BrowseAsync(
null,
null,
kMaxReferencesPerNode,
browseCollection,
ct)
.ConfigureAwait(false);
browseResultCollection = browseResponse.Results;
diagnosticsInfoCollection = browseResponse.DiagnosticInfos;
ClientBase.ValidateResponse(browseResultCollection, browseCollection);
ClientBase.ValidateDiagnosticInfos(
diagnosticsInfoCollection,
browseCollection);
// separate unprocessed nodes for later
int ii = 0;
foreach (BrowseResult browseResult in browseResultCollection)
{
// check for error.
StatusCode statusCode = browseResult.StatusCode;
if (StatusCode.IsBad(statusCode))
{
// this error indicates that the server does not have enough simultaneously active
// continuation points. This request will need to be resent after the other operations
// have been completed and their continuation points released.
if (statusCode == StatusCodes.BadNoContinuationPoints)
{
unprocessedOperations.Add(browseCollection[ii++]);
continue;
}
}
// save results.
allBrowseResults.Add(browseResult);
ii++;
}
}