feat(cli): read --attribute reads one node attribute (e.g. Historizing, AccessLevel) (#921)

This commit is contained in:
Joseph Doherty
2026-11-28 09:28:59 -05:00
parent 05f431f5d8
commit a2a1104f20
7 changed files with 106 additions and 3 deletions
@@ -29,11 +29,29 @@ public class ReadCommand : CommandBase
[CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")]
public double MaxAgeMilliseconds { get; init; }
/// <summary>Gets the attribute to read; <c>Value</c> (the default) is the current value.</summary>
[CommandOption("attribute", 'a', Description = "Attribute to read: Value (default), Historizing, AccessLevel, UserAccessLevel, DataType, ValueRank, ArrayDimensions, MinimumSamplingInterval, NodeClass, BrowseName, DisplayName, EventNotifier")]
public string Attribute { get; init; } = "Value";
/// <summary>The attributes <c>--attribute</c> accepts (case-insensitive), by name.</summary>
internal static readonly IReadOnlyDictionary<string, uint> AttributeIds = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase)
{
["Value"] = Attributes.Value, ["Historizing"] = Attributes.Historizing, ["AccessLevel"] = Attributes.AccessLevel,
["UserAccessLevel"] = Attributes.UserAccessLevel, ["DataType"] = Attributes.DataType, ["ValueRank"] = Attributes.ValueRank,
["ArrayDimensions"] = Attributes.ArrayDimensions, ["MinimumSamplingInterval"] = Attributes.MinimumSamplingInterval,
["NodeClass"] = Attributes.NodeClass, ["BrowseName"] = Attributes.BrowseName, ["DisplayName"] = Attributes.DisplayName,
["EventNotifier"] = Attributes.EventNotifier,
};
/// <inheritdoc />
public override async ValueTask ExecuteAsync(IConsole console)
{
if (!double.IsFinite(MaxAgeMilliseconds) || MaxAgeMilliseconds < 0 || MaxAgeMilliseconds > int.MaxValue)
throw new CommandException("Invalid --max-age value: expected a finite number from 0 to 2147483647 milliseconds.");
if (!AttributeIds.TryGetValue(Attribute ?? "", out var attributeId))
throw new CommandException($"Invalid --attribute value: expected one of {string.Join(", ", AttributeIds.Keys)}.");
if (attributeId != Attributes.Value && MaxAgeMilliseconds != 0)
throw new CommandException("--max-age applies to the Value attribute only.");
ConfigureLogging();
@@ -56,9 +74,11 @@ public class ReadCommand : CommandBase
DataValue value;
try
{
value = MaxAgeMilliseconds == 0
? await service.ReadValueAsync(nodeId, ct)
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
value = attributeId != Attributes.Value
? await service.ReadAttributeAsync(nodeId, attributeId, ct)
: MaxAgeMilliseconds == 0
? await service.ReadValueAsync(nodeId, ct)
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
}
catch (ServiceResultException ex) when (ex.StatusCode != StatusCodes.BadSessionIdInvalid
&& ex.StatusCode != StatusCodes.BadConnectionClosed
@@ -68,12 +88,14 @@ public class ReadCommand : CommandBase
// BadUserAccessDenied, ...) as an exception. A read command's job is to REPORT that status,
// not crash with a stack trace — session-level failures still propagate.
await console.Output.WriteLineAsync($"Node: {NodeId}");
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
await console.Output.WriteLineAsync($"Value: ");
await console.Output.WriteLineAsync($"Status: {(StatusCode)ex.StatusCode} ({ex.StatusCode.SymbolicId})");
return;
}
await console.Output.WriteLineAsync($"Node: {NodeId}");
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
await console.Output.WriteLineAsync($"Value: {ValueFormatter.Format(ValueConverter.ToClrObject(value.WrappedValue))}");
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}");
@@ -76,6 +76,14 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
}
/// <inheritdoc />
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct)
{
ArrayOf<ReadValueId> nodes = [new ReadValueId { NodeId = nodeId, AttributeId = attributeId }];
var response = await _session.ReadAsync(null, 0, TimestampsToReturn.Both, nodes, ct);
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
}
internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf<DataValue> results, NodeId nodeId)
{
var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
@@ -64,6 +64,17 @@ internal interface ISessionAdapter : IDisposable
/// <summary>Reads a value using the supplied maximum cache age.</summary>
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default);
/// <summary>
/// Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>). A Bad result throws
/// <see cref="ServiceResultException"/> with its status, like <see cref="ReadValueAsync(NodeId, CancellationToken)"/>.
/// </summary>
/// <param name="nodeId">The node to read.</param>
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
/// <param name="ct">The cancellation token that aborts the read.</param>
/// <returns>The attribute's data value.</returns>
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
throw new NotSupportedException("This session adapter does not read node attributes.");
/// <summary>
/// Writes a typed value to a node on the connected OPC UA server.
/// </summary>
@@ -56,6 +56,14 @@ public interface IOpcUaClientService : IDisposable
return ReadValueAsync(nodeId, ct);
}
/// <summary>Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>).</summary>
/// <param name="nodeId">The node to read.</param>
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
/// <param name="ct">The cancellation token that aborts the read.</param>
/// <returns>The attribute's data value; a Bad result throws <see cref="ServiceResultException"/>.</returns>
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
throw new NotSupportedException("This client does not read node attributes.");
/// <summary>
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
/// </summary>
@@ -223,6 +223,14 @@ public sealed class OpcUaClientService : IOpcUaClientService
return await _session!.ReadValueAsync(nodeId, maximumAge, ct);
}
/// <inheritdoc />
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.ReadAttributeAsync(nodeId, attributeId, ct);
}
/// <inheritdoc />
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
@@ -199,6 +199,17 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
public TimeSpan? LastMaximumAge { get; private set; }
/// <summary>The (node, attribute id) pairs passed to ReadAttributeAsync.</summary>
public List<(NodeId NodeId, uint AttributeId)> ReadAttributes { get; } = [];
/// <inheritdoc />
public Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default)
{
ReadAttributes.Add((nodeId, attributeId));
if (ReadException != null) throw ReadException;
return Task.FromResult(ReadValueResult);
}
public Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
{
LastMaximumAge = maximumAge;
@@ -42,6 +42,41 @@ public class ReadCommandTests
service.ReadNodeIds.ShouldBeEmpty();
}
/// <summary>lmxopcua#921: <c>--attribute Historizing</c> reads that attribute (not the value) and labels the output.</summary>
[Fact]
public async Task Execute_ReadsTheRequestedAttribute()
{
var service = new FakeOpcUaClientService { ReadValueResult = new DataValue(new Variant(false), StatusCodes.Good) };
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = "historizing"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
service.ReadAttributes.ShouldBe([(new NodeId("Test", 2), Attributes.Historizing)]);
service.ReadNodeIds.ShouldBeEmpty();
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Attribute: historizing");
output.ShouldContain("Value: False");
}
/// <summary>An unknown attribute, or <c>--max-age</c> with a non-Value attribute, is refused before connecting.</summary>
[Theory]
[InlineData("Bogus", 0)]
[InlineData("Historizing", 5000)]
public async Task Execute_RejectsAnUnknownAttributeOrMaxAgeOffTheValue(string attribute, double maxAge)
{
var service = new FakeOpcUaClientService();
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = attribute, MaxAgeMilliseconds = maxAge
};
using var console = TestConsoleHelper.CreateConsole();
await Should.ThrowAsync<CliFx.Exceptions.CommandException>(async () => await command.ExecuteAsync(console));
service.ReadAttributes.ShouldBeEmpty();
service.ReadNodeIds.ShouldBeEmpty();
}
/// <summary>Verifies that execute prints the read value.</summary>
[Fact]
public async Task Execute_PrintsReadValue()