Files
lmxopcua/src/Drivers/Cli/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Cli/Commands/SubscribeCommand.cs
T
Joseph Doherty f9fbd4ee0d fix(cli): AbCip subscribe serialises and guards console writes; Ctrl-C exits cleanly; arrays render
R07 U7: Driver.Cli.Common gains RunCancellableAsync (moved up from AbLegacy) and
CreateChangeLineWriter (one lock-serialised line per change; a failing console
write is logged and swallowed so it cannot fault the poll loop). AbCip
probe/read/write print Cancelled. on Ctrl-C instead of a stack trace, and AbCip
subscribe uses the shared writer. SnapshotFormatter renders arrays/lists as
[a, b, c] instead of System.Int32[].

Refs #747
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
2026-10-22 16:34:48 -04:00

109 lines
4.3 KiB
C#

using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Cli.Commands;
/// <summary>
/// Watch a Logix tag via polled subscription until Ctrl+C. Uses the driver's
/// <c>ISubscribable</c> surface (PollGroupEngine under the hood). Prints each change
/// event with an HH:mm:ss.fff timestamp.
/// </summary>
[Command("subscribe", Description = "Watch a Logix tag via polled subscription until Ctrl+C.")]
public sealed class SubscribeCommand : AbCipCommandBase
{
/// <summary>Gets or sets the Logix tag path to subscribe to.</summary>
[CommandOption("tag", 't', Description =
"Logix symbolic path — same format as `read`.", IsRequired = true)]
public string TagPath { get; init; } = default!;
/// <summary>Gets or sets the data type of the tag.</summary>
[CommandOption("type", Description =
"Bool / SInt / Int / DInt / LInt / USInt / UInt / UDInt / ULInt / Real / LReal / " +
"String / Dt (default DInt).")]
public AbCipDataType DataType { get; init; } = AbCipDataType.DInt;
/// <summary>Gets or sets the subscription interval in milliseconds.</summary>
[CommandOption("interval-ms", 'i', Description =
"Publishing interval in milliseconds (default 1000). PollGroupEngine floors " +
"sub-250ms values.")]
public int IntervalMs { get; init; } = 1000;
/// <inheritdoc />
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
RejectStructure(DataType);
ValidateInterval(IntervalMs);
_ = Timeout;
var ct = console.RegisterCancellationHandler();
var tagName = ReadCommand.SynthesiseTagName(TagPath, DataType);
var tag = new AbCipTagDefinition(
Name: tagName,
DeviceHostAddress: Gateway,
TagPath: TagPath,
DataType: DataType,
Writable: false);
var options = BuildOptions([tag]);
await using var driver = new AbCipDriver(options, DriverInstanceId);
ISubscriptionHandle? handle = null;
// The poll engine raises OnDataChange on a background thread: serialise its lines against each other and
// against this thread's own, and never let a failed console write fault the poll loop (review 07 U7).
var writeLock = new object();
try
{
await driver.InitializeAsync("{}", ct);
driver.OnDataChange += CreateChangeLineWriter(console.Output, writeLock);
handle = await driver.SubscribeAsync([tagName], TimeSpan.FromMilliseconds(IntervalMs), ct);
lock (writeLock)
{
console.Output.WriteLine($"Subscribed to {TagPath} @ {IntervalMs}ms. Ctrl+C to stop.");
}
try
{
await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct);
}
catch (OperationCanceledException)
{
// Expected on Ctrl+C.
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Ctrl+C while still connecting/subscribing: a clean exit, not a stack trace (review 07 U7).
}
finally
{
if (handle is not null)
{
try { await driver.UnsubscribeAsync(handle, CancellationToken.None); }
catch { /* teardown best-effort */ }
}
await driver.ShutdownAsync(CancellationToken.None);
FlushLogging();
}
}
/// <summary>
/// Guards <c>--interval-ms</c> against zero or negative values.
/// A non-positive interval would produce a non-positive <see cref="TimeSpan"/> into
/// <c>SubscribeAsync</c>; the CLI should fail fast with an actionable error rather
/// than relying on the downstream <c>PollGroupEngine</c> to clamp the value.
/// </summary>
/// <param name="intervalMs">The interval in milliseconds.</param>
internal static void ValidateInterval(int intervalMs)
{
if (intervalMs <= 0)
throw new CliFx.Exceptions.CommandException(
$"--interval-ms must be > 0 (got {intervalMs}). " +
"PollGroupEngine floors sub-250ms values, but accepts any positive integer.");
}
}