using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Cli.Commands;
///
/// Read one FOCAS address (PMC R/G/F file, parameter, macro, axis register).
///
[Command("read", Description = "Read a single FOCAS address.")]
public sealed class ReadCommand : FocasCommandBase
{
/// Gets the FOCAS address to read.
[CommandOption("address", 'a', Description =
"FOCAS address. Examples: R100 (PMC R-file word); X0.0 (PMC X-bit); " +
"PARAM:1815/0 (parameter 1815, axis 0); MACRO:500 (macro variable 500).",
IsRequired = true)]
public string Address { get; init; } = default!;
/// Gets the data type to interpret the address as.
[CommandOption("type", 't', Description =
"Bit / Byte / Int16 / Int32 / Float32 / Float64 / String (default Int16).")]
public FocasDataType DataType { get; init; } = FocasDataType.Int16;
///
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
// Validate numeric option ranges before any driver work.
ValidateOptions();
var ct = console.RegisterCancellationHandler();
var tagName = SynthesiseTagName(Address, DataType);
var tag = new FocasTagDefinition(
Name: tagName,
DeviceHostAddress: HostAddress,
Address: Address,
DataType: DataType,
Writable: false);
var options = BuildOptions([tag]);
// `await using` is the sole disposal mechanism — FocasDriver.DisposeAsync
// already invokes ShutdownAsync, so a redundant explicit ShutdownAsync(CancellationToken.None)
// in a finally block ran shutdown twice. The await-using on the next line is enough.
await using var driver = new FocasDriver(options, DriverInstanceId);
try
{
await driver.InitializeAsync("{}", ct);
var snapshot = await driver.ReadAsync([tagName], ct);
await console.Output.WriteLineAsync(SnapshotFormatter.Format(Address, snapshot[0]));
}
finally
{
// Flush Serilog before process exit so buffered log output
// emitted during driver shutdown is not silently dropped (matching DriverCommandBase
// docs and every sibling CLI — Modbus / AbCip / AbLegacy / TwinCAT).
FlushLogging();
}
}
/// Constructs a tag name from address and data type.
/// The FOCAS address.
/// The data type.
/// The synthesised tag name in address:type form.
internal static string SynthesiseTagName(string address, FocasDataType type)
=> $"{address}:{type}";
}