434 lines
18 KiB
C#
434 lines
18 KiB
C#
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Serilog;
|
|
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
|
|
|
/// <summary>
|
|
/// Production session adapter wrapping a real OPC UA Session.
|
|
/// </summary>
|
|
internal sealed class DefaultSessionAdapter : ISessionAdapter
|
|
{
|
|
private static readonly ILogger Logger = Log.ForContext<DefaultSessionAdapter>();
|
|
private readonly Session _session;
|
|
private readonly IDisposable? _certificateManager;
|
|
private int _disposed;
|
|
|
|
/// <summary>
|
|
/// Wraps a live OPC UA session so the shared client can issue runtime operations through a testable adapter surface.
|
|
/// </summary>
|
|
/// <param name="session">The connected OPC UA session used for browsing, reads, writes, history, and subscriptions.</param>
|
|
/// <param name="certificateManager">The per-connection certificate manager owned until session disposal.</param>
|
|
public DefaultSessionAdapter(Session session, IDisposable? certificateManager = null)
|
|
{
|
|
_session = session;
|
|
_certificateManager = certificateManager;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public bool Connected => _session.Connected;
|
|
|
|
/// <inheritdoc />
|
|
public string SessionId => _session.SessionId.IsNull ? string.Empty : _session.SessionId.ToString();
|
|
|
|
/// <inheritdoc />
|
|
public string SessionName => _session.SessionName ?? string.Empty;
|
|
|
|
/// <inheritdoc />
|
|
public string EndpointUrl => _session.Endpoint?.EndpointUrl ?? string.Empty;
|
|
|
|
/// <inheritdoc />
|
|
public string ServerName => _session.Endpoint?.Server?.ApplicationName.Text ?? string.Empty;
|
|
|
|
/// <inheritdoc />
|
|
public string SecurityMode => _session.Endpoint?.SecurityMode.ToString() ?? string.Empty;
|
|
|
|
/// <inheritdoc />
|
|
public string SecurityPolicyUri => _session.Endpoint?.SecurityPolicyUri ?? string.Empty;
|
|
|
|
/// <inheritdoc />
|
|
public NamespaceTable NamespaceUris => _session.NamespaceUris;
|
|
|
|
/// <inheritdoc />
|
|
public void RegisterKeepAliveHandler(Action<bool> callback)
|
|
{
|
|
_session.KeepAlive += (_, e) =>
|
|
{
|
|
var isGood = e.Status == null || ServiceResult.IsGood(e.Status);
|
|
callback(isGood);
|
|
};
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
|
|
{
|
|
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);
|
|
}
|
|
|
|
/// <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;
|
|
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)
|
|
{
|
|
var writeValue = new WriteValue
|
|
{
|
|
NodeId = nodeId,
|
|
AttributeId = Attributes.Value,
|
|
Value = value
|
|
};
|
|
|
|
ArrayOf<WriteValue> writeCollection = [writeValue];
|
|
var response = await _session.WriteAsync(null, writeCollection, ct);
|
|
// A malformed or service-level-faulted response can come back with an empty
|
|
// Results collection alongside a service fault. Surface the service result
|
|
// (or BadUnexpectedError) rather than letting Results[0] throw
|
|
// IndexOutOfRangeException upstream.
|
|
if (response.Results.Count == 0)
|
|
{
|
|
var serviceResult = response.ResponseHeader?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
|
|
throw new ServiceResultException(serviceResult,
|
|
$"Write response contained no results for node {nodeId}.");
|
|
}
|
|
|
|
return response.Results[0];
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<(byte[]? ContinuationPoint, ArrayOf<ReferenceDescription> References)> BrowseAsync(
|
|
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
|
|
{
|
|
var (_, continuationPoint, references) = await _session.BrowseAsync(
|
|
null,
|
|
null,
|
|
nodeId,
|
|
0u,
|
|
BrowseDirection.Forward,
|
|
ReferenceTypeIds.HierarchicalReferences,
|
|
true,
|
|
nodeClassMask, ct);
|
|
|
|
return (continuationPoint.IsNull ? null : continuationPoint.ToArray(), references);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<(byte[]? ContinuationPoint, ArrayOf<ReferenceDescription> References)> BrowseNextAsync(
|
|
byte[] continuationPoint, CancellationToken ct)
|
|
{
|
|
// Pass the caller's token so a cancelled browse does not block on the continuation
|
|
// round-trip.
|
|
var (_, nextCp, nextRefs) = await _session.BrowseNextAsync(null, false, ByteString.From(continuationPoint), ct);
|
|
return (nextCp.IsNull ? null : nextCp.ToArray(), nextRefs);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task ReleaseBrowseContinuationPointAsync(byte[] continuationPoint, CancellationToken ct)
|
|
{
|
|
await _session.BrowseNextAsync(null, true, ByteString.From(continuationPoint), ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<Models.HistoryUpdateOutcome> HistoryUpdateAsync(HistoryUpdateDetails details, CancellationToken ct)
|
|
{
|
|
var response = await _session.HistoryUpdateAsync(
|
|
null,
|
|
[new ExtensionObject(details)],
|
|
ct).ConfigureAwait(false);
|
|
|
|
var statuses = new List<StatusCode>();
|
|
var ops = new List<IReadOnlyList<StatusCode>>();
|
|
if (!response.Results.IsEmpty)
|
|
foreach (var r in response.Results)
|
|
{
|
|
statuses.Add(r.StatusCode);
|
|
ops.Add(r.OperationResults.ToArray() ?? []);
|
|
}
|
|
|
|
return new Models.HistoryUpdateOutcome(response.ResponseHeader.ServiceResult, statuses, ops);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
|
|
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
|
|
{
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = startTime,
|
|
EndTime = endTime,
|
|
NumValuesPerNode = (uint)maxValues,
|
|
IsReadModified = false,
|
|
ReturnBounds = false
|
|
};
|
|
|
|
// Continuation pages are READ, never released, until the server finishes or the cap is reached; a read stopped
|
|
// by the cap releases the server's cursor (HistoryReadPaging). This path used to pass
|
|
// `releaseContinuationPoints: continuationPoint != null`, which RELEASED the second page instead of reading it,
|
|
// silently truncating every raw read to its first server page.
|
|
return await HistoryReadPaging.ReadAllAsync<DataValue>(
|
|
(cp, release, token) => ReadHistoryPageAsync(details, nodeId, cp, release, TimestampsToReturn.Source, token),
|
|
result => result.HistoryData.TryGetValue(out HistoryData? historyData)
|
|
? historyData.DataValues.ToArray() ?? []
|
|
: [],
|
|
maxValues, nodeId, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<Models.HistoryModifiedEntry>> HistoryReadModifiedAsync(
|
|
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
|
|
{
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = startTime,
|
|
EndTime = endTime,
|
|
NumValuesPerNode = (uint)maxValues,
|
|
IsReadModified = true,
|
|
ReturnBounds = false
|
|
};
|
|
|
|
return await HistoryReadPaging.ReadAllAsync(
|
|
(cp, release, token) => ReadHistoryPageAsync(details, nodeId, cp, release, TimestampsToReturn.Both, token),
|
|
ToModifiedEntries, maxValues, nodeId, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<Models.HistoryEventEntry>> HistoryReadEventsAsync(
|
|
NodeId nodeId, DateTime startTime, DateTime endTime, int maxEvents, EventFilter filter, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(filter);
|
|
var details = new ReadEventDetails
|
|
{
|
|
StartTime = startTime,
|
|
EndTime = endTime,
|
|
NumValuesPerNode = (uint)maxEvents,
|
|
Filter = filter
|
|
};
|
|
|
|
return await HistoryReadPaging.ReadAllAsync(
|
|
(cp, release, token) => ReadHistoryPageAsync(details, nodeId, cp, release, TimestampsToReturn.Both, token),
|
|
result => result.HistoryData.TryGetValue(out HistoryEvent? historyEvent)
|
|
? (historyEvent.Events.ToArray() ?? []).Select(e => new Models.HistoryEventEntry(e.EventFields.ToArray() ?? []))
|
|
: [],
|
|
maxEvents, nodeId, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
private static IEnumerable<Models.HistoryModifiedEntry> ToModifiedEntries(HistoryReadResult result)
|
|
{
|
|
if (!result.HistoryData.TryGetValue(out HistoryModifiedData? modified)) yield break;
|
|
for (var i = 0; i < modified.DataValues.Count; i++)
|
|
{
|
|
var info = i < modified.ModificationInfos.Count ? modified.ModificationInfos[i] : null;
|
|
yield return new Models.HistoryModifiedEntry(
|
|
modified.DataValues[i],
|
|
info?.ModificationTime.ToDateTime() ?? DateTime.MinValue,
|
|
info?.UpdateType ?? default,
|
|
info?.UserName);
|
|
}
|
|
}
|
|
|
|
/// <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)
|
|
{
|
|
ArrayOf<HistoryReadValueId> nodesToRead =
|
|
[
|
|
new HistoryReadValueId { NodeId = nodeId, ContinuationPoint = ByteString.From(continuationPoint) }
|
|
];
|
|
|
|
// The async overload honours the token and does not block the caller's thread (the UI dispatcher for
|
|
// client.ui consumers).
|
|
var response = await _session.HistoryReadAsync(
|
|
null, new ExtensionObject(details), timestamps, release, nodesToRead, ct).ConfigureAwait(false);
|
|
|
|
return response.Results is { Count: > 0 } results ? results[0] : null;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
|
|
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs,
|
|
CancellationToken ct)
|
|
{
|
|
var details = new ReadProcessedDetails
|
|
{
|
|
StartTime = startTime,
|
|
EndTime = endTime,
|
|
ProcessingInterval = intervalMs,
|
|
AggregateType = [aggregateId],
|
|
// The SDK's default AggregateConfiguration is all-false/0 — a NON-default configuration, which this server
|
|
// refuses BadAggregateConfigurationRejected (#677). Ask for the server's own defaults, as Part 13 intends.
|
|
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
|
|
};
|
|
|
|
ArrayOf<HistoryReadValueId> nodesToRead = [new HistoryReadValueId { NodeId = nodeId }];
|
|
|
|
// Use the async overload so the method honors the cancellation token and
|
|
// does not block on a synchronous service round-trip.
|
|
var response = await _session.HistoryReadAsync(
|
|
null,
|
|
new ExtensionObject(details),
|
|
TimestampsToReturn.Source,
|
|
false,
|
|
nodesToRead,
|
|
ct).ConfigureAwait(false);
|
|
|
|
var results = response.Results;
|
|
var allValues = new List<DataValue>();
|
|
|
|
if (results.Count > 0)
|
|
{
|
|
var result = results[0];
|
|
try
|
|
{
|
|
HistoryReadStatus.ThrowIfRefused(result.StatusCode, nodeId);
|
|
if (result.HistoryData.TryGetValue(out HistoryData? historyData))
|
|
allValues.AddRange(historyData.DataValues);
|
|
}
|
|
finally
|
|
{
|
|
// Keep the existing one-shot processed read; it owns no outstanding server cursor on return.
|
|
if (!result.ContinuationPoint.IsEmpty)
|
|
await HistoryReadPaging.ReleaseAsync(
|
|
(cp, release, token) => ReadHistoryPageAsync(details, nodeId, cp, release, TimestampsToReturn.Source, token),
|
|
result.ContinuationPoint.ToArray(), nodeId).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
return allValues;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
|
|
{
|
|
var subscription = new Subscription(_session.DefaultSubscription)
|
|
{
|
|
PublishingInterval = publishingIntervalMs,
|
|
DisplayName = "ClientShared_Subscription"
|
|
};
|
|
|
|
_session.AddSubscription(subscription);
|
|
try
|
|
{
|
|
await subscription.CreateAsync(ct);
|
|
}
|
|
catch
|
|
{
|
|
// A subscription the server never created must not linger in Session.Subscriptions either.
|
|
try { await _session.RemoveSubscriptionAsync(subscription, CancellationToken.None); }
|
|
catch (Exception ex) { Logger.Warning(ex, "Error removing a subscription that failed to create"); }
|
|
throw;
|
|
}
|
|
|
|
// Deleting the adapter also removes the subscription from the SDK session, so a re-targeted alarm/data
|
|
// subscription does not accumulate dead Subscription objects in Session.Subscriptions.
|
|
return new DefaultSubscriptionAdapter(subscription,
|
|
async (s, token) => await _session.RemoveSubscriptionAsync(s, token).ConfigureAwait(false));
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task CloseAsync(CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
// Use the async overload so the caller does not block on the close
|
|
// service round-trip and the cancellation token is honored.
|
|
if (_session.Connected) await _session.CloseAsync(ct).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Warning(ex, "Error closing session");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Releases the wrapped OPC UA session when the shared client shuts down or swaps endpoints during failover.
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
|
try
|
|
{
|
|
if (_session.Connected) DisposeBridge.Run(ct => _session.CloseAsync(ct));
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
try { _session.Dispose(); }
|
|
finally { _certificateManager?.Dispose(); }
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments,
|
|
CancellationToken ct = default)
|
|
{
|
|
var result = await _session.CallAsync(
|
|
null,
|
|
new CallMethodRequest[]
|
|
{
|
|
new()
|
|
{
|
|
ObjectId = objectId,
|
|
MethodId = methodId,
|
|
InputArguments = inputArguments.Select(ValueConverter.ToVariant).ToArrayOf()
|
|
}
|
|
},
|
|
ct);
|
|
|
|
// An empty Results collection paired with a service fault must surface as
|
|
// a ServiceResultException, not an IndexOutOfRangeException from Results[0].
|
|
if (result.Results.Count == 0)
|
|
{
|
|
var serviceResult = result.ResponseHeader?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
|
|
throw new ServiceResultException(serviceResult,
|
|
$"Call response contained no results for method {methodId} on {objectId}.");
|
|
}
|
|
|
|
var callResult = result.Results[0];
|
|
if (StatusCode.IsBad(callResult.StatusCode))
|
|
throw new ServiceResultException(callResult.StatusCode);
|
|
|
|
return callResult.OutputArguments.IsNull ? null
|
|
: (callResult.OutputArguments.ToArray() ?? []).Select(v => ValueConverter.ToClrObject(v)!).ToList();
|
|
}
|
|
}
|