Compare commits
7 Commits
b21d550836
...
phase-3-pr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a65215684c | ||
| 82f2dfcfa3 | |||
|
|
0433d3a35e | ||
| 141673fc80 | |||
|
|
db56a95819 | ||
| 89bd726fa8 | |||
|
|
238748bc98 |
@@ -27,8 +27,27 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
|
|||||||
/// </para>
|
/// </para>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string driverInstanceId)
|
public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string driverInstanceId)
|
||||||
: IDriver, IDisposable, IAsyncDisposable
|
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IDisposable, IAsyncDisposable
|
||||||
{
|
{
|
||||||
|
// ---- ISubscribable + IHostConnectivityProbe state ----
|
||||||
|
|
||||||
|
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, RemoteSubscription> _subscriptions = new();
|
||||||
|
private long _nextSubscriptionId;
|
||||||
|
private readonly object _probeLock = new();
|
||||||
|
private HostState _hostState = HostState.Unknown;
|
||||||
|
private DateTime _hostStateChangedUtc = DateTime.UtcNow;
|
||||||
|
private KeepAliveEventHandler? _keepAliveHandler;
|
||||||
|
|
||||||
|
public event EventHandler<DataChangeEventArgs>? OnDataChange;
|
||||||
|
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
|
||||||
|
|
||||||
|
// OPC UA StatusCode constants the driver surfaces for local-side faults. Upstream-server
|
||||||
|
// StatusCodes are passed through verbatim per driver-specs.md §8 "cascading quality" —
|
||||||
|
// downstream clients need to distinguish 'remote source down' from 'local driver failure'.
|
||||||
|
private const uint StatusBadNodeIdInvalid = 0x80330000u;
|
||||||
|
private const uint StatusBadInternalError = 0x80020000u;
|
||||||
|
private const uint StatusBadCommunicationError = 0x80050000u;
|
||||||
|
|
||||||
private readonly OpcUaClientDriverOptions _options = options;
|
private readonly OpcUaClientDriverOptions _options = options;
|
||||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||||
|
|
||||||
@@ -55,15 +74,9 @@ public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string d
|
|||||||
// requested security policy/mode so the driver doesn't have to hand-validate.
|
// requested security policy/mode so the driver doesn't have to hand-validate.
|
||||||
// UseSecurity=false when SecurityMode=None shortcuts around cert validation
|
// UseSecurity=false when SecurityMode=None shortcuts around cert validation
|
||||||
// entirely and is the typical dev-bench configuration.
|
// entirely and is the typical dev-bench configuration.
|
||||||
var useSecurity = _options.SecurityMode != OpcUaSecurityMode.None;
|
var selected = await SelectMatchingEndpointAsync(
|
||||||
// The non-obsolete SelectEndpointAsync overloads all require an ITelemetryContext
|
appConfig, _options.EndpointUrl, _options.SecurityPolicy, _options.SecurityMode,
|
||||||
// parameter. Passing null is valid — the SDK falls through to its built-in default
|
cancellationToken).ConfigureAwait(false);
|
||||||
// trace sink. Plumbing a telemetry context through every driver surface is out of
|
|
||||||
// scope; the driver emits its own logs via the health surface anyway.
|
|
||||||
var selected = await CoreClientUtils.SelectEndpointAsync(
|
|
||||||
appConfig, _options.EndpointUrl, useSecurity,
|
|
||||||
telemetry: null!,
|
|
||||||
ct: cancellationToken).ConfigureAwait(false);
|
|
||||||
var endpointConfig = EndpointConfiguration.Create(appConfig);
|
var endpointConfig = EndpointConfiguration.Create(appConfig);
|
||||||
endpointConfig.OperationTimeout = (int)_options.Timeout.TotalMilliseconds;
|
endpointConfig.OperationTimeout = (int)_options.Timeout.TotalMilliseconds;
|
||||||
var endpoint = new ConfiguredEndpoint(null, selected, endpointConfig);
|
var endpoint = new ConfiguredEndpoint(null, selected, endpointConfig);
|
||||||
@@ -103,8 +116,21 @@ public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string d
|
|||||||
|
|
||||||
session.KeepAliveInterval = (int)_options.KeepAliveInterval.TotalMilliseconds;
|
session.KeepAliveInterval = (int)_options.KeepAliveInterval.TotalMilliseconds;
|
||||||
|
|
||||||
|
// Wire the session's keep-alive channel into HostState. OPC UA keep-alives are
|
||||||
|
// authoritative for session liveness: the SDK pings on KeepAliveInterval and sets
|
||||||
|
// KeepAliveStopped when N intervals elapse without a response. That's strictly
|
||||||
|
// better than a driver-side polling probe — no extra round-trip, no duplicate
|
||||||
|
// semantic.
|
||||||
|
_keepAliveHandler = (_, e) =>
|
||||||
|
{
|
||||||
|
var healthy = !ServiceResult.IsBad(e.Status);
|
||||||
|
TransitionTo(healthy ? HostState.Running : HostState.Stopped);
|
||||||
|
};
|
||||||
|
session.KeepAlive += _keepAliveHandler;
|
||||||
|
|
||||||
Session = session;
|
Session = session;
|
||||||
_health = new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null);
|
_health = new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null);
|
||||||
|
TransitionTo(HostState.Running);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -199,6 +225,67 @@ public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string d
|
|||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Select the remote endpoint matching both the requested <paramref name="policy"/>
|
||||||
|
/// and <paramref name="mode"/>. The SDK's <c>CoreClientUtils.SelectEndpointAsync</c>
|
||||||
|
/// only honours a boolean "use security" flag; we need policy-aware matching so an
|
||||||
|
/// operator asking for <c>Basic256Sha256</c> against a server that also offers
|
||||||
|
/// <c>Basic128Rsa15</c> doesn't silently end up on the weaker cipher.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<EndpointDescription> SelectMatchingEndpointAsync(
|
||||||
|
ApplicationConfiguration appConfig,
|
||||||
|
string endpointUrl,
|
||||||
|
OpcUaSecurityPolicy policy,
|
||||||
|
OpcUaSecurityMode mode,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
// GetEndpoints returns everything the server advertises; policy + mode filter is
|
||||||
|
// applied client-side so the selection is explicit and fails loudly if the operator
|
||||||
|
// asks for a combination the server doesn't publish. DiscoveryClient.CreateAsync
|
||||||
|
// is the non-obsolete path in SDK 1.5.378; the synchronous Create(..) variants are
|
||||||
|
// all deprecated.
|
||||||
|
using var client = await DiscoveryClient.CreateAsync(
|
||||||
|
appConfig, new Uri(endpointUrl), Opc.Ua.DiagnosticsMasks.None, ct).ConfigureAwait(false);
|
||||||
|
var all = await client.GetEndpointsAsync(null, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var wantedPolicyUri = MapSecurityPolicy(policy);
|
||||||
|
var wantedMode = mode switch
|
||||||
|
{
|
||||||
|
OpcUaSecurityMode.None => MessageSecurityMode.None,
|
||||||
|
OpcUaSecurityMode.Sign => MessageSecurityMode.Sign,
|
||||||
|
OpcUaSecurityMode.SignAndEncrypt => MessageSecurityMode.SignAndEncrypt,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(mode)),
|
||||||
|
};
|
||||||
|
|
||||||
|
var match = all.FirstOrDefault(e =>
|
||||||
|
e.SecurityPolicyUri == wantedPolicyUri && e.SecurityMode == wantedMode);
|
||||||
|
|
||||||
|
if (match is null)
|
||||||
|
{
|
||||||
|
var advertised = string.Join(", ", all
|
||||||
|
.Select(e => $"{ShortPolicyName(e.SecurityPolicyUri)}/{e.SecurityMode}"));
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"No endpoint at '{endpointUrl}' matches SecurityPolicy={policy} + SecurityMode={mode}. " +
|
||||||
|
$"Server advertises: {advertised}");
|
||||||
|
}
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Convert a driver <see cref="OpcUaSecurityPolicy"/> to the OPC UA policy URI.</summary>
|
||||||
|
internal static string MapSecurityPolicy(OpcUaSecurityPolicy policy) => policy switch
|
||||||
|
{
|
||||||
|
OpcUaSecurityPolicy.None => SecurityPolicies.None,
|
||||||
|
OpcUaSecurityPolicy.Basic128Rsa15 => SecurityPolicies.Basic128Rsa15,
|
||||||
|
OpcUaSecurityPolicy.Basic256 => SecurityPolicies.Basic256,
|
||||||
|
OpcUaSecurityPolicy.Basic256Sha256 => SecurityPolicies.Basic256Sha256,
|
||||||
|
OpcUaSecurityPolicy.Aes128_Sha256_RsaOaep => SecurityPolicies.Aes128_Sha256_RsaOaep,
|
||||||
|
OpcUaSecurityPolicy.Aes256_Sha256_RsaPss => SecurityPolicies.Aes256_Sha256_RsaPss,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(policy), policy, null),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string ShortPolicyName(string policyUri) =>
|
||||||
|
policyUri?.Substring(policyUri.LastIndexOf('#') + 1) ?? "(null)";
|
||||||
|
|
||||||
public async Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
|
public async Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
await ShutdownAsync(cancellationToken).ConfigureAwait(false);
|
await ShutdownAsync(cancellationToken).ConfigureAwait(false);
|
||||||
@@ -207,10 +294,29 @@ public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string d
|
|||||||
|
|
||||||
public async Task ShutdownAsync(CancellationToken cancellationToken)
|
public async Task ShutdownAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
// Tear down remote subscriptions first — otherwise Session.Close will try and may fail
|
||||||
|
// with BadSubscriptionIdInvalid noise in the upstream log. _subscriptions is cleared
|
||||||
|
// whether or not the wire-side delete succeeds since the local handles are useless
|
||||||
|
// after close anyway.
|
||||||
|
foreach (var rs in _subscriptions.Values)
|
||||||
|
{
|
||||||
|
try { await rs.Subscription.DeleteAsync(silent: true, cancellationToken).ConfigureAwait(false); }
|
||||||
|
catch { /* best-effort */ }
|
||||||
|
}
|
||||||
|
_subscriptions.Clear();
|
||||||
|
|
||||||
|
if (_keepAliveHandler is not null && Session is not null)
|
||||||
|
{
|
||||||
|
try { Session.KeepAlive -= _keepAliveHandler; } catch { }
|
||||||
|
}
|
||||||
|
_keepAliveHandler = null;
|
||||||
|
|
||||||
try { if (Session is Session s) await s.CloseAsync(cancellationToken).ConfigureAwait(false); }
|
try { if (Session is Session s) await s.CloseAsync(cancellationToken).ConfigureAwait(false); }
|
||||||
catch { /* best-effort */ }
|
catch { /* best-effort */ }
|
||||||
try { Session?.Dispose(); } catch { }
|
try { Session?.Dispose(); } catch { }
|
||||||
Session = null;
|
Session = null;
|
||||||
|
|
||||||
|
TransitionTo(HostState.Unknown);
|
||||||
_health = new DriverHealth(DriverState.Unknown, _health.LastSuccessfulRead, null);
|
_health = new DriverHealth(DriverState.Unknown, _health.LastSuccessfulRead, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,6 +324,390 @@ public sealed class OpcUaClientDriver(OpcUaClientDriverOptions options, string d
|
|||||||
public long GetMemoryFootprint() => 0;
|
public long GetMemoryFootprint() => 0;
|
||||||
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||||
|
|
||||||
|
// ---- IReadable ----
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<DataValueSnapshot>> ReadAsync(
|
||||||
|
IReadOnlyList<string> fullReferences, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var session = RequireSession();
|
||||||
|
var results = new DataValueSnapshot[fullReferences.Count];
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
|
||||||
|
// Parse NodeIds up-front. Tags whose reference doesn't parse get BadNodeIdInvalid
|
||||||
|
// and are omitted from the wire request — saves a round-trip against the upstream
|
||||||
|
// server for a fault the driver can detect locally.
|
||||||
|
var toSend = new ReadValueIdCollection();
|
||||||
|
var indexMap = new List<int>(fullReferences.Count); // maps wire-index -> results-index
|
||||||
|
for (var i = 0; i < fullReferences.Count; i++)
|
||||||
|
{
|
||||||
|
if (!TryParseNodeId(session, fullReferences[i], out var nodeId))
|
||||||
|
{
|
||||||
|
results[i] = new DataValueSnapshot(null, StatusBadNodeIdInvalid, null, now);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
toSend.Add(new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value });
|
||||||
|
indexMap.Add(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toSend.Count == 0) return results;
|
||||||
|
|
||||||
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var resp = await session.ReadAsync(
|
||||||
|
requestHeader: null,
|
||||||
|
maxAge: 0,
|
||||||
|
timestampsToReturn: TimestampsToReturn.Both,
|
||||||
|
nodesToRead: toSend,
|
||||||
|
ct: cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var values = resp.Results;
|
||||||
|
for (var w = 0; w < values.Count; w++)
|
||||||
|
{
|
||||||
|
var r = indexMap[w];
|
||||||
|
var dv = values[w];
|
||||||
|
// Preserve the upstream StatusCode verbatim — including Bad codes per
|
||||||
|
// §8's cascading-quality rule. Also preserve SourceTimestamp so downstream
|
||||||
|
// clients can detect stale upstream data.
|
||||||
|
results[r] = new DataValueSnapshot(
|
||||||
|
Value: dv.Value,
|
||||||
|
StatusCode: dv.StatusCode.Code,
|
||||||
|
SourceTimestampUtc: dv.SourceTimestamp == DateTime.MinValue ? null : dv.SourceTimestamp,
|
||||||
|
ServerTimestampUtc: dv.ServerTimestamp == DateTime.MinValue ? now : dv.ServerTimestamp);
|
||||||
|
}
|
||||||
|
_health = new DriverHealth(DriverState.Healthy, now, null);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Transport / timeout / session-dropped — fan out the same fault across every
|
||||||
|
// tag in this batch. Per-tag StatusCode stays BadCommunicationError (not
|
||||||
|
// BadInternalError) so operators distinguish "upstream unreachable" from
|
||||||
|
// "driver bug".
|
||||||
|
for (var w = 0; w < indexMap.Count; w++)
|
||||||
|
{
|
||||||
|
var r = indexMap[w];
|
||||||
|
results[r] = new DataValueSnapshot(null, StatusBadCommunicationError, null, now);
|
||||||
|
}
|
||||||
|
_health = new DriverHealth(DriverState.Degraded, _health.LastSuccessfulRead, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { _gate.Release(); }
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- IWritable ----
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||||
|
IReadOnlyList<Core.Abstractions.WriteRequest> writes, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var session = RequireSession();
|
||||||
|
var results = new WriteResult[writes.Count];
|
||||||
|
|
||||||
|
var toSend = new WriteValueCollection();
|
||||||
|
var indexMap = new List<int>(writes.Count);
|
||||||
|
for (var i = 0; i < writes.Count; i++)
|
||||||
|
{
|
||||||
|
if (!TryParseNodeId(session, writes[i].FullReference, out var nodeId))
|
||||||
|
{
|
||||||
|
results[i] = new WriteResult(StatusBadNodeIdInvalid);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
toSend.Add(new WriteValue
|
||||||
|
{
|
||||||
|
NodeId = nodeId,
|
||||||
|
AttributeId = Attributes.Value,
|
||||||
|
Value = new DataValue(new Variant(writes[i].Value)),
|
||||||
|
});
|
||||||
|
indexMap.Add(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toSend.Count == 0) return results;
|
||||||
|
|
||||||
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var resp = await session.WriteAsync(
|
||||||
|
requestHeader: null,
|
||||||
|
nodesToWrite: toSend,
|
||||||
|
ct: cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var codes = resp.Results;
|
||||||
|
for (var w = 0; w < codes.Count; w++)
|
||||||
|
{
|
||||||
|
var r = indexMap[w];
|
||||||
|
// Pass upstream WriteResult StatusCode through verbatim. Success codes
|
||||||
|
// include Good (0) and any warning-level Good* variants; anything with
|
||||||
|
// the severity bits set is a Bad.
|
||||||
|
results[r] = new WriteResult(codes[w].Code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
for (var w = 0; w < indexMap.Count; w++)
|
||||||
|
results[indexMap[w]] = new WriteResult(StatusBadCommunicationError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { _gate.Release(); }
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parse a tag's full-reference string as a NodeId. Accepts the standard OPC UA
|
||||||
|
/// serialized forms (<c>ns=2;s=…</c>, <c>i=2253</c>, <c>ns=4;g=…</c>, <c>ns=3;b=…</c>).
|
||||||
|
/// Empty + malformed strings return false; the driver surfaces that as
|
||||||
|
/// <see cref="StatusBadNodeIdInvalid"/> without a wire round-trip.
|
||||||
|
/// </summary>
|
||||||
|
internal static bool TryParseNodeId(ISession session, string fullReference, out NodeId nodeId)
|
||||||
|
{
|
||||||
|
nodeId = NodeId.Null;
|
||||||
|
if (string.IsNullOrWhiteSpace(fullReference)) return false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
nodeId = NodeId.Parse(session.MessageContext, fullReference);
|
||||||
|
return !NodeId.IsNull(nodeId);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ISession RequireSession() =>
|
||||||
|
Session ?? throw new InvalidOperationException("OpcUaClientDriver not initialized");
|
||||||
|
|
||||||
|
// ---- ITagDiscovery ----
|
||||||
|
|
||||||
|
public async Task DiscoverAsync(IAddressSpaceBuilder builder, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(builder);
|
||||||
|
var session = RequireSession();
|
||||||
|
|
||||||
|
var root = !string.IsNullOrEmpty(_options.BrowseRoot)
|
||||||
|
? NodeId.Parse(session.MessageContext, _options.BrowseRoot)
|
||||||
|
: ObjectIds.ObjectsFolder;
|
||||||
|
|
||||||
|
var rootFolder = builder.Folder("Remote", "Remote");
|
||||||
|
var visited = new HashSet<NodeId>();
|
||||||
|
var discovered = 0;
|
||||||
|
|
||||||
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await BrowseRecursiveAsync(session, root, rootFolder, visited,
|
||||||
|
depth: 0, discovered: () => discovered, increment: () => discovered++,
|
||||||
|
ct: cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally { _gate.Release(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task BrowseRecursiveAsync(
|
||||||
|
ISession session, NodeId node, IAddressSpaceBuilder folder, HashSet<NodeId> visited,
|
||||||
|
int depth, Func<int> discovered, Action increment, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (depth >= _options.MaxBrowseDepth) return;
|
||||||
|
if (discovered() >= _options.MaxDiscoveredNodes) return;
|
||||||
|
if (!visited.Add(node)) return;
|
||||||
|
|
||||||
|
var browseDescriptions = new BrowseDescriptionCollection
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
NodeId = node,
|
||||||
|
BrowseDirection = BrowseDirection.Forward,
|
||||||
|
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
|
||||||
|
IncludeSubtypes = true,
|
||||||
|
NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable),
|
||||||
|
ResultMask = (uint)(BrowseResultMask.BrowseName | BrowseResultMask.DisplayName
|
||||||
|
| BrowseResultMask.NodeClass | BrowseResultMask.TypeDefinition),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BrowseResponse resp;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
resp = await session.BrowseAsync(
|
||||||
|
requestHeader: null,
|
||||||
|
view: null,
|
||||||
|
requestedMaxReferencesPerNode: 0,
|
||||||
|
nodesToBrowse: browseDescriptions,
|
||||||
|
ct: ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Transient browse failure on a sub-tree — don't kill the whole discovery, just
|
||||||
|
// skip this branch. The driver's health surface will reflect the cascade via the
|
||||||
|
// probe loop (PR 69).
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resp.Results.Count == 0) return;
|
||||||
|
var refs = resp.Results[0].References;
|
||||||
|
|
||||||
|
foreach (var rf in refs)
|
||||||
|
{
|
||||||
|
if (discovered() >= _options.MaxDiscoveredNodes) break;
|
||||||
|
|
||||||
|
var childId = ExpandedNodeId.ToNodeId(rf.NodeId, session.NamespaceUris);
|
||||||
|
if (NodeId.IsNull(childId)) continue;
|
||||||
|
|
||||||
|
var browseName = rf.BrowseName?.Name ?? childId.ToString();
|
||||||
|
var displayName = rf.DisplayName?.Text ?? browseName;
|
||||||
|
|
||||||
|
if (rf.NodeClass == NodeClass.Object)
|
||||||
|
{
|
||||||
|
var subFolder = folder.Folder(browseName, displayName);
|
||||||
|
increment();
|
||||||
|
await BrowseRecursiveAsync(session, childId, subFolder, visited,
|
||||||
|
depth + 1, discovered, increment, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else if (rf.NodeClass == NodeClass.Variable)
|
||||||
|
{
|
||||||
|
// Serialize the NodeId so the IReadable/IWritable surface receives a
|
||||||
|
// round-trippable string. Deferring the DataType + AccessLevel fetch to a
|
||||||
|
// follow-up PR — initial browse uses a conservative ViewOnly + Int32 default.
|
||||||
|
var nodeIdString = childId.ToString() ?? string.Empty;
|
||||||
|
folder.Variable(browseName, displayName, new DriverAttributeInfo(
|
||||||
|
FullName: nodeIdString,
|
||||||
|
DriverDataType: DriverDataType.Int32,
|
||||||
|
IsArray: false,
|
||||||
|
ArrayDim: null,
|
||||||
|
SecurityClass: SecurityClassification.ViewOnly,
|
||||||
|
IsHistorized: false,
|
||||||
|
IsAlarm: false));
|
||||||
|
increment();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- ISubscribable ----
|
||||||
|
|
||||||
|
public async Task<ISubscriptionHandle> SubscribeAsync(
|
||||||
|
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var session = RequireSession();
|
||||||
|
var id = Interlocked.Increment(ref _nextSubscriptionId);
|
||||||
|
var handle = new OpcUaSubscriptionHandle(id);
|
||||||
|
|
||||||
|
// Floor the publishing interval at 50ms — OPC UA servers routinely negotiate
|
||||||
|
// minimum-supported intervals up anyway, but sending sub-50ms wastes negotiation
|
||||||
|
// bandwidth on every subscription create.
|
||||||
|
var intervalMs = publishingInterval < TimeSpan.FromMilliseconds(50)
|
||||||
|
? 50
|
||||||
|
: (int)publishingInterval.TotalMilliseconds;
|
||||||
|
|
||||||
|
var subscription = new Subscription(telemetry: null!, new SubscriptionOptions
|
||||||
|
{
|
||||||
|
DisplayName = $"opcua-sub-{id}",
|
||||||
|
PublishingInterval = intervalMs,
|
||||||
|
KeepAliveCount = 10,
|
||||||
|
LifetimeCount = 1000,
|
||||||
|
MaxNotificationsPerPublish = 0,
|
||||||
|
PublishingEnabled = true,
|
||||||
|
Priority = 0,
|
||||||
|
TimestampsToReturn = TimestampsToReturn.Both,
|
||||||
|
});
|
||||||
|
|
||||||
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
session.AddSubscription(subscription);
|
||||||
|
await subscription.CreateAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
foreach (var fullRef in fullReferences)
|
||||||
|
{
|
||||||
|
if (!TryParseNodeId(session, fullRef, out var nodeId)) continue;
|
||||||
|
// The tag string is routed through MonitoredItem.Handle so the Notification
|
||||||
|
// handler can identify which tag changed without an extra lookup.
|
||||||
|
var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions
|
||||||
|
{
|
||||||
|
DisplayName = fullRef,
|
||||||
|
StartNodeId = nodeId,
|
||||||
|
AttributeId = Attributes.Value,
|
||||||
|
MonitoringMode = MonitoringMode.Reporting,
|
||||||
|
SamplingInterval = intervalMs,
|
||||||
|
QueueSize = 1,
|
||||||
|
DiscardOldest = true,
|
||||||
|
})
|
||||||
|
{
|
||||||
|
Handle = fullRef,
|
||||||
|
};
|
||||||
|
item.Notification += (mi, args) => OnMonitoredItemNotification(handle, mi, args);
|
||||||
|
subscription.AddItem(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
await subscription.CreateItemsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
_subscriptions[id] = new RemoteSubscription(subscription, handle);
|
||||||
|
}
|
||||||
|
finally { _gate.Release(); }
|
||||||
|
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (handle is not OpcUaSubscriptionHandle h) return;
|
||||||
|
if (!_subscriptions.TryRemove(h.Id, out var rs)) return;
|
||||||
|
|
||||||
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
try { await rs.Subscription.DeleteAsync(silent: true, cancellationToken).ConfigureAwait(false); }
|
||||||
|
catch { /* best-effort — the subscription may already be gone on reconnect */ }
|
||||||
|
}
|
||||||
|
finally { _gate.Release(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMonitoredItemNotification(OpcUaSubscriptionHandle handle, MonitoredItem item, MonitoredItemNotificationEventArgs args)
|
||||||
|
{
|
||||||
|
// args.NotificationValue arrives as a MonitoredItemNotification for value-change
|
||||||
|
// subscriptions; extract its DataValue. The Handle property carries our tag string.
|
||||||
|
if (args.NotificationValue is not MonitoredItemNotification mn) return;
|
||||||
|
var dv = mn.Value;
|
||||||
|
if (dv is null) return;
|
||||||
|
var fullRef = (item.Handle as string) ?? item.DisplayName ?? string.Empty;
|
||||||
|
var snapshot = new DataValueSnapshot(
|
||||||
|
Value: dv.Value,
|
||||||
|
StatusCode: dv.StatusCode.Code,
|
||||||
|
SourceTimestampUtc: dv.SourceTimestamp == DateTime.MinValue ? null : dv.SourceTimestamp,
|
||||||
|
ServerTimestampUtc: dv.ServerTimestamp == DateTime.MinValue ? DateTime.UtcNow : dv.ServerTimestamp);
|
||||||
|
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, fullRef, snapshot));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record RemoteSubscription(Subscription Subscription, OpcUaSubscriptionHandle Handle);
|
||||||
|
|
||||||
|
private sealed record OpcUaSubscriptionHandle(long Id) : ISubscriptionHandle
|
||||||
|
{
|
||||||
|
public string DiagnosticId => $"opcua-sub-{Id}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- IHostConnectivityProbe ----
|
||||||
|
|
||||||
|
/// <summary>Endpoint-URL-keyed host identity for the Admin /hosts dashboard.</summary>
|
||||||
|
public string HostName => _options.EndpointUrl;
|
||||||
|
|
||||||
|
public IReadOnlyList<HostConnectivityStatus> GetHostStatuses()
|
||||||
|
{
|
||||||
|
lock (_probeLock)
|
||||||
|
return [new HostConnectivityStatus(HostName, _hostState, _hostStateChangedUtc)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TransitionTo(HostState newState)
|
||||||
|
{
|
||||||
|
HostState old;
|
||||||
|
lock (_probeLock)
|
||||||
|
{
|
||||||
|
old = _hostState;
|
||||||
|
if (old == newState) return;
|
||||||
|
_hostState = newState;
|
||||||
|
_hostStateChangedUtc = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs(HostName, old, newState));
|
||||||
|
}
|
||||||
|
|
||||||
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
|
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||||
|
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
|
|||||||
@@ -16,8 +16,16 @@ public sealed class OpcUaClientDriverOptions
|
|||||||
/// <summary>Remote OPC UA endpoint URL, e.g. <c>opc.tcp://plc.internal:4840</c>.</summary>
|
/// <summary>Remote OPC UA endpoint URL, e.g. <c>opc.tcp://plc.internal:4840</c>.</summary>
|
||||||
public string EndpointUrl { get; init; } = "opc.tcp://localhost:4840";
|
public string EndpointUrl { get; init; } = "opc.tcp://localhost:4840";
|
||||||
|
|
||||||
/// <summary>Security policy. One of <c>None</c>, <c>Basic256Sha256</c>, <c>Aes128_Sha256_RsaOaep</c>.</summary>
|
/// <summary>
|
||||||
public string SecurityPolicy { get; init; } = "None";
|
/// Security policy to require when selecting an endpoint. Either a
|
||||||
|
/// <see cref="OpcUaSecurityPolicy"/> enum constant or a free-form string (for
|
||||||
|
/// forward-compatibility with future OPC UA policies not yet in the enum).
|
||||||
|
/// Matched against <c>EndpointDescription.SecurityPolicyUri</c> suffix — the driver
|
||||||
|
/// connects to the first endpoint whose policy name matches AND whose mode matches
|
||||||
|
/// <see cref="SecurityMode"/>. When set to <see cref="OpcUaSecurityPolicy.None"/>
|
||||||
|
/// the driver picks any unsecured endpoint regardless of policy string.
|
||||||
|
/// </summary>
|
||||||
|
public OpcUaSecurityPolicy SecurityPolicy { get; init; } = OpcUaSecurityPolicy.None;
|
||||||
|
|
||||||
/// <summary>Security mode.</summary>
|
/// <summary>Security mode.</summary>
|
||||||
public OpcUaSecurityMode SecurityMode { get; init; } = OpcUaSecurityMode.None;
|
public OpcUaSecurityMode SecurityMode { get; init; } = OpcUaSecurityMode.None;
|
||||||
@@ -62,6 +70,30 @@ public sealed class OpcUaClientDriverOptions
|
|||||||
|
|
||||||
/// <summary>Connect + per-operation timeout.</summary>
|
/// <summary>Connect + per-operation timeout.</summary>
|
||||||
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
|
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Root NodeId to mirror. Default <c>null</c> = <c>ObjectsFolder</c> (i=85). Set to
|
||||||
|
/// a scoped root to restrict the address space the driver exposes locally — useful
|
||||||
|
/// when the remote server has tens of thousands of nodes and only a subset is
|
||||||
|
/// needed downstream.
|
||||||
|
/// </summary>
|
||||||
|
public string? BrowseRoot { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cap on total nodes discovered during <c>DiscoverAsync</c>. Default 10_000 —
|
||||||
|
/// bounds memory on runaway remote servers without being so low that normal
|
||||||
|
/// deployments hit it. When the cap is reached discovery stops and a warning is
|
||||||
|
/// written to the driver health surface; the partially-discovered tree is still
|
||||||
|
/// projected into the local address space.
|
||||||
|
/// </summary>
|
||||||
|
public int MaxDiscoveredNodes { get; init; } = 10_000;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Max hierarchical depth of the browse. Default 10 — deep enough for realistic
|
||||||
|
/// OPC UA information models, shallow enough that cyclic graphs can't spin the
|
||||||
|
/// browse forever.
|
||||||
|
/// </summary>
|
||||||
|
public int MaxBrowseDepth { get; init; } = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>OPC UA message security mode.</summary>
|
/// <summary>OPC UA message security mode.</summary>
|
||||||
@@ -72,6 +104,33 @@ public enum OpcUaSecurityMode
|
|||||||
SignAndEncrypt,
|
SignAndEncrypt,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// OPC UA security policies recognized by the driver. Maps to the standard
|
||||||
|
/// <c>http://opcfoundation.org/UA/SecurityPolicy#</c> URI suffixes the SDK uses for
|
||||||
|
/// endpoint matching.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <see cref="Basic128Rsa15"/> and <see cref="Basic256"/> are <b>deprecated</b> per OPC UA
|
||||||
|
/// spec v1.04 — they remain in the enum only for brownfield interop with older servers.
|
||||||
|
/// Prefer <see cref="Basic256Sha256"/>, <see cref="Aes128_Sha256_RsaOaep"/>, or
|
||||||
|
/// <see cref="Aes256_Sha256_RsaPss"/> for new deployments.
|
||||||
|
/// </remarks>
|
||||||
|
public enum OpcUaSecurityPolicy
|
||||||
|
{
|
||||||
|
/// <summary>No security. Unsigned, unencrypted wire.</summary>
|
||||||
|
None,
|
||||||
|
/// <summary>Deprecated (OPC UA 1.04). Retained for legacy server interop.</summary>
|
||||||
|
Basic128Rsa15,
|
||||||
|
/// <summary>Deprecated (OPC UA 1.04). Retained for legacy server interop.</summary>
|
||||||
|
Basic256,
|
||||||
|
/// <summary>Recommended baseline for current deployments.</summary>
|
||||||
|
Basic256Sha256,
|
||||||
|
/// <summary>Current OPC UA policy; AES-128 + SHA-256 + RSA-OAEP.</summary>
|
||||||
|
Aes128_Sha256_RsaOaep,
|
||||||
|
/// <summary>Current OPC UA policy; AES-256 + SHA-256 + RSA-PSS.</summary>
|
||||||
|
Aes256_Sha256_RsaPss,
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>User authentication type sent to the remote server.</summary>
|
/// <summary>User authentication type sent to the remote server.</summary>
|
||||||
public enum OpcUaAuthType
|
public enum OpcUaAuthType
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scaffold tests for <see cref="OpcUaClientDriver"/>'s <see cref="ITagDiscovery"/>
|
||||||
|
/// surface that don't require a live remote server. Live-browse coverage lands in a
|
||||||
|
/// follow-up PR once the in-process OPC UA server fixture is scaffolded.
|
||||||
|
/// </summary>
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class OpcUaClientDiscoveryTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverAsync_without_initialize_throws_InvalidOperationException()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-disco");
|
||||||
|
var builder = new NullAddressSpaceBuilder();
|
||||||
|
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||||
|
await drv.DiscoverAsync(builder, TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverAsync_rejects_null_builder()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-disco");
|
||||||
|
Should.ThrowAsync<ArgumentNullException>(async () =>
|
||||||
|
await drv.DiscoverAsync(null!, TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Discovery_caps_are_sensible_defaults()
|
||||||
|
{
|
||||||
|
var opts = new OpcUaClientDriverOptions();
|
||||||
|
opts.MaxDiscoveredNodes.ShouldBe(10_000, "bounds memory on runaway servers without clipping normal models");
|
||||||
|
opts.MaxBrowseDepth.ShouldBe(10, "deep enough for realistic info models; shallow enough for cycle safety");
|
||||||
|
opts.BrowseRoot.ShouldBeNull("null = default to ObjectsFolder i=85");
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class NullAddressSpaceBuilder : IAddressSpaceBuilder
|
||||||
|
{
|
||||||
|
public IAddressSpaceBuilder Folder(string browseName, string displayName) => this;
|
||||||
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
||||||
|
=> new StubHandle();
|
||||||
|
public void AddProperty(string browseName, DriverDataType dataType, object? value) { }
|
||||||
|
public void AttachAlarmCondition(IVariableHandle sourceVariable, string alarmName, DriverAttributeInfo alarmInfo) { }
|
||||||
|
|
||||||
|
private sealed class StubHandle : IVariableHandle
|
||||||
|
{
|
||||||
|
public string FullReference => "stub";
|
||||||
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info) => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ public sealed class OpcUaClientDriverScaffoldTests
|
|||||||
var opts = new OpcUaClientDriverOptions();
|
var opts = new OpcUaClientDriverOptions();
|
||||||
opts.EndpointUrl.ShouldBe("opc.tcp://localhost:4840", "4840 is the IANA-assigned OPC UA port");
|
opts.EndpointUrl.ShouldBe("opc.tcp://localhost:4840", "4840 is the IANA-assigned OPC UA port");
|
||||||
opts.SecurityMode.ShouldBe(OpcUaSecurityMode.None);
|
opts.SecurityMode.ShouldBe(OpcUaSecurityMode.None);
|
||||||
|
opts.SecurityPolicy.ShouldBe(OpcUaSecurityPolicy.None);
|
||||||
opts.AuthType.ShouldBe(OpcUaAuthType.Anonymous);
|
opts.AuthType.ShouldBe(OpcUaAuthType.Anonymous);
|
||||||
opts.AutoAcceptCertificates.ShouldBeFalse("production default must reject untrusted server certs");
|
opts.AutoAcceptCertificates.ShouldBeFalse("production default must reject untrusted server certs");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unit tests for the IReadable/IWritable surface that don't need a live remote OPC UA
|
||||||
|
/// server. Wire-level round-trips against a local in-process server fixture land in a
|
||||||
|
/// follow-up PR once we have one scaffolded.
|
||||||
|
/// </summary>
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class OpcUaClientReadWriteTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ReadAsync_without_initialize_throws_InvalidOperationException()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-uninit");
|
||||||
|
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||||
|
await drv.ReadAsync(["ns=2;s=Demo"], TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task WriteAsync_without_initialize_throws_InvalidOperationException()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-uninit");
|
||||||
|
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||||
|
await drv.WriteAsync(
|
||||||
|
[new WriteRequest("ns=2;s=Demo", 42)],
|
||||||
|
TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using Opc.Ua;
|
||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||||
|
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class OpcUaClientSecurityPolicyTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.None)]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.Basic128Rsa15)]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.Basic256)]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.Basic256Sha256)]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.Aes128_Sha256_RsaOaep)]
|
||||||
|
[InlineData(OpcUaSecurityPolicy.Aes256_Sha256_RsaPss)]
|
||||||
|
public void MapSecurityPolicy_returns_known_non_empty_uri_for_every_enum_value(OpcUaSecurityPolicy policy)
|
||||||
|
{
|
||||||
|
var uri = OpcUaClientDriver.MapSecurityPolicy(policy);
|
||||||
|
uri.ShouldNotBeNullOrEmpty();
|
||||||
|
// Each URI should end in the enum name (for the non-None policies) so a driver
|
||||||
|
// operator reading logs can correlate the URI back to the config value.
|
||||||
|
if (policy != OpcUaSecurityPolicy.None)
|
||||||
|
uri.ShouldContain(policy.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapSecurityPolicy_None_matches_SDK_None_URI()
|
||||||
|
{
|
||||||
|
OpcUaClientDriver.MapSecurityPolicy(OpcUaSecurityPolicy.None)
|
||||||
|
.ShouldBe(SecurityPolicies.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapSecurityPolicy_Basic256Sha256_matches_SDK_URI()
|
||||||
|
{
|
||||||
|
OpcUaClientDriver.MapSecurityPolicy(OpcUaSecurityPolicy.Basic256Sha256)
|
||||||
|
.ShouldBe(SecurityPolicies.Basic256Sha256);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MapSecurityPolicy_Aes256_Sha256_RsaPss_matches_SDK_URI()
|
||||||
|
{
|
||||||
|
OpcUaClientDriver.MapSecurityPolicy(OpcUaSecurityPolicy.Aes256_Sha256_RsaPss)
|
||||||
|
.ShouldBe(SecurityPolicies.Aes256_Sha256_RsaPss);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Every_enum_value_has_a_mapping()
|
||||||
|
{
|
||||||
|
foreach (OpcUaSecurityPolicy p in Enum.GetValues<OpcUaSecurityPolicy>())
|
||||||
|
Should.NotThrow(() => OpcUaClientDriver.MapSecurityPolicy(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scaffold tests for <c>ISubscribable</c> + <c>IHostConnectivityProbe</c> that don't
|
||||||
|
/// need a live remote server. Live-session tests (subscribe/unsubscribe round-trip,
|
||||||
|
/// keep-alive transitions) land in a follow-up PR once the in-process OPC UA server
|
||||||
|
/// fixture is scaffolded.
|
||||||
|
/// </summary>
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class OpcUaClientSubscribeAndProbeTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task SubscribeAsync_without_initialize_throws_InvalidOperationException()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-sub-uninit");
|
||||||
|
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||||
|
await drv.SubscribeAsync(["ns=2;s=Demo"], TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UnsubscribeAsync_with_unknown_handle_is_noop()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-sub-unknown");
|
||||||
|
// UnsubscribeAsync returns cleanly for handles it doesn't recognise — protects against
|
||||||
|
// the caller's race with server-side cleanup after a session drop.
|
||||||
|
await drv.UnsubscribeAsync(new FakeHandle(), TestContext.Current.CancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetHostStatuses_returns_endpoint_url_row_pre_init()
|
||||||
|
{
|
||||||
|
using var drv = new OpcUaClientDriver(
|
||||||
|
new OpcUaClientDriverOptions { EndpointUrl = "opc.tcp://plc.example:4840" },
|
||||||
|
"opcua-hosts");
|
||||||
|
var rows = drv.GetHostStatuses();
|
||||||
|
rows.Count.ShouldBe(1);
|
||||||
|
rows[0].HostName.ShouldBe("opc.tcp://plc.example:4840",
|
||||||
|
"host identity mirrors the endpoint URL so the Admin /hosts dashboard can link back to the remote server");
|
||||||
|
rows[0].State.ShouldBe(HostState.Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class FakeHandle : ISubscriptionHandle
|
||||||
|
{
|
||||||
|
public string DiagnosticId => "fake";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user