From a2a1104f2029f6ff3444d64cbf51fc8e557ebfb1 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 28 Nov 2026 09:28:59 -0500 Subject: [PATCH] feat(cli): read --attribute reads one node attribute (e.g. Historizing, AccessLevel) (#921) --- .../Commands/ReadCommand.cs | 28 +++++++++++++-- .../Adapters/DefaultSessionAdapter.cs | 8 +++++ .../Adapters/ISessionAdapter.cs | 11 ++++++ .../IOpcUaClientService.cs | 8 +++++ .../OpcUaClientService.cs | 8 +++++ .../Fakes/FakeOpcUaClientService.cs | 11 ++++++ .../ReadCommandTests.cs | 35 +++++++++++++++++++ 7 files changed, 106 insertions(+), 3 deletions(-) diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs index aac885270..de8b94e31 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs @@ -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; } + /// Gets the attribute to read; Value (the default) is the current value. + [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"; + + /// The attributes --attribute accepts (case-insensitive), by name. + internal static readonly IReadOnlyDictionary AttributeIds = new Dictionary(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, + }; + /// 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")}"); diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs index f086ab4bb..aa9e82589 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs @@ -76,6 +76,14 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter return ValidateReadResult(response.ResponseHeader, response.Results, nodeId); } + /// + public async Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct) + { + ArrayOf 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 results, NodeId nodeId) { var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError; diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs index e59ddb9fb..70e6c0b4b 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs @@ -64,6 +64,17 @@ internal interface ISessionAdapter : IDisposable /// Reads a value using the supplied maximum cache age. Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default); + /// + /// Reads one attribute of a node (for example ). A Bad result throws + /// with its status, like . + /// + /// The node to read. + /// The attribute id (). + /// The cancellation token that aborts the read. + /// The attribute's data value. + Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) => + throw new NotSupportedException("This session adapter does not read node attributes."); + /// /// Writes a typed value to a node on the connected OPC UA server. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index c19f3210b..02b7aa453 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -56,6 +56,14 @@ public interface IOpcUaClientService : IDisposable return ReadValueAsync(nodeId, ct); } + /// Reads one attribute of a node (for example ). + /// The node to read. + /// The attribute id (). + /// The cancellation token that aborts the read. + /// The attribute's data value; a Bad result throws . + Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) => + throw new NotSupportedException("This client does not read node attributes."); + /// /// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs index 402fdcc1a..026d48030 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -223,6 +223,14 @@ public sealed class OpcUaClientService : IOpcUaClientService return await _session!.ReadValueAsync(nodeId, maximumAge, ct); } + /// + public async Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) + { + ThrowIfDisposed(); + ThrowIfNotConnected(); + return await _session!.ReadAttributeAsync(nodeId, attributeId, ct); + } + /// public async Task WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs index 151a58579..b63f64b6e 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs @@ -199,6 +199,17 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService public TimeSpan? LastMaximumAge { get; private set; } + /// The (node, attribute id) pairs passed to ReadAttributeAsync. + public List<(NodeId NodeId, uint AttributeId)> ReadAttributes { get; } = []; + + /// + public Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) + { + ReadAttributes.Add((nodeId, attributeId)); + if (ReadException != null) throw ReadException; + return Task.FromResult(ReadValueResult); + } + public Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default) { LastMaximumAge = maximumAge; diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs index 321c17a5e..86ff4a267 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs @@ -42,6 +42,41 @@ public class ReadCommandTests service.ReadNodeIds.ShouldBeEmpty(); } + /// lmxopcua#921: --attribute Historizing reads that attribute (not the value) and labels the output. + [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"); + } + + /// An unknown attribute, or --max-age with a non-Value attribute, is refused before connecting. + [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(async () => await command.ExecuteAsync(console)); + service.ReadAttributes.ShouldBeEmpty(); + service.ReadNodeIds.ShouldBeEmpty(); + } + /// Verifies that execute prints the read value. [Fact] public async Task Execute_PrintsReadValue()