Phase 0 — mechanical rename ZB.MOM.WW.LmxOpcUa.* → ZB.MOM.WW.OtOpcUa.*
Renames all 11 projects (5 src + 6 tests), the .slnx solution file, all source-file namespaces, all axaml namespace references, and all v1 documentation references in CLAUDE.md and docs/*.md (excluding docs/v2/ which is already in OtOpcUa form). Also updates the TopShelf service registration name from "LmxOpcUa" to "OtOpcUa" per Phase 0 Task 0.6.
Preserves runtime identifiers per Phase 0 Out-of-Scope rules to avoid breaking v1/v2 client trust during coexistence: OPC UA `ApplicationUri` defaults (`urn:{GalaxyName}:LmxOpcUa`), server `EndpointPath` (`/LmxOpcUa`), `ServerName` default (feeds cert subject CN), `MxAccessConfiguration.ClientName` default (defensive — stays "LmxOpcUa" for MxAccess audit-trail consistency), client OPC UA identifiers (`ApplicationName = "LmxOpcUaClient"`, `ApplicationUri = "urn:localhost:LmxOpcUaClient"`, cert directory `%LocalAppData%\LmxOpcUaClient\pki\`), and the `LmxOpcUaServer` class name (class rename out of Phase 0 scope per Task 0.5 sed pattern; happens in Phase 1 alongside `LmxNodeManager → GenericDriverNodeManager` Core extraction). 23 LmxOpcUa references retained, all enumerated and justified in `docs/v2/implementation/exit-gate-phase-0.md`.
Build clean: 0 errors, 30 warnings (lower than baseline 167). Tests at strict improvement over baseline: 821 passing / 1 failing vs baseline 820 / 2 (one flaky pre-existing failure passed this run; the other still fails — both pre-existing and unrelated to the rename). `Client.UI.Tests`, `Historian.Aveva.Tests`, `Client.Shared.Tests`, `IntegrationTests` all match baseline exactly. Exit gate compliance results recorded in `docs/v2/implementation/exit-gate-phase-0.md` with all 7 checks PASS or DEFERRED-to-PR-review (#7 service install verification needs Windows service permissions on the reviewer's box).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production implementation that builds a real OPC UA ApplicationConfiguration.
|
||||
/// </summary>
|
||||
internal sealed class DefaultApplicationConfigurationFactory : IApplicationConfigurationFactory
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultApplicationConfigurationFactory>();
|
||||
|
||||
public async Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct)
|
||||
{
|
||||
var storePath = settings.CertificateStorePath;
|
||||
|
||||
var config = new ApplicationConfiguration
|
||||
{
|
||||
ApplicationName = "LmxOpcUaClient",
|
||||
ApplicationUri = "urn:localhost:LmxOpcUaClient",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
SecurityConfiguration = new SecurityConfiguration
|
||||
{
|
||||
ApplicationCertificate = new CertificateIdentifier
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "own")
|
||||
},
|
||||
TrustedIssuerCertificates = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "issuer")
|
||||
},
|
||||
TrustedPeerCertificates = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "trusted")
|
||||
},
|
||||
RejectedCertificateStore = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "rejected")
|
||||
},
|
||||
AutoAcceptUntrustedCertificates = settings.AutoAcceptCertificates
|
||||
},
|
||||
ClientConfiguration = new ClientConfiguration
|
||||
{
|
||||
DefaultSessionTimeout = settings.SessionTimeoutSeconds * 1000
|
||||
}
|
||||
};
|
||||
|
||||
await config.Validate(ApplicationType.Client);
|
||||
|
||||
if (settings.AutoAcceptCertificates)
|
||||
config.CertificateValidator.CertificateValidation += (_, e) => e.Accept = true;
|
||||
|
||||
if (settings.SecurityMode != SecurityMode.None)
|
||||
{
|
||||
var app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "LmxOpcUaClient",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
ApplicationConfiguration = config
|
||||
};
|
||||
await app.CheckApplicationInstanceCertificatesAsync(false, 2048);
|
||||
}
|
||||
|
||||
Logger.Debug("ApplicationConfiguration created for {EndpointUrl}", settings.EndpointUrl);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production endpoint discovery that queries the real server.
|
||||
/// </summary>
|
||||
internal sealed class DefaultEndpointDiscovery : IEndpointDiscovery
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultEndpointDiscovery>();
|
||||
|
||||
public EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl,
|
||||
MessageSecurityMode requestedMode)
|
||||
{
|
||||
if (requestedMode == MessageSecurityMode.None)
|
||||
{
|
||||
#pragma warning disable CS0618 // Acceptable for endpoint selection
|
||||
return CoreClientUtils.SelectEndpoint(config, endpointUrl, false);
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
using var client = DiscoveryClient.Create(new Uri(endpointUrl));
|
||||
var allEndpoints = client.GetEndpoints(null);
|
||||
|
||||
EndpointDescription? best = null;
|
||||
|
||||
foreach (var ep in allEndpoints)
|
||||
{
|
||||
if (ep.SecurityMode != requestedMode)
|
||||
continue;
|
||||
|
||||
if (best == null)
|
||||
{
|
||||
best = ep;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ep.SecurityPolicyUri == SecurityPolicies.Basic256Sha256)
|
||||
best = ep;
|
||||
}
|
||||
|
||||
if (best == null)
|
||||
{
|
||||
var available = string.Join(", ", allEndpoints.Select(e => $"{e.SecurityMode}/{e.SecurityPolicyUri}"));
|
||||
throw new InvalidOperationException(
|
||||
$"No endpoint found with security mode '{requestedMode}'. Available endpoints: {available}");
|
||||
}
|
||||
|
||||
// Rewrite endpoint URL hostname to match user-supplied hostname
|
||||
var serverUri = new Uri(best.EndpointUrl);
|
||||
var requestedUri = new Uri(endpointUrl);
|
||||
if (serverUri.Host != requestedUri.Host)
|
||||
{
|
||||
var builder = new UriBuilder(best.EndpointUrl) { Host = requestedUri.Host };
|
||||
best.EndpointUrl = builder.ToString();
|
||||
Logger.Debug("Rewrote endpoint host from {ServerHost} to {RequestedHost}", serverUri.Host,
|
||||
requestedUri.Host);
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
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;
|
||||
|
||||
/// <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>
|
||||
public DefaultSessionAdapter(Session session)
|
||||
{
|
||||
_session = session;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Connected => _session.Connected;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SessionId => _session.SessionId?.ToString() ?? string.Empty;
|
||||
|
||||
/// <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<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
|
||||
{
|
||||
var writeValue = new WriteValue
|
||||
{
|
||||
NodeId = nodeId,
|
||||
AttributeId = Attributes.Value,
|
||||
Value = value
|
||||
};
|
||||
|
||||
var writeCollection = new WriteValueCollection { writeValue };
|
||||
var response = await _session.WriteAsync(null, writeCollection, ct);
|
||||
return response.Results[0];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
|
||||
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
|
||||
{
|
||||
var (_, continuationPoint, references) = await _session.BrowseAsync(
|
||||
null,
|
||||
null,
|
||||
nodeId,
|
||||
0u,
|
||||
BrowseDirection.Forward,
|
||||
ReferenceTypeIds.HierarchicalReferences,
|
||||
true,
|
||||
nodeClassMask);
|
||||
|
||||
return (continuationPoint, references ?? []);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct)
|
||||
{
|
||||
var (_, nextCp, nextRefs) = await _session.BrowseNextAsync(null, false, continuationPoint);
|
||||
return (nextCp, nextRefs ?? []);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
var (_, _, references) = await _session.BrowseAsync(
|
||||
null,
|
||||
null,
|
||||
nodeId,
|
||||
1u,
|
||||
BrowseDirection.Forward,
|
||||
ReferenceTypeIds.HierarchicalReferences,
|
||||
true,
|
||||
0u);
|
||||
|
||||
return references != null && references.Count > 0;
|
||||
}
|
||||
|
||||
/// <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
|
||||
};
|
||||
|
||||
var nodesToRead = new HistoryReadValueIdCollection
|
||||
{
|
||||
new HistoryReadValueId { NodeId = nodeId }
|
||||
};
|
||||
|
||||
var allValues = new List<DataValue>();
|
||||
byte[]? continuationPoint = null;
|
||||
|
||||
do
|
||||
{
|
||||
if (continuationPoint != null)
|
||||
nodesToRead[0].ContinuationPoint = continuationPoint;
|
||||
|
||||
_session.HistoryRead(
|
||||
null,
|
||||
new ExtensionObject(details),
|
||||
TimestampsToReturn.Source,
|
||||
continuationPoint != null,
|
||||
nodesToRead,
|
||||
out var results,
|
||||
out _);
|
||||
|
||||
if (results == null || results.Count == 0)
|
||||
break;
|
||||
|
||||
var result = results[0];
|
||||
if (StatusCode.IsBad(result.StatusCode))
|
||||
break;
|
||||
|
||||
if (result.HistoryData is ExtensionObject ext && ext.Body is HistoryData historyData)
|
||||
allValues.AddRange(historyData.DataValues);
|
||||
|
||||
continuationPoint = result.ContinuationPoint;
|
||||
} while (continuationPoint != null && continuationPoint.Length > 0 && allValues.Count < maxValues);
|
||||
|
||||
return allValues;
|
||||
}
|
||||
|
||||
/// <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]
|
||||
};
|
||||
|
||||
var nodesToRead = new HistoryReadValueIdCollection
|
||||
{
|
||||
new HistoryReadValueId { NodeId = nodeId }
|
||||
};
|
||||
|
||||
_session.HistoryRead(
|
||||
null,
|
||||
new ExtensionObject(details),
|
||||
TimestampsToReturn.Source,
|
||||
false,
|
||||
nodesToRead,
|
||||
out var results,
|
||||
out _);
|
||||
|
||||
var allValues = new List<DataValue>();
|
||||
|
||||
if (results != null && results.Count > 0)
|
||||
{
|
||||
var result = results[0];
|
||||
if (!StatusCode.IsBad(result.StatusCode) &&
|
||||
result.HistoryData is ExtensionObject ext &&
|
||||
ext.Body is HistoryData historyData)
|
||||
allValues.AddRange(historyData.DataValues);
|
||||
}
|
||||
|
||||
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);
|
||||
await subscription.CreateAsync(ct);
|
||||
|
||||
return new DefaultSubscriptionAdapter(subscription);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task CloseAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected) _session.Close();
|
||||
}
|
||||
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()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected) _session.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_session.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var result = await _session.CallAsync(
|
||||
null,
|
||||
new CallMethodRequestCollection
|
||||
{
|
||||
new()
|
||||
{
|
||||
ObjectId = objectId,
|
||||
MethodId = methodId,
|
||||
InputArguments = new VariantCollection(inputArguments.Select(a => new Variant(a)))
|
||||
}
|
||||
},
|
||||
ct);
|
||||
|
||||
var callResult = result.Results[0];
|
||||
if (StatusCode.IsBad(callResult.StatusCode))
|
||||
throw new ServiceResultException(callResult.StatusCode);
|
||||
|
||||
return callResult.OutputArguments?.Select(v => v.Value).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production session factory that creates real OPC UA sessions.
|
||||
/// </summary>
|
||||
internal sealed class DefaultSessionFactory : ISessionFactory
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultSessionFactory>();
|
||||
|
||||
public async Task<ISessionAdapter> CreateSessionAsync(
|
||||
ApplicationConfiguration config,
|
||||
EndpointDescription endpoint,
|
||||
string sessionName,
|
||||
uint sessionTimeoutMs,
|
||||
UserIdentity identity,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var endpointConfig = EndpointConfiguration.Create(config);
|
||||
var configuredEndpoint = new ConfiguredEndpoint(null, endpoint, endpointConfig);
|
||||
|
||||
var session = await Session.Create(
|
||||
config,
|
||||
configuredEndpoint,
|
||||
false,
|
||||
sessionName,
|
||||
sessionTimeoutMs,
|
||||
identity,
|
||||
null);
|
||||
|
||||
Logger.Information("Session created: {SessionName} -> {EndpointUrl}", sessionName, endpoint.EndpointUrl);
|
||||
return new DefaultSessionAdapter(session);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production subscription adapter wrapping a real OPC UA Subscription.
|
||||
/// </summary>
|
||||
internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultSubscriptionAdapter>();
|
||||
private readonly Dictionary<uint, MonitoredItem> _monitoredItems = new();
|
||||
private readonly Subscription _subscription;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a live OPC UA subscription so client code can manage monitored items through a testable abstraction.
|
||||
/// </summary>
|
||||
/// <param name="subscription">The underlying OPC UA subscription that owns monitored items for this client workflow.</param>
|
||||
public DefaultSubscriptionAdapter(Subscription subscription)
|
||||
{
|
||||
_subscription = subscription;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public uint SubscriptionId => _subscription.Id;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<uint> AddDataChangeMonitoredItemAsync(
|
||||
NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct)
|
||||
{
|
||||
var item = new MonitoredItem(_subscription.DefaultItem)
|
||||
{
|
||||
StartNodeId = nodeId,
|
||||
DisplayName = nodeId.ToString(),
|
||||
SamplingInterval = samplingIntervalMs
|
||||
};
|
||||
|
||||
item.Notification += (_, e) =>
|
||||
{
|
||||
if (e.NotificationValue is MonitoredItemNotification notification)
|
||||
onDataChange(nodeId.ToString(), notification.Value);
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
|
||||
Logger.Debug("Added data change monitored item for {NodeId}, handle={Handle}", nodeId, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
|
||||
{
|
||||
if (!_monitoredItems.TryGetValue(clientHandle, out var item))
|
||||
return;
|
||||
|
||||
_subscription.RemoveItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
_monitoredItems.Remove(clientHandle);
|
||||
|
||||
Logger.Debug("Removed monitored item handle={Handle}", clientHandle);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<uint> AddEventMonitoredItemAsync(
|
||||
NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct)
|
||||
{
|
||||
var item = new MonitoredItem(_subscription.DefaultItem)
|
||||
{
|
||||
StartNodeId = nodeId,
|
||||
DisplayName = "AlarmMonitor",
|
||||
SamplingInterval = samplingIntervalMs,
|
||||
NodeClass = NodeClass.Object,
|
||||
AttributeId = Attributes.EventNotifier,
|
||||
Filter = filter
|
||||
};
|
||||
|
||||
item.Notification += (_, e) =>
|
||||
{
|
||||
if (e.NotificationValue is EventFieldList eventFields) onEvent(eventFields);
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
|
||||
Logger.Debug("Added event monitored item for {NodeId}, handle={Handle}", nodeId, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ConditionRefreshAsync(CancellationToken ct)
|
||||
{
|
||||
await _subscription.ConditionRefreshAsync(ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DeleteAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _subscription.DeleteAsync(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error deleting subscription");
|
||||
}
|
||||
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the wrapped OPC UA subscription and clears tracked monitored items held by the adapter.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_subscription.Delete(true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Creates and configures an OPC UA ApplicationConfiguration.
|
||||
/// </summary>
|
||||
internal interface IApplicationConfigurationFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a validated ApplicationConfiguration for the given connection settings.
|
||||
/// </summary>
|
||||
Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts OPC UA endpoint discovery for testability.
|
||||
/// </summary>
|
||||
internal interface IEndpointDiscovery
|
||||
{
|
||||
/// <summary>
|
||||
/// Discovers endpoints at the given URL and returns the best match for the requested security mode.
|
||||
/// Also rewrites the endpoint URL hostname to match the requested URL when they differ.
|
||||
/// </summary>
|
||||
EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl,
|
||||
MessageSecurityMode requestedMode);
|
||||
}
|
||||
140
src/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs
Normal file
140
src/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts the OPC UA session for read, write, browse, history, and subscription operations.
|
||||
/// </summary>
|
||||
internal interface ISessionAdapter : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the underlying OPC UA session is currently usable for client operations.
|
||||
/// </summary>
|
||||
bool Connected { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the server-assigned session identifier for diagnostics and failover reporting.
|
||||
/// </summary>
|
||||
string SessionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the friendly session name presented to the OPC UA server.
|
||||
/// </summary>
|
||||
string SessionName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the active endpoint URL that this adapter is connected to.
|
||||
/// </summary>
|
||||
string EndpointUrl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the server name reported by the connected OPC UA endpoint.
|
||||
/// </summary>
|
||||
string ServerName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the negotiated OPC UA message security mode for the session.
|
||||
/// </summary>
|
||||
string SecurityMode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the negotiated OPC UA security policy URI for the session.
|
||||
/// </summary>
|
||||
string SecurityPolicyUri { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the namespace table used to resolve expanded node identifiers returned by browse operations.
|
||||
/// </summary>
|
||||
NamespaceTable NamespaceUris { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers a keep-alive callback. The callback receives true when the session is healthy, false on failure.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback used by higher-level clients to trigger reconnect or failover behavior.</param>
|
||||
void RegisterKeepAliveHandler(Action<bool> callback);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current value for a node from the connected OPC UA server.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose current runtime value should be read.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the server read if the client cancels the request.</param>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Writes a typed value to a node on the connected OPC UA server.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose value should be updated.</param>
|
||||
/// <param name="value">The typed OPC UA data value to write to the server.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the write if the client cancels the request.</param>
|
||||
Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Browses forward hierarchical references from the given node.
|
||||
/// Returns (continuationPoint, references).
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The starting node for the hierarchical browse.</param>
|
||||
/// <param name="nodeClassMask">The node classes that should be returned to the caller.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the browse request.</param>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
|
||||
NodeId nodeId, uint nodeClassMask = 0, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Continues a browse from a continuation point.
|
||||
/// </summary>
|
||||
/// <param name="continuationPoint">The continuation token returned by a prior browse result page.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the browse-next request.</param>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a node has any forward hierarchical child references.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to inspect for child objects or variables.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the child lookup.</param>
|
||||
Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads raw historical data.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose raw samples should be retrieved.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested history window.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested history window.</param>
|
||||
/// <param name="maxValues">The maximum number of raw samples to return to the client.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the history read.</param>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
int maxValues, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads processed/aggregate historical data.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose processed values should be retrieved.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested processed-history window.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested processed-history window.</param>
|
||||
/// <param name="aggregateId">The OPC UA aggregate function to evaluate over the history window.</param>
|
||||
/// <param name="intervalMs">The processing interval, in milliseconds, for each aggregate bucket.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the aggregate history read.</param>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
NodeId aggregateId, double intervalMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a subscription adapter for this session.
|
||||
/// </summary>
|
||||
/// <param name="publishingIntervalMs">The requested publishing interval for monitored items on the new subscription.</param>
|
||||
/// <param name="ct">The cancellation token that aborts subscription creation.</param>
|
||||
Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Calls an OPC UA method node with the provided input arguments.
|
||||
/// </summary>
|
||||
/// <param name="objectId">The object node that owns the target method.</param>
|
||||
/// <param name="methodId">The method node to invoke.</param>
|
||||
/// <param name="inputArguments">The ordered input arguments supplied to the server method call.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the method invocation.</param>
|
||||
Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Closes the underlying session gracefully before the adapter is disposed or replaced during failover.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts the close request.</param>
|
||||
Task CloseAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Creates OPC UA sessions from a configured endpoint.
|
||||
/// </summary>
|
||||
internal interface ISessionFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a session to the given endpoint.
|
||||
/// </summary>
|
||||
/// <param name="config">The application configuration.</param>
|
||||
/// <param name="endpoint">The configured endpoint.</param>
|
||||
/// <param name="sessionName">The session name.</param>
|
||||
/// <param name="sessionTimeoutMs">Session timeout in milliseconds.</param>
|
||||
/// <param name="identity">The user identity.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A session adapter wrapping the created session.</returns>
|
||||
Task<ISessionAdapter> CreateSessionAsync(
|
||||
ApplicationConfiguration config,
|
||||
EndpointDescription endpoint,
|
||||
string sessionName,
|
||||
uint sessionTimeoutMs,
|
||||
UserIdentity identity,
|
||||
CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts OPC UA subscription and monitored item management.
|
||||
/// </summary>
|
||||
internal interface ISubscriptionAdapter : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the server-assigned subscription identifier for diagnostics and reconnect workflows.
|
||||
/// </summary>
|
||||
uint SubscriptionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds a data-change monitored item and returns its client handle for tracking.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to monitor.</param>
|
||||
/// <param name="samplingIntervalMs">The sampling interval in milliseconds.</param>
|
||||
/// <param name="onDataChange">Callback when data changes. Receives (nodeIdString, DataValue).</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A client handle that can be used to remove the item.</returns>
|
||||
Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs,
|
||||
Action<string, DataValue> onDataChange, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a previously added monitored item by its client handle.
|
||||
/// </summary>
|
||||
/// <param name="clientHandle">The client handle returned when the monitored item was created.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the monitored-item removal.</param>
|
||||
Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Adds an event monitored item with the given event filter.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to monitor for events.</param>
|
||||
/// <param name="samplingIntervalMs">The sampling interval.</param>
|
||||
/// <param name="filter">The event filter defining which fields to select.</param>
|
||||
/// <param name="onEvent">Callback when events arrive. Receives the event field list.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A client handle for the monitored item.</returns>
|
||||
Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter,
|
||||
Action<EventFieldList> onEvent, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Requests a condition refresh for this subscription.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts the condition refresh request.</param>
|
||||
Task ConditionRefreshAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes all monitored items and deletes the subscription.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts subscription deletion.</param>
|
||||
Task DeleteAsync(CancellationToken ct = default);
|
||||
}
|
||||
Reference in New Issue
Block a user