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("read", Description = "Read a value from a node")]
public class ReadCommand : CommandBase
{
///
/// Creates the point-read command used to inspect the current value of a node.
///
/// The factory that creates the shared client service for the command run.
public ReadCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
///
/// Gets the node whose current value should be read.
///
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
public string NodeId { get; init; } = default!;
///
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
NodeId nodeId;
try
{
nodeId = NodeIdParser.ParseRequired(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 value = await service.ReadValueAsync(nodeId, ct);
await console.Output.WriteLineAsync($"Node: {NodeId}");
await console.Output.WriteLineAsync($"Value: {value.Value}");
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}");
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}