Files
2026-11-04 07:53:40 +01:00

171 lines
5.5 KiB
C#

using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Configuration;
namespace EonaCat.Connections.OpcUa.Server;
public sealed class OpcUaNetworkServer : IAsyncDisposable, IDisposable
{
private readonly OpcUaServerOptions _options;
private readonly List<OpcUaNodeDefinition> _nodes = [];
private readonly List<OpcUaMethodDefinition> _methods = [];
private readonly SemaphoreSlim _lifecycleLock = new(1, 1);
private ApplicationInstance? _application;
private EonaCatOpcUaServer? _server;
private bool _disposed;
public OpcUaNetworkServer(OpcUaServerOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public bool IsStarted { get; private set; }
public string EndpointUrl => _options.BaseAddress;
public string NamespaceUri => _options.NamespaceUri;
public event EventHandler? Started;
public event EventHandler? Stopped;
public event EventHandler<OpcUaValueChangedEventArgs>? ValueChanged;
public event EventHandler<Exception>? Error;
public OpcUaNetworkServer AddVariable(OpcUaNodeDefinition definition)
{
EnsureNotStarted();
ArgumentNullException.ThrowIfNull(definition);
if (_nodes.Any(node => string.Equals(node.Identifier, definition.Identifier, StringComparison.Ordinal)))
{
throw new ArgumentException($"A node with identifier '{definition.Identifier}' is already registered.", nameof(definition));
}
_nodes.Add(definition);
return this;
}
public OpcUaNetworkServer AddMethod(OpcUaMethodDefinition definition)
{
EnsureNotStarted();
ArgumentNullException.ThrowIfNull(definition);
if (_methods.Any(method => string.Equals(method.Identifier, definition.Identifier, StringComparison.Ordinal)))
{
throw new ArgumentException($"A method with identifier '{definition.Identifier}' is already registered.", nameof(definition));
}
_methods.Add(definition);
return this;
}
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsStarted)
{
return;
}
var configuration = await OpcUaApplicationConfigurationFactory
.CreateServerAsync(_options, cancellationToken)
.ConfigureAwait(false);
_server = new EonaCatOpcUaServer(_options.NamespaceUri, _nodes.ToArray(), _methods.ToArray());
_application = new ApplicationInstance(OpcUaRuntime.Telemetry)
{
ApplicationName = _options.ApplicationName,
ApplicationType = ApplicationType.Server,
ApplicationConfiguration = configuration
};
await _application.StartAsync(_server).ConfigureAwait(false);
if (_server.AddressSpace != null)
{
_server.AddressSpace.ValueChanged += HandleValueChanged;
}
IsStarted = true;
Started?.Invoke(this, EventArgs.Empty);
}
catch (Exception exception)
{
Error?.Invoke(this, exception);
throw;
}
finally
{
_lifecycleLock.Release();
}
}
public NodeId GetNodeId(string identifier)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
return _server?.AddressSpace?.ResolveNodeId(identifier)
?? throw new InvalidOperationException("The OPC UA server has not started.");
}
public bool TrySetValue(string identifier, object? value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identifier);
return _server?.AddressSpace?.TrySetValue(identifier, value) == true;
}
public async Task StopAsync(CancellationToken cancellationToken = default)
{
await _lifecycleLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (!IsStarted)
{
return;
}
if (_server?.AddressSpace != null)
{
_server.AddressSpace.ValueChanged -= HandleValueChanged;
}
if (_application != null)
{
await _application.StopAsync().ConfigureAwait(false);
}
_server?.Dispose();
_server = null;
_application = null;
IsStarted = false;
Stopped?.Invoke(this, EventArgs.Empty);
}
finally
{
_lifecycleLock.Release();
}
}
private void HandleValueChanged(object? sender, OpcUaValueChangedEventArgs args) =>
ValueChanged?.Invoke(this, args);
private void EnsureNotStarted()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (IsStarted)
{
throw new InvalidOperationException("Nodes and methods must be registered before the OPC UA server starts.");
}
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
await StopAsync().ConfigureAwait(false);
_disposed = true;
_lifecycleLock.Dispose();
}
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
}