Add comprehensive smoke and feature tests for Gateway API

- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality.
- Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management.
- Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications.
- Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing.
- Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
This commit is contained in:
jhartworks committed 2026-11-19 16:06:54 +01:00
1 parent d9165a60ff
commit 98c48d9d78
80 files changed
+11120 -315

No files matched your search

@@ -0,0 +1,37 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Services;
using Microsoft.Extensions.Logging.Abstractions;
internal static class BacnetBridgeTests
{
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
{
var point = store.CreatePoint(new CreatePointRequest("Native priority bridge AV", PointProtocol.Bacnet, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue));
var trend = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "Native observed trend", 902, 1, 100, true));
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(22), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good", bacnetPriority: 16);
Check(store.ListPointValues().All(value => value.PointId != point.Id), "A BACnet command must not become an effective value before native arbitration.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 0, "Commands must not be trended as actual values.");
using var connection = database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT priority FROM bacnet_commands WHERE point_id=$id";
command.Parameters.AddWithValue("$id", point.Id.ToString());
Check((long)command.ExecuteScalar()! == 16, "BACnet priority must reach the native queue.");
command.CommandText = "INSERT OR REPLACE INTO bacnet_runtime VALUES(1,$time,'Test'); INSERT INTO bacnet_observations(point_id,value_json,status,observed_ms) VALUES($id,'30','Good',$time)";
command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); command.ExecuteNonQuery();
using var bridge = new BacnetNativeBridgeService(database, store, NullLogger<BacnetNativeBridgeService>.Instance);
await bridge.StartAsync(CancellationToken.None);
try
{
var deadline = DateTime.UtcNow.AddSeconds(3);
while (store.ListPointValues().All(value => value.PointId != point.Id)) { if (DateTime.UtcNow > deadline) throw new InvalidOperationException("Native observation timed out."); await Task.Delay(25); }
Check(store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetInt32() == 30, "Native arbitration must determine the effective value.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 1, "Native observations must feed the trend once.");
command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE point_id=$id";
Check((long)command.ExecuteScalar()! == 1, "Native feedback must not enqueue another write.");
}
finally { await bridge.StopAsync(CancellationToken.None); }
Console.WriteLine("BACnet bridge tests passed: command/observation separation, priority transport, effective-value trend, no echo.");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
+137
View File
@@ -0,0 +1,137 @@
using System.Net;
using System.Text.Json;
using Gateway.Api.Contracts;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
internal static class LtdFeatureTests
{
private static readonly string[] WhatsAppFieldNames = ["api_key", "message", "number", "pn", "template"];
public static async Task RunAsync(GatewayStore store, GatewayDatabase database, IOptions<GatewayOptions> options, AuthenticatedGatewayUser admin)
{
var source = store.CreatePoint(new CreatePointRequest("Vorlauftemperatur", PointProtocol.Bacnet, PointScope.Gateway,
"Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue, 601));
var opc = store.CreatePoint(new CreatePointRequest("OPC-UA Betriebszustand", PointProtocol.OpcUa, PointScope.Gateway,
"Boolean", true, true, null, JsonSerializer.SerializeToElement(new { })));
var bacnetLog = store.CreateTrendLog(new CreateTrendLogRequest(source.Id, "Vorlauftemperatur", 601, 1, 1000, true));
var opcLog = store.CreateTrendLog(new CreateTrendLogRequest(opc.Id, "Betriebszustand", 602, 1, 1000, true));
var start = DateTimeOffset.UtcNow.AddHours(-2);
for (var index = 0; index < 120; index++)
{
store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(25 + Math.Sin(index / 15d) * 3), PointProtocol.Bacnet, start.AddMinutes(index));
store.SetPointValue(opc.Id, JsonSerializer.SerializeToElement(index % 20 < 10), PointProtocol.OpcUa, start.AddMinutes(index));
}
Check(store.ListTrendRecords(bacnetLog.Id, 200).Count == 120 && store.ListTrendRecords(opcLog.Id, 200).Count == 120,
"Gateway-owned BACnet and OPC UA point updates must feed their internal trends.");
store.SaveDisplayUnit(new DisplayUnit("bar", "Bar"));
store.SaveDisplayUnit(new DisplayUnit("°C", "Grad Celsius", false));
Check(store.ListDisplayUnits().Single(unit => unit.Symbol == "°C").IsSystem, "System units must retain their identity.");
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#12d0d3"), new(opc.Id, "Betrieb Anlage 1", "bool", 1, "digital", "#27e72e")]);
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#c9dc1e")]);
Check(store.ListPointPresentations().Count == 2, "Partial alias updates must not delete other aliases.");
var export = store.ListTrendExportRows([bacnetLog.Id], start);
Check(export.Count == 120 && export.All(row => row.PointName == "Vorlauf Anlage 1" && row.Unit == "°C"), "CSV exports must use the configured aliases and units.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "missing", 1, "analog", "#ffffff")]), "Unknown units must be rejected.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "°C", 1, "analog", "red;display:none")]), "CSS injection must be rejected.");
var selection = store.CreateTrendSelection(new CreateTrendSelectionRequest("Heizkreis", null, false, [bacnetLog.Id]), admin.User.Id);
store.SaveDashboard(admin.User.Id, true, [new(Guid.NewGuid(), "Heizkreis – Vorlauf", selection.Id, 24, "Graph")]);
Check(store.GetDashboard(admin.User.Id).Count == 1, "Widgets must persist per user.");
var viewer = store.CreateUser(new CreateUserRequest("ltd.viewer", "LTD Viewer", null, "safe testing password", "viewer"));
Reject(() => store.SaveDashboard(viewer.Id, false, [new(Guid.NewGuid(), "Private", selection.Id, 24, "Graph")]), "Other users' private selections must not be added to dashboards.");
store.UpdateKomariEnrollmentToken("test-komari-enrollment");
var tokenPath = Path.Combine(options.Value.DataDirectory, "token-test");
Check(store.MaterializeKomariEnrollmentToken(tokenPath) && File.ReadAllText(tokenPath) == "test-komari-enrollment", "Encrypted Komari token must materialize for the agent.");
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new("test-secret-" + channel));
using (var connection = database.OpenConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT value FROM settings WHERE key LIKE 'integration.%.api-key' OR key = 'komari.enrollment-token';";
using var reader = command.ExecuteReader();
while (reader.Read()) Check(!reader.GetString(0).Contains("test-", StringComparison.Ordinal), "Keys must not be stored in plaintext.");
}
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Saved keys must roundtrip.");
store.UpdateNotificationKey(NotificationChannel.Mail, new(null));
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Empty key edit must retain an existing key.");
Check(NotificationTransport.NormalizeTemplateText(" Störung\r\n\t Küche 21 °C 😀 ") == "Störung Küche 21 °C 😀", "WhatsApp must normalize whitespace and preserve Unicode.");
Reject(() => NotificationTransport.NormalizeTemplateText(new string('a', 1025)), "Overlong template parameters must not be truncated or sent.");
var destination = new AlarmDestination(NotificationChannel.WhatsApp, "+491234567890", "stoerung", "Prüfung");
var rule = store.SaveAlarmRule(new AlarmRule(Guid.Empty, "Vorlauf hoch", source.Id, AlarmCondition.Above, 30, 2, true, true, "Temperatur prüfen\nHeizkreis 1", [destination]));
var alarmTime = DateTimeOffset.UtcNow;
void Observe(double value, int seconds, string? status = null) => store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(value), PointProtocol.Bacnet, alarmTime.AddSeconds(seconds), status);
Observe(29, 1); Check(store.ListNotificationDeliveries().Count == 0, "Initial normal state must not send a recovery.");
Observe(31, 2); Observe(31, 3); Observe(29, 4);
Check(store.ListNotificationDeliveries().Count == 1, "Unchanged and hysteresis-band values must not repeat an alarm.");
var delivery = store.ClaimNotification()!;
Check(delivery.State == "Sending" && store.ClaimNotification() is null, "A notification can be claimed only once.");
using (var form = NotificationTransport.BuildAlarmForm("mock-key", delivery))
{
var fields = new Dictionary<string, string>();
foreach (var part in form) fields[part.Headers.ContentDisposition!.Name!.Trim('"')] = await part.ReadAsStringAsync();
Check(fields.Keys.Order().SequenceEqual(WhatsAppFieldNames.Order()), "WhatsApp form fields must match the supplied PHP API.");
Check(!fields["message"].Contains('\n') && fields["message"].Contains("prüfen", StringComparison.Ordinal), "Sent template variables must be normalized Unicode text.");
}
store.RecoverInterruptedNotifications();
Check(store.ListNotificationDeliveries().Single().State == "Unknown", "Uncertain sends must not be automatically duplicated after restart.");
Observe(27, 5); Observe(32, 4); Observe(33, 6, "bad");
Check(store.ListNotificationDeliveries().Count == 2, "Recovery should send once; stale or invalid-quality observations must not alarm.");
store.SaveAlarmRule(rule with { Message = "Neue Beschreibung" });
Observe(27, 7);
Check(store.ListNotificationDeliveries().Count == 2, "Editing descriptions must preserve alarm edge state.");
Observe(31, 8);
Check(store.ListNotificationDeliveries().Count == 3, "A new rising edge must send again.");
store.DeleteAlarmRule(rule.Id);
Check(store.ClaimNotification() is null, "Deleting a rule must cancel pending sends.");
store.UpdateNotificationKey(NotificationChannel.WhatsApp, new(null, true));
Reject(() => store.SaveAlarmRule(rule with { Id = Guid.Empty }), "A channel without a key must not activate an alarm.");
var handler = new FakeNotificationHandler();
var transport = new NotificationTransport(new FakeClientFactory(handler));
await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None);
Check(handler.Address == "https://whatsappapi.se-inno.de/" && handler.Multipart, "Notifications must use the fixed endpoint and multipart forms.");
handler.ResponseBody = "{\"success\":false,\"error\":\"secret raw response\"}";
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("API error should fail."); }
catch (DomainValidationException exception) { Check(!exception.Message.Contains("secret raw", StringComparison.Ordinal), "Remote response must not leak into logs or UI."); }
handler.ResponseBody = "{}"; handler.Status = HttpStatusCode.BadRequest;
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("HTTP error should fail."); }
catch (DomainValidationException) { }
var sessions = new SessionService(store);
var session = "Bearer " + sessions.Create(store.Authenticate(viewer.Username, "safe testing password")!);
Check(sessions.IsValid(session), "Viewer session must initially authenticate.");
store.UpdateUser(viewer.Id, new(null, null, null, null, null, false), admin.User.Id);
Check(!sessions.IsValid(session), "Disabling users must revoke existing sessions immediately.");
// Leave preview fixtures inert: no credentials or active alarm rules can send messages.
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new(null, true));
var configuration = store.GetGatewayConfiguration();
store.UpdateGatewayConfiguration(configuration with { OpcUa = configuration.OpcUa with { ServerEnabled = false }, Mqtt = (configuration.Mqtt ?? MqttConfiguration.CreateDefault()) with { Enabled = false }, ModbusServers = [] });
Console.WriteLine("LTD presentation, notifications, encryption and session tests passed (no real API messages).");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
private static void Reject(Action action, string message)
{
try { action(); } catch (DomainValidationException) { return; }
throw new InvalidOperationException(message);
}
private sealed class FakeClientFactory(FakeNotificationHandler handler) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private sealed class FakeNotificationHandler : HttpMessageHandler
{
public string? Address { get; private set; }
public bool Multipart { get; private set; }
public string ResponseBody { get; set; } = "{\"success\":true}";
public HttpStatusCode Status { get; set; } = HttpStatusCode.OK;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Address = request.RequestUri!.AbsoluteUri;
Multipart = request.Content is MultipartFormDataContent;
return Task.FromResult(new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) });
}
}
}
@@ -0,0 +1,89 @@
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<OpcUaClientService>.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<bool> 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
@@ -0,0 +1,128 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Contracts;
using Gateway.Api.Services;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
#pragma warning disable CS0618 // Exercise the same pinned SDK API as production.
internal static class OpcUaFeatureTests
{
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
{
var previous = store.GetGatewayConfiguration();
using var portReservation = new TcpListener(IPAddress.Loopback, 0);
portReservation.Start();
var port = ((IPEndPoint)portReservation.LocalEndpoint).Port;
portReservation.Stop();
store.UpdateGatewayConfiguration(previous with { OpcUa = previous.OpcUa with { Port = port, ServerEnabled = true, AllowAnonymous = true } });
var point = store.CreatePoint(new CreatePointRequest("UA Sollwert", PointProtocol.OpcUa, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { })));
var readOnly = store.CreatePoint(new CreatePointRequest("UA Eingang", PointProtocol.OpcUa, PointScope.Gateway, "Boolean", true, false, null, JsonSerializer.SerializeToElement(new { })));
var history = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "UA Drahttest", 901, 1, 100, true));
var applications = new OpcUaApplicationFactory(database);
var configuration = await applications.CreateServerConfigurationAsync(port, true);
configuration.ServerConfiguration.MaxBrowseContinuationPoints = 20;
var application = new ApplicationInstance(configuration);
var server = new GatewayOpcUaServer(store);
var updates = 0;
store.PointValueUpdated += Count;
void Count(object? sender, PointValue value) { if (value.PointId == point.Id) Interlocked.Increment(ref updates); }
try
{
await application.StartAsync(server);
var clientConfiguration = await applications.CreateClientConfigurationAsync();
// Explicitly trust this exact local test server; never bypass arbitrary certificate errors.
using (var trust = clientConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore())
{
var certificate = configuration.SecurityConfiguration.ApplicationCertificate.Certificate;
if ((await trust.FindByThumbprintAsync(certificate.Thumbprint)).Count == 0) await trust.AddAsync(certificate);
}
await clientConfiguration.CertificateValidator.UpdateAsync(clientConfiguration.SecurityConfiguration);
var url = $"opc.tcp://127.0.0.1:{port}";
var selected = await CoreClientUtils.SelectEndpointAsync(clientConfiguration, url, true, 15_000, CancellationToken.None);
var endpoint = new ConfiguredEndpoint(null, selected, EndpointConfiguration.Create(clientConfiguration));
using var session = await Session.Create(clientConfiguration, endpoint, false, true, "Gateway wire test", 60_000,
new UserIdentity("admin", Encoding.UTF8.GetBytes("correct horse battery staple")), null);
var index = (ushort)session.NamespaceUris.GetIndex(GatewayOpcUaServer.PointsNamespace);
var node = new NodeId(point.Id, index);
session.Browse(null, null, new NodeId("Gateway", index), 100, BrowseDirection.Forward, ReferenceTypeIds.Organizes, true, (uint)NodeClass.Variable, out _, out var references);
Check(references.Any(reference => reference.NodeId == node), "Gateway variable must be browsable with a stable GUID node id.");
session.Read(null, 0, TimestampsToReturn.Both, [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], out var initial, out _);
Check(initial[0].StatusCode == StatusCodes.BadWaitingForInitialData, "Missing values must not appear as good zeroes.");
var notified = new TaskCompletionSource<float>(TaskCreationOptions.RunContinuationsAsynchronously);
using var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = node, AttributeId = Attributes.Value, SamplingInterval = 100, QueueSize = 10, DiscardOldest = true };
item.Notification += (_, _) =>
{
foreach (var data in item.DequeueValues())
if (data.StatusCode == StatusCodes.Good && data.Value is float number && number == 24.5f) notified.TrySetResult(number);
};
subscription.AddItem(item);
session.AddSubscription(subscription);
subscription.Create();
Check(Write(session, node, 21.5f) == StatusCodes.Good, "Authenticated scalar writes must be accepted.");
Check(updates == 1 && store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetSingle() == 21.5f, "UA write must enter the common store exactly once.");
Check(store.ListTrendRecords(history.Id, 10).Count == 1, "UA write must feed the configured trend.");
Check(Write(session, node, true) == StatusCodes.BadTypeMismatch, "Boolean must not overwrite a Real point.");
Check(Write(session, new NodeId(readOnly.Id, index), true) == StatusCodes.BadNotWritable, "Read-only input must reject writes.");
Check(updates == 1, "Rejected writes must not enter the point store.");
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(24.5), PointProtocol.Internal, DateTimeOffset.UtcNow.AddSeconds(2), "Good");
server.RefreshPoints(false);
await notified.Task.WaitAsync(TimeSpan.FromSeconds(10));
Check(updates == 2 && store.ListTrendRecords(history.Id, 10).Count == 2, "Subscription notifications must not echo into the store or trend.");
var late = store.CreatePoint(new CreatePointRequest("UA später angelegt", PointProtocol.OpcUa, PointScope.Gateway, "String", true, true, null, JsonSerializer.SerializeToElement(new { })));
server.RefreshPoints(true);
Check(Write(session, new NodeId(late.Id, index), "ÄÖÜ ✓") == StatusCodes.Good, "New nodes must appear without a server restart and support Unicode.");
var browsed = await new OpcUaBrowserService(applications).BrowseAsync(new OpcUaBrowseRequest(url, new NodeId("Gateway", index).ToString(), true, OpcUaAuthenticationMode.Username, "admin", "correct horse battery staple"));
Check(browsed.Any(value => value.NodeId == new NodeId(late.Id, index).ToString() && value.Value?.GetString() == "ÄÖÜ ✓"), "The web browser service must authenticate, browse and read real server variables.");
using var anonymous = await Session.Create(clientConfiguration, endpoint, false, "Anonymous read-only test", 60_000, new UserIdentity(), null);
Check(StatusCode.IsBad(Write(anonymous, node, 31f)), "Anonymous sessions must not write process values.");
using var viewer = await Session.Create(clientConfiguration, endpoint, false, "Viewer read-only test", 60_000, new UserIdentity("trend.viewer", Encoding.UTF8.GetBytes("another secure password")), null);
Check(StatusCode.IsBad(Write(viewer, node, 31f)), "Viewer accounts must not write process values.");
try
{
using var invalid = await Session.Create(clientConfiguration, endpoint, false, "Wrong password test", 60_000, new UserIdentity("admin", Encoding.UTF8.GetBytes("wrong password")), null);
throw new InvalidOperationException("Invalid password was accepted.");
}
catch (ServiceResultException exception) when (exception.StatusCode == StatusCodes.BadUserAccessDenied) { }
var viewerAccount = store.ListUsers().Single(user => user.Username == "trend.viewer");
var admin = store.ListUsers().Single(user => user.Username == "admin");
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, false), admin.Id);
server.RefreshPoints(true);
Check(server.CurrentInstance.SessionManager.GetSessions().All(active => active.Id != viewer.SessionId), "Revoking a user must close its existing OPC UA session and subscriptions.");
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, true), admin.Id);
await viewer.CloseAsync();
await anonymous.CloseAsync();
subscription.Delete(true);
await session.CloseAsync();
await OpcUaClientTests.RunAsync(store, server, url, point, configuration);
Console.WriteLine("OPC UA wire tests passed: browse, authentication, read/write, subscription, live nodes, trend, no echo.");
}
finally
{
store.PointValueUpdated -= Count;
await application.StopAsync();
server.Dispose();
store.UpdateGatewayConfiguration(previous);
}
}
private static StatusCode Write(Session session, NodeId node, object value)
{
session.Write(null, [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new DataValue(new Variant(value)) }], out var results, out _);
return results[0];
}
private static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
}
#pragma warning restore CS0618
+153 -1
View File
@@ -4,6 +4,8 @@ using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging.Abstractions;
using System.Net.Sockets;
var validator = new MappingValidator();
var sourceOne = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
@@ -45,9 +47,133 @@ store.Initialize();
Assert(!store.HasAdmin(), "A new database must not contain an admin password.");
store.CreateInitialAdmin(new SetInitialAdminRequest("correct horse battery staple", "P190726", 1));
Assert(store.HasAdmin() && store.VerifyAdminPassword("correct horse battery staple"), "The configured admin must authenticate.");
var authenticatedAdmin = store.Authenticate("admin", "correct horse battery staple");
Assert(authenticatedAdmin is not null && authenticatedAdmin.Permissions.Contains(GatewayPermissions.ManageUsers), "The migrated administrator must receive the complete admin role.");
var viewer = store.CreateUser(new CreateUserRequest("trend.viewer", "Trend Viewer", null, "another secure password", "viewer"));
Assert(store.Authenticate(viewer.Username, "another secure password")?.Permissions.SequenceEqual([GatewayPermissions.ViewDashboard, GatewayPermissions.ViewTrends]) == true, "Viewer accounts must receive only viewer permissions.");
Assert(store.GetGatewayConfiguration().VendorId == 815 && store.GetGatewayConfiguration().DeviceInstance == 23, "BACnet bootstrap defaults must be persisted.");
Assert(store.GetGatewayConfiguration().Installation?.HostName == "SE-UGW-P190726-ISP01", "First commissioning must create the requested Komari-visible hostname.");
Assert(File.Exists(Path.Combine(dataDirectory, "provisioning", "host.json")), "The NixOS hostname helper must receive an identity-only provisioning request.");
var oldConfiguration = store.GetGatewayConfiguration();
var installation = store.UpdateInstallationIdentity(new InstallationIdentity(" p260123 ", 3));
store.UpdateGatewayConfiguration(oldConfiguration);
Assert(installation.HostName == "SE-UGW-P260123-ISP03" && store.GetGatewayConfiguration().Installation == installation &&
File.ReadAllText(Path.Combine(dataDirectory, "provisioning", "host.json")).Contains("P260123", StringComparison.Ordinal),
"Changing installation identity must provision the new name and survive updates from an older protocol form.");
var etsXml = "<Project><GroupAddresses><GroupAddress Name=\"Room temperature\" Address=\"1/2/3\" DatapointType=\"DPT-9-001\" /></GroupAddresses></Project>";
var knxImport = KnxEtsImporter.Import(new KnxEtsImportRequest("sample.xml", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(etsXml))), store);
Assert(knxImport.Imported == 1 && store.ListPoints().Any(point => point.Protocol == PointProtocol.Knx && point.ExternalIdentity == "knx:1/2/3"), "ETS group addresses must be imported with their KNX identity.");
var mappingSource = store.CreatePoint(new CreatePointRequest(
"Mapped internal source", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappedTarget = store.CreatePoint(new CreatePointRequest(
"Mapped internal target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappingRuntime = new MappingRuntimeService(store, journal);
await mappingRuntime.StartAsync(CancellationToken.None);
var mappingRequest = new CreateMappingRequest(mappingSource.Id, mappedTarget.Id, MappingDirection.OneWay, true, null, false, JsonElementFor("{}"));
var editableMapping = store.CreateMapping(mappingRequest).Mapping;
store.SetPointValue(mappingSource.Id, JsonElementFor("42.5"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Any(value => value.PointId == mappedTarget.Id && value.Value.GetDouble() == 42.5), "The active mapping graph must forward a point value exactly once.");
var nextTarget = store.CreatePoint(new CreatePointRequest(
"New mapping target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var updatedMapping = store.UpdateMapping(editableMapping.Id, mappingRequest with { TargetPointId = nextTarget.Id })?.Mapping;
Assert(updatedMapping?.Id == editableMapping.Id && updatedMapping.CreatedAtUtc == editableMapping.CreatedAtUtc, "Editing must retain mapping identity.");
store.SetPointValue(mappingSource.Id, JsonElementFor("43"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == mappedTarget.Id).Value.GetDouble() == 42.5 &&
store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43, "Edited mappings must switch targets live.");
Assert(store.DeleteMapping(editableMapping.Id) && !store.DeleteMapping(editableMapping.Id), "Mapping deletion must distinguish missing mappings.");
store.SetPointValue(mappingSource.Id, JsonElementFor("44"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43 &&
store.GetPointDependencies(mappingSource.Id)?.Mappings == 0 && store.ListPoints().Any(point => point.Id == nextTarget.Id),
"Removing a mapping must stop forwarding and preserve both points.");
await mappingRuntime.StopAsync(CancellationToken.None);
var modbusServerId = Guid.NewGuid();
store.UpdateGatewayConfiguration(store.GetGatewayConfiguration() with
{
ModbusServers = [new ModbusServerConfiguration(modbusServerId, "Smoke", "127.0.0.1", 15022, 1, 0, 100, [])]
});
var modbusGatewayPoint = store.CreatePoint(new CreatePointRequest(
"Modbus server value", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, true, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"HoldingRegister\",\"address\":12,\"dataType\":\"UInt16\"}}")));
store.CreatePoint(new CreatePointRequest(
"Reserved input register", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, false, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"InputRegister\",\"address\":1,\"dataType\":\"UInt16\"}}")));
var csvSource = store.CreatePoint(new CreatePointRequest(
"=\"Zuluft; Vorlauf\"", PointProtocol.Internal, PointScope.Internal, "UInt16", true, false, null, JsonElementFor("{}")));
store.SetPointValue(csvSource.Id, JsonElementFor("73"), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
var batch = new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Modbus, modbusServerId);
Assert(store.CreateBulkMappings(batch) is { Created: 2, Existing: 0 }, "Bulk Modbus mapping must create both routes.");
var targets = store.ListMappings().Where(mapping => batch.SourcePointIds.Contains(mapping.SourcePointId)).ToDictionary(
mapping => mapping.SourcePointId, mapping => store.ListPoints().Single(point => point.Id == mapping.TargetPointId));
Assert(targets[mappingSource.Id].Address.GetProperty("address").GetInt32() == 2 &&
targets[csvSource.Id].Address.GetProperty("address").GetInt32() == 4 &&
store.ListPointValues().Single(value => value.PointId == targets[csvSource.Id].Id).Value.GetInt32() == 73 &&
store.CreateBulkMappings(batch) is { Created: 0, Existing: 2 }, "Register allocation must skip conflicts, preserve widths and seed current values.");
var batchMqtt = store.CreateBulkMappings(new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Mqtt, MqttTopicPrefix: "test/batch"));
Assert(batchMqtt.Created == 2 && batchMqtt.Assignments.Distinct().Count() == 2, "Bulk MQTT requires a unique topic for each point.");
var statePoint = store.CreatePoint(new("Pumpe läuft", PointProtocol.Internal, PointScope.Internal, "Bool", true, false, null, JsonElementFor("{}")));
var alarmPoint = store.CreatePoint(new("Pumpe Störung", PointProtocol.Internal, PointScope.Internal, "Boolean", true, false, null, JsonElementFor("{}")));
store.UpdateNotificationKey(NotificationChannel.Mail, new("local-smoke-key"));
var rule = store.SaveAlarmRule(new(Guid.NewGuid(), "Smoke alarm", alarmPoint.Id, AlarmCondition.Active, 0, 0, true, false, "",
[new(NotificationChannel.Mail, "alarm@example.invalid")]));
var mqttDefaults = store.GetMqttMappingDefaults();
Assert(mqttDefaults.Site == new MqttMonitoringSite(2026, "P260123", "ISP3") &&
mqttDefaults.Points.Single(point => point.PointId == csvSource.Id).Category == SeMonitoringCategory.Analog &&
mqttDefaults.Points.Single(point => point.PointId == statePoint.Id).Category == SeMonitoringCategory.Notify &&
mqttDefaults.Points.Single(point => point.PointId == alarmPoint.Id).Category == SeMonitoringCategory.Alarms,
"The MQTT default must use commissioning data and distinguish numerics, digital states and active alarm points.");
var monitoringBatch = store.CreateBulkMappings(new([csvSource.Id, statePoint.Id, alarmPoint.Id], BulkMappingTarget.Mqtt));
Assert(monitoringBatch.Created == 3 && monitoringBatch.Assignments.Any(item => item.Contains("/Alarms/", StringComparison.Ordinal)) &&
monitoringBatch.Assignments.Any(item => item.Contains("/Notify/", StringComparison.Ordinal)), "Bulk MQTT should use SE-Monitoring by default.");
var rawMqtt = store.CreateMqttMapping(new(csvSource.Id, MqttMappingFormat.SingleTopic, MqttDirection.Publish, MqttQualityOfService.AtLeastOnce,
false, null, null, null, null, null, "plant/temperature", null));
Assert(GatewayStore.GetMqttTopic(rawMqtt) == "plant/temperature", "A numeric single-topic mapping must use the specified topic exactly.");
store.DeleteAlarmRule(rule.Id);
store.UpdateNotificationKey(NotificationChannel.Mail, new(null, true));
foreach (var kind in Enum.GetValues<ConfigurationCsvKind>())
{
var csv = store.ExportConfigurationCsv(kind);
Assert(store.ImportConfigurationCsv(kind, csv) is { Created: 0, Updated: > 0 } &&
store.ExportConfigurationCsv(kind) == csv, $"CSV round-trip must preserve IDs and escaping for {kind}.");
}
var exportedPoints = store.ExportConfigurationCsv(ConfigurationCsvKind.Points);
var editedPoints = exportedPoints.Replace("Modbus server value", "Modbus renamed", StringComparison.Ordinal);
try
{
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints + "invalid\r\n");
throw new InvalidOperationException("A malformed row should fail the whole CSV import.");
}
catch (DomainValidationException exception)
{
Assert(exception.Message.Contains("CSV-Zeile", StringComparison.Ordinal) &&
store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus server value",
"A failed CSV import must report the row and roll back earlier changes.");
}
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints);
Assert(store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus renamed", "A CSV edit must update the existing point.");
var modbusService = new ModbusProtocolService(store, journal, NullLogger<ModbusProtocolService>.Instance);
await modbusService.StartAsync(CancellationToken.None);
await Task.Delay(350);
store.SetPointValue(modbusGatewayPoint.Id, JsonElementFor("42"), PointProtocol.Internal, DateTimeOffset.UtcNow);
using (var modbusClient = new TcpClient())
{
await modbusClient.ConnectAsync("127.0.0.1", 15022);
var request = new byte[] { 0, 1, 0, 0, 0, 6, 1, 3, 0, 12, 0, 1 };
await modbusClient.GetStream().WriteAsync(request);
var response = new byte[11];
await modbusClient.GetStream().ReadExactlyAsync(response);
Assert(response.SequenceEqual(new byte[] { 0, 1, 0, 0, 0, 5, 1, 3, 2, 0, 42 }), "The Modbus TCP server must expose mapped holding registers.");
}
await modbusService.StopAsync(CancellationToken.None);
modbusService.Dispose();
var opcFactory = new OpcUaApplicationFactory(database);
var opcClientConfiguration = await opcFactory.CreateClientConfigurationAsync();
Assert(opcClientConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate is not null, "The OPC UA browser must create a persistent application certificate.");
try { await OpcUaFeatureTests.RunAsync(store, database); }
catch (Exception exception) { Console.Error.WriteLine(exception); Environment.ExitCode = 1; return; }
await BacnetBridgeTests.RunAsync(store, database);
var sourcePoint = store.CreatePoint(new CreatePointRequest(
"Internal temperature",
@@ -82,6 +208,12 @@ var analogMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
Assert(
GatewayStore.GetMqttTopic(analogMqttMapping) == "Projekte2019/P1909015/ISP1/Analog/iVlTempFuehler4Speicher_Wert",
"SE Monitoring topics must match the requested hierarchy.");
var editedMqtt = store.UpdateMqttMapping(analogMqttMapping.Id, new CreateMqttMappingRequest(
sourcePoint.Id, MqttMappingFormat.Json, MqttDirection.Publish, MqttQualityOfService.AtMostOnce, false,
null, null, null, null, null, "test/updated-topic", "value"));
Assert(editedMqtt?.Id == analogMqttMapping.Id && GatewayStore.GetMqttTopic(editedMqtt) == "test/updated-topic", "MQTT edits must replace the mapped topic.");
Assert(store.DeleteMqttMapping(analogMqttMapping.Id) && store.GetPointDependencies(sourcePoint.Id)?.MqttMappings == 0,
"Deleting an MQTT mapping must unlink its source point.");
var invalidNotifyMappingRejected = false;
try
@@ -156,7 +288,8 @@ var scheduleJsonMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
"plant/schedule",
"weekProgram"));
Assert(GatewayStore.GetMqttTopic(scheduleJsonMapping) == "plant/schedule", "Structured BACnet values must be mappable through JSON MQTT.");
var trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true));
var trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true, true));
Assert(store.IsPublicTrendLog(trendLog.Id) && store.ListPublicTrendLogs().Single().Id == trendLog.Id, "Only explicitly marked trend logs may be exposed publicly.");
var historyStart = new DateTimeOffset(2026, 10, 7, 8, 0, 0, TimeSpan.Zero);
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("21.5"), PointProtocol.Internal, null, historyStart));
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.0"), PointProtocol.Internal, null, historyStart.AddMinutes(1)));
@@ -180,7 +313,26 @@ Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.1"
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.2"), PointProtocol.Internal, null, sampleTime.AddSeconds(60)).Count == 1, "Observations at the configured interval must be recorded.");
Assert(store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "The sampled trend log must contain two records.");
var renamedPoint = store.UpdatePoint(sampledSourcePoint.Id, new CreatePointRequest(
"Humidity renamed", sampledSourcePoint.Protocol, sampledSourcePoint.Scope, sampledSourcePoint.ValueType,
sampledSourcePoint.Readable, sampledSourcePoint.Writable, null, JsonElementFor("{}")));
Assert(renamedPoint?.Id == sampledSourcePoint.Id && renamedPoint.DisplayName == "Humidity renamed", "Point editing must keep the point identity.");
var usage = store.GetPointDependencies(sampledSourcePoint.Id);
Assert(usage?.TrendLogs == 1, "The delete preview must include linked trend logs.");
try
{
store.DeletePoint(sampledSourcePoint.Id, null);
throw new InvalidOperationException("Deleting a linked point must require confirmation.");
}
catch (DomainValidationException) { }
Assert(store.DeletePoint(sampledSourcePoint.Id, usage!.Confirmation), "A confirmed point must be removable.");
Assert(store.ListPoints().All(point => point.Id != sampledSourcePoint.Id) &&
!store.ListTrendLogs().Single(log => log.Id == sampledLog.Id).Enabled &&
store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "Removing a point must stop logging and preserve the history.");
await LtdFeatureTests.RunAsync(store, database, options, authenticatedAdmin!);
Console.WriteLine("Gateway smoke tests passed.");
if (args.Contains("--preview", StringComparer.Ordinal)) Console.WriteLine($"Preview data: {dataDirectory}");
static GatewayPoint CreatePoint(PointProtocol protocol, PointScope scope, string? externalIdentity)
{
+149
View File
@@ -0,0 +1,149 @@
"""Isolated wire test: only loopback, a temporary DB, no building-network writes."""
import json
import os
import socket
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import time
runtime = Path(sys.argv[1]) / "bin"
work = Path(tempfile.mkdtemp(prefix="seiugw-bacnet-wire-"))
db = sqlite3.connect(work / "seiugw.db")
# Share the exact schema with the application rather than maintaining a fixture copy.
source = Path(__file__).resolve().parents[1] / "src/Gateway.Api/Services/GatewayDatabase.cs"
schema = source.read_text().split('command.CommandText = """', 1)[1].split('""";', 1)[0]
db.executescript(schema)
config = {"deviceInstance": 900023, "deviceName": "SE-UGW-Wire-Test", "bacnet": {"interface": "lo", "ipPort": 47828, "bbmdMode": "Disabled"}}
db.execute("INSERT INTO settings VALUES(?,?)", ("gateway.configuration", json.dumps(config)))
types = [("AnalogInput", 0), ("AnalogOutput", 1), ("AnalogValue", 2), ("BinaryInput", 3), ("BinaryOutput", 4), ("BinaryValue", 5),
("MultiStateInput", 13), ("MultiStateOutput", 14), ("MultiStateValue", 19), ("Schedule", 17), ("Calendar", 6)]
for i, (kind, number) in enumerate(types, 1):
db.execute("INSERT INTO points VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NULL)", (f"00000000-0000-0000-0000-{i:012}", kind, "Bacnet", "Gateway", "Real", 1, 1,
None, '{"units":62,"numberOfStates":16}', "2026-10-09T00:00:00Z", kind, 77))
db.commit()
environment = {**os.environ, "LC_ALL": "C", "BACNET_DATALINK": "bip", "BACNET_IFACE": "lo", "BACNET_IP_PORT": "47829", "BACNET_IP_BROADCAST_PORT": "47828", "BACNET_APDU_TIMEOUT": "1000"}
log = open(work / "server.log", "w")
server = None
cov = None
def start():
global server
server = subprocess.Popen([runtime / "bacserv", "900023"], cwd=work, env={**environment, "SEIUGW_DATABASE": str(work / "seiugw.db")}, stdout=log, stderr=log)
time.sleep(1.5)
assert server.poll() is None, (work / "server.log").read_text()
def call(tool, args, success=True):
result = subprocess.run([runtime / tool, "900023", *map(str, args), "--mac", "127.0.0.1:47828", "--dnet", "0"], env=environment, cwd=work, text=True, capture_output=True, timeout=10)
assert (result.returncode == 0) == success, (args, result.stdout, result.stderr)
return result.stdout.strip()
def read(obj, prop=85, index=None):
return call("bacrp", [obj, 77 if obj != 8 else 900023, prop, *([] if index is None else [index])])
def write(obj, tag, value, priority=16, prop=85, success=True):
return call("bacwp", [obj, 77, prop, priority, -1, tag, value], success)
def command(i, value, priority=16):
cursor = db.execute("INSERT INTO bacnet_commands(point_id,value_json,priority,created_ms) VALUES(?,?,?,?)",
(f"00000000-0000-0000-0000-{i:012}", json.dumps(value), priority, int(time.time()*1000)))
db.commit()
limit = time.monotonic()+5
while time.monotonic() < limit:
row = db.execute("SELECT state,result FROM bacnet_commands WHERE id=?", (cursor.lastrowid,)).fetchone()
if row[0] != "pending" and row[0] != "claimed":
assert row[0] == "done", row
return
time.sleep(.05)
raise AssertionError("Command was not processed")
try:
start()
# Field devices may send I-Am to the BACnet port, as a broadcast or unicast.
# The native socket must receive these while its normal ReadProperty service stays available.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as broadcast, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as peer:
broadcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
broadcast.bind(("127.255.255.255", 47828))
broadcast.settimeout(5)
peer.bind(("127.0.0.2", 47828))
peer.settimeout(5)
peer.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
for target in (None, "127.0.0.2"):
scan_id = "wire-broadcast" if target is None else "wire-direct"
db.execute("INSERT OR REPLACE INTO bacnet_discovery VALUES(1,?,?,?,?,0)",
(scan_id, target, 47828, int((time.time()+7)*1000)))
db.commit()
request, origin = (broadcast if target is None else peer).recvfrom(512)
assert origin == ("127.0.0.1", 47828) and request.endswith(b"\x10\x08"), (request.hex(), origin)
payload = bytes.fromhex("01001000c4") + ((8 << 22) | 1975).to_bytes(4, "big") + bytes.fromhex("2205c4910022032f")
function = 0x0b if target is None else 0x0a
peer.sendto(bytes([0x81, function, 0, len(payload)+4]) + payload,
("127.255.255.255" if target is None else "127.0.0.1", 47828))
if target is None:
routed = bytes.fromhex("01080014012a")
routed += payload[2:5] + ((8 << 22) | 1976).to_bytes(4, "big") + payload[9:]
peer.sendto(bytes([0x81, 0x0b, 0, len(routed)+4]) + routed, ("127.255.255.255", 47828))
for _ in range(30):
results = db.execute("SELECT device_instance,address,port,vendor,max_apdu,network,mac FROM bacnet_discovered_devices WHERE scan_id=? ORDER BY device_instance", (scan_id,)).fetchall()
if len(results) == (2 if target is None else 1):
break
time.sleep(.1)
assert results[0] == (1975, "127.0.0.2", 47828, 815, 1476, 0, None), results
if target is None:
assert results[1] == (1976, "127.0.0.2", 47828, 815, 1476, 20, "2A"), results
print("Native BACnet discovery passed: source port, broadcast and direct I-Am")
assert read(8, 120) == "815", read(8, 120)
object_list = read(8, 76)
for _, number in types: assert read(number, 75), number
assert "analog-value" in object_list.lower(), object_list
write(0, 4, 10, success=False) # AI Present_Value is not externally writable while in service.
write(2, 4, 21.5)
assert float(read(2)) == 21.5
write(2, 4, 30, 14)
command(3, 22, 16)
assert float(read(2)) == 30 and float(read(2, 87, 16)) == 22
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 31, 14)
server.terminate(); server.wait(timeout=5); start()
assert float(read(2)) == 31 and float(read(2, 87, 16)) == 22, "Priority slots must survive a native service restart"
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 99, 6, success=False)
command(1, 18.75)
assert float(read(0)) == 18.75
command(6, True)
assert "active" in read(5).lower() or read(5) == "1", read(5)
command(9, 3)
assert int(read(19)) == 3
# Use the upstream COV client with an explicit loopback-only address cache.
(work / "address_cache").write_text("900023 7F:00:00:01:BA:D4 0 0 1476\n")
cov_log = open(work / "cov.log", "w")
cov = subprocess.Popen(["stdbuf", "-oL", str(runtime / "bacscov"), "900023", "2", "77", "17", "unconfirmed", "30"],
cwd=work, env={**environment, "BACNET_IP_PORT": "47830"}, stdout=cov_log, stderr=cov_log)
time.sleep(1)
write(2, 4, 42.5)
time.sleep(2)
cov_log.flush()
cov_text = (work / "cov.log").read_text()
assert "Acknowledged" in cov_text and cov_text.count("Received Notification!") >= 2 and float(read(2)) == 42.5, cov_text
latest = db.execute("SELECT value_json,status FROM bacnet_observations WHERE point_id LIKE '%000000000003' ORDER BY id DESC LIMIT 1").fetchone()
assert float(latest[0]) == 42.5 and latest[1] == "Good", latest
# A new object appears without restarting the server.
db.execute("INSERT INTO points SELECT '00000000-0000-0000-0000-000000000099','Late AV',protocol,scope,value_type,readable,writable,NULL,address_json,created_at_utc,bacnet_object_kind,99,NULL FROM points WHERE bacnet_object_kind='AnalogValue'")
db.commit(); time.sleep(1.3)
assert "99" in read(8, 76)
db.execute("UPDATE points SET display_name='Renamed AV' WHERE bacnet_object_kind='AnalogValue' AND bacnet_object_instance=77")
db.commit(); time.sleep(1.3)
assert "Renamed AV" in read(2, 77) and float(read(2)) == 42.5
db.execute("UPDATE points SET deleted_at_utc='2026-11-19T00:00:00Z' WHERE id LIKE '%000000000099'")
db.commit(); time.sleep(1.3)
assert "99" not in read(8, 76)
print("BACnet wire tests passed: native Object_List, AI/AO/AV/BI/BO/BV/MSI/MSO/MSV/Schedule/Calendar, priority 16/14/NULL, persistence, COV, live creation, command/observation bridge.")
finally:
if cov is not None: cov.terminate(); cov.wait(timeout=5)
if server is not None and server.poll() is None: server.terminate(); server.wait(timeout=5)
db.close(); log.close()
print(f"Isolated test evidence: {work}")
+86
View File
@@ -0,0 +1,86 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { test } = require('node:test');
// No browser dependencies; exercise the same theme/tab functions as the shipped UI.
function element(dataset = {}) {
const classes = new Set();
return { dataset, handlers: {}, attributes: {}, hidden: false,
classList: { toggle(name, on) { on ? classes.add(name) : classes.delete(name); } },
addEventListener(name, handler) { this.handlers[name] = handler; },
setAttribute(name, value) { this.attributes[name] = value; },
focus() { this.focused = true; }
};
}
function harness() {
const themes = ['light','dark','system'].map(theme => element({ theme }));
const tabs = ['points','bacnet','opcua','modbus','knx','mqtt','serial','status'].map(pointsTab => element({ pointsTab }));
const panels = tabs.map(tab => element({ pointsPanel: tab.dataset.pointsTab }));
const storage = new Map();
const document = { documentElement: element(), querySelector: () => null,
querySelectorAll(selector) { return selector === 'button[data-theme]' ? themes : selector === '[data-points-tab]' ? tabs : selector === '[data-points-panel]' ? panels : []; }
};
const context = vm.createContext({ document, window: { matchMedia: () => ({ matches: true, addEventListener() {} }) },
sessionStorage: { getItem() { return null; } }, localStorage: { getItem: key => storage.get(key), setItem: (key,value) => storage.set(key,value) }
});
const root = path.join(__dirname, '../src/Gateway.Api/wwwroot');
const app = fs.readFileSync(path.join(root,'app.js'),'utf8');
vm.runInContext(fs.readFileSync(path.join(root,'ltd.js'),'utf8'),context);
vm.runInContext(fs.readFileSync(path.join(root,'gateway-status.js'),'utf8'),context);
vm.runInContext(app.slice(0,app.lastIndexOf('boot().catch(')),context);
return { context, document, themes, tabs, panels, storage, run: code => vm.runInContext(code,context) };
}
test('theme updates every switch in place, persists preference, and does not rebuild forms', async () => {
const h = harness();
h.run("renderShell = () => { throw new Error('Theme must preserve forms'); }; api = async () => ({ theme: 'light', sidebarPinned: true });");
await h.run("setTheme('light')");
assert.equal(h.document.documentElement.dataset.theme,'light');
assert.equal(h.storage.get('seiugw-theme'),'light');
assert.equal(h.themes[0].attributes['aria-pressed'],'true');
assert.equal(h.themes[1].attributes['aria-pressed'],'false');
h.run("applyTheme('system')");
assert.equal(h.document.documentElement.dataset.theme,'dark');
assert.equal(h.themes[2].attributes['aria-pressed'],'true');
});
test('tab clicks and arrow keys select exactly one retained panel', () => {
const h = harness();
h.run("renderView = () => { throw new Error('Tabs must preserve mounted forms'); }; bindPointTabs();");
h.panels[3].draft = 'unsaved';
h.tabs[3].handlers.click();
assert.deepEqual(h.panels.filter(p => !p.hidden).map(p => p.dataset.pointsPanel),['modbus']);
h.tabs[3].handlers.keydown({ key: 'ArrowRight', preventDefault() {} });
assert.deepEqual(h.panels.filter(p => !p.hidden).map(p => p.dataset.pointsPanel),['knx']);
assert.equal(h.tabs[4].focused,true);
h.tabs[3].handlers.click();
assert.equal(h.panels[3].draft,'unsaved');
assert.equal(h.tabs.filter(tab => tab.tabIndex === 0).length,1);
});
test('protocol forms and browser hosts belong to separate accessible panels', () => {
const h = harness();
h.run("state.configuration = { bacnet: {}, opcUa: {}, knx: {} }; state.pointsTab = 'bacnet';");
const markup = h.run('viewProtocols()');
const expected = { bacnet: ['bacnet-form','bacnet-browser'], opcua: ['opcua-form','opcua-browser'], modbus: ['modbus-server-form','modbus-import-form'], knx: ['knx-form'], serial: ['serial-port-form'] };
const sections = [...markup.matchAll(/<section id="point-panel-([^"]+)"[\s\S]*?(?=<section id="point-panel-|$)/g)];
assert.equal(sections.length,5);
for (const [markup,id] of sections) {
for (const form of expected[id]) assert.ok(markup.includes(`id="${form}"`),`${form} must be in ${id}`);
assert.ok(markup.includes(`aria-labelledby="point-tab-${id}"`));
assert.equal(/data-points-panel="[^"]+" hidden/.test(markup),id !== 'bacnet');
}
});
test('protocol tabs respect permissions, including MQTT-only accounts', () => {
const h = harness();
h.run("bodyOf = markup => markup; viewMqtt = () => '<div>MQTT test</div>'; state.user = { permissions: ['manage_integrations'] };");
const markup = h.run('viewDataPoints()');
assert.ok(markup.includes('point-tab-mqtt'));
assert.ok(markup.includes('point-tab-status'));
assert.ok(!markup.includes('point-tab-bacnet'));
assert.ok(!markup.includes('point-tab-points'));
assert.equal(h.run('state.pointsTab'),'mqtt');
});