test: validate grpc data connections with local docker and opcua cli
This commit is contained in:
@@ -25,9 +25,16 @@ public class ReadCommand : CommandBase
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
/// <summary>Gets the maximum acceptable cache age in milliseconds.</summary>
|
||||
[CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")]
|
||||
public double MaxAgeMilliseconds { get; init; }
|
||||
|
||||
/// <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.");
|
||||
|
||||
ConfigureLogging();
|
||||
|
||||
NodeId nodeId;
|
||||
@@ -49,7 +56,9 @@ public class ReadCommand : CommandBase
|
||||
DataValue value;
|
||||
try
|
||||
{
|
||||
value = await service.ReadValueAsync(nodeId, ct);
|
||||
value = 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
|
||||
@@ -67,8 +76,8 @@ public class ReadCommand : CommandBase
|
||||
await console.Output.WriteLineAsync($"Node: {NodeId}");
|
||||
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:O}");
|
||||
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
|
||||
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}");
|
||||
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp.ToString("O")}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -131,7 +131,7 @@ public class SubscribeCommand : CommandBase
|
||||
if (!Quiet)
|
||||
{
|
||||
var line =
|
||||
$"[{e.Value.SourceTimestamp:O}] {displayNameByNodeId.GetValueOrDefault(key, key)} = {ValueFormatter.Format(ValueConverter.ToClrObject(e.Value.WrappedValue))} ({e.Value.StatusCode})";
|
||||
$"[{e.Value.SourceTimestamp.ToString("O")}] {displayNameByNodeId.GetValueOrDefault(key, key)} = {ValueFormatter.Format(ValueConverter.ToClrObject(e.Value.WrappedValue))} ({e.Value.StatusCode})";
|
||||
outputChannel.Writer.TryWrite(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Exceptions;
|
||||
using CliFx.Infrastructure;
|
||||
@@ -31,6 +32,12 @@ public class WriteCommand : CommandBase
|
||||
[CommandOption("value", 'v', Description = "Value to write", IsRequired = true)]
|
||||
public string Value { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets an optional built-in scalar type, allowing a write without reading the current value.
|
||||
/// </summary>
|
||||
[CommandOption("type", Description = "Scalar type: Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float, Double, String; omit to infer from a read")]
|
||||
public string? Type { get; init; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -46,15 +53,20 @@ public class WriteCommand : CommandBase
|
||||
throw new CommandException($"Invalid --node value: {ex.Message}");
|
||||
}
|
||||
|
||||
object typedValue = Type is null ? Value : ConvertExplicitValue(Value, Type);
|
||||
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
var ct = console.RegisterCancellationHandler();
|
||||
(service, _) = await CreateServiceAndConnectAsync(ct);
|
||||
|
||||
// Read current value to determine type for conversion
|
||||
var currentValue = await service.ReadValueAsync(nodeId, ct);
|
||||
var typedValue = ValueConverter.ConvertValue(Value, ValueConverter.ToClrObject(currentValue.WrappedValue));
|
||||
if (Type is null)
|
||||
{
|
||||
// Preserve runtime type inference for callers that omit --type.
|
||||
var currentValue = await service.ReadValueAsync(nodeId, ct);
|
||||
typedValue = ValueConverter.ConvertValue(Value, ValueConverter.ToClrObject(currentValue.WrappedValue));
|
||||
}
|
||||
|
||||
var statusCode = await service.WriteValueAsync(nodeId, typedValue, ct);
|
||||
|
||||
@@ -72,4 +84,35 @@ public class WriteCommand : CommandBase
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Converts an explicitly typed scalar before opening a client connection.</summary>
|
||||
/// <param name="value">The raw operator-entered value.</param>
|
||||
/// <param name="type">The supported OPC UA built-in scalar type name.</param>
|
||||
/// <returns>The exact CLR scalar required by the selected type.</returns>
|
||||
private static object ConvertExplicitValue(string value, string type)
|
||||
{
|
||||
try
|
||||
{
|
||||
return type.ToUpperInvariant() switch
|
||||
{
|
||||
"BOOLEAN" => ValueConverter.ConvertValue(value, false),
|
||||
"BYTE" => byte.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"SBYTE" => sbyte.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"INT16" => short.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"UINT16" => ushort.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"INT32" => int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"UINT32" => uint.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"INT64" => long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"UINT64" => ulong.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture),
|
||||
"FLOAT" => float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture),
|
||||
"DOUBLE" => double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture),
|
||||
"STRING" => value,
|
||||
_ => throw new CommandException($"Unsupported --type value '{type}'. Use Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float, Double, or String.")
|
||||
};
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or OverflowException)
|
||||
{
|
||||
throw new CommandException($"Invalid --value for --type {type}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,29 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
|
||||
return await _session.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct)
|
||||
{
|
||||
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
|
||||
throw new ArgumentOutOfRangeException(nameof(maximumAge));
|
||||
ArrayOf<ReadValueId> nodes = [new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value }];
|
||||
var response = await _session.ReadAsync(null, maximumAge.TotalMilliseconds, 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;
|
||||
if (StatusCode.IsBad(serviceStatus))
|
||||
throw new ServiceResultException(serviceStatus);
|
||||
if (results.Count != 1)
|
||||
throw new ServiceResultException(StatusCodes.BadUnexpectedError, $"Read response contained {results.Count} results for node {nodeId}.");
|
||||
var value = results[0];
|
||||
if (StatusCode.IsBad(value.StatusCode))
|
||||
throw new ServiceResultException(value.StatusCode);
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -53,8 +53,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
|
||||
onDataChange(nodeId.ToString(), notification.Value);
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
await AddItemAsync(item, ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
@@ -95,8 +94,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
|
||||
if (Volatile.Read(ref _finishing) == 0 && e.NotificationValue is EventFieldList eventFields) onEvent(eventFields);
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
await AddItemAsync(item, ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
@@ -105,6 +103,24 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
|
||||
return handle;
|
||||
}
|
||||
|
||||
private async Task AddItemAsync(MonitoredItem item, CancellationToken ct)
|
||||
{
|
||||
_subscription.AddItem(item);
|
||||
try
|
||||
{
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
if (item.Status.Error is { } error && StatusCode.IsBad(error.StatusCode))
|
||||
throw new ServiceResultException(error.StatusCode);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Keep a rejected or interrupted add out of the tracked subscription; the
|
||||
// SDK will carry any required deletion on its next ApplyChanges call.
|
||||
_subscription.RemoveItem(item);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ConditionRefreshAsync(CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -61,6 +61,9 @@ internal interface ISessionAdapter : IDisposable
|
||||
/// <returns>The current data value read from the server.</returns>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Reads a value using the supplied maximum cache age.</summary>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Writes a typed value to a node on the connected OPC UA server.
|
||||
/// </summary>
|
||||
|
||||
@@ -42,6 +42,20 @@ public interface IOpcUaClientService : IDisposable
|
||||
/// <returns>The current data value of the node.</returns>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Reads a value allowing a cached value up to the specified age.</summary>
|
||||
/// <param name="nodeId">The node whose value should be retrieved.</param>
|
||||
/// <param name="maximumAge">Maximum cache age, from zero to Int32.MaxValue milliseconds.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the read request.</param>
|
||||
/// <returns>The data value returned by the server.</returns>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
|
||||
{
|
||||
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
|
||||
throw new ArgumentOutOfRangeException(nameof(maximumAge));
|
||||
if (maximumAge != TimeSpan.Zero)
|
||||
throw new NotSupportedException("This client does not support reads with a maximum age.");
|
||||
return ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
|
||||
/// </summary>
|
||||
|
||||
@@ -155,7 +155,8 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
// A new epoch first: a failover still connecting abandons itself instead of resurrecting the connection.
|
||||
lock (_subscriptionLock) _connectionEpoch++;
|
||||
|
||||
var endpointUrl = _session?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
|
||||
// The SDK transport may already be disposed when teardown begins.
|
||||
var endpointUrl = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
|
||||
|
||||
// Snapshot the subscription adapter references under the lock so a concurrent
|
||||
// RunFailoverAsync that nulls _dataSubscription / _alarmSubscription
|
||||
@@ -210,6 +211,18 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
return await _session!.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
|
||||
{
|
||||
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
|
||||
throw new ArgumentOutOfRangeException(nameof(maximumAge));
|
||||
if (maximumAge == TimeSpan.Zero)
|
||||
return await ReadValueAsync(nodeId, ct);
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
return await _session!.ReadValueAsync(nodeId, maximumAge, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
|
||||
{
|
||||
@@ -391,10 +404,17 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
var monitorNode = sourceNodeId ?? ObjectIds.Server;
|
||||
var subscription = await session.CreateSubscriptionAsync(intervalMs, ct);
|
||||
lock (_subscriptionLock) _alarmSubscription = subscription;
|
||||
|
||||
var filter = CreateAlarmEventFilter();
|
||||
await subscription.AddEventMonitoredItemAsync(
|
||||
monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct);
|
||||
try
|
||||
{
|
||||
var filter = CreateAlarmEventFilter();
|
||||
await subscription.AddEventMonitoredItemAsync(
|
||||
monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await CleanupFailedAlarmSubscriptionAsync(subscription);
|
||||
throw;
|
||||
}
|
||||
|
||||
lock (_subscriptionLock)
|
||||
{
|
||||
@@ -871,7 +891,7 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
return;
|
||||
|
||||
var oldSession = _session;
|
||||
var oldEndpoint = oldSession?.EndpointUrl ?? string.Empty;
|
||||
var oldEndpoint = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
|
||||
if (!TransitionStateIfCurrent(epoch, ConnectionState.Reconnecting, oldEndpoint)) return;
|
||||
Logger.Warning("Session lost on {EndpointUrl}. Attempting failover...", oldEndpoint);
|
||||
|
||||
@@ -1012,10 +1032,11 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
if (alarmSubscription.HasValue)
|
||||
{
|
||||
var (sourceNodeId, intervalMs) = alarmSubscription.Value;
|
||||
ISubscriptionAdapter? replayedAlarms = null;
|
||||
try
|
||||
{
|
||||
var monitorNode = sourceNodeId ?? ObjectIds.Server;
|
||||
var replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
|
||||
replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
|
||||
lock (_subscriptionLock) _alarmSubscription = replayedAlarms;
|
||||
var filter = CreateAlarmEventFilter();
|
||||
await replayedAlarms.AddEventMonitoredItemAsync(
|
||||
@@ -1028,11 +1049,32 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (replayedAlarms is not null) await CleanupFailedAlarmSubscriptionAsync(replayedAlarms);
|
||||
Logger.Warning(ex, "Failed to replay alarm subscription");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CleanupFailedAlarmSubscriptionAsync(ISubscriptionAdapter subscription)
|
||||
{
|
||||
lock (_subscriptionLock)
|
||||
{
|
||||
if (ReferenceEquals(_alarmSubscription, subscription))
|
||||
{
|
||||
_alarmSubscription = null;
|
||||
_activeAlarmSubscription = null;
|
||||
}
|
||||
}
|
||||
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
try { await subscription.DeleteAsync(cleanup.Token); }
|
||||
catch (Exception ex) { Logger.Warning(ex, "Failed to delete rejected alarm subscription"); }
|
||||
finally
|
||||
{
|
||||
try { subscription.Dispose(); }
|
||||
catch (Exception ex) { Logger.Warning(ex, "Failed to dispose rejected alarm subscription"); }
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsCurrentNotification(ISessionAdapter session, ISubscriptionAdapter subscription, bool alarm)
|
||||
{
|
||||
lock (_subscriptionLock)
|
||||
|
||||
Reference in New Issue
Block a user