feat(client-cli): add ack/confirm/shelve alarm commands with service layer

Adds ConfirmAlarmAsync and ShelveAlarmAsync to IOpcUaClientService and
OpcUaClientService (mirroring the AcknowledgeAlarmAsync pattern: same
CallMethodAsync/ServiceResultException/StatusCode contract). Adds ShelveKind
enum (OneShot/Timed/Unshelve). Adds three new CLI commands — ack, confirm,
shelve — with hex EventId input and per-command argument validation.
Updates both fakes (CLI + UI) to implement the new interface members and
record calls. Adds 16 unit tests covering argument mapping, invalid-input
CommandException paths, bad-status output, and disconnect-in-finally.
This commit is contained in:
Joseph Doherty
2026-06-11 05:46:25 -04:00
parent a6fed85ac9
commit 1f172e55f7
11 changed files with 819 additions and 1 deletions
@@ -0,0 +1,78 @@
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("ack", Description = "Acknowledge an active alarm condition (OPC UA Part 9)")]
public class AcknowledgeCommand : CommandBase
{
/// <summary>
/// Creates the acknowledge command used to acknowledge an active OPC UA condition from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public AcknowledgeCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the condition node ID of the alarm event to acknowledge.
/// </summary>
[CommandOption("node", 'n', Description = "Condition node ID of the alarm to acknowledge", IsRequired = true)]
public string NodeId { get; init; } = default!;
/// <summary>
/// Gets the event ID (hex-encoded) returned by the server in the alarm notification.
/// </summary>
[CommandOption("event-id", 'e', Description = "EventId from the alarm notification (hex-encoded byte array)", IsRequired = true)]
public string EventId { get; init; } = default!;
/// <summary>
/// Gets the operator comment to include with the acknowledgment.
/// </summary>
[CommandOption("comment", 'c', Description = "Operator comment for the acknowledgment")]
public string Comment { get; init; } = string.Empty;
/// <summary>
/// Connects to the server and acknowledges the specified alarm condition.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
byte[] eventId;
try
{
eventId = Convert.FromHexString(EventId);
}
catch (FormatException ex)
{
throw new CommandException($"Invalid --event-id value: {ex.Message} (expected hex-encoded bytes, e.g. 0A1B2C)");
}
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var statusCode = await service.AcknowledgeAlarmAsync(NodeId, eventId, Comment, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Acknowledge successful: {NodeId}");
else
await console.Output.WriteLineAsync($"Acknowledge failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}
@@ -0,0 +1,78 @@
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("confirm", Description = "Confirm an acknowledged alarm condition (OPC UA Part 9 two-stage acknowledgment)")]
public class ConfirmCommand : CommandBase
{
/// <summary>
/// Creates the confirm command used to confirm an acknowledged OPC UA condition from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public ConfirmCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the condition node ID of the alarm event to confirm.
/// </summary>
[CommandOption("node", 'n', Description = "Condition node ID of the alarm to confirm", IsRequired = true)]
public string NodeId { get; init; } = default!;
/// <summary>
/// Gets the event ID (hex-encoded) returned by the server in the alarm notification.
/// </summary>
[CommandOption("event-id", 'e', Description = "EventId from the alarm notification (hex-encoded byte array)", IsRequired = true)]
public string EventId { get; init; } = default!;
/// <summary>
/// Gets the operator comment to include with the confirmation.
/// </summary>
[CommandOption("comment", 'c', Description = "Operator comment for the confirmation")]
public string Comment { get; init; } = string.Empty;
/// <summary>
/// Connects to the server and confirms the specified acknowledged alarm condition.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
byte[] eventId;
try
{
eventId = Convert.FromHexString(EventId);
}
catch (FormatException ex)
{
throw new CommandException($"Invalid --event-id value: {ex.Message} (expected hex-encoded bytes, e.g. 0A1B2C)");
}
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var statusCode = await service.ConfirmAlarmAsync(NodeId, eventId, Comment, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Confirm successful: {NodeId}");
else
await console.Output.WriteLineAsync($"Confirm failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}
@@ -0,0 +1,77 @@
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("shelve", Description = "Shelve or unshelve an active alarm condition (OPC UA Part 9 ShelvedStateMachine)")]
public class ShelveCommand : CommandBase
{
/// <summary>
/// Creates the shelve command used to shelve or unshelve an OPC UA alarm condition from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public ShelveCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the condition node ID of the alarm to shelve or unshelve.
/// </summary>
[CommandOption("node", 'n', Description = "Condition node ID of the alarm to shelve/unshelve", IsRequired = true)]
public string NodeId { get; init; } = default!;
/// <summary>
/// Gets the shelve operation kind: OneShot, Timed, or Unshelve.
/// </summary>
[CommandOption("kind", 'k', Description = "Shelve operation: OneShot | Timed | Unshelve", IsRequired = true)]
public string Kind { get; init; } = default!;
/// <summary>
/// Gets the shelving duration in seconds for Timed shelving (ignored for OneShot and Unshelve).
/// </summary>
[CommandOption("duration", 'd', Description = "Shelving duration in seconds (required for --kind Timed)")]
public double DurationSeconds { get; init; }
/// <summary>
/// Connects to the server and shelves or unshelves the specified alarm condition.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
if (!Enum.TryParse<ShelveKind>(Kind, ignoreCase: true, out var shelveKind))
throw new CommandException(
$"Invalid --kind value '{Kind}'. Expected one of: OneShot, Timed, Unshelve.");
if (shelveKind == ShelveKind.Timed && DurationSeconds <= 0)
throw new CommandException(
"--duration must be greater than 0 when --kind is Timed.");
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var statusCode = await service.ShelveAlarmAsync(NodeId, shelveKind, DurationSeconds, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Shelve ({shelveKind}) successful: {NodeId}");
else
await console.Output.WriteLineAsync($"Shelve ({shelveKind}) failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}
@@ -103,6 +103,36 @@ public interface IOpcUaClientService : IDisposable
/// </returns>
Task<StatusCode> AcknowledgeAlarmAsync(string conditionNodeId, byte[] eventId, string comment, CancellationToken ct = default);
/// <summary>
/// Confirms an acknowledged condition (Part 9 two-stage acknowledgment) using the event identifier returned by an alarm notification.
/// </summary>
/// <param name="conditionNodeId">The condition node associated with the alarm event being confirmed.</param>
/// <param name="eventId">The event identifier returned by the OPC UA server for the alarm event.</param>
/// <param name="comment">The operator confirmation comment to write with the method call.</param>
/// <param name="ct">The cancellation token that aborts the confirmation request.</param>
/// <returns>
/// <see cref="StatusCodes.Good"/> on success, or the server's bad <see cref="StatusCode"/>
/// (from the underlying <see cref="ServiceResultException"/>) when the confirm call
/// returns a bad result. Other transport-level failures still surface as exceptions.
/// </returns>
Task<StatusCode> ConfirmAlarmAsync(string conditionNodeId, byte[] eventId, string comment, CancellationToken ct = default);
/// <summary>
/// Shelves or unshelves an active alarm condition (OPC UA Part 9 ShelvedStateMachine).
/// </summary>
/// <param name="conditionNodeId">The condition node associated with the alarm being shelved.</param>
/// <param name="kind">The shelve operation: <c>OneShot</c>, <c>Timed</c>, or <c>Unshelve</c>.</param>
/// <param name="shelvingTimeSeconds">
/// For <c>Timed</c> shelving: the shelving duration in seconds. Ignored for <c>OneShot</c> and <c>Unshelve</c>.
/// </param>
/// <param name="ct">The cancellation token that aborts the shelve request.</param>
/// <returns>
/// <see cref="StatusCodes.Good"/> on success, or the server's bad <see cref="StatusCode"/>
/// (from the underlying <see cref="ServiceResultException"/>) when the shelve call
/// returns a bad result. Other transport-level failures still surface as exceptions.
/// </returns>
Task<StatusCode> ShelveAlarmAsync(string conditionNodeId, ShelveKind kind, double shelvingTimeSeconds = 0, CancellationToken ct = default);
/// <summary>
/// Reads raw historical samples for a historized node.
/// </summary>
@@ -0,0 +1,25 @@
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
/// <summary>
/// Shelve operations supported by the OPC UA Part 9 ShelvedStateMachine.
/// </summary>
public enum ShelveKind
{
/// <summary>
/// OneShotShelve: suppresses the alarm for one occurrence. The alarm automatically
/// unshelves when it next returns to the inactive state.
/// </summary>
OneShot,
/// <summary>
/// TimedShelve: suppresses the alarm for a specified duration (seconds).
/// Requires a positive <c>shelvingTimeSeconds</c> argument.
/// </summary>
Timed,
/// <summary>
/// Unshelve: removes an active OneShotShelve or TimedShelve, returning the alarm
/// to its normal active-notification state.
/// </summary>
Unshelve
}
@@ -376,6 +376,88 @@ public sealed class OpcUaClientService : IOpcUaClientService
return StatusCodes.Good;
}
/// <inheritdoc />
public async Task<StatusCode> ConfirmAlarmAsync(string conditionNodeId, byte[] eventId, string comment,
CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
// Confirm lives on the same .Condition child node as Acknowledge
var conditionObjId = conditionNodeId.EndsWith(".Condition")
? NodeId.Parse(conditionNodeId)
: NodeId.Parse(conditionNodeId + ".Condition");
var confirmMethodId = MethodIds.AcknowledgeableConditionType_Confirm;
try
{
await _session!.CallMethodAsync(
conditionObjId,
confirmMethodId,
[eventId, new LocalizedText(comment)],
ct);
}
catch (ServiceResultException ex)
{
Logger.Warning(ex, "Failed to confirm alarm on {ConditionId} (status {Status})",
conditionNodeId, ex.StatusCode);
return ex.StatusCode;
}
Logger.Debug("Confirmed alarm on {ConditionId}", conditionNodeId);
return StatusCodes.Good;
}
/// <inheritdoc />
public async Task<StatusCode> ShelveAlarmAsync(string conditionNodeId, ShelveKind kind,
double shelvingTimeSeconds = 0, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
// The shelve methods live on the ShelvingState child of the condition node.
// conditionNodeId is the alarm/condition node; append .ShelvingState to get the state machine node.
var shelvingStateNodeId = NodeId.Parse(conditionNodeId + ".ShelvingState");
NodeId methodId;
object[] inputArgs;
switch (kind)
{
case ShelveKind.OneShot:
methodId = MethodIds.AlarmConditionType_ShelvingState_OneShotShelve;
inputArgs = [];
break;
case ShelveKind.Timed:
if (shelvingTimeSeconds <= 0)
throw new ArgumentOutOfRangeException(nameof(shelvingTimeSeconds),
"Timed shelving requires a positive shelvingTimeSeconds value.");
methodId = MethodIds.AlarmConditionType_ShelvingState_TimedShelve;
inputArgs = [shelvingTimeSeconds];
break;
case ShelveKind.Unshelve:
methodId = MethodIds.AlarmConditionType_ShelvingState_Unshelve;
inputArgs = [];
break;
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown ShelveKind value.");
}
try
{
await _session!.CallMethodAsync(shelvingStateNodeId, methodId, inputArgs, ct);
}
catch (ServiceResultException ex)
{
Logger.Warning(ex, "Failed to shelve alarm on {ConditionId} kind={Kind} (status {Status})",
conditionNodeId, kind, ex.StatusCode);
return ex.StatusCode;
}
Logger.Debug("Shelved alarm on {ConditionId} kind={Kind}", conditionNodeId, kind);
return StatusCodes.Good;
}
/// <inheritdoc />
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)