Files
lmxopcua/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/AlarmsCommand.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

147 lines
5.8 KiB
C#

using System.Threading.Channels;
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;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("alarms", Description = "Subscribe to alarm events")]
public class AlarmsCommand : CommandBase
{
/// <summary>
/// Creates the alarm-monitoring command used to stream OPC UA condition events to the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public AlarmsCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the optional source node whose alarm events should be monitored instead of the server root.
/// </summary>
[CommandOption("node", 'n', Description = "Node ID to monitor for events (default: Server node)")]
public string? NodeId { get; init; }
/// <summary>
/// Gets the publishing interval, in milliseconds, for the alarm subscription.
/// </summary>
[CommandOption("interval", 'i', Description = "Publishing interval in milliseconds")]
public int Interval { get; init; } = 1000;
/// <summary>
/// Gets a value indicating whether retained alarm conditions should be refreshed immediately after subscribing.
/// </summary>
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
public bool Refresh { get; init; }
/// <summary>
/// Connects to the server, subscribes to alarm events, and streams operator-facing alarm state changes to the console.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
if (Interval <= 0)
throw new CommandException($"--interval must be greater than 0 (was {Interval}).");
NodeId? sourceNodeId;
try
{
sourceNodeId = 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);
// Channel serialises SDK notification-thread writes to the main async loop so
// that concurrent alarm callbacks never interleave on the shared TextWriter.
var outputChannel = Channel.CreateUnbounded<string>(
new UnboundedChannelOptions { SingleReader = true });
void AlarmEventHandler(object? sender, AlarmEventArgs e)
{
try
{
var activeStr = e.ActiveState ? "Active" : "Inactive";
var ackedStr = e.AckedState ? "Acknowledged" : "Unacknowledged";
outputChannel.Writer.TryWrite($"[{e.Time:O}] ALARM {e.SourceName}");
outputChannel.Writer.TryWrite($" Condition: {e.ConditionName}");
outputChannel.Writer.TryWrite($" State: {activeStr}, {ackedStr}");
outputChannel.Writer.TryWrite($" Severity: {e.Severity}");
if (!string.IsNullOrEmpty(e.Message))
outputChannel.Writer.TryWrite($" Message: {e.Message}");
outputChannel.Writer.TryWrite($" Retain: {e.Retain}");
outputChannel.Writer.TryWrite(string.Empty);
}
catch
{
// Never let handler exceptions escape into the SDK callback.
}
}
service.AlarmEvent += AlarmEventHandler;
await service.SubscribeAlarmsAsync(sourceNodeId, Interval, ct);
await console.Output.WriteLineAsync(
$"Subscribed to alarm events (interval: {Interval}ms). Press Ctrl+C to stop.");
if (Refresh)
try
{
await service.RequestConditionRefreshAsync(ct);
await console.Output.WriteLineAsync("Condition refresh requested.");
}
catch (Exception ex)
{
await console.Output.WriteLineAsync($"Condition refresh not supported: {ex.Message}");
}
// Drain the output channel on the main thread until cancellation fires.
using var drainCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var drainTask = Task.Run(async () =>
{
await foreach (var line in outputChannel.Reader.ReadAllAsync(drainCts.Token))
await console.Output.WriteLineAsync(line);
}, CancellationToken.None);
// Wait until cancellation
try
{
await Task.Delay(Timeout.Infinite, ct);
}
catch (OperationCanceledException)
{
// Expected on Ctrl+C
}
// Stop accepting new notifications before writing final output.
service.AlarmEvent -= AlarmEventHandler;
outputChannel.Writer.Complete();
await drainCts.CancelAsync();
try { await drainTask; } catch (OperationCanceledException) { }
await service.UnsubscribeAlarmsAsync();
await console.Output.WriteLineAsync("Unsubscribed.");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}