This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 07:53:40 +01:00
1 parent 2c5b69bf2c
commit 22dee59f47
132 files changed
+19653 -7192

No files matched your search

@@ -0,0 +1,309 @@
using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Client;
using System.Text;
using OpcUaClientOptions = EonaCat.Connections.OpcUa.Configuration.OpcUaClientOptions;
namespace EonaCat.Connections.OpcUa.Client;
public sealed class OpcUaNetworkClient : IAsyncDisposable, IDisposable
{
private readonly OpcUaClientOptions _options;
private readonly SemaphoreSlim _lifecycleLock = new(1, 1);
private ApplicationConfiguration? _configuration;
private ISession? _session;
private SessionReconnectHandler? _reconnectHandler;
private bool _disposed;
public OpcUaNetworkClient(OpcUaClientOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public bool IsConnected => _session?.Connected == true;
public ISession? Session => _session;
public string EndpointUrl => _options.EndpointUrl;
public event EventHandler<OpcUaConnectionEventArgs>? Connected;
public event EventHandler<OpcUaConnectionEventArgs>? Disconnected;
public event EventHandler<Exception>? Error;
public NodeId GetNodeId(string namespaceUri, string identifier)
{
ArgumentException.ThrowIfNullOrWhiteSpace(namespaceUri);
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
var namespaceIndex = GetSession().NamespaceUris.GetIndex(namespaceUri);
if (namespaceIndex < 0)
{
throw new ArgumentException($"Namespace '{namespaceUri}' is not registered by the server.", nameof(namespaceUri));
}
return new NodeId(identifier, (ushort)namespaceIndex);
}
public async Task<bool> ConnectAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsConnected)
{
return true;
}
_configuration ??= await OpcUaApplicationConfigurationFactory
.CreateClientAsync(_options, cancellationToken)
.ConfigureAwait(false);
var endpointDescription = await CoreClientUtils.SelectEndpointAsync(
_configuration,
_options.EndpointUrl,
_options.UseSecurity,
_options.OperationTimeoutMilliseconds,
OpcUaRuntime.Telemetry,
cancellationToken).ConfigureAwait(false);
var endpoint = new ConfiguredEndpoint(
null,
endpointDescription,
EndpointConfiguration.Create(_configuration));
var identity = string.IsNullOrWhiteSpace(_options.Username)
? new UserIdentity()
: new UserIdentity(
_options.Username,
Encoding.UTF8.GetBytes(_options.Password ?? string.Empty));
_session = await OpcUaRuntime.SessionFactory.CreateAsync(
_configuration,
endpoint,
false,
_options.SessionName,
(uint)_options.SessionTimeoutMilliseconds,
identity,
default,
cancellationToken).ConfigureAwait(false);
_session.KeepAlive += HandleKeepAlive;
Connected?.Invoke(this, CreateConnectionEventArgs());
return true;
}
catch (Exception exception)
{
Error?.Invoke(this, exception);
return false;
}
finally
{
_lifecycleLock.Release();
}
}
public async Task<IReadOnlyList<ReferenceDescription>> BrowseAsync(
NodeId? nodeId = null,
CancellationToken cancellationToken = default)
{
var session = GetSession();
var browser = new Browser(session)
{
BrowseDirection = BrowseDirection.Forward,
NodeClassMask = (int)(NodeClass.Object | NodeClass.Variable | NodeClass.Method),
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true
};
var references = await browser.BrowseAsync(nodeId ?? ObjectIds.ObjectsFolder, cancellationToken).ConfigureAwait(false);
return references.ToArray();
}
public async Task<DataValue> ReadAsync(NodeId nodeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeId);
return await GetSession().ReadValueAsync(nodeId, cancellationToken).ConfigureAwait(false);
}
public async Task WriteAsync(NodeId nodeId, object? value, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeId);
var values = new[]
{
new WriteValue
{
NodeId = nodeId,
AttributeId = Attributes.Value,
Value = new DataValue(new Variant(value))
}
};
var response = await GetSession().WriteAsync(null, values, cancellationToken).ConfigureAwait(false);
if (StatusCode.IsBad(response.Results[0]))
{
throw new ServiceResultException(response.Results[0]);
}
}
public async Task<IReadOnlyList<object?>> CallAsync(
NodeId objectId,
NodeId methodId,
IEnumerable<object?>? arguments = null,
CancellationToken cancellationToken = default)
{
var request = new CallMethodRequest
{
ObjectId = objectId,
MethodId = methodId,
InputArguments = (arguments ?? []).Select(value => new Variant(value)).ToArray()
};
var methods = new[] { request };
var response = await GetSession().CallAsync(null, methods, cancellationToken).ConfigureAwait(false);
var result = response.Results[0];
if (StatusCode.IsBad(result.StatusCode))
{
throw new ServiceResultException(result.StatusCode);
}
return result.OutputArguments.ToArray().Select(argument => argument.Value).ToArray();
}
public async Task<OpcUaSubscription> SubscribeAsync(
IEnumerable<NodeId> nodeIds,
EventHandler<OpcUaValueChangedEventArgs> handler,
int publishingIntervalMilliseconds = 1_000,
int samplingIntervalMilliseconds = 1_000,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(nodeIds);
ArgumentNullException.ThrowIfNull(handler);
var session = GetSession();
var subscription = new Subscription(session.DefaultSubscription)
{
PublishingInterval = publishingIntervalMilliseconds
};
foreach (var nodeId in nodeIds)
{
var item = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = nodeId,
AttributeId = Attributes.Value,
SamplingInterval = samplingIntervalMilliseconds,
QueueSize = 10,
DiscardOldest = true
};
item.Notification += (monitoredItem, _) =>
{
foreach (var value in monitoredItem.DequeueValues())
{
handler(this, new OpcUaValueChangedEventArgs
{
NodeId = nodeId,
Value = value.WrappedValue.Value,
StatusCode = value.StatusCode,
SourceTimestamp = value.SourceTimestamp.ToDateTime()
});
}
};
subscription.AddItem(item);
}
session.AddSubscription(subscription);
await subscription.CreateAsync(cancellationToken).ConfigureAwait(false);
return new OpcUaSubscription(subscription);
}
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
_reconnectHandler?.Dispose();
_reconnectHandler = null;
if (_session != null)
{
_session.KeepAlive -= HandleKeepAlive;
await _session.CloseAsync(cancellationToken).ConfigureAwait(false);
_session.Dispose();
_session = null;
Disconnected?.Invoke(this, CreateConnectionEventArgs());
}
}
finally
{
_lifecycleLock.Release();
}
}
private ISession GetSession()
{
if (_session?.Connected != true)
{
throw new InvalidOperationException("The OPC UA client is not connected.");
}
return _session;
}
private void HandleKeepAlive(ISession session, KeepAliveEventArgs args)
{
if (ServiceResult.IsGood(args.Status))
{
return;
}
Disconnected?.Invoke(this, CreateConnectionEventArgs());
if (!_options.AutoReconnect || _reconnectHandler != null)
{
return;
}
var currentSession = _session;
if (currentSession == null)
{
return;
}
_reconnectHandler = new SessionReconnectHandler(OpcUaRuntime.Telemetry);
_reconnectHandler.BeginReconnect(
currentSession,
_options.ReconnectPeriodMilliseconds,
(_, _) =>
{
if (_reconnectHandler?.Session is ISession reconnectedSession)
{
_session = reconnectedSession;
_session.KeepAlive += HandleKeepAlive;
Connected?.Invoke(this, CreateConnectionEventArgs());
}
_reconnectHandler?.Dispose();
_reconnectHandler = null;
});
}
private OpcUaConnectionEventArgs CreateConnectionEventArgs() => new()
{
EndpointUrl = _options.EndpointUrl,
SessionName = _session?.SessionName
};
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await DisconnectAsync().ConfigureAwait(false);
_disposed = true;
_lifecycleLock.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}
@@ -0,0 +1,30 @@
using Opc.Ua.Client;
namespace EonaCat.Connections.OpcUa.Client;
public sealed class OpcUaSubscription : IAsyncDisposable, IDisposable
{
private readonly Subscription _subscription;
private bool _disposed;
internal OpcUaSubscription(Subscription subscription)
{
_subscription = subscription;
}
public uint Id => _subscription.Id;
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
await _subscription.DeleteAsync(true, CancellationToken.None).ConfigureAwait(false);
_subscription.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}