392 lines
25 KiB
C#
392 lines
25 KiB
C#
using System.Text.Json;
|
|
using Gateway.Api.Contracts;
|
|
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);
|
|
var sourceTwo = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
|
|
var bacnetTarget = CreatePoint(PointProtocol.Bacnet, PointScope.External, "device:77/analog-value:3");
|
|
|
|
var firstMapping = CreateMapping(sourceOne.Id, bacnetTarget.Id, MappingDirection.OneWay, null, false);
|
|
var validSingleWriter = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [firstMapping]);
|
|
Assert(validSingleWriter.IsValid, "A single external writer must be valid.");
|
|
|
|
var conflictingSecondWriter = CreateMapping(sourceTwo.Id, bacnetTarget.Id, MappingDirection.OneWay, null, false);
|
|
var conflict = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [firstMapping, conflictingSecondWriter]);
|
|
Assert(!conflict.IsValid, "Two unqualified writers must be rejected.");
|
|
|
|
var priorityOne = firstMapping with { BacnetPriority = 16, AcknowledgeMultipleExternalWriters = true };
|
|
var priorityTwo = conflictingSecondWriter with { BacnetPriority = 14, AcknowledgeMultipleExternalWriters = true };
|
|
var explicitPriorityCase = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [priorityOne, priorityTwo]);
|
|
Assert(explicitPriorityCase.IsValid && explicitPriorityCase.Warnings.Count == 1, "Explicitly acknowledged BACnet priorities must be permitted with a warning.");
|
|
|
|
var reverseMapping = CreateMapping(bacnetTarget.Id, sourceOne.Id, MappingDirection.OneWay, null, false);
|
|
var loop = validator.Validate([sourceOne, bacnetTarget], [firstMapping, reverseMapping]);
|
|
Assert(!loop.IsValid, "Two opposing one-way mappings must be rejected.");
|
|
|
|
var journal = new WriteJournal();
|
|
journal.Register("bacnet:77/av:3", "21.5", TimeSpan.FromSeconds(10));
|
|
Assert(journal.ConsumeReflection("bacnet:77/av:3", "21.5"), "The first adapter reflection must be consumed.");
|
|
Assert(!journal.ConsumeReflection("bacnet:77/av:3", "21.5"), "A reflection cannot be consumed twice.");
|
|
|
|
var dataDirectory = Path.Combine(Path.GetTempPath(), "seiugw-smoke-" + Guid.NewGuid().ToString("N"));
|
|
var options = Options.Create(new GatewayOptions
|
|
{
|
|
DataDirectory = dataDirectory,
|
|
Bacnet = new BacnetBootstrapOptions { Interface = "eth0", DeviceInstance = 23, IpPort = 47808 },
|
|
OpcUa = new OpcUaBootstrapOptions { Port = 4840 }
|
|
});
|
|
var database = new GatewayDatabase(options);
|
|
var store = new GatewayStore(database, new PasswordService(), validator, new SecretProtector(options), options);
|
|
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 oldTopics = store.ListMqttMappings().ToDictionary(mapping => mapping.Id, GatewayStore.GetMqttTopic);
|
|
var templateView = store.UpdateMqttTopicTemplate("Anlagen/{Rechnername}/{Kategorie}/{Datenpunkt}");
|
|
Assert(templateView.PreviewValues["{Rechnername}"] == "SE-UGW-P260123-ISP03", "The preview must show the configured installation identity.");
|
|
var templatedRequest = new CreateMqttMappingRequest(csvSource.Id, MqttMappingFormat.SeMonitoring, MqttDirection.Publish,
|
|
MqttQualityOfService.AtLeastOnce, false, null, "P260123", "ISP3", SeMonitoringCategory.Analog, "Vorlauf", null, null);
|
|
var customMapping = store.CreateMqttMapping(templatedRequest);
|
|
const string customTopic = "Anlagen/SE-UGW-P260123-ISP03/Analog/Vorlauf";
|
|
Assert(GatewayStore.GetMqttTopic(customMapping) == customTopic &&
|
|
store.ListMqttMappings().Where(mapping => oldTopics.ContainsKey(mapping.Id)).All(mapping => GatewayStore.GetMqttTopic(mapping) == oldTopics[mapping.Id]),
|
|
"A new template must affect new mappings and preserve every previously resolved topic.");
|
|
var bulkTemplate = store.UpdateMqttTopicTemplate("Messwerte/{Projekt}/{Datenpunkt}");
|
|
var batchWithTemplate = store.CreateBulkMappings(new([statePoint.Id], BulkMappingTarget.Mqtt));
|
|
Assert(batchWithTemplate.Created == 1 && batchWithTemplate.Assignments.Single().EndsWith("Messwerte/P260123/Pumpe_läuft", StringComparison.Ordinal) &&
|
|
GatewayStore.GetMqttTopic(store.UpdateMqttMapping(customMapping.Id, templatedRequest with { Retain = true })!) == customTopic,
|
|
"Bulk mappings must use the active template while an existing mapping edit keeps its saved path.");
|
|
try
|
|
{
|
|
store.UpdateMqttTopicTemplate("Messwerte/{Unbekannt}/{Datenpunkt}");
|
|
throw new InvalidOperationException("An unknown MQTT placeholder must be rejected.");
|
|
}
|
|
catch (DomainValidationException)
|
|
{
|
|
Assert(store.GetMqttMappingDefaults().TopicTemplate.Template == bulkTemplate.Template, "Rejected templates must not overwrite the saved template.");
|
|
}
|
|
var legacyMqttCsv = "Id;PointId;Format;Direction;QualityOfService;Retain;ProjectYear;ProjectNumber;IspNumber;SeCategory;TopicName;JsonTopic;JsonProperty\r\n" +
|
|
$";{csvSource.Id};SeMonitoring;Publish;AtLeastOnce;False;2026;P260123;ISP3;Analog;CsvLegacy;;\r\n";
|
|
Assert(store.ImportConfigurationCsv(ConfigurationCsvKind.MqttMappings, legacyMqttCsv).Created == 1 &&
|
|
store.ListMqttMappings().Any(mapping => GatewayStore.GetMqttTopic(mapping) == "Projekte2026/P260123/ISP3/Analog/CsvLegacy_Wert"),
|
|
"MQTT CSVs exported before the template field must continue to resolve legacy paths.");
|
|
store.UpdateMqttTopicTemplate(templateView.DefaultTemplate);
|
|
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",
|
|
PointProtocol.Internal,
|
|
PointScope.Internal,
|
|
"Real",
|
|
true,
|
|
false,
|
|
null,
|
|
JsonElementFor("{}")));
|
|
store.UpdateMqttConfiguration(new UpdateMqttConfigurationRequest(
|
|
new MqttConfiguration(true, "mqtt.example.local", 8883, true, true, "seiugw-test", "gateway"),
|
|
"broker-secret",
|
|
false));
|
|
var mqttConfiguration = store.GetMqttConfiguration();
|
|
Assert(mqttConfiguration.Configuration.UseTls && mqttConfiguration.Configuration.IgnoreCertificateErrors && mqttConfiguration.HasPassword, "MQTTS configuration and encrypted password marker must be persisted.");
|
|
Assert(store.GetMqttConnectionConfiguration().Password == "broker-secret", "The MQTT client must receive the locally protected broker password.");
|
|
|
|
var analogMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
|
sourcePoint.Id,
|
|
MqttMappingFormat.SeMonitoring,
|
|
MqttDirection.Publish,
|
|
MqttQualityOfService.AtLeastOnce,
|
|
true,
|
|
2019,
|
|
"P1909015",
|
|
"ISP1",
|
|
SeMonitoringCategory.Analog,
|
|
"iVlTempFuehler4Speicher",
|
|
null,
|
|
null));
|
|
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
|
|
{
|
|
store.CreateMqttMapping(new CreateMqttMappingRequest(
|
|
sourcePoint.Id,
|
|
MqttMappingFormat.SeMonitoring,
|
|
MqttDirection.Publish,
|
|
MqttQualityOfService.AtLeastOnce,
|
|
false,
|
|
2019,
|
|
"P1909015",
|
|
"ISP1",
|
|
SeMonitoringCategory.Notify,
|
|
"temperatureAsNotify",
|
|
null,
|
|
null));
|
|
}
|
|
catch (DomainValidationException)
|
|
{
|
|
invalidNotifyMappingRejected = true;
|
|
}
|
|
Assert(invalidNotifyMappingRejected, "Analog values must not be mapped to Notify.");
|
|
|
|
var setpoint = store.CreatePoint(new CreatePointRequest(
|
|
"Supply setpoint",
|
|
PointProtocol.Internal,
|
|
PointScope.Internal,
|
|
"Real",
|
|
true,
|
|
true,
|
|
null,
|
|
JsonElementFor("{}")));
|
|
var setpointMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
|
setpoint.Id,
|
|
MqttMappingFormat.SeMonitoring,
|
|
MqttDirection.Bidirectional,
|
|
MqttQualityOfService.AtLeastOnce,
|
|
false,
|
|
2019,
|
|
"P1909015",
|
|
"ISP1",
|
|
SeMonitoringCategory.Setpoints,
|
|
"supplyTemperature",
|
|
null,
|
|
null));
|
|
Assert(GatewayStore.GetMqttTopic(setpointMqttMapping).Contains("/Setpoints/", StringComparison.Ordinal), "Setpoints must use their dedicated bidirectional category.");
|
|
store.SetPointValue(setpoint.Id, JsonElementFor("21.5"), PointProtocol.Mqtt, DateTimeOffset.UtcNow);
|
|
Assert(store.ListPointValues().Single(value => value.PointId == setpoint.Id).Value.GetDouble() == 21.5, "Incoming MQTT values must persist as point values.");
|
|
|
|
var schedule = store.CreatePoint(new CreatePointRequest(
|
|
"Week schedule",
|
|
PointProtocol.Bacnet,
|
|
PointScope.Gateway,
|
|
"Schedule",
|
|
true,
|
|
false,
|
|
null,
|
|
JsonElementFor("{}"),
|
|
BacnetObjectKind.Schedule));
|
|
var scheduleJsonMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
|
schedule.Id,
|
|
MqttMappingFormat.Json,
|
|
MqttDirection.Publish,
|
|
MqttQualityOfService.AtLeastOnce,
|
|
false,
|
|
null,
|
|
null,
|
|
null,
|
|
null,
|
|
null,
|
|
"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, 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)));
|
|
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.5"), PointProtocol.Internal, null, historyStart.AddMinutes(2)));
|
|
var retainedRecords = store.ListTrendRecords(trendLog.Id, 10);
|
|
Assert(retainedRecords.Count == 2 && retainedRecords[0].SequenceNumber == 3, "Trend retention must remove only the oldest records.");
|
|
|
|
var sampledSourcePoint = store.CreatePoint(new CreatePointRequest(
|
|
"Internal humidity",
|
|
PointProtocol.Internal,
|
|
PointScope.Internal,
|
|
"Real",
|
|
true,
|
|
false,
|
|
null,
|
|
JsonElementFor("{}")));
|
|
var sampledLog = store.CreateTrendLog(new CreateTrendLogRequest(sampledSourcePoint.Id, "Humidity sampled", 102, 60, 10, true));
|
|
var sampleTime = new DateTimeOffset(2026, 10, 7, 9, 0, 0, TimeSpan.Zero);
|
|
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.0"), PointProtocol.Internal, null, sampleTime).Count == 1, "The first source observation must be recorded.");
|
|
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.1"), PointProtocol.Internal, null, sampleTime.AddSeconds(30)).Count == 0, "Observations inside the configured interval must not be recorded twice.");
|
|
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)
|
|
{
|
|
using var document = JsonDocument.Parse("{}");
|
|
return new GatewayPoint(Guid.NewGuid(), Guid.NewGuid().ToString(), protocol, scope, "Real", true, true, externalIdentity, document.RootElement.Clone(), DateTimeOffset.UtcNow);
|
|
}
|
|
|
|
static PointMapping CreateMapping(Guid source, Guid target, MappingDirection direction, int? priority, bool acknowledged)
|
|
{
|
|
using var document = JsonDocument.Parse("{}");
|
|
return new PointMapping(Guid.NewGuid(), source, target, direction, true, priority, acknowledged, document.RootElement.Clone(), DateTimeOffset.UtcNow);
|
|
}
|
|
|
|
static JsonElement JsonElementFor(string json)
|
|
{
|
|
using var document = JsonDocument.Parse(json);
|
|
return document.RootElement.Clone();
|
|
}
|
|
|
|
static void Assert(bool condition, string message)
|
|
{
|
|
if (!condition)
|
|
{
|
|
throw new InvalidOperationException(message);
|
|
}
|
|
}
|