using System.Text.Json; using Gateway.Api.Domain; using Gateway.Api.Options; using Gateway.Api.Services; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Opc.Ua; #pragma warning disable CS0618 internal static class OpcUaClientTests { public static async Task RunAsync(GatewayStore remote, GatewayOpcUaServer server, string url, GatewayPoint remotePoint, ApplicationConfiguration serverConfiguration) { var options = Options.Create(new GatewayOptions { DataDirectory = Path.Combine(Path.GetTempPath(), "seiugw-ua-client-" + Guid.NewGuid().ToString("N")), Bacnet = new BacnetBootstrapOptions { Interface = "lo", DeviceInstance = 24, IpPort = 47829 } }); var database = new GatewayDatabase(options); var store = new GatewayStore(database, new PasswordService(), new MappingValidator(), new SecretProtector(options), options); store.Initialize(); var applications = new OpcUaApplicationFactory(database); var config = await applications.CreateClientConfigurationAsync(); using (var trust = config.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(serverConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate); using (var trust = serverConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(config.SecurityConfiguration.ApplicationCertificate.Certificate); await serverConfiguration.CertificateValidator.UpdateAsync(serverConfiguration.SecurityConfiguration); var client = store.SaveOpcUaClient(new SaveOpcUaClientRequest(new OpcUaClientConfiguration(Guid.NewGuid(), "Wire client", url, OpcUaAuthenticationMode.Username, "admin", PublishingIntervalMilliseconds: 100), "correct horse battery staple")).Configuration; store.SaveOpcUaClient(new SaveOpcUaClientRequest(client)); // Blank edit retains the encrypted password. Check(store.GetOpcUaClientCredentials(client.Id).Password == "correct horse battery staple", "Saved password must survive edits."); using (var connection = database.OpenConnection()) using (var command = connection.CreateCommand()) { command.CommandText = "SELECT value FROM settings WHERE key LIKE 'opcua.password.%'"; Check(!((string)command.ExecuteScalar()!).Contains("correct horse", StringComparison.Ordinal), "OPC UA password must be encrypted at rest."); } var browser = new OpcUaBrowserService(applications, store); var browsed = await browser.BrowseAsync(new OpcUaBrowseRequest("", "nsu=" + GatewayOpcUaServer.PointsNamespace + ";s=Gateway", ClientId: client.Id)); var item = browsed.Single(item => item.DisplayName == remotePoint.DisplayName); Check(item.ValueType == "Float" && item.Writable && item.StableNodeId!.Contains("nsu=", StringComparison.Ordinal), "Import needs scalar type, access and a stable namespace URI."); var imported = store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)])); var point = imported.Single(); Check(store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)])).Count == 0, "Duplicate import must not create duplicate writers."); var local = store.CreatePoint(new CreatePointRequest("Local setpoint", PointProtocol.Internal, PointScope.Internal, "Float", true, true, null, JsonSerializer.SerializeToElement(new { }))); store.CreateMapping(new CreateMappingRequest(local.Id, point.Id, MappingDirection.Bidirectional, true, null, false, JsonSerializer.SerializeToElement(new { }))); using var mappings = new MappingRuntimeService(store, new WriteJournal()); using var runtime = new OpcUaClientService(store, applications, NullLogger.Instance); await mappings.StartAsync(CancellationToken.None); await runtime.StartAsync(CancellationToken.None); var writes = 0; void Count(object? sender, PointValue update) { if (update.PointId == remotePoint.Id) Interlocked.Increment(ref writes); } remote.PointValueUpdated += Count; try { await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good")); Check(writes == 0, "Initial synchronization must never write to the remote device."); store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(37.25), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good"); await Until(() => remote.ListPointValues().Any(value => value.PointId == remotePoint.Id && value.Value.GetSingle() == 37.25f)); server.RefreshPoints(false); await Task.Delay(700); Check(writes == 1, "A mapped command and its subscription echo must produce exactly one remote write."); remote.SetPointValue(remotePoint.Id, JsonSerializer.SerializeToElement(38.5), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good"); server.RefreshPoints(false); await Until(() => store.ListPointValues().Any(value => value.PointId == local.Id && value.Value.ValueKind == JsonValueKind.Number && value.Value.GetDouble() == 38.5)); Check(writes == 2, "A remote update must reach the reverse mapping without being written back."); store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(99), PointProtocol.Internal, DateTimeOffset.UtcNow, "BadNotConnected"); await Task.Delay(350); Check(writes == 2, "Bad quality must never actuate an external point."); var active = server.CurrentInstance.SessionManager.GetSessions().Single(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client"); server.CurrentInstance.CloseSession(null, active.Id, true); await Until(() => server.CurrentInstance.SessionManager.GetSessions().Any(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client" && session.Id != active.Id), 25000); await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good")); Check(writes == 2, "Reconnect must rebuild subscriptions, read current values and never replay commands."); Console.WriteLine("OPC UA client tests passed: encrypted credentials, typed import, subscription, bidirectional mapping, no echo, bad quality, reconnect."); } finally { remote.PointValueUpdated -= Count; await runtime.StopAsync(CancellationToken.None); await mappings.StopAsync(CancellationToken.None); } } private static async Task Until(Func predicate, int timeout = 12000) { var limit = DateTime.UtcNow.AddMilliseconds(timeout); while (!predicate()) { if (DateTime.UtcNow > limit) throw new InvalidOperationException("OPC UA client condition timed out."); await Task.Delay(50); } } private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } } #pragma warning restore CS0618