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; /// /// Watch a Logix tag via polled subscription until Ctrl+C. Uses the driver's /// ISubscribable surface (PollGroupEngine under the hood). Prints each change /// event with an HH:mm:ss.fff timestamp. /// [Command("subscribe", Description = "Watch a Logix tag via polled subscription until Ctrl+C.")] public sealed class SubscribeCommand : AbCipCommandBase { [CommandOption("tag", 't', Description = "Logix symbolic path — same format as `read`.", IsRequired = true)] public string TagPath { get; init; } = default!; [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; [CommandOption("interval-ms", 'i', Description = "Publishing interval in milliseconds (default 1000). PollGroupEngine floors " + "sub-250ms values.")] public int IntervalMs { get; init; } = 1000; public override async ValueTask ExecuteAsync(IConsole console) { ConfigureLogging(); 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; try { await driver.InitializeAsync("{}", ct); driver.OnDataChange += (_, e) => { var line = $"[{DateTime.UtcNow:HH:mm:ss.fff}] " + $"{e.FullReference} = {SnapshotFormatter.FormatValue(e.Snapshot.Value)} " + $"({SnapshotFormatter.FormatStatus(e.Snapshot.StatusCode)})"; console.Output.WriteLine(line); }; handle = await driver.SubscribeAsync([tagName], TimeSpan.FromMilliseconds(IntervalMs), ct); await console.Output.WriteLineAsync( $"Subscribed to {TagPath} @ {IntervalMs}ms. Ctrl+C to stop."); try { await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct); } catch (OperationCanceledException) { // Expected on Ctrl+C. } } finally { if (handle is not null) { try { await driver.UnsubscribeAsync(handle, CancellationToken.None); } catch { /* teardown best-effort */ } } await driver.ShutdownAsync(CancellationToken.None); } } }