Files
lmxopcua/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/BrowseCommand.cs
T
Joseph Doherty 7fe9f16cf8 fix(client-cli): resolve Low code-review findings (Client.CLI-002,003,004,006,007,008,009,010)
- Client.CLI-002: SubscribeCommand's neverWentBad list now requires the
  node to be present in lastStatus (i.e. received at least one update)
  so the 'suspect' bucket only contains observed nodes.
- Client.CLI-003: every long-running command validates numeric option
  ranges (Interval / Depth / MaxDepth / Duration / Max) and throws
  CliFx CommandException on out-of-range values.
- Client.CLI-004: SubscribeCommand carries XML summary docs on the
  type, ctor, every [CommandOption] property, and ExecuteAsync —
  matching the sibling commands' style.
- Client.CLI-006: HistoryReadCommand parses --start / --end with
  InvariantCulture+UTC and surfaces FormatException as CommandException;
  every NodeIdParser.ParseRequired call wraps FormatException /
  ArgumentException as CommandException.
- Client.CLI-007: CommandBase.ConfigureLogging calls Log.CloseAndFlush()
  before assigning a new Log.Logger so prior sinks are disposed.
- Client.CLI-008: rewrote the subscribe and historyread sections of
  docs/Client.CLI.md (every flag documented, summary-bucket vocabulary,
  StandardDeviation aggregate, UTC --start/--end convention).
- Client.CLI-009: SubscribeCommand / AlarmsCommand use named local
  handlers and detach them via -= after UnsubscribeAsync so no
  notification reaches the console after the command's output phase
  ends.
- Client.CLI-010: added CommandRangeValidationTests,
  EventHandlerLifecycleTests, InputValidationErrorsTests,
  LoggerLifecycleTests, and SubscribeCommandSummaryTests pinning every
  Low fix; FakeOpcUaClientService gained AddDiscoveredVariable +
  RaiseDataChanged + BrowseResultsByParent helpers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 11:13:08 -04:00

111 lines
3.6 KiB
C#

using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("browse", Description = "Browse the OPC UA address space")]
public class BrowseCommand : CommandBase
{
/// <summary>
/// Creates the browse command used to inspect the server address space from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public BrowseCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the optional starting node for the browse, defaulting to the Objects folder.
/// </summary>
[CommandOption("node", 'n', Description = "Node ID to browse (default: Objects folder)")]
public string? NodeId { get; init; }
/// <summary>
/// Gets the maximum browse depth the command should traverse.
/// </summary>
[CommandOption("depth", 'd', Description = "Maximum browse depth")]
public int Depth { get; init; } = 1;
/// <summary>
/// Gets a value indicating whether child nodes should be traversed recursively.
/// </summary>
[CommandOption("recursive", 'r', Description = "Browse recursively (uses --depth as max depth)")]
public bool Recursive { get; init; }
/// <summary>
/// Connects to the server and prints a tree view of the requested address-space branch.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
if (Depth <= 0)
throw new CommandException($"--depth must be greater than 0 (was {Depth}).");
NodeId? startNode;
try
{
startNode = NodeIdParser.Parse(NodeId);
}
catch (Exception ex) when (ex is FormatException or ArgumentException)
{
throw new CommandException($"Invalid --node value: {ex.Message}");
}
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var maxDepth = Recursive ? Depth : 1;
await BrowseNodeAsync(service, console, startNode, maxDepth, 0, ct);
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
private static async Task BrowseNodeAsync(
IOpcUaClientService service,
IConsole console,
NodeId? nodeId,
int maxDepth,
int currentDepth,
CancellationToken ct)
{
var indent = new string(' ', currentDepth * 2);
var results = await service.BrowseAsync(nodeId, ct);
foreach (var result in results)
{
var marker = result.NodeClass switch
{
"Object" => "[Object]",
"Variable" => "[Variable]",
"Method" => "[Method]",
_ => $"[{result.NodeClass}]"
};
await console.Output.WriteLineAsync(
$"{indent}{marker} {result.DisplayName} (NodeId: {result.NodeId})");
if (currentDepth + 1 < maxDepth && result.HasChildren)
{
var childNodeId = NodeIdParser.Parse(result.NodeId);
await BrowseNodeAsync(service, console, childNodeId, maxDepth, currentDepth + 1, ct);
}
}
}
}