From 3b630ab1a91b99d9277e666d2295ce9f0207944d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:36:47 -0500 Subject: [PATCH] feat(cli): historyread --page-size/--pause-after-page/--abandon/--release and --at-time Hand-paged raw reads in one session print each page's status and continuation (a refused resume is printed, not thrown), can hold the session across a failover (resume when a file appears, then one fresh read), abandon a point to the session close or release it explicitly. --at-time reads AtTime and prints value types. Backed by IOpcUaClientService.HistoryReadPageAsync (default-throwing interface member so existing fakes compile). Used by the gRPC data H3 live gate on projected nodes. --- docs/Client.CLI.md | 22 +++ .../Commands/HistoryReadCommand.cs | 168 ++++++++++++++++++ .../Adapters/DefaultSessionAdapter.cs | 11 ++ .../Adapters/ISessionAdapter.cs | 13 ++ .../IOpcUaClientService.cs | 14 ++ .../Models/HistoryPage.cs | 13 ++ .../OpcUaClientService.cs | 9 + .../Fakes/FakeOpcUaClientService.cs | 15 ++ .../HistoryReadPagedCommandTests.cs | 126 +++++++++++++ 9 files changed, 391 insertions(+) create mode 100644 src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs create mode 100644 tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 5f71be86b..fa1e131f8 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -259,6 +259,28 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie | `--events` | Read event history (Part 11 HistoryReadEvents) from an event notifier instead of raw samples | | `--fields` | With `--events`: comma-separated event fields to select (default `EventId,EventType,Time,SourceName,Severity,Message,ConditionName,SourceNode`) | | `--of-type` | With `--events`: keep only events of this type or a subtype (an `OfType` where-clause), e.g. `i=2955` | +| `--at-time` | HistoryRead-AtTime at these comma-separated ISO 8601 UTC times; prints the status, the rows and each value's CLR type | +| `--page-size` | Raw only: page by hand at this `NumValuesPerNode`, printing every page as `Page k: values= continuation=[ resumed]` (a refused page is printed, never thrown) | +| `--pause-after-page` / `--resume-when-file` / `--pause-timeout` | With `--page-size`: after page k hold the session (and its continuation point) until the file exists, then resume | +| `--fresh-after-failure` | With `--page-size`: after a refused resumed page, issue one fresh read of the same window (`Fresh: …`) | +| `--abandon-after-page` | With `--page-size`: stop after page k WITHOUT releasing its continuation point — the disconnect (session close) releases it | +| `--release-after-page` | With `--page-size`: send `releaseContinuationPoints` for page k's point and stop | +| `--hold-seconds` | With `--abandon-after-page` / `--release-after-page`: keep the session open this long before disconnecting | + +The hand-paged modes exist for continuation-point lifecycle checks — most usefully on **projected** nodes of a gRPC data +connection (`DataConnections.md` §"OPC UA HistoryRead on projected nodes"), where a resumed page is bound to the origin endpoint +that issued it: pause after page 1, fail the origin over, create the resume file, and the resumed page prints +`BadContinuationPointInvalid` while `--fresh-after-failure` shows the fresh read moving to the new endpoint. + +```bash +# Page 1 of a projected node, hold the session, resume once /tmp/go exists; then one fresh read if the resume is refused +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \ + --start 2026-11-20T10:00:00Z --end 2026-11-20T11:00:00Z --page-size 5 \ + --pause-after-page 1 --resume-when-file /tmp/go --fresh-after-failure +# AtTime on an integer node +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \ + --at-time 2026-11-20T10:00:00Z,2026-11-20T10:00:05Z +``` ### historyupdate diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs index 7d087c8eb..804faa364 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs @@ -83,6 +83,152 @@ public class HistoryReadCommand : CommandBase [CommandOption("of-type", Description = "With --events: keep only events of this type or a subtype (an OfType where-clause), e.g. i=2955 (LimitAlarmType)")] public string? OfType { get; init; } + /// AtTime: the requested times (ISO 8601 UTC, comma-separated). One page, printed with its status. + [CommandOption("at-time", Description = "HistoryRead-AtTime at these comma-separated ISO 8601 UTC times (instead of raw/aggregate)")] + public string? AtTimes { get; init; } + + /// Raw: page by hand at this NumValuesPerNode, printing each page's status, size and continuation. + [CommandOption("page-size", Description = "Raw: read page by page with this NumValuesPerNode, printing each page's status and continuation (0 = off)")] + public int PageSize { get; init; } + + /// With --page-size: after this page, wait for --resume-when-file before resuming in the SAME session. + [CommandOption("pause-after-page", Description = "With --page-size: pause after this page (holding the session) until --resume-when-file exists, then resume")] + public int PauseAfterPage { get; init; } + + /// The file whose appearance ends a --pause-after-page pause (written by the operator / a live gate). + [CommandOption("resume-when-file", Description = "With --pause-after-page: resume once this file exists (it is not read or deleted)")] + public string? ResumeWhenFile { get; init; } + + /// How long a pause waits for --resume-when-file before giving up. + [CommandOption("pause-timeout", Description = "With --pause-after-page: seconds to wait for --resume-when-file (default 300)")] + public int PauseTimeoutSeconds { get; init; } = 300; + + /// With --page-size: when a resumed page is refused, issue one fresh read of the same window and print it. + [CommandOption("fresh-after-failure", Description = "With --page-size: after a refused resumed page, issue one fresh read of the same window")] + public bool FreshAfterFailure { get; init; } + + /// With --page-size: stop after this page WITHOUT releasing its continuation (the session close releases it). + [CommandOption("abandon-after-page", Description = "With --page-size: stop after this page without releasing its continuation point (disconnect releases it)")] + public int AbandonAfterPage { get; init; } + + /// With --page-size: after this page, send releaseContinuationPoints for its continuation and stop. + [CommandOption("release-after-page", Description = "With --page-size: after this page, release its continuation point (releaseContinuationPoints) and stop")] + public int ReleaseAfterPage { get; init; } + + /// With --abandon-after-page: keep the session open this long before disconnecting. + [CommandOption("hold-seconds", Description = "With --abandon-after-page / --release-after-page: keep the session open this many seconds before disconnecting")] + public int HoldSeconds { get; init; } + + + private static string Format(StatusCode status) + { + var text = status.ToString(); + return text.Contains("[0x", StringComparison.Ordinal) ? text : $"{text} [0x{status.Code:X8}]"; + } + + private static async Task WriteRowsAsync(IConsole console, IReadOnlyList values) + { + foreach (var dv in values) + { + var status = StatusCode.IsGood(dv.StatusCode) ? "Good" : StatusCode.IsBad(dv.StatusCode) ? "Bad" : "Uncertain"; + await console.Output.WriteLineAsync( + $"{dv.SourceTimestamp.ToString("O"),-35} {ValueFormatter.Format(ValueConverter.ToClrObject(dv.WrappedValue)),-15} {status}"); + } + } + + /// HistoryRead-AtTime: one page, its status, then the rows (the value type is printed, so integer nodes show). + private async Task ReadAtTimeAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, CancellationToken ct) + { + DateTime[] times; + try + { + times = AtTimes!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(t => DateTime.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) + .ToArray(); + } + catch (FormatException ex) + { + throw new CommandException($"Invalid --at-time value: {ex.Message}"); + } + if (times.Length == 0) throw new CommandException("--at-time needs at least one time."); + var details = new ReadAtTimeDetails { ReqTimes = times.Select(t => (DateTimeUtc)t).ToArray(), UseSimpleBounds = true }; + var page = await service.HistoryReadPageAsync(details, nodeId, null, false, ct); + await console.Output.WriteLineAsync($"AtTime history for {NodeId} ({times.Length} times)"); + await console.Output.WriteLineAsync($"Status: {Format(page.Status)}"); + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{"Timestamp",-35} {"Value",-15} {"Status"}"); + await WriteRowsAsync(console, page.Values); + foreach (var dv in page.Values) + await console.Output.WriteLineAsync($"Type: {ValueConverter.ToClrObject(dv.WrappedValue)?.GetType().Name ?? "null"}"); + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{page.Values.Count} values returned."); + } + + /// + /// Raw history page by page in ONE session: each page's status, size and continuation are printed, so a resume that + /// the server refuses (BadContinuationPointInvalid) is visible instead of an exception, and a pause holds the + /// session (and its continuation point) open while something else happens (a failover, a rebuild). + /// + private async Task ReadPagesAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, DateTime start, DateTime end, CancellationToken ct) + { + var details = new ReadRawModifiedDetails + { + StartTime = start, EndTime = end, NumValuesPerNode = (uint)PageSize, IsReadModified = false, ReturnBounds = false, + }; + await console.Output.WriteLineAsync($"Paged history for {NodeId} (page size {PageSize})"); + byte[]? cp = null; + var total = 0; + for (var number = 1; ; number++) + { + var resumed = cp is not null; + var page = await service.HistoryReadPageAsync(details, nodeId, cp, false, ct); + await console.Output.WriteLineAsync( + $"Page {number}: {Format(page.Status)} values={page.Values.Count} continuation={(page.ContinuationPoint is null ? "no" : "yes")}{(resumed ? " resumed" : "")}"); + await WriteRowsAsync(console, page.Values); + total += page.Values.Count; + if (StatusCode.IsBad(page.Status)) + { + if (resumed && FreshAfterFailure) + { + var fresh = await service.HistoryReadPageAsync(details, nodeId, null, false, ct); + await console.Output.WriteLineAsync( + $"Fresh: {Format(fresh.Status)} values={fresh.Values.Count} continuation={(fresh.ContinuationPoint is null ? "no" : "yes")}"); + await WriteRowsAsync(console, fresh.Values); + if (fresh.ContinuationPoint is { } freshCp) await service.HistoryReadPageAsync(details, nodeId, freshCp, true, ct); + } + break; + } + cp = page.ContinuationPoint; + if (cp is null || total >= MaxValues) break; + if (number == AbandonAfterPage) + { + await console.Output.WriteLineAsync($"Abandoned after page {number} (continuation not released; holding {HoldSeconds}s)"); + if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); + return; + } + if (number == ReleaseAfterPage) + { + var released = await service.HistoryReadPageAsync(details, nodeId, cp, true, ct); + await console.Output.WriteLineAsync($"Released after page {number}: {Format(released.Status)}"); + if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); + return; + } + if (number == PauseAfterPage) + { + await console.Output.WriteLineAsync($"Paused after page {number}; waiting for {ResumeWhenFile}"); + var deadline = DateTime.UtcNow.AddSeconds(PauseTimeoutSeconds); + while (!File.Exists(ResumeWhenFile)) + { + if (DateTime.UtcNow >= deadline) throw new CommandException($"--resume-when-file did not appear within {PauseTimeoutSeconds}s."); + await Task.Delay(200, ct); + } + await console.Output.WriteLineAsync("Resuming"); + } + } + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{total} values returned."); + } + /// The event fields an event read selects when --fields is omitted. internal static readonly string[] DefaultEventFields = ["EventId", "EventType", "Time", "SourceName", "Severity", "Message", "ConditionName", "SourceNode"]; @@ -101,6 +247,16 @@ public class HistoryReadCommand : CommandBase throw new CommandException("--events cannot be combined with --modified or --aggregate."); if (!Events && (Fields is not null || OfType is not null)) throw new CommandException("--fields and --of-type apply only to --events."); + if (PageSize < 0 || PauseAfterPage < 0 || AbandonAfterPage < 0 || ReleaseAfterPage < 0 || HoldSeconds < 0 || PauseTimeoutSeconds <= 0) + throw new CommandException("--page-size, --pause-after-page, --abandon-after-page, --release-after-page and --hold-seconds must be >= 0; --pause-timeout > 0."); + if (PageSize == 0 && (PauseAfterPage > 0 || AbandonAfterPage > 0 || ReleaseAfterPage > 0 || FreshAfterFailure)) + throw new CommandException("--pause-after-page, --abandon-after-page, --release-after-page and --fresh-after-failure need --page-size."); + if (PauseAfterPage > 0 && string.IsNullOrWhiteSpace(ResumeWhenFile)) + throw new CommandException("--pause-after-page needs --resume-when-file."); + if ((PageSize > 0 || AtTimes is not null) && (Events || Modified || !string.IsNullOrEmpty(Aggregate))) + throw new CommandException("--page-size and --at-time read raw / AtTime history only."); + if (PageSize > 0 && AtTimes is not null) + throw new CommandException("--page-size and --at-time cannot be combined."); NodeId nodeId; try @@ -220,6 +376,18 @@ public class HistoryReadCommand : CommandBase return; } + if (AtTimes is not null) + { + await ReadAtTimeAsync(service, console, nodeId, ct); + return; + } + + if (PageSize > 0) + { + await ReadPagesAsync(service, console, nodeId, start, end, ct); + return; + } + IReadOnlyList values; if (string.IsNullOrEmpty(Aggregate)) 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 8c3710d39..bd929f58f 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 @@ -247,6 +247,17 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter } /// Issues one single-node HistoryRead (or a release of its continuation point). + /// + public async Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, + bool release, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(details); + var result = await ReadHistoryPageAsync(details, nodeId, continuationPoint, release, TimestampsToReturn.Both, ct).ConfigureAwait(false); + if (result is null) return new Models.HistoryPage(StatusCodes.BadUnexpectedError, [], null); + IReadOnlyList values = result.HistoryData.TryGetValue(out HistoryData? data) ? data.DataValues.ToArray() ?? [] : []; + return new Models.HistoryPage(result.StatusCode, values, result.ContinuationPoint.IsEmpty ? null : result.ContinuationPoint.ToArray()); + } + private async Task ReadHistoryPageAsync( HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release, TimestampsToReturn timestamps, CancellationToken ct) 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 cb1c6c87b..9b216a19d 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 @@ -162,6 +162,19 @@ internal interface ISessionAdapter : IDisposable Task> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct = default); + /// + /// Reads (or, with , releases) ONE HistoryRead page for one node, returning the server's + /// status, values and continuation point verbatim — no paging, no refusal exception. + /// + /// Raw, Processed or AtTime details. + /// The node. + /// The point to resume (or release); null = a fresh read. + /// Send releaseContinuationPoints = true. + /// Cancellation. + /// The page. + Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release, + CancellationToken ct = default) => throw new NotSupportedException(); + /// /// Creates a subscription adapter for this session. /// 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 b7933f880..4edde2ff3 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -258,6 +258,20 @@ public interface IOpcUaClientService : IDisposable Task> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default); + /// + /// Reads (or, with , releases) ONE HistoryRead page for one node and returns the server's + /// status, values and continuation point verbatim — for callers that page by hand and must see each page's status + /// (a BadContinuationPointInvalid resume, a refusal) instead of an exception. + /// + /// Raw, Processed or AtTime details. + /// The node. + /// The point to resume (or release); null = a fresh read. + /// Send releaseContinuationPoints = true. + /// Cancellation. + /// The page. + Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, bool release = false, + CancellationToken ct = default) => throw new NotSupportedException(); + /// /// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs new file mode 100644 index 000000000..34f8d27bc --- /dev/null +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs @@ -0,0 +1,13 @@ +using Opc.Ua; + +namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models; + +/// +/// One HistoryRead page exactly as the server answered it: the per-node status (never thrown), its values and the +/// continuation point the server returned (null when the read is complete). Used by callers that page by hand — +/// the CLI's --page-size / --pause-after-page modes and the gRPC data live gate. +/// +/// The per-node operation status. +/// The returned values (empty on a refusal). +/// The next continuation point, or null when the read is complete. +public sealed record HistoryPage(StatusCode Status, IReadOnlyList Values, byte[]? ContinuationPoint); 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 d14de8060..89b68bcbf 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -711,6 +711,15 @@ public sealed class OpcUaClientService : IOpcUaClientService return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct); } + /// + public async Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, + bool release = false, CancellationToken ct = default) + { + ThrowIfDisposed(); + ThrowIfNotConnected(); + return await _session!.HistoryReadPageAsync(details, nodeId, continuationPoint, release, ct); + } + /// public async Task GetRedundancyInfoAsync(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 1a9538134..151a58579 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 @@ -108,6 +108,21 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService /// public Dictionary> BrowseResultsByParent { get; } = new(); + /// Pages HistoryReadPageAsync answers, in order (a release call consumes nothing). + public Queue HistoryPages { get; } = new(); + + /// Every HistoryReadPageAsync call: details, the continuation point passed, and the release flag. + public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = []; + + /// + public Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, + bool release = false, CancellationToken ct = default) + { + HistoryPageCalls.Add((details, continuationPoint, release)); + if (release) return Task.FromResult(new HistoryPage(StatusCodes.Good, [], null)); + return Task.FromResult(HistoryPages.Count > 0 ? HistoryPages.Dequeue() : new HistoryPage(StatusCodes.GoodNoData, [], null)); + } + /// Gets or sets an exception thrown by HistoryReadRawAsync (simulates a refused read). public Exception? HistoryReadException { get; set; } diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs new file mode 100644 index 000000000..b73402c6a --- /dev/null +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs @@ -0,0 +1,126 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands; +using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes; +using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; + +namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests; + +/// +/// The hand-paged (--page-size + pause / abandon / release / fresh-after-failure) and AtTime (--at-time) +/// modes of historyread the gRPC data H3 live gate drives against projected nodes. +/// +public class HistoryReadPagedCommandTests +{ + private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); + + private static DataValue Value(int v, int second) => new(new Variant(v), StatusCodes.Good, T0.AddSeconds(second), T0.AddSeconds(second)); + + [Fact] + public async Task Pages_print_each_status_and_resume_with_the_returned_continuation_point() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0), Value(2, 1)], [1, 2, 3])); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(3, 2)], null)); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", StartTime = "2026-11-20T09:00:00Z", EndTime = "2026-11-20T11:00:00Z", PageSize = 2, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Page 1: Good [0x00000000] values=2 continuation=yes"); + output.ShouldContain("Page 2: Good [0x00000000] values=1 continuation=no resumed"); + output.ShouldContain("3 values returned."); + fake.HistoryPageCalls.Count.ShouldBe(2); + fake.HistoryPageCalls[0].ContinuationPoint.ShouldBeNull(); + fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 1, 2, 3 }); + ((ReadRawModifiedDetails)fake.HistoryPageCalls[0].Details).NumValuesPerNode.ShouldBe(2u); + } + + [Fact] + public async Task A_refused_resume_is_printed_and_followed_by_one_fresh_read() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [9])); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.BadContinuationPointInvalid, [], null)); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [7])); + var marker = Path.Combine(Path.GetTempPath(), "cli-resume-" + Guid.NewGuid().ToString("N")); + File.WriteAllText(marker, ""); + try + { + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1, ResumeWhenFile = marker, + FreshAfterFailure = true, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Paused after page 1"); + output.ShouldContain("Page 2: BadContinuationPointInvalid [0x804A0000] values=0 continuation=no resumed"); + output.ShouldContain("Fresh: Good [0x00000000] values=1 continuation=yes"); + fake.HistoryPageCalls.Last().Release.ShouldBeTrue("the fresh read's own continuation is released"); + } + finally { File.Delete(marker); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Abandon_leaves_the_point_to_the_session_close_and_release_sends_releaseContinuationPoints(bool release) + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [5])); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, + AbandonAfterPage = release ? 0 : 1, ReleaseAfterPage = release ? 1 : 0, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + if (release) + { + output.ShouldContain("Released after page 1: Good"); + fake.HistoryPageCalls.Count.ShouldBe(2); + fake.HistoryPageCalls[1].Release.ShouldBeTrue(); + fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 5 }); + } + else + { + output.ShouldContain("Abandoned after page 1"); + fake.HistoryPageCalls.Count.ShouldBe(1); + } + } + + [Fact] + public async Task AtTime_reads_the_requested_times_and_prints_the_status_and_value_types() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [new DataValue(new Variant((ushort)7), StatusCodes.Good, T0, T0)], null)); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", AtTimes = "2026-11-20T10:00:00Z, 2026-11-20T10:00:01Z", + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Status: Good [0x00000000]"); + output.ShouldContain("Type: UInt16"); + var details = fake.HistoryPageCalls.Single().Details.ShouldBeOfType(); + details.ReqTimes.Count.ShouldBe(2); + } + + [Fact] + public async Task Pause_without_a_resume_file_is_refused() + { + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService())) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1, + }; + using var console = TestConsoleHelper.CreateConsole(); + await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + } +}