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.
This commit is contained in:
@@ -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: <status> values=<n> continuation=<yes\|no>[ 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
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
/// <summary>AtTime: the requested times (ISO 8601 UTC, comma-separated). One page, printed with its status.</summary>
|
||||
[CommandOption("at-time", Description = "HistoryRead-AtTime at these comma-separated ISO 8601 UTC times (instead of raw/aggregate)")]
|
||||
public string? AtTimes { get; init; }
|
||||
|
||||
/// <summary>Raw: page by hand at this NumValuesPerNode, printing each page's status, size and continuation.</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>With <c>--page-size</c>: after this page, wait for <c>--resume-when-file</c> before resuming in the SAME session.</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>The file whose appearance ends a <c>--pause-after-page</c> pause (written by the operator / a live gate).</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>How long a pause waits for <c>--resume-when-file</c> before giving up.</summary>
|
||||
[CommandOption("pause-timeout", Description = "With --pause-after-page: seconds to wait for --resume-when-file (default 300)")]
|
||||
public int PauseTimeoutSeconds { get; init; } = 300;
|
||||
|
||||
/// <summary>With <c>--page-size</c>: when a resumed page is refused, issue one fresh read of the same window and print it.</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>With <c>--page-size</c>: stop after this page WITHOUT releasing its continuation (the session close releases it).</summary>
|
||||
[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; }
|
||||
|
||||
/// <summary>With <c>--page-size</c>: after this page, send releaseContinuationPoints for its continuation and stop.</summary>
|
||||
[CommandOption("release-after-page", Description = "With --page-size: after this page, release its continuation point (releaseContinuationPoints) and stop")]
|
||||
public int ReleaseAfterPage { get; init; }
|
||||
|
||||
/// <summary>With <c>--abandon-after-page</c>: keep the session open this long before disconnecting.</summary>
|
||||
[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<DataValue> 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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>HistoryRead-AtTime: one page, its status, then the rows (the value type is printed, so integer nodes show).</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raw history page by page in ONE session: each page's status, size and continuation are printed, so a resume that
|
||||
/// the server refuses (<c>BadContinuationPointInvalid</c>) 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).
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>The event fields an event read selects when <c>--fields</c> is omitted.</summary>
|
||||
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<DataValue> values;
|
||||
|
||||
if (string.IsNullOrEmpty(Aggregate))
|
||||
|
||||
@@ -247,6 +247,17 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
|
||||
}
|
||||
|
||||
/// <summary>Issues one single-node HistoryRead (or a release of its continuation point).</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<Models.HistoryPage> 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<DataValue> 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<HistoryReadResult?> ReadHistoryPageAsync(
|
||||
HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release,
|
||||
TimestampsToReturn timestamps, CancellationToken ct)
|
||||
|
||||
@@ -162,6 +162,19 @@ internal interface ISessionAdapter : IDisposable
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
NodeId aggregateId, double intervalMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads (or, with <paramref name="release"/>, releases) ONE HistoryRead page for one node, returning the server's
|
||||
/// status, values and continuation point verbatim — no paging, no refusal exception.
|
||||
/// </summary>
|
||||
/// <param name="details">Raw, Processed or AtTime details.</param>
|
||||
/// <param name="nodeId">The node.</param>
|
||||
/// <param name="continuationPoint">The point to resume (or release); null = a fresh read.</param>
|
||||
/// <param name="release">Send <c>releaseContinuationPoints = true</c>.</param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
Task<Models.HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release,
|
||||
CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a subscription adapter for this session.
|
||||
/// </summary>
|
||||
|
||||
@@ -258,6 +258,20 @@ public interface IOpcUaClientService : IDisposable
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads (or, with <paramref name="release"/>, 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 <c>BadContinuationPointInvalid</c> resume, a refusal) instead of an exception.
|
||||
/// </summary>
|
||||
/// <param name="details">Raw, Processed or AtTime details.</param>
|
||||
/// <param name="nodeId">The node.</param>
|
||||
/// <param name="continuationPoint">The point to resume (or release); null = a fresh read.</param>
|
||||
/// <param name="release">Send <c>releaseContinuationPoints = true</c>.</param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
Task<HistoryPage> HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, bool release = false,
|
||||
CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
||||
/// <summary>
|
||||
/// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>--page-size</c> / <c>--pause-after-page</c> modes and the gRPC data live gate.
|
||||
/// </summary>
|
||||
/// <param name="Status">The per-node operation status.</param>
|
||||
/// <param name="Values">The returned values (empty on a refusal).</param>
|
||||
/// <param name="ContinuationPoint">The next continuation point, or null when the read is complete.</param>
|
||||
public sealed record HistoryPage(StatusCode Status, IReadOnlyList<DataValue> Values, byte[]? ContinuationPoint);
|
||||
@@ -711,6 +711,15 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<HistoryPage> 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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -108,6 +108,21 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
|
||||
/// </summary>
|
||||
public Dictionary<string, IReadOnlyList<BrowseResult>> BrowseResultsByParent { get; } = new();
|
||||
|
||||
/// <summary>Pages HistoryReadPageAsync answers, in order (a release call consumes nothing).</summary>
|
||||
public Queue<HistoryPage> HistoryPages { get; } = new();
|
||||
|
||||
/// <summary>Every HistoryReadPageAsync call: details, the continuation point passed, and the release flag.</summary>
|
||||
public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<HistoryPage> 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));
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets an exception thrown by HistoryReadRawAsync (simulates a refused read).</summary>
|
||||
public Exception? HistoryReadException { get; set; }
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The hand-paged (<c>--page-size</c> + pause / abandon / release / fresh-after-failure) and AtTime (<c>--at-time</c>)
|
||||
/// modes of <c>historyread</c> the gRPC data H3 live gate drives against projected nodes.
|
||||
/// </summary>
|
||||
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<ReadAtTimeDetails>();
|
||||
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<CliFx.Exceptions.CommandException>(async () => await command.ExecuteAsync(console));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user