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();
}
@@ -0,0 +1,20 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Configuration;
public sealed class OpcUaClientOptions
{
public required string EndpointUrl { get; init; }
public string ApplicationName { get; init; } = "EonaCat OPC UA Client";
public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Client";
public string SessionName { get; init; } = "EonaCat OPC UA Session";
public string? Username { get; init; }
public string? Password { get; init; }
public bool UseSecurity { get; init; } = true;
public bool AutoAcceptUntrustedCertificates { get; init; }
public bool CheckCertificateRevocation { get; init; } = true;
public bool AutoReconnect { get; init; } = true;
public int ReconnectPeriodMilliseconds { get; init; } = 5_000;
public int SessionTimeoutMilliseconds { get; init; } = 60_000;
public int OperationTimeoutMilliseconds { get; init; } = 15_000;
}
@@ -0,0 +1,19 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Configuration;
public sealed class OpcUaServerOptions
{
public string ApplicationName { get; init; } = "EonaCat OPC UA Server";
public string ApplicationUri { get; init; } = $"urn:{Utils.GetHostName()}:EonaCat:OpcUa:Server";
public string ProductUri { get; init; } = "urn:EonaCat:Connector:OpcUa";
public string BaseAddress { get; init; } = "opc.tcp://localhost:4840/EonaCat/Connector";
public string NamespaceUri { get; init; } = "urn:EonaCat:Connector:OpcUa:AddressSpace";
public bool EnableSecureEndpoint { get; init; } = true;
public bool AllowUnsecuredEndpoint { get; init; } = true;
public bool AutoAcceptUntrustedCertificates { get; init; }
public bool CheckCertificateRevocation { get; init; } = true;
public int OperationTimeoutMilliseconds { get; init; } = 15_000;
public int MaxSessionCount { get; init; } = 100;
public int MaxSubscriptionCount { get; init; } = 1_000;
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>EonaCat.Connections.OpcUa</Title>
<Company>EonaCat</Company>
<PackageId>EonaCat.Connections.OpcUa</PackageId>
<Version>1.0.0</Version>
<Authors>Jeroen Saey</Authors>
<Description>OPC UA client and server for EonaCat.Connections</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="2.0.1" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="2.0.1" />
</ItemGroup>
</Project>
@@ -0,0 +1,158 @@
using Opc.Ua;
using Opc.Ua.Configuration;
namespace EonaCat.Connections.OpcUa.Infrastructure;
internal static class OpcUaApplicationConfigurationFactory
{
public static async Task<ApplicationConfiguration> CreateClientAsync(
Configuration.OpcUaClientOptions options,
CancellationToken cancellationToken)
{
var configuration = CreateBase(
options.ApplicationName,
options.ApplicationUri,
ApplicationType.Client,
options.AutoAcceptUntrustedCertificates,
options.CheckCertificateRevocation,
options.OperationTimeoutMilliseconds);
configuration.ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = options.SessionTimeoutMilliseconds
};
await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false);
return configuration;
}
public static async Task<ApplicationConfiguration> CreateServerAsync(
Configuration.OpcUaServerOptions options,
CancellationToken cancellationToken)
{
var configuration = CreateBase(
options.ApplicationName,
options.ApplicationUri,
ApplicationType.Server,
options.AutoAcceptUntrustedCertificates,
options.CheckCertificateRevocation,
options.OperationTimeoutMilliseconds);
configuration.ServerConfiguration = new ServerConfiguration
{
BaseAddresses = new[] { options.BaseAddress },
SecurityPolicies = CreateSecurityPolicies(options),
UserTokenPolicies = new[]
{
new UserTokenPolicy(UserTokenType.Anonymous)
},
MaxSessionCount = options.MaxSessionCount,
MaxSubscriptionCount = options.MaxSubscriptionCount
};
await ValidateAndCreateCertificateAsync(configuration, cancellationToken).ConfigureAwait(false);
return configuration;
}
private static List<ServerSecurityPolicy> CreateSecurityPolicies(
Configuration.OpcUaServerOptions options)
{
var policies = new List<ServerSecurityPolicy>();
if (options.AllowUnsecuredEndpoint)
{
policies.Add(new ServerSecurityPolicy
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
});
}
if (options.EnableSecureEndpoint)
{
policies.Add(new ServerSecurityPolicy
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256
});
}
if (policies.Count == 0)
{
throw new ArgumentException("At least one OPC UA endpoint security policy must be enabled.", nameof(options));
}
return policies;
}
private static ApplicationConfiguration CreateBase(
string applicationName,
string applicationUri,
ApplicationType applicationType,
bool autoAcceptUntrustedCertificates,
bool checkCertificateRevocation,
int operationTimeoutMilliseconds)
{
var certificateRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"EonaCat",
"OpcUa",
applicationType.ToString());
return new ApplicationConfiguration(OpcUaRuntime.Telemetry)
{
ApplicationName = applicationName,
ApplicationUri = applicationUri,
ApplicationType = applicationType,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = "Directory",
StorePath = Path.Combine(certificateRoot, "own"),
SubjectName = $"CN={applicationName}, DC={Utils.GetHostName()}"
},
TrustedPeerCertificates = CreateTrustList(certificateRoot, "trusted"),
TrustedIssuerCertificates = CreateTrustList(certificateRoot, "issuers"),
RejectedCertificateStore = new CertificateTrustList
{
StoreType = "Directory",
StorePath = Path.Combine(certificateRoot, "rejected")
},
AutoAcceptUntrustedCertificates = autoAcceptUntrustedCertificates,
RejectSHA1SignedCertificates = true,
MinimumCertificateKeySize = 2048,
RejectUnknownRevocationStatus = checkCertificateRevocation
},
TransportConfigurations = Array.Empty<TransportConfiguration>(),
TransportQuotas = new TransportQuotas
{
OperationTimeout = operationTimeoutMilliseconds
}
};
}
private static CertificateTrustList CreateTrustList(string root, string name) => new()
{
StoreType = "Directory",
StorePath = Path.Combine(root, name)
};
private static async Task ValidateAndCreateCertificateAsync(
ApplicationConfiguration configuration,
CancellationToken cancellationToken)
{
await configuration.ValidateAsync(configuration.ApplicationType, cancellationToken).ConfigureAwait(false);
var application = new ApplicationInstance(OpcUaRuntime.Telemetry)
{
ApplicationName = configuration.ApplicationName,
ApplicationType = configuration.ApplicationType,
ApplicationConfiguration = configuration
};
if (!await application.CheckApplicationInstanceCertificatesAsync(false, 2048, cancellationToken).ConfigureAwait(false))
{
throw new InvalidOperationException("OPC UA application certificate could not be created or validated.");
}
}
}
@@ -0,0 +1,12 @@
using Opc.Ua;
using Opc.Ua.Client;
namespace EonaCat.Connections.OpcUa.Infrastructure;
internal static class OpcUaRuntime
{
private static readonly ITelemetryContext TelemetryContext = DefaultTelemetry.Create(_ => { });
public static DefaultSessionFactory SessionFactory { get; } = new(TelemetryContext);
public static ITelemetryContext Telemetry => SessionFactory.Telemetry;
}
@@ -0,0 +1,7 @@
namespace EonaCat.Connections.OpcUa.Models;
public sealed class OpcUaConnectionEventArgs : EventArgs
{
public required string EndpointUrl { get; init; }
public string? SessionName { get; init; }
}
@@ -0,0 +1,13 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed record OpcUaMethodArgument(string Name, NodeId DataType, string? Description = null);
public sealed record OpcUaMethodDefinition(
string Identifier,
string DisplayName,
IReadOnlyList<OpcUaMethodArgument> InputArguments,
IReadOnlyList<OpcUaMethodArgument> OutputArguments,
Func<IReadOnlyList<object?>, IReadOnlyList<object?>> Handler,
string? Description = null);
@@ -0,0 +1,11 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed record OpcUaNodeDefinition(
string Identifier,
string DisplayName,
NodeId DataType,
object? InitialValue = null,
byte AccessLevel = AccessLevels.CurrentReadOrWrite,
string? Description = null);
@@ -0,0 +1,11 @@
using Opc.Ua;
namespace EonaCat.Connections.OpcUa.Models;
public sealed class OpcUaValueChangedEventArgs : EventArgs
{
public required NodeId NodeId { get; init; }
public object? Value { get; init; }
public StatusCode StatusCode { get; init; }
public DateTime SourceTimestamp { get; init; }
}
@@ -0,0 +1,44 @@
using EonaCat.Connections.OpcUa.Infrastructure;
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Server;
namespace EonaCat.Connections.OpcUa.Server;
internal sealed class EonaCatOpcUaServer : StandardServer
{
private readonly string _namespaceUri;
private readonly IReadOnlyCollection<OpcUaNodeDefinition> _nodes;
private readonly IReadOnlyCollection<OpcUaMethodDefinition> _methods;
public EonaCatOpcUaServer(
string namespaceUri,
IReadOnlyCollection<OpcUaNodeDefinition> nodes,
IReadOnlyCollection<OpcUaMethodDefinition> methods)
: base(OpcUaRuntime.Telemetry)
{
_namespaceUri = namespaceUri;
_nodes = nodes;
_methods = methods;
}
public OpcUaAddressSpace? AddressSpace { get; private set; }
protected override MasterNodeManager CreateMasterNodeManager(
IServerInternal server,
ApplicationConfiguration configuration)
{
AddressSpace = new OpcUaAddressSpace(server, configuration, _namespaceUri, _nodes, _methods);
return new MasterNodeManager(server, configuration, null, AddressSpace);
}
protected override ServerProperties LoadServerProperties() => new()
{
ManufacturerName = "EonaCat",
ProductName = "EonaCat Generic OPC UA Server",
ProductUri = "urn:EonaCat:Connector:OpcUa",
SoftwareVersion = Utils.GetAssemblySoftwareVersion(),
BuildNumber = Utils.GetAssemblyBuildNumber(),
BuildDate = Utils.GetAssemblyTimestamp()
};
}
@@ -0,0 +1,197 @@
using EonaCat.Connections.OpcUa.Models;
using Opc.Ua;
using Opc.Ua.Server;
using System.Collections.Concurrent;
namespace EonaCat.Connections.OpcUa.Server;
internal sealed class OpcUaAddressSpace : CustomNodeManager2
{
private readonly IReadOnlyCollection<OpcUaNodeDefinition> _nodeDefinitions;
private readonly IReadOnlyCollection<OpcUaMethodDefinition> _methodDefinitions;
private readonly ConcurrentDictionary<string, BaseDataVariableState> _variables = new(StringComparer.Ordinal);
public OpcUaAddressSpace(
IServerInternal server,
ApplicationConfiguration configuration,
string namespaceUri,
IReadOnlyCollection<OpcUaNodeDefinition> nodeDefinitions,
IReadOnlyCollection<OpcUaMethodDefinition> methodDefinitions)
: base(server, configuration, namespaceUri)
{
_nodeDefinitions = nodeDefinitions;
_methodDefinitions = methodDefinitions;
SystemContext.NodeIdFactory = this;
}
public event EventHandler<OpcUaValueChangedEventArgs>? ValueChanged;
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references))
{
references = new List<IReference>();
externalReferences[ObjectIds.ObjectsFolder] = references;
}
var root = new FolderState(null)
{
NodeId = new NodeId("EonaCat", NamespaceIndex),
BrowseName = new QualifiedName("EonaCat", NamespaceIndex),
DisplayName = (LocalizedText)"EonaCat",
TypeDefinitionId = ObjectTypeIds.FolderType,
EventNotifier = EventNotifiers.None
};
root.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder);
references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, root.NodeId));
foreach (var definition in _nodeDefinitions)
{
AddVariable(root, definition);
}
foreach (var definition in _methodDefinitions)
{
AddMethod(root, definition);
}
AddPredefinedNode(SystemContext, root);
}
}
public NodeId ResolveNodeId(string identifier) => new(identifier, NamespaceIndex);
public bool TrySetValue(string identifier, object? value)
{
if (!_variables.TryGetValue(identifier, out var variable))
{
return false;
}
lock (Lock)
{
variable.Value = new Variant(value);
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
variable.ClearChangeMasks(SystemContext, false);
}
RaiseValueChanged(variable);
return true;
}
private void AddVariable(NodeState parent, OpcUaNodeDefinition definition)
{
var variable = new BaseDataVariableState(parent)
{
NodeId = ResolveNodeId(definition.Identifier),
BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex),
DisplayName = (LocalizedText)definition.DisplayName,
Description = (LocalizedText)definition.Description,
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
ReferenceTypeId = ReferenceTypeIds.HasComponent,
DataType = definition.DataType,
ValueRank = ValueRanks.Scalar,
AccessLevel = definition.AccessLevel,
UserAccessLevel = definition.AccessLevel,
Historizing = false,
Value = new Variant(definition.InitialValue),
StatusCode = StatusCodes.Good,
Timestamp = DateTime.UtcNow
};
variable.OnSimpleWriteValue = HandleWrite;
parent.AddChild(variable);
_variables[definition.Identifier] = variable;
}
private void AddMethod(NodeState parent, OpcUaMethodDefinition definition)
{
var method = new MethodState(parent)
{
NodeId = ResolveNodeId(definition.Identifier),
BrowseName = new QualifiedName(definition.DisplayName, NamespaceIndex),
DisplayName = (LocalizedText)definition.DisplayName,
Description = (LocalizedText)definition.Description,
ReferenceTypeId = ReferenceTypeIds.HasComponent,
Executable = true,
UserExecutable = true
};
method.InputArguments = CreateArguments(method, "InputArguments", definition.InputArguments);
method.OutputArguments = CreateArguments(method, "OutputArguments", definition.OutputArguments);
method.OnCallMethod = (_, _, inputArguments, outputArguments) =>
{
try
{
var inputs = new object?[inputArguments.Count];
for (var index = 0; index < inputs.Length; index++)
{
inputs[index] = inputArguments[index].Value;
}
var results = definition.Handler(inputs);
for (var index = 0; index < Math.Min(results.Count, outputArguments.Count); index++)
{
outputArguments[index] = new Variant(results[index]);
}
return ServiceResult.Good;
}
catch (Exception exception)
{
return new ServiceResult(exception, StatusCodes.BadUnexpectedError);
}
};
parent.AddChild(method);
}
private PropertyState<ArrayOf<Argument>> CreateArguments(
NodeState parent,
string name,
IReadOnlyList<OpcUaMethodArgument> definitions)
{
var property = PropertyState<ArrayOf<Argument>>.With<StructureBuilder<Argument>>(parent);
property.NodeId = new NodeId($"{parent.NodeId.Identifier}.{name}", NamespaceIndex);
property.BrowseName = (QualifiedName)(name == "InputArguments" ? BrowseNames.InputArguments : BrowseNames.OutputArguments);
property.DisplayName = (LocalizedText)name;
property.TypeDefinitionId = VariableTypeIds.PropertyType;
property.ReferenceTypeId = ReferenceTypeIds.HasProperty;
property.DataType = DataTypeIds.Argument;
property.ValueRank = ValueRanks.OneDimension;
property.Value = definitions.Select(definition => new Argument
{
Name = definition.Name,
DataType = definition.DataType,
ValueRank = ValueRanks.Scalar,
Description = (LocalizedText)definition.Description
}).ToArray();
return property;
}
private ServiceResult HandleWrite(ISystemContext context, NodeState node, ref Variant value)
{
if (node is not BaseDataVariableState variable || (variable.AccessLevel & AccessLevels.CurrentWrite) == 0)
{
return StatusCodes.BadNotWritable;
}
variable.Value = value;
variable.Timestamp = DateTime.UtcNow;
variable.StatusCode = StatusCodes.Good;
RaiseValueChanged(variable);
return ServiceResult.Good;
}
private void RaiseValueChanged(BaseDataVariableState variable)
{
ValueChanged?.Invoke(this, new OpcUaValueChangedEventArgs
{
NodeId = variable.NodeId,
Value = variable.Value.Value,
StatusCode = variable.StatusCode,
SourceTimestamp = variable.Timestamp.ToDateTime()
});
}
}
@@ -0,0 +1,170 @@
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();
}