BrowseCrawler — Offline crawling of entire trees
Overview
IDE During startup or when going HMI online, it is often necessary to load the server’s AddressSpace subtree locally so that subsequent node searches and autocomplete do not require additional requests Browse RPC.BrowseCrawler The subtree is traversed BFS in order, and already-visited nodes are automatically removed (the server’s node graph may contain cycles), with maxDepth maxNodes dual upper bounds to prevent overflow.
Corresponding section of the standard: Part 4 §5.8 (Browse Service Set).
API
| Members | Category | Reading and Writing | Note |
|---|---|---|---|
| new BrowseCrawler(ua, maxDepth, maxNodes, nodeClassFilter) | Structure | — | Building a Web Crawler |
| CrawlAsync(rootNodeId, progress, cancellationToken) | Methods | Read | Asynchronous Crawling BFS, Returns Task<CrawlResult> |
| CrawlResult.AllNodes | Properties | Read | Flat Node List (List<CrawlNode>, BFS Order) |
| CrawlResult.ChildrenByParent | Properties | Read | Dictionary of Father-Son Relationships (Dictionary<string, List<string>>) |
| CrawlResult.CrawledAt | Properties | Read | Start time UTC of the crawl |
| CrawlResult.Elapsed | Properties | Read | Total time (TimeSpan) |
| CrawlNode.NodeId / DisplayName / BrowseName / NodeClass / ParentNodeId | Properties | Read | Node Field (positional record) |
BrowseCrawler Structure and Signature CrawlAsync:
public BrowseCrawler(DarraOpcUa ua, int maxDepth = 10, int maxNodes = 100_000,
NodeClass nodeClassFilter = NodeClass.Unspecified);
public Task<CrawlResult> CrawlAsync(string rootNodeId,
IProgress<(int count, string currentNid)> progress = null,
CancellationToken cancellationToken = default);
Construction Parameters:
| Parameters | Type | Default | Note |
|---|---|---|---|
| ua | DarraOpcUa | — | Connected session; returns null or throws an exception ArgumentNullException |
| maxDepth | int | 10 | Maximum Recursion Depth (to prevent stack overflow); <= 0 Discard ArgumentOutOfRangeException |
| maxNodes | int | 100,000 | Maximum number of nodes (to prevent an overflow); <= 0 Discard ArgumentOutOfRangeException |
| nodeClassFilter | NodeClass | Unspecified | Only the result NodeClass is filtered; BFS still walks every child node |
CrawlAsync Parameters:
| Parameters | Type | Default | Note |
|---|---|---|---|
| rootNodeId | string | — | Starting Point NodeId; Automatically switches to when passing null or an empty string ( WellKnownNodes.ObjectsFolder i=85) |
| progress | IProgress<(int count, string currentNid)> | null | Progress callback: Triggered once for every 100 nodes written; an additional callback is triggered at the end (where currentNid is null). |
| cancellationToken | CancellationToken | default | Revoke Token |
Code Example
using System;
using System.Threading;
using System.Threading.Tasks;
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();
// 1) Climb the entire tree ObjectsFolder
var crawler = new BrowseCrawler(ua, maxDepth: 8, maxNodes: 50_000);
var result = await crawler.CrawlAsync(
WellKnownNodes.ObjectsFolder,
progress: new Progress<(int count, string currentNid)>(p =>
Console.Write($"\r已抓 {p.count} 个, 当前 {p.currentNid}")));
Console.WriteLine($"\n共 {result.AllNodes.Count} 节点, 耗时 {result.Elapsed.TotalSeconds:F1}s");
// 2) Capture only Variable nodes (create a local tag dictionary)
var c2 = new BrowseCrawler(ua, nodeClassFilter: NodeClass.Variable);
var r2 = await c2.CrawlAsync("ns=2;s=Boilers");
foreach (var n in r2.AllNodes)
Console.WriteLine($" {n.BrowseName} ({n.NodeId}) ← {n.ParentNodeId}");
// 3) Cancel (user closes the dialog box)
using var cts = new CancellationTokenSource();
cancelButton.Click += (_, _) => cts.Cancel();
try
{
var r3 = await crawler.CrawlAsync("i=85", null, cts.Token);
Console.WriteLine($"共抓 {r3.AllNodes.Count} 个");
}
catch (OperationCanceledException)
{
Console.WriteLine("爬取已取消");
}
Implementation Details
- Single-point failure Browse: Only skips that node; does not interrupt the entire crawl.
- The progress callback is triggered once for every 100 nodes written to prevent the UI thread from being flooded with messages.
- NodeId Use exact
StringComparer.Ordinalmatch to remove duplicates; do not normalize case. CrawlAsyncExecuted in a background thread; the call returns immediately and does not block the calling thread.- In the results,
AllNodesExcludes root itself; conceptuallyParentNodeId, root is null maxNodesCount only the nodes withAllNodes"write" — Neither the root itself nor the filterednodeClassFilternodes count toward the quota.
Implementation Constraints
- Cancelling does not always return partial results: if the token was cancelled before the crawl started,
awaitthrowsTaskCanceledExceptionand noCrawlResultis returned; only a cancellation made after the crawl has begun returns the portion already fetched. maxDepthThe calculation method is based on the number of layers of the edge.:maxDepth: 8When the root has depth 0, the deepest child node reached is the 7th-level child nodenodeClassFilterMatch by combination of symbols: When passing multiple combinations NodeClass, perform a bitwise OR match
Best Practices
- Restricted to root — Don't start from
i=84(Root); instead, start fromi=85(Objects) or a specific subtree - Use
nodeClassFilter— Filters only when Variable is of interest, saving memory - Crawl all at once on startup — Subsequent Editor / Tree Panel: Look up locally
AllNodes - For the "Cancel Load" button — Pass by reference
CancellationToken; however, be sure to writeOperationCanceledExceptiona catch block—don’t assume you’ll always receive a partial result. - Don't Get Stuck in an Infinite Loop —
maxDepth/maxNodesRequired to prevent the "Infinite Node Server" from freezing
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| BrowseCrawler | BrowseCrawler | BrowseCrawler | BrowseCrawler | BrowseCrawler | DarraUa_Session_CrawlAddressSpace |
| CrawlAsync | crawl | crawlAsync | CrawlAsync | crawl | DarraUa_Session_CrawlAddressSpace |
The entry point for C is a single function DarraUa_Session_CrawlAddressSpace(session, config, on_node, ctx), accompanied by DarraUa_CrawlerConfig(DarraUa_CrawlerConfig_Init initialization) / DarraUa_CrawlNode / DarraUa_OnCrawlNode,There is no such DarraUa_BrowseCrawler_* family; The two lines above represent the same function on the C side.
Capability differences: C#'s CrawlAsync has a CancellationToken parameter, Python's crawl() has none (to stop early you must truncate with maxDepth / maxNodes). Both columns use each side's real method names.