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:
1 parent
d9165a60ff
commit
98c48d9d78
80 files changed
+11120
-315
No files matched your search
@@ -4,6 +4,16 @@ public sealed record SetInitialAdminRequest(string Password, string ProjectNumbe
|
||||
|
||||
public sealed record LoginRequest(string Username, string Password);
|
||||
|
||||
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAtUtc);
|
||||
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAtUtc, Gateway.Api.Domain.AuthenticatedGatewayUser User);
|
||||
|
||||
public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword);
|
||||
public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword, string NewPasswordConfirmation);
|
||||
|
||||
public sealed record CreateUserRequest(string Username, string DisplayName, string? Email, string Password, string Role, bool Active = true);
|
||||
|
||||
public sealed record UpdateUserRequest(string? Username, string? DisplayName, string? Email, string? Password, string? Role, bool? Active, string? PasswordConfirmation = null);
|
||||
|
||||
public sealed record SaveRoleRequest(string Name, string Label, IReadOnlyList<string> Permissions);
|
||||
|
||||
public sealed record UpdateKomariEnrollmentTokenRequest(string EnrollmentToken);
|
||||
|
||||
public sealed record UpdateUserPreferencesRequest(string? Theme, string? CsvDelimiter, bool? SidebarPinned, decimal? TrendLineWidth);
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public enum NotificationChannel { Mail, WhatsApp, Ntfy }
|
||||
public enum AlarmCondition { Active, Inactive, Above, Below }
|
||||
public sealed record NotificationIntegration(NotificationChannel Channel, string Endpoint, bool HasApiKey);
|
||||
public sealed record UpdateNotificationKeyRequest(string? ApiKey, bool ClearApiKey = false);
|
||||
public sealed record AlarmDestination(NotificationChannel Channel, string Recipient, string Template = "stoerung", string PersonName = "SE-Inno", int Priority = 0, string Tags = "alarm");
|
||||
public sealed record AlarmRule(Guid Id, string Name, Guid PointId, AlarmCondition Condition, double Threshold,
|
||||
double Hysteresis, bool Enabled, bool NotifyRecovery, string Message, IReadOnlyList<AlarmDestination> Destinations);
|
||||
public sealed record NotificationDelivery(long Id, Guid RuleId, string Title, string Message,
|
||||
AlarmDestination Destination, string State, DateTimeOffset CreatedAtUtc, string? Result);
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
/// <summary>A reusable group of trend logs, equivalent to an LTD saved selection.</summary>
|
||||
public sealed record GatewayTrendSelection(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
Guid OwnerId,
|
||||
bool Shared,
|
||||
IReadOnlyList<Guid> TrendLogIds,
|
||||
DateTimeOffset CreatedAtUtc,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record CreateTrendSelectionRequest(string Name, string? Description, bool Shared, IReadOnlyList<Guid> TrendLogIds);
|
||||
public sealed record UpdateTrendSelectionRequest(string? Name, string? Description, bool? Shared, IReadOnlyList<Guid>? TrendLogIds);
|
||||
|
||||
/// <summary>Scheduled CSV export and optional mail dispatch for one saved selection.</summary>
|
||||
public sealed record CsvRunnerJob(
|
||||
Guid Id,
|
||||
string Name,
|
||||
Guid SelectionId,
|
||||
string Time,
|
||||
int RangeHours,
|
||||
string Delimiter,
|
||||
bool Enabled,
|
||||
bool MailEnabled,
|
||||
string? MailTo,
|
||||
string MailSubject,
|
||||
string MailMessage,
|
||||
string? LastRunLocalDate,
|
||||
CsvRunnerJobResult? LastResult,
|
||||
DateTimeOffset CreatedAtUtc,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record CsvRunnerJobResult(bool Success, string? FilePath, string? Error, DateTimeOffset RanAtUtc);
|
||||
public sealed record CsvRunnerExecution(Guid Id, Guid JobId, string Name, string State, DateTimeOffset EnqueuedAtUtc);
|
||||
|
||||
public sealed record CreateCsvRunnerJobRequest(
|
||||
string Name,
|
||||
Guid SelectionId,
|
||||
string Time,
|
||||
int RangeHours,
|
||||
string Delimiter,
|
||||
bool Enabled,
|
||||
bool MailEnabled,
|
||||
string? MailTo,
|
||||
string? MailSubject,
|
||||
string? MailMessage);
|
||||
|
||||
public sealed record UpdateCsvRunnerJobRequest(
|
||||
string? Name,
|
||||
Guid? SelectionId,
|
||||
string? Time,
|
||||
int? RangeHours,
|
||||
string? Delimiter,
|
||||
bool? Enabled,
|
||||
bool? MailEnabled,
|
||||
string? MailTo,
|
||||
string? MailSubject,
|
||||
string? MailMessage);
|
||||
|
||||
public sealed record MailIntegrationView(bool MailConfigured, string Endpoint);
|
||||
public sealed record UpdateMailIntegrationRequest(string? ApiKey, bool ClearApiKey = false);
|
||||
|
||||
public sealed record TrendExportRow(
|
||||
DateTimeOffset TimestampUtc,
|
||||
string TrendLogName,
|
||||
uint BacnetObjectInstance,
|
||||
string PointName,
|
||||
System.Text.Json.JsonElement Value,
|
||||
PointProtocol SourceProtocol,
|
||||
string? Status,
|
||||
string Unit = "");
|
||||
@@ -9,7 +9,9 @@ public sealed record GatewayConfiguration(
|
||||
IReadOnlyList<ModbusServerConfiguration> ModbusServers,
|
||||
KnxConfiguration Knx,
|
||||
MqttConfiguration? Mqtt = null,
|
||||
InstallationIdentity? Installation = null)
|
||||
InstallationIdentity? Installation = null,
|
||||
IReadOnlyList<SerialPortConfiguration>? SerialPorts = null,
|
||||
IReadOnlyList<ModbusRtuServerConfiguration>? ModbusRtuServers = null)
|
||||
{
|
||||
public static GatewayConfiguration CreateDefault(int deviceInstance, int bacnetPort, int opcUaPort, string interfaceName) => new(
|
||||
VendorId: 815,
|
||||
@@ -20,7 +22,9 @@ public sealed record GatewayConfiguration(
|
||||
ModbusServers: [],
|
||||
Knx: new KnxConfiguration(false, false),
|
||||
Mqtt: MqttConfiguration.CreateDefault(),
|
||||
Installation: null);
|
||||
Installation: null,
|
||||
SerialPorts: [],
|
||||
ModbusRtuServers: []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -52,7 +56,26 @@ public sealed record OpcUaConfiguration(
|
||||
int Port,
|
||||
bool ClientEnabled,
|
||||
bool ServerEnabled,
|
||||
bool AllowAnonymous);
|
||||
bool AllowAnonymous,
|
||||
IReadOnlyList<OpcUaClientConfiguration>? Clients = null);
|
||||
|
||||
public enum OpcUaAuthenticationMode
|
||||
{
|
||||
Anonymous,
|
||||
Username,
|
||||
Certificate
|
||||
}
|
||||
|
||||
public sealed record OpcUaClientConfiguration(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string EndpointUrl,
|
||||
OpcUaAuthenticationMode AuthenticationMode,
|
||||
string? Username,
|
||||
bool AcceptUntrustedServerCertificate = false,
|
||||
bool Enabled = true,
|
||||
bool UseSecurity = true,
|
||||
int PublishingIntervalMilliseconds = 1000);
|
||||
|
||||
public sealed record ModbusServerConfiguration(
|
||||
Guid Id,
|
||||
@@ -64,7 +87,37 @@ public sealed record ModbusServerConfiguration(
|
||||
int HoldingRegisterCount,
|
||||
IReadOnlyList<string> AllowedClientIps);
|
||||
|
||||
public sealed record KnxConfiguration(bool Enabled, bool Secure);
|
||||
/// <summary>Named serial interface. The device path remains a Linux path such as /dev/ttyUSB0.</summary>
|
||||
public sealed record SerialPortConfiguration(
|
||||
Guid Id,
|
||||
string Alias,
|
||||
string DevicePath,
|
||||
int BaudRate,
|
||||
string Parity,
|
||||
int DataBits,
|
||||
int StopBits);
|
||||
|
||||
/// <summary>Modbus RTU slave configuration addressed through a configured serial alias.</summary>
|
||||
public sealed record ModbusRtuServerConfiguration(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string SerialPortAlias,
|
||||
int UnitId,
|
||||
int FirstHoldingRegister,
|
||||
int HoldingRegisterCount);
|
||||
|
||||
public enum KnxTransport
|
||||
{
|
||||
Ip,
|
||||
Tp
|
||||
}
|
||||
|
||||
public sealed record KnxConfiguration(
|
||||
bool Enabled,
|
||||
bool Secure,
|
||||
KnxTransport Transport = KnxTransport.Ip,
|
||||
string? SerialPortAlias = null,
|
||||
string? LocalIpAddress = null);
|
||||
|
||||
public sealed record MqttConfiguration(
|
||||
bool Enabled,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
/// <summary>Locally managed account. Password material never leaves the store.</summary>
|
||||
public sealed record GatewayUser(
|
||||
Guid Id,
|
||||
string Username,
|
||||
string DisplayName,
|
||||
string? Email,
|
||||
string Role,
|
||||
bool Active,
|
||||
DateTimeOffset CreatedAtUtc,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record GatewayRole(
|
||||
string Name,
|
||||
string Label,
|
||||
IReadOnlyList<string> Permissions,
|
||||
bool IsSystem,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public sealed record AuthenticatedGatewayUser(
|
||||
GatewayUser User,
|
||||
IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>Personal presentation settings, kept server-side like the former LTD UI.</summary>
|
||||
public sealed record GatewayUserPreferences(
|
||||
string Theme,
|
||||
string CsvDelimiter,
|
||||
bool SidebarPinned,
|
||||
decimal TrendLineWidth,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
public static class GatewayPermissions
|
||||
{
|
||||
public const string ViewDashboard = "view_dashboard";
|
||||
public const string ViewTrends = "view_trends";
|
||||
public const string EditAliases = "edit_aliases";
|
||||
public const string ManageSources = "manage_sources";
|
||||
public const string ViewDebug = "view_debug";
|
||||
public const string ManageAlarms = "manage_alarms";
|
||||
public const string ManageUsers = "manage_users";
|
||||
public const string ManageRoles = "manage_roles";
|
||||
public const string ManageIntegrations = "manage_integrations";
|
||||
public const string ManageRunner = "manage_runner";
|
||||
public const string ManageGateway = "manage_gateway";
|
||||
|
||||
public static readonly IReadOnlyList<string> Catalog =
|
||||
[
|
||||
ViewDashboard, ViewTrends, EditAliases, ManageSources, ViewDebug,
|
||||
ManageAlarms, ManageUsers, ManageRoles, ManageIntegrations,
|
||||
ManageRunner, ManageGateway
|
||||
];
|
||||
}
|
||||
@@ -5,7 +5,8 @@ namespace Gateway.Api.Domain;
|
||||
public enum MqttMappingFormat
|
||||
{
|
||||
SeMonitoring,
|
||||
Json
|
||||
Json,
|
||||
SingleTopic
|
||||
}
|
||||
|
||||
public enum MqttDirection
|
||||
@@ -20,7 +21,8 @@ public enum SeMonitoringCategory
|
||||
Analog,
|
||||
Notify,
|
||||
Alarm,
|
||||
Setpoints
|
||||
Setpoints,
|
||||
Alarms
|
||||
}
|
||||
|
||||
public enum MqttQualityOfService
|
||||
@@ -67,6 +69,10 @@ public sealed record UpdateMqttConfigurationRequest(
|
||||
|
||||
public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool HasPassword);
|
||||
|
||||
public sealed record MqttMonitoringSite(int? ProjectYear, string? ProjectNumber, string? IspNumber);
|
||||
public sealed record MqttPointDefaults(Guid PointId, SeMonitoringCategory? Category, string TopicName);
|
||||
public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList<MqttPointDefaults> Points);
|
||||
|
||||
public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc);
|
||||
|
||||
public sealed record MqttClientStatus(
|
||||
@@ -76,4 +82,6 @@ public sealed record MqttClientStatus(
|
||||
string? LastError,
|
||||
DateTimeOffset? ConnectedAtUtc,
|
||||
DateTimeOffset? LastReceivedAtUtc,
|
||||
DateTimeOffset? LastPublishedAtUtc);
|
||||
DateTimeOffset? LastPublishedAtUtc,
|
||||
string? LastFailure = null,
|
||||
DateTimeOffset? LastFailureAtUtc = null);
|
||||
@@ -67,12 +67,18 @@ public sealed record CreatePointRequest(
|
||||
BacnetObjectKind? BacnetObjectKind = null,
|
||||
uint? BacnetObjectInstance = null);
|
||||
|
||||
public sealed record PointDependencies(int Mappings, int MqttMappings, int Alarms, int TrendLogs)
|
||||
{
|
||||
public string Confirmation => $"{Mappings}-{MqttMappings}-{Alarms}-{TrendLogs}";
|
||||
}
|
||||
|
||||
public sealed record PointValue(
|
||||
Guid PointId,
|
||||
JsonElement Value,
|
||||
PointProtocol SourceProtocol,
|
||||
DateTimeOffset UpdatedAtUtc,
|
||||
string? Status);
|
||||
string? Status,
|
||||
Guid? OriginPointId = null);
|
||||
|
||||
public enum MappingDirection
|
||||
{
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public sealed record DisplayUnit(string Symbol, string Name, bool IsSystem = false);
|
||||
public sealed record PointPresentation(Guid PointId, string Alias, string Unit, double Factor, string Kind, string Color);
|
||||
public sealed record DashboardWidget(Guid Id, string Title, Guid SelectionId, int RangeHours, string Type);
|
||||
@@ -11,6 +11,7 @@ public sealed record GatewayTrendLog(
|
||||
int IntervalSeconds,
|
||||
int MaxRecords,
|
||||
bool Enabled,
|
||||
bool IsPublic,
|
||||
DateTimeOffset CreatedAtUtc);
|
||||
|
||||
public sealed record CreateTrendLogRequest(
|
||||
@@ -19,7 +20,8 @@ public sealed record CreateTrendLogRequest(
|
||||
uint BacnetObjectInstance,
|
||||
int IntervalSeconds,
|
||||
int MaxRecords,
|
||||
bool Enabled);
|
||||
bool Enabled,
|
||||
bool IsPublic = false);
|
||||
|
||||
public sealed record TrendRecord(
|
||||
Guid TrendLogId,
|
||||
|
||||
@@ -2,5 +2,10 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.31" />
|
||||
<PackageReference Include="MQTTnet" Version="5.2.0.1603" />
|
||||
<PackageReference Include="NModbus" Version="3.0.83" />
|
||||
<PackageReference Include="NModbus.Serial" Version="3.0.83" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.5.378.182" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.378.182" />
|
||||
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+498
-27
@@ -1,3 +1,4 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using Gateway.Api.Contracts;
|
||||
using Gateway.Api.Domain;
|
||||
@@ -9,9 +10,12 @@ using Gateway.Api.Services;
|
||||
// store. Explicitly use the executable directory as the content/web root so
|
||||
// the web UI is available no matter which working directory systemd uses.
|
||||
var applicationRoot = AppContext.BaseDirectory;
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.WebHost.UseContentRoot(applicationRoot);
|
||||
builder.WebHost.UseWebRoot(Path.Combine(applicationRoot, "wwwroot"));
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
||||
{
|
||||
Args = args,
|
||||
ContentRootPath = applicationRoot,
|
||||
WebRootPath = Path.Combine(applicationRoot, "wwwroot")
|
||||
});
|
||||
builder.Services.Configure<GatewayOptions>(builder.Configuration.GetSection("Gateway"));
|
||||
builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
builder.Services.AddSingleton<GatewayDatabase>();
|
||||
@@ -21,11 +25,45 @@ builder.Services.AddSingleton<MappingValidator>();
|
||||
builder.Services.AddSingleton<WriteJournal>();
|
||||
builder.Services.AddSingleton<SecretProtector>();
|
||||
builder.Services.AddSingleton<GatewayStore>();
|
||||
builder.Services.AddSingleton<HardwareDiscoveryService>();
|
||||
builder.Services.AddSingleton<HostNetworkService>();
|
||||
builder.Services.AddSingleton<BacnetBrowserService>();
|
||||
builder.Services.AddHostedService<BacnetExternalPointService>();
|
||||
builder.Services.AddHttpClient("seiugw-notifications", client => { client.Timeout = TimeSpan.FromSeconds(10); client.MaxResponseContentBufferSize = 64 * 1024; })
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddSingleton<NotificationTransport>();
|
||||
builder.Services.AddHostedService<AlarmNotificationService>();
|
||||
builder.Services.AddSingleton<CsvRunnerService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<CsvRunnerService>());
|
||||
builder.Services.AddSingleton<MqttClientService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MqttClientService>());
|
||||
builder.Services.AddSingleton<MqttTopicBrowserService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MqttTopicBrowserService>());
|
||||
builder.Services.AddSingleton<MappingRuntimeService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MappingRuntimeService>());
|
||||
builder.Services.AddSingleton<ModbusProtocolService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<ModbusProtocolService>());
|
||||
builder.Services.AddSingleton<OpcUaApplicationFactory>();
|
||||
builder.Services.AddSingleton<OpcUaBrowserService>();
|
||||
builder.Services.AddSingleton<OpcUaServerService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<OpcUaServerService>());
|
||||
builder.Services.AddSingleton<OpcUaClientService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<OpcUaClientService>());
|
||||
builder.Services.AddHostedService<BacnetNativeBridgeService>();
|
||||
|
||||
var app = builder.Build();
|
||||
app.Services.GetRequiredService<GatewayStore>().Initialize();
|
||||
var commandStore = app.Services.GetRequiredService<GatewayStore>();
|
||||
if (args.Length == 2 && args[0] == "--materialize-komari-token")
|
||||
{
|
||||
Environment.ExitCode = commandStore.MaterializeKomariEnrollmentToken(args[1]) ? 0 : 1;
|
||||
return;
|
||||
}
|
||||
if (args.Length == 2 && args[0] == "--import-komari-token")
|
||||
{
|
||||
commandStore.ImportKomariEnrollmentTokenFile(args[1]);
|
||||
return;
|
||||
}
|
||||
commandStore.Initialize();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
@@ -43,11 +81,95 @@ app.Use(async (context, next) =>
|
||||
app.UseDefaultFiles();
|
||||
app.UseStaticFiles();
|
||||
|
||||
app.MapGet("/api/presentation", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(new { units = store.ListDisplayUnits(), points = store.ListPointPresentations() }) : Results.Unauthorized());
|
||||
app.MapPut("/api/presentation/units", (DisplayUnit unit, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases)
|
||||
? Results.Ok(store.SaveDisplayUnit(unit)) : Results.StatusCode(403));
|
||||
app.MapPut("/api/presentation/points", (PointPresentation[] points, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases)) return Results.StatusCode(403);
|
||||
store.SavePointPresentations(points);
|
||||
return Results.NoContent();
|
||||
});
|
||||
app.MapGet("/api/dashboard", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Contains(GatewayPermissions.ViewDashboard)
|
||||
? Results.Ok(store.GetDashboard(user.User.Id)) : Results.StatusCode(403));
|
||||
app.MapPut("/api/dashboard", (DashboardWidget[] widgets, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (sessions.GetUser(request.Headers.Authorization) is not { } user || !user.Permissions.Contains(GatewayPermissions.ViewDashboard)) return Results.StatusCode(403);
|
||||
store.SaveDashboard(user.User.Id, user.User.Role == "admin", widgets);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/points/catalog", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Any(permission => permission is GatewayPermissions.ManageSources or GatewayPermissions.EditAliases or GatewayPermissions.ManageAlarms or GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(store.ListPoints().Select(point => new { point.Id, point.DisplayName, point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable })) : Results.StatusCode(403));
|
||||
|
||||
app.MapGet("/api/points/status", (HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt,
|
||||
OpcUaClientService opcUaClient, OpcUaServerService opcUaServer, ModbusProtocolService modbus) =>
|
||||
{
|
||||
var auth = request.Headers.Authorization;
|
||||
var gateway = sessions.HasPermission(auth, GatewayPermissions.ManageGateway);
|
||||
var sources = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageSources);
|
||||
var integrations = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageIntegrations);
|
||||
if (!sources && !integrations) return Results.StatusCode(403);
|
||||
var configuration = store.GetGatewayConfiguration();
|
||||
var clientStatus = opcUaClient.GetStatus().ToDictionary(client => client.ClientId);
|
||||
var pointNames = sources ? store.ListPoints().ToDictionary(point => point.Id, point => point.DisplayName) : [];
|
||||
return Results.Ok(new
|
||||
{
|
||||
checkedAtUtc = DateTimeOffset.UtcNow,
|
||||
mqtt = integrations ? mqtt.GetStatus() : null,
|
||||
bacnet = sources ? store.GetBacnetNativeStatus() : null,
|
||||
opcUa = sources ? new
|
||||
{
|
||||
serverEnabled = configuration.OpcUa.ServerEnabled,
|
||||
server = opcUaServer.GetStatus(),
|
||||
clientsEnabled = configuration.OpcUa.ClientEnabled,
|
||||
clients = (configuration.OpcUa.Clients ?? []).Select(client => new { client.Id, client.Name, client.Enabled, status = clientStatus.GetValueOrDefault(client.Id) })
|
||||
} : null,
|
||||
modbus = sources ? new
|
||||
{
|
||||
servers = configuration.ModbusServers.Select(server => new { server.Name, server.Port, listening = modbus.IsTcpListening(server), error = modbus.GetTcpError(server.Id) }),
|
||||
pointErrors = modbus.GetPointErrors().Where(issue => pointNames.ContainsKey(issue.Id)).OrderByDescending(issue => issue.OccurredAtUtc)
|
||||
.Select(issue => new { pointId = issue.Id, name = pointNames[issue.Id], issue.Error, issue.OccurredAtUtc }).ToArray()
|
||||
} : null,
|
||||
pointErrors = sources ? store.ListPointValues()
|
||||
.Where(value => pointNames.ContainsKey(value.PointId) && value.Status is { Length: > 0 } quality &&
|
||||
!quality.Equals("Good", StringComparison.OrdinalIgnoreCase) && !quality.Equals("ok", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(value => new { value.PointId, name = pointNames[value.PointId], value.SourceProtocol, value.Status, value.UpdatedAtUtc }).ToArray() : null
|
||||
});
|
||||
});
|
||||
|
||||
app.MapGet("/api/integrations/notifications", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms)
|
||||
? Results.Ok(store.ListNotificationIntegrations()) : Results.StatusCode(403));
|
||||
app.MapPut("/api/integrations/notifications/{channel}", (NotificationChannel channel, UpdateNotificationKeyRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
|
||||
store.UpdateNotificationKey(channel, update);
|
||||
return Results.NoContent();
|
||||
});
|
||||
app.MapGet("/api/alarms", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListAlarmRules()) : Results.StatusCode(403));
|
||||
app.MapPut("/api/alarms", (AlarmRule rule, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.SaveAlarmRule(rule)) : Results.StatusCode(403));
|
||||
app.MapDelete("/api/alarms/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms)) return Results.StatusCode(403);
|
||||
store.DeleteAlarmRule(id);
|
||||
return Results.NoContent();
|
||||
});
|
||||
app.MapGet("/api/alarms/deliveries", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListNotificationDeliveries()) : Results.StatusCode(403));
|
||||
|
||||
app.MapGet("/api/health", (GatewayStore store) => Results.Ok(new
|
||||
{
|
||||
status = "ok",
|
||||
adminConfigured = store.HasAdmin(),
|
||||
protocolDataPlane = "not-started"
|
||||
protocolDataPlane = builder.Configuration["Gateway:ProtocolDataPlane"] ?? "not-started"
|
||||
}));
|
||||
|
||||
app.MapGet("/api/setup", (GatewayStore store) => Results.Ok(new { adminConfigured = store.HasAdmin() }));
|
||||
@@ -60,15 +182,21 @@ app.MapPost("/api/setup", (SetInitialAdminRequest request, GatewayStore store) =
|
||||
|
||||
app.MapPost("/api/auth/login", (LoginRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (request.Username != "admin" || !store.VerifyAdminPassword(request.Password))
|
||||
var user = store.Authenticate(request.Username, request.Password);
|
||||
if (user is null)
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var token = sessions.Create();
|
||||
return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12)));
|
||||
var token = sessions.Create(user);
|
||||
return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12), user));
|
||||
});
|
||||
|
||||
app.MapGet("/api/auth/me", (HttpRequest request, SessionService sessions) =>
|
||||
sessions.GetUser(request.Headers.Authorization) is { } user
|
||||
? Results.Ok(new { user })
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) =>
|
||||
{
|
||||
sessions.Remove(request.Headers.Authorization);
|
||||
@@ -77,24 +205,99 @@ app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) =
|
||||
|
||||
app.MapPost("/api/auth/password", (ChangePasswordRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(httpRequest.Headers.Authorization))
|
||||
if (sessions.GetUser(httpRequest.Headers.Authorization) is not { } user)
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
store.ChangeAdminPassword(request.CurrentPassword, request.NewPassword);
|
||||
if (string.IsNullOrEmpty(request.NewPasswordConfirmation) ||
|
||||
!string.Equals(request.NewPassword, request.NewPasswordConfirmation, StringComparison.Ordinal))
|
||||
{
|
||||
return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." });
|
||||
}
|
||||
store.ChangeUserPassword(user.User.Id, request.CurrentPassword, request.NewPassword);
|
||||
sessions.Remove(httpRequest.Headers.Authorization);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/auth/preferences", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.GetUser(request.Headers.Authorization) is { } user
|
||||
? Results.Ok(store.GetUserPreferences(user.User.Id))
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/auth/preferences", (UpdateUserPreferencesRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.GetUser(request.Headers.Authorization) is { } user
|
||||
? Results.Ok(store.UpdateUserPreferences(user.User.Id, update))
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapGet("/api/system/komari", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
|
||||
? Results.Ok(new { hasEnrollmentToken = store.HasKomariEnrollmentToken() })
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/system/komari", (UpdateKomariEnrollmentTokenRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(httpRequest.Headers.Authorization, GatewayPermissions.ManageGateway))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
store.UpdateKomariEnrollmentToken(request.EnrollmentToken);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/users", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers)
|
||||
? Results.Ok(store.ListUsers())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/users", (CreateUserRequest user, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
var created = store.CreateUser(user);
|
||||
return Results.Created($"/api/users/{created.Id}", created);
|
||||
});
|
||||
|
||||
app.MapPatch("/api/users/{userId:guid}", (Guid userId, UpdateUserRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
var actingUser = sessions.GetUser(request.Headers.Authorization);
|
||||
if (actingUser is null || !actingUser.Permissions.Contains(GatewayPermissions.ManageUsers, StringComparer.Ordinal))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
if (update.Password is not null &&
|
||||
!string.Equals(update.Password, update.PasswordConfirmation, StringComparison.Ordinal))
|
||||
{
|
||||
return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." });
|
||||
}
|
||||
return Results.Ok(store.UpdateUser(userId, update, actingUser.User.Id));
|
||||
});
|
||||
|
||||
app.MapGet("/api/roles", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
(sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers))
|
||||
? Results.Ok(new { roles = store.ListRoles(), permissions = GatewayPermissions.Catalog })
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/roles", (SaveRoleRequest role, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
var saved = store.SaveRole(role);
|
||||
return Results.Created($"/api/roles/{saved.Name}", saved);
|
||||
});
|
||||
|
||||
app.MapGet("/api/gateway/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
|
||||
? Results.Ok(store.GetGatewayConfiguration())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
@@ -103,14 +306,60 @@ app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, Ht
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/gateway/hardware", (HttpRequest request, HardwareDiscoveryService hardware, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
|
||||
? Results.Ok(hardware.GetInventory())
|
||||
: Results.Unauthorized());
|
||||
app.MapPut("/api/gateway/installation", (InstallationIdentity identity, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
|
||||
? Results.Ok(store.UpdateInstallationIdentity(identity)) : Results.StatusCode(403));
|
||||
|
||||
var network = app.MapGroup("/api/system/network");
|
||||
network.AddEndpointFilter(async (context, next) =>
|
||||
{
|
||||
var http = context.HttpContext;
|
||||
return http.RequestServices.GetRequiredService<SessionService>()
|
||||
.HasPermission(http.Request.Headers.Authorization, GatewayPermissions.ManageGateway)
|
||||
? await next(context) : Results.StatusCode(403);
|
||||
});
|
||||
network.MapGet("", (HostNetworkService service, CancellationToken ct) => service.SendAsync(new { action = "status" }, ct));
|
||||
network.MapPost("/apply", (HostNetworkProfile profile, HostNetworkService service, CancellationToken ct) =>
|
||||
service.SendAsync(new { action = "apply", profile }, ct));
|
||||
network.MapPost("/confirm", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) =>
|
||||
service.SendAsync(new { action = "confirm", change.Id }, ct));
|
||||
network.MapPost("/revert", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) =>
|
||||
service.SendAsync(new { action = "revert", change.Id }, ct));
|
||||
|
||||
app.MapPost("/api/bacnet/scan", async (BacnetScanRequest scan, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized();
|
||||
return Results.Ok(await browser.ScanAsync(scan, cancellationToken));
|
||||
});
|
||||
|
||||
app.MapPost("/api/bacnet/browse", async (BacnetBrowseRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized();
|
||||
return Results.Ok(await browser.BrowseObjectListAsync(browse, cancellationToken));
|
||||
});
|
||||
app.MapPost("/api/bacnet/objects", async (BacnetObjectsRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return Results.Ok(await browser.BrowseDetailsAsync(browse, cancellationToken));
|
||||
});
|
||||
app.MapPost("/api/bacnet/import", async (BacnetImportRequest import, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return Results.Ok(await browser.ImportAsync(import, cancellationToken));
|
||||
});
|
||||
|
||||
app.MapGet("/api/points", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.ListPoints())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
@@ -118,54 +367,150 @@ app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, Gatew
|
||||
var createdPoint = store.CreatePoint(point);
|
||||
return Results.Created($"/api/points/{createdPoint.Id}", createdPoint);
|
||||
});
|
||||
app.MapGet("/api/points/{id:guid}/dependencies", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return store.GetPointDependencies(id) is { } dependencies ? Results.Ok(dependencies) : Results.NotFound();
|
||||
});
|
||||
app.MapPut("/api/points/{id:guid}", (Guid id, CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return store.UpdatePoint(id, point) is { } updated ? Results.Ok(updated) : Results.NotFound();
|
||||
});
|
||||
app.MapDelete("/api/points/{id:guid}", (Guid id, string? confirmation, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return store.DeletePoint(id, confirmation) ? Results.NoContent() : Results.NotFound();
|
||||
});
|
||||
|
||||
app.MapGet("/api/imports/modbus-example.csv", (HttpRequest request, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.File(System.Text.Encoding.UTF8.GetBytes(ModbusCsvImporter.Example), "text/csv; charset=utf-8", "seiugw-modbus-beispiel.csv")
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/imports/modbus-csv", (ModbusCsvImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
return Results.Ok(ModbusCsvImporter.Import(import.Csv, store));
|
||||
});
|
||||
|
||||
app.MapPost("/api/imports/knx-ets", (KnxEtsImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
return Results.Ok(KnxEtsImporter.Import(import, store));
|
||||
});
|
||||
|
||||
app.MapPost("/api/opcua/browse", async (OpcUaBrowseRequest browse, HttpRequest request, OpcUaBrowserService browser, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
return Results.Ok(await browser.BrowseAsync(browse));
|
||||
});
|
||||
|
||||
app.MapGet("/api/opcua/clients", (HttpRequest request, GatewayStore store, OpcUaClientService clients, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(new { clients = store.ListOpcUaClients(), status = clients.GetStatus() }) : Results.Unauthorized());
|
||||
app.MapGet("/api/bacnet/status", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.GetBacnetNativeStatus()) : Results.Unauthorized());
|
||||
app.MapPost("/api/opcua/clients", (SaveOpcUaClientRequest configuration, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.SaveOpcUaClient(configuration)) : Results.Unauthorized());
|
||||
app.MapPost("/api/opcua/import", (OpcUaImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.ImportOpcUaPoints(import)) : Results.Unauthorized());
|
||||
|
||||
app.MapGet("/api/mqtt/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(store.GetMqttConfiguration())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/mqtt/configuration", (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
app.MapPut("/api/mqtt/configuration", async (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store,
|
||||
SessionService sessions, MqttClientService mqttClient, MqttTopicBrowserService browser) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
store.UpdateMqttConfiguration(mqtt);
|
||||
mqttClient.RequestReconfigure();
|
||||
await browser.ResetAsync(CancellationToken.None);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapPost("/api/mqtt/browser", async (MqttTopicBrowseRequest browse, HttpRequest request, SessionService sessions,
|
||||
MqttTopicBrowserService browser, CancellationToken cancellationToken) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(await browser.StartBrowseAsync(browse, cancellationToken)) : Results.StatusCode(403));
|
||||
app.MapGet("/api/mqtt/browser/{id:guid}", (Guid id, HttpRequest request, SessionService sessions, MqttTopicBrowserService browser) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(browser.GetBrowse(id)) : Results.StatusCode(403));
|
||||
app.MapPost("/api/mqtt/browser/import", async (MqttTopicImportRequest import, HttpRequest request, SessionService sessions,
|
||||
MqttTopicBrowserService browser, CancellationToken cancellationToken) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) &&
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(await browser.ImportAsync(import, cancellationToken)) : Results.StatusCode(403));
|
||||
|
||||
app.MapGet("/api/mqtt/status", (HttpRequest request, SessionService sessions, MqttClientService mqttClient) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(mqttClient.GetStatus())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(store.ListMqttMappings().Select(mapping => new { Mapping = mapping, Topic = GatewayStore.GetMqttTopic(mapping) }))
|
||||
: Results.Unauthorized());
|
||||
app.MapGet("/api/mqtt/mapping-defaults", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
|
||||
? Results.Ok(store.GetMqttMappingDefaults()) : Results.StatusCode(403));
|
||||
|
||||
app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var createdMapping = store.CreateMqttMapping(mapping);
|
||||
if (createdMapping.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([createdMapping.Id]);
|
||||
mqttClient.RequestReconfigure();
|
||||
return Results.Created($"/api/mqtt/mappings/{createdMapping.Id}", new { Mapping = createdMapping, Topic = GatewayStore.GetMqttTopic(createdMapping) });
|
||||
});
|
||||
app.MapPut("/api/mqtt/mappings/{id:guid}", (Guid id, CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
|
||||
if (store.UpdateMqttMapping(id, mapping) is not { } updated) return Results.NotFound();
|
||||
if (updated.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([updated.Id]);
|
||||
mqttClient.RequestReconfigure();
|
||||
return Results.Ok(new { Mapping = updated, Topic = GatewayStore.GetMqttTopic(updated) });
|
||||
});
|
||||
app.MapDelete("/api/mqtt/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
|
||||
if (!store.DeleteMqttMapping(id)) return Results.NotFound();
|
||||
mqttClient.RequestReconfigure();
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.ListMappings())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
@@ -173,15 +518,59 @@ app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request,
|
||||
var response = store.CreateMapping(mapping);
|
||||
return Results.Created($"/api/mappings/{response.Mapping.Id}", response);
|
||||
});
|
||||
app.MapPut("/api/mappings/{id:guid}", (Guid id, CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return store.UpdateMapping(id, mapping) is { } updated ? Results.Ok(updated) : Results.NotFound();
|
||||
});
|
||||
app.MapDelete("/api/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
|
||||
return store.DeleteMapping(id) ? Results.NoContent() : Results.NotFound();
|
||||
});
|
||||
app.MapGet("/api/mappings/bulk/modbus-servers", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
|
||||
? Results.Ok(store.GetGatewayConfiguration().ModbusServers.Select(server =>
|
||||
new { server.Id, server.Name, server.FirstHoldingRegister, server.HoldingRegisterCount }))
|
||||
: Results.StatusCode(403));
|
||||
app.MapPost("/api/mappings/bulk", (BulkMappingRequest bulk, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) =>
|
||||
{
|
||||
var authorization = request.Headers.Authorization;
|
||||
if (!sessions.HasPermission(authorization, GatewayPermissions.ManageSources) ||
|
||||
bulk.Target == BulkMappingTarget.Mqtt && !sessions.HasPermission(authorization, GatewayPermissions.ManageIntegrations))
|
||||
return Results.StatusCode(403);
|
||||
var result = store.CreateBulkMappings(bulk);
|
||||
mqtt.QueueInitialPublications(result.NewMqttMappings);
|
||||
return Results.Ok(result);
|
||||
});
|
||||
|
||||
MapConfigurationCsv("/api/points/csv", "seiugw-datenpunkte.csv", ConfigurationCsvKind.Points, GatewayPermissions.ManageSources);
|
||||
MapConfigurationCsv("/api/mappings/csv", "seiugw-mappings.csv", ConfigurationCsvKind.Mappings, GatewayPermissions.ManageSources);
|
||||
MapConfigurationCsv("/api/mqtt/mappings/csv", "seiugw-mqtt-mappings.csv", ConfigurationCsvKind.MqttMappings, GatewayPermissions.ManageIntegrations);
|
||||
|
||||
void MapConfigurationCsv(string route, string file, ConfigurationCsvKind kind, string permission)
|
||||
{
|
||||
app.MapGet(route, (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, permission)
|
||||
? Results.File(Encoding.UTF8.GetBytes(store.ExportConfigurationCsv(kind)), "text/csv; charset=utf-8", file)
|
||||
: Results.StatusCode(403));
|
||||
app.MapPost(route, (ConfigurationCsvRequest input, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, permission)) return Results.StatusCode(403);
|
||||
var result = store.ImportConfigurationCsv(kind, input.Csv);
|
||||
if (kind == ConfigurationCsvKind.MqttMappings && result.Created + result.Updated > 0) mqtt.RequestReconfigure();
|
||||
return Results.Ok(result);
|
||||
});
|
||||
}
|
||||
|
||||
app.MapGet("/api/trend-logs", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends)
|
||||
? Results.Ok(store.ListTrendLogs())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
@@ -191,13 +580,22 @@ app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest requ
|
||||
});
|
||||
|
||||
app.MapGet("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends)
|
||||
? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500))
|
||||
: Results.Unauthorized());
|
||||
|
||||
// Public trend access is deliberately opt-in per trend log. It exposes only sampled values,
|
||||
// never gateway configuration, credentials, points, mappings, or write functions.
|
||||
app.MapGet("/api/public/trend-logs", (GatewayStore store) => Results.Ok(store.ListPublicTrendLogs()));
|
||||
|
||||
app.MapGet("/api/public/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, GatewayStore store) =>
|
||||
store.IsPublicTrendLog(trendLogId)
|
||||
? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500))
|
||||
: Results.NotFound());
|
||||
|
||||
app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, AppendTrendRecordRequest trendRecord, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
@@ -206,8 +604,81 @@ app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, Appen
|
||||
return createdRecord is null ? Results.NoContent() : Results.Created($"/api/trend-logs/{trendLogId}/records/{createdRecord.SequenceNumber}", createdRecord);
|
||||
});
|
||||
|
||||
app.MapGet("/api/trend-selections", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
var user = sessions.GetUser(request.Headers.Authorization);
|
||||
return user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)
|
||||
? Results.Unauthorized()
|
||||
: Results.Ok(store.ListTrendSelections(user.User.Id, user.User.Role == "admin"));
|
||||
});
|
||||
|
||||
app.MapPost("/api/trend-selections", (CreateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
var user = sessions.GetUser(request.Headers.Authorization);
|
||||
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
|
||||
var created = store.CreateTrendSelection(selection, user.User.Id);
|
||||
return Results.Created($"/api/trend-selections/{created.Id}", created);
|
||||
});
|
||||
|
||||
app.MapPatch("/api/trend-selections/{selectionId:guid}", (Guid selectionId, UpdateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
var user = sessions.GetUser(request.Headers.Authorization);
|
||||
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
|
||||
return Results.Ok(store.UpdateTrendSelection(selectionId, selection, user.User.Id, user.User.Role == "admin"));
|
||||
});
|
||||
|
||||
app.MapDelete("/api/trend-selections/{selectionId:guid}", (Guid selectionId, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
var user = sessions.GetUser(request.Headers.Authorization);
|
||||
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
|
||||
store.DeleteTrendSelection(selectionId, user.User.Id, user.User.Role == "admin");
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/integrations/mail", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.GetMailIntegration()) : Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/integrations/mail", (UpdateMailIntegrationRequest integration, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.Unauthorized();
|
||||
store.UpdateMailIntegration(integration);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/runner/jobs", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(store.ListCsvRunnerJobs()) : Results.Unauthorized());
|
||||
|
||||
app.MapGet("/api/runner/queue", (HttpRequest request, CsvRunnerService runner, SessionService sessions) =>
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(runner.ListExecutions()) : Results.StatusCode(403));
|
||||
|
||||
app.MapPost("/api/runner/jobs", (CreateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
|
||||
var created = store.CreateCsvRunnerJob(job);
|
||||
return Results.Created($"/api/runner/jobs/{created.Id}", created);
|
||||
});
|
||||
|
||||
app.MapPatch("/api/runner/jobs/{jobId:guid}", (Guid jobId, UpdateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
|
||||
return Results.Ok(store.UpdateCsvRunnerJob(jobId, job));
|
||||
});
|
||||
|
||||
app.MapPost("/api/runner/jobs/{jobId:guid}/test", async (Guid jobId, HttpRequest request, CsvRunnerService runner, SessionService sessions, CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
|
||||
return Results.Ok(await runner.RunNowAsync(jobId, cancellationToken));
|
||||
});
|
||||
|
||||
app.MapDelete("/api/runner/jobs/{jobId:guid}", (Guid jobId, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
|
||||
store.DeleteCsvRunnerJob(jobId);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/audit", (int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewDebug)
|
||||
? Results.Ok(store.ListAudit(limit ?? 100))
|
||||
: Results.Unauthorized());
|
||||
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record BacnetScanRequest(string? Interface = null, int? TimeoutSeconds = null, string? TargetAddress = null, int? TargetPort = null);
|
||||
public sealed record BacnetDiscoveredDevice(int DeviceInstance, string Address, int Port, int? VendorId, int? MaxApdu,
|
||||
int Network = 0, string? Mac = null, string? DeviceName = null);
|
||||
public sealed record BacnetBrowseRequest(string Address, int DeviceInstance, int? Port = null, int? MaxObjects = null,
|
||||
string? Interface = null, int Network = 0, string? Mac = null);
|
||||
public sealed record BacnetObjectReference(string ObjectType, int ObjectInstance, string ObjectIdentifier);
|
||||
|
||||
/// <summary>
|
||||
/// BACnet/IP discovery and object-list reader. It sends standard BVLC/NPDU/APDU
|
||||
/// requests from its own ephemeral UDP socket, so it never competes with the native
|
||||
/// BACnet device service that owns the configured BACnet/IP port.
|
||||
/// </summary>
|
||||
public sealed partial class BacnetBrowserService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly GatewayDatabase _database;
|
||||
|
||||
public BacnetBrowserService(GatewayStore store, GatewayDatabase database)
|
||||
{
|
||||
_store = store;
|
||||
_database = database;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<BacnetDiscoveredDevice>> ScanAsync(BacnetScanRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var configuration = _store.GetGatewayConfiguration();
|
||||
var port = request.TargetPort ?? configuration.Bacnet.IpPort;
|
||||
if (port is < 1 or > 65535)
|
||||
{
|
||||
throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
|
||||
}
|
||||
var timeout = Math.Clamp(request.TimeoutSeconds ?? 5, 1, 30);
|
||||
var localAddresses = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface);
|
||||
if (localAddresses.Length == 0)
|
||||
{
|
||||
throw new DomainValidationException("Für die ausgewählte Schnittstelle wurde keine IPv4-Adresse gefunden.");
|
||||
}
|
||||
IPAddress? target = null;
|
||||
if (!string.IsNullOrWhiteSpace(request.TargetAddress) &&
|
||||
(!IPAddress.TryParse(request.TargetAddress, out target) ||
|
||||
target.AddressFamily != AddressFamily.InterNetwork || target.Equals(IPAddress.Any)))
|
||||
{
|
||||
throw new DomainValidationException("Für einen direkten BACnet-Scan ist eine gültige IPv4-Adresse erforderlich.");
|
||||
}
|
||||
if (OperatingSystem.IsLinux() && (request.Interface ?? configuration.Bacnet.Interface) == configuration.Bacnet.Interface &&
|
||||
(target is not null || port == configuration.Bacnet.IpPort))
|
||||
{
|
||||
var discovered = await ScanNativeAsync(target, port, timeout, cancellationToken);
|
||||
return await ReadDeviceNamesAsync(discovered, localAddresses[0].Address, cancellationToken);
|
||||
}
|
||||
|
||||
using var socket = CreateSocket(localAddresses[0].Address);
|
||||
if (target is not null)
|
||||
{
|
||||
await socket.SendAsync(new byte[] { 0x81, 0x0a, 0, 8, 1, 0, 0x10, 0x08 }, new IPEndPoint(target, port), cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var address in localAddresses)
|
||||
{
|
||||
await socket.SendAsync(CreateWhoIsPacket(), new IPEndPoint(GetBroadcastAddress(address), port), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
var devices = new Dictionary<string, BacnetDiscoveredDevice>(StringComparer.Ordinal);
|
||||
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutSource.CancelAfter(TimeSpan.FromSeconds(timeout));
|
||||
try
|
||||
{
|
||||
while (!timeoutSource.IsCancellationRequested)
|
||||
{
|
||||
var received = await socket.ReceiveAsync(timeoutSource.Token);
|
||||
if (TryParseIAm(received.Buffer, received.RemoteEndPoint, out var device))
|
||||
{
|
||||
devices[$"{device.DeviceInstance}@{device.Address}:{device.Port}"] = device;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Expected end of discovery window.
|
||||
}
|
||||
return await ReadDeviceNamesAsync(devices.Values.OrderBy(device => device.DeviceInstance)
|
||||
.ThenBy(device => device.Address, StringComparer.Ordinal).ToArray(), localAddresses[0].Address, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<BacnetDiscoveredDevice>> ScanNativeAsync(IPAddress? target, int port, int timeoutSeconds, CancellationToken cancellationToken)
|
||||
{
|
||||
var scanId = Guid.NewGuid().ToString("N");
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
var deadline = now + (timeoutSeconds * 1000L) + 1500;
|
||||
using (var connection = _database.OpenConnection())
|
||||
using (var transaction = connection.BeginTransaction())
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
|
||||
if (command.ExecuteScalar() is not long heartbeat || now - heartbeat >= 5000)
|
||||
throw new DomainValidationException("Der native BACnet-Dienst ist nicht erreichbar.");
|
||||
command.CommandText = "DELETE FROM bacnet_discovery WHERE expires_ms < $now";
|
||||
command.Parameters.AddWithValue("$now", now);
|
||||
command.ExecuteNonQuery();
|
||||
command.CommandText = "INSERT OR IGNORE INTO bacnet_discovery(id,scan_id,target,port,expires_ms) VALUES(1,$id,$target,$port,$deadline)";
|
||||
command.Parameters.Clear();
|
||||
command.Parameters.AddWithValue("$id", scanId);
|
||||
command.Parameters.AddWithValue("$target", (object?)target?.ToString() ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$port", port);
|
||||
command.Parameters.AddWithValue("$deadline", deadline + 5000);
|
||||
if (command.ExecuteNonQuery() != 1)
|
||||
throw new DomainValidationException("Eine BACnet-Gerätesuche läuft bereits.");
|
||||
command.CommandText = "DELETE FROM bacnet_discovered_devices WHERE scan_id <> $id";
|
||||
command.ExecuteNonQuery();
|
||||
transaction.Commit();
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(deadline - now), cancellationToken);
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT sent FROM bacnet_discovery WHERE scan_id=$id";
|
||||
command.Parameters.AddWithValue("$id", scanId);
|
||||
if (command.ExecuteScalar() is not 1L)
|
||||
throw new DomainValidationException("Der native BACnet-Dienst hat die Suche nicht gestartet.");
|
||||
command.CommandText = """
|
||||
SELECT device_instance,address,port,vendor,max_apdu,network,mac FROM bacnet_discovered_devices
|
||||
WHERE scan_id=$id ORDER BY device_instance,address,port
|
||||
""";
|
||||
using var reader = command.ExecuteReader();
|
||||
var devices = new List<BacnetDiscoveredDevice>();
|
||||
while (reader.Read())
|
||||
devices.Add(new(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4),
|
||||
reader.GetInt32(5), reader.IsDBNull(6) ? null : reader.GetString(6)));
|
||||
return devices;
|
||||
}
|
||||
finally
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "DELETE FROM bacnet_discovery WHERE scan_id=$id";
|
||||
command.Parameters.AddWithValue("$id", scanId);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<BacnetObjectReference>> BrowseObjectListAsync(BacnetBrowseRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IPAddress.TryParse(request.Address, out var address) || address.AddressFamily != AddressFamily.InterNetwork || address.Equals(IPAddress.Any))
|
||||
{
|
||||
throw new DomainValidationException("Für das BACnet-Browsing ist eine erreichbare IPv4-Adresse erforderlich. 0.0.0.0 ist keine Zieladresse.");
|
||||
}
|
||||
if (request.DeviceInstance is < 0 or > 4_194_303)
|
||||
{
|
||||
throw new DomainValidationException("Die BACnet-Device-Instance ist ungültig.");
|
||||
}
|
||||
|
||||
var configuration = _store.GetGatewayConfiguration();
|
||||
var localAddresses = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface);
|
||||
if (localAddresses.Length == 0)
|
||||
{
|
||||
throw new DomainValidationException("Für die konfigurierte BACnet-Schnittstelle wurde keine IPv4-Adresse gefunden.");
|
||||
}
|
||||
var port = request.Port ?? configuration.Bacnet.IpPort;
|
||||
if (port is < 1 or > 65535) throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
|
||||
var target = new IPEndPoint(address, port);
|
||||
var route = ReadRoute(request);
|
||||
using var socket = CreateSocket(localAddresses[0].Address);
|
||||
var count = await ReadObjectListCountAsync(socket, target, request.DeviceInstance, route, cancellationToken);
|
||||
var maximum = Math.Min(count, Math.Clamp(request.MaxObjects ?? 500, 1, 5_000));
|
||||
var objects = new List<BacnetObjectReference>(maximum);
|
||||
for (var index = 1; index <= maximum; index++)
|
||||
{
|
||||
var value = await ReadObjectListItemAsync(socket, target, request.DeviceInstance, index, route, cancellationToken);
|
||||
if (value is { } objectId)
|
||||
{
|
||||
objects.Add(ToObjectReference(objectId));
|
||||
}
|
||||
}
|
||||
return objects;
|
||||
}
|
||||
|
||||
private sealed record BacnetRoute(int Network, byte[] Mac);
|
||||
|
||||
private static BacnetRoute? ReadRoute(BacnetBrowseRequest request)
|
||||
{
|
||||
if (request.Network == 0 && string.IsNullOrEmpty(request.Mac)) return null;
|
||||
if (request.Network is < 1 or > 65534 || request.Mac is null ||
|
||||
request.Mac.Length is < 2 or > 14 || request.Mac.Length % 2 != 0 ||
|
||||
!request.Mac.All(Uri.IsHexDigit))
|
||||
throw new DomainValidationException("BACnet-Netznummer oder Geräte-MAC ist ungültig.");
|
||||
return new(request.Network, Convert.FromHexString(request.Mac));
|
||||
}
|
||||
|
||||
private static UdpClient CreateSocket(IPAddress localAddress)
|
||||
{
|
||||
var socket = new UdpClient(AddressFamily.InterNetwork);
|
||||
socket.EnableBroadcast = true;
|
||||
socket.Client.Bind(new IPEndPoint(localAddress, 0));
|
||||
return socket;
|
||||
}
|
||||
|
||||
private static UnicastIPAddressInformation[] GetLocalAddresses(string? interfaceName)
|
||||
{
|
||||
var networks = NetworkInterface.GetAllNetworkInterfaces()
|
||||
.Where(network => network.OperationalStatus == OperationalStatus.Up && network.NetworkInterfaceType != NetworkInterfaceType.Loopback);
|
||||
if (!string.IsNullOrWhiteSpace(interfaceName))
|
||||
{
|
||||
networks = networks.Where(network => string.Equals(network.Name, interfaceName, StringComparison.Ordinal));
|
||||
}
|
||||
return networks.SelectMany(network => network.GetIPProperties().UnicastAddresses)
|
||||
.Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork && address.IPv4Mask is not null)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static IPAddress GetBroadcastAddress(UnicastIPAddressInformation address)
|
||||
{
|
||||
var bytes = address.Address.GetAddressBytes();
|
||||
var mask = address.IPv4Mask.GetAddressBytes();
|
||||
for (var index = 0; index < bytes.Length; index++)
|
||||
{
|
||||
bytes[index] = (byte)(bytes[index] | ~mask[index]);
|
||||
}
|
||||
return new IPAddress(bytes);
|
||||
}
|
||||
|
||||
private static byte[] CreateWhoIsPacket() => [
|
||||
0x81, 0x0b, 0x00, 0x0c, // BVLC original-broadcast NPDU
|
||||
0x01, 0x20, 0xff, 0xff, 0x00, 0xff, // global broadcast NPDU
|
||||
0x10, 0x08 // unconfirmed-request / Who-Is
|
||||
];
|
||||
|
||||
private static bool TryParseIAm(byte[] packet, IPEndPoint endpoint, out BacnetDiscoveredDevice device)
|
||||
{
|
||||
device = default!;
|
||||
if (packet.Length < 16 || packet[0] != 0x81 || ((packet[2] << 8) | packet[3]) != packet.Length)
|
||||
return false;
|
||||
var position = packet[1] switch { 0x04 => 10, 0x0a or 0x0b => 4, _ => -1 };
|
||||
if (position < 0 || position + 2 >= packet.Length || packet[position++] != 1) return false;
|
||||
var control = packet[position++];
|
||||
if ((control & 0x80) != 0) return false;
|
||||
if ((control & 0x20) != 0 && !SkipNetworkAddress(packet, ref position)) return false;
|
||||
var sourceNetwork = 0;
|
||||
string? sourceMac = null;
|
||||
if ((control & 0x08) != 0)
|
||||
{
|
||||
var start = position;
|
||||
if (!SkipNetworkAddress(packet, ref position) || position == start + 3) return false;
|
||||
sourceNetwork = (packet[start] << 8) | packet[start + 1];
|
||||
sourceMac = Convert.ToHexString(packet.AsSpan(start + 3, position - start - 3));
|
||||
}
|
||||
if ((control & 0x20) != 0) position++; // Hop count follows both addresses.
|
||||
if (position + 7 > packet.Length || packet[position] != 0x10 ||
|
||||
packet[position + 1] != 0 || packet[position + 2] != 0xc4) return false;
|
||||
var rawObject = ReadUInt32(packet, position + 3);
|
||||
position += 7;
|
||||
if ((rawObject >> 22) != 8 ||
|
||||
!ReadApplicationNumber(packet, ref position, 0x20, out var maxApdu) ||
|
||||
!ReadApplicationNumber(packet, ref position, 0x90, out var segmentation) ||
|
||||
!ReadApplicationNumber(packet, ref position, 0x20, out var vendor) ||
|
||||
maxApdu > ushort.MaxValue || segmentation > 3 || vendor > ushort.MaxValue) return false;
|
||||
if (packet[1] == 0x04)
|
||||
endpoint = new IPEndPoint(new IPAddress(packet.AsSpan(4, 4)), (packet[8] << 8) | packet[9]);
|
||||
device = new BacnetDiscoveredDevice((int)(rawObject & 0x3f_ffff), endpoint.Address.ToString(), endpoint.Port, (int)vendor, (int)maxApdu, sourceNetwork, sourceMac);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool SkipNetworkAddress(byte[] packet, ref int position)
|
||||
{
|
||||
if (position + 3 > packet.Length) return false;
|
||||
position += 3 + packet[position + 2];
|
||||
return position <= packet.Length;
|
||||
}
|
||||
|
||||
private static bool ReadApplicationNumber(byte[] packet, ref int position, byte type, out uint value)
|
||||
{
|
||||
value = 0;
|
||||
if (position >= packet.Length) return false;
|
||||
var tag = packet[position++];
|
||||
var length = tag & 7;
|
||||
if ((tag & 0xf8) != type || length is < 1 or > 4 || position + length > packet.Length) return false;
|
||||
for (var end = position + length; position < end; position++) value = (value << 8) | packet[position];
|
||||
return true;
|
||||
}
|
||||
|
||||
private static async Task<int> ReadObjectListCountAsync(UdpClient socket, IPEndPoint target, int deviceInstance, BacnetRoute? route, CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await ReadPropertyAsync(socket, target, deviceInstance, 76, 0, route, cancellationToken);
|
||||
var openTag = Array.IndexOf(response, (byte)0x3e);
|
||||
if (openTag < 0 || openTag + 2 >= response.Length)
|
||||
{
|
||||
throw new DomainValidationException("Das BACnet-Gerät lieferte keine Object_List zurück.");
|
||||
}
|
||||
var tag = response[openTag + 1];
|
||||
var length = tag & 0x07;
|
||||
if ((tag & 0xf8) != 0x20 || length is < 1 or > 4 || openTag + 2 + length > response.Length)
|
||||
{
|
||||
throw new DomainValidationException("Die BACnet Object_List hat ein nicht unterstütztes Format.");
|
||||
}
|
||||
var count = 0;
|
||||
for (var index = 0; index < length; index++) count = (count << 8) | response[openTag + 2 + index];
|
||||
if (count < 0) throw new DomainValidationException("Die BACnet Object_List meldet eine ungültige Objektanzahl.");
|
||||
return count;
|
||||
}
|
||||
|
||||
private static async Task<uint?> ReadObjectListItemAsync(UdpClient socket, IPEndPoint target, int deviceInstance, int index, BacnetRoute? route, CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await ReadPropertyAsync(socket, target, deviceInstance, 76, index, route, cancellationToken);
|
||||
var openTag = Array.IndexOf(response, (byte)0x3e);
|
||||
for (var position = openTag + 1; openTag >= 0 && position + 4 < response.Length; position++)
|
||||
{
|
||||
if (response[position] == 0xc4)
|
||||
{
|
||||
return ReadUInt32(response, position + 1);
|
||||
}
|
||||
if (response[position] == 0x3f) break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadPropertyAsync(UdpClient socket, IPEndPoint target, int deviceInstance, int propertyId, int arrayIndex, BacnetRoute? route, CancellationToken cancellationToken)
|
||||
=> await ReadPropertyAsync(socket, target, 8, deviceInstance, propertyId, arrayIndex, route, cancellationToken);
|
||||
|
||||
private static async Task<byte[]> ReadPropertyAsync(UdpClient socket, IPEndPoint target, int objectType, int objectInstance,
|
||||
int propertyId, int? arrayIndex, BacnetRoute? route, CancellationToken cancellationToken, int timeoutMilliseconds = 3000)
|
||||
{
|
||||
var invokeId = (byte)Random.Shared.Next(1, 255);
|
||||
var packet = CreateReadPropertyPacket(objectType, objectInstance, propertyId, arrayIndex, invokeId, route);
|
||||
await socket.SendAsync(packet, target, cancellationToken);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(timeoutMilliseconds);
|
||||
try
|
||||
{
|
||||
while (!timeout.IsCancellationRequested)
|
||||
{
|
||||
var received = await socket.ReceiveAsync(timeout.Token);
|
||||
if (!received.RemoteEndPoint.Equals(target)) continue;
|
||||
var apdu = FindSequence(received.Buffer, 4, 0x30, invokeId, 0x0c);
|
||||
if (apdu >= 0)
|
||||
{
|
||||
return received.Buffer[(apdu + 3)..];
|
||||
}
|
||||
if (FindSequence(received.Buffer, 4, 0x50, invokeId, 0x0c) >= 0)
|
||||
{
|
||||
throw new DomainValidationException("Das BACnet-Gerät hat die Object_List-Abfrage abgelehnt.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new DomainValidationException("Keine Antwort auf die BACnet Object_List-Abfrage.");
|
||||
}
|
||||
throw new DomainValidationException("Keine Antwort auf die BACnet Object_List-Abfrage.");
|
||||
}
|
||||
|
||||
private static byte[] CreateReadPropertyPacket(int objectType, int objectInstance, int propertyId, int? arrayIndex, byte invokeId, BacnetRoute? route)
|
||||
{
|
||||
var parameters = new List<byte> { 0x0c };
|
||||
WriteUInt32(parameters, (uint)((objectType << 22) | objectInstance));
|
||||
parameters.Add(0x19);
|
||||
parameters.Add((byte)propertyId);
|
||||
if (arrayIndex.HasValue) WriteContextUnsigned(parameters, 2, arrayIndex.Value);
|
||||
var payload = new List<byte> { 0x01, route is null ? (byte)0x04 : (byte)0x24 };
|
||||
if (route is not null)
|
||||
{
|
||||
payload.Add((byte)(route.Network >> 8));
|
||||
payload.Add((byte)route.Network);
|
||||
payload.Add((byte)route.Mac.Length);
|
||||
payload.AddRange(route.Mac);
|
||||
payload.Add(0xff); // Hop count.
|
||||
}
|
||||
payload.AddRange(new byte[] { 0x00, 0x05, invokeId, 0x0c });
|
||||
payload.AddRange(parameters);
|
||||
var packet = new List<byte> { 0x81, 0x0a, 0x00, 0x00 };
|
||||
packet.AddRange(payload);
|
||||
packet[2] = (byte)(packet.Count >> 8);
|
||||
packet[3] = (byte)packet.Count;
|
||||
return packet.ToArray();
|
||||
}
|
||||
|
||||
private static void WriteContextUnsigned(List<byte> output, int tagNumber, int value)
|
||||
{
|
||||
if (value <= byte.MaxValue)
|
||||
{
|
||||
output.Add((byte)((tagNumber << 4) | 0x09));
|
||||
output.Add((byte)value);
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Add((byte)((tagNumber << 4) | 0x0a));
|
||||
output.Add((byte)(value >> 8));
|
||||
output.Add((byte)value);
|
||||
}
|
||||
}
|
||||
|
||||
private static BacnetObjectReference ToObjectReference(uint objectId)
|
||||
{
|
||||
var type = (int)(objectId >> 22);
|
||||
var instance = (int)(objectId & 0x3f_ffff);
|
||||
return new BacnetObjectReference(BacnetObjectTypeName(type), instance, $"{type}:{instance}");
|
||||
}
|
||||
|
||||
private static string BacnetObjectTypeName(int type) => type switch
|
||||
{
|
||||
0 => "AnalogInput", 1 => "AnalogOutput", 2 => "AnalogValue", 3 => "BinaryInput", 4 => "BinaryOutput", 5 => "BinaryValue",
|
||||
8 => "Device", 13 => "MultiStateInput", 14 => "MultiStateOutput", 19 => "MultiStateValue", 17 => "Schedule", 6 => "Calendar", 20 => "TrendLog", _ => $"ObjectType{type}"
|
||||
};
|
||||
|
||||
private static int FindSequence(IReadOnlyList<byte> value, int start, params byte[] sequence)
|
||||
{
|
||||
for (var index = start; index <= value.Count - sequence.Length; index++)
|
||||
{
|
||||
var matches = true;
|
||||
for (var offset = 0; offset < sequence.Length; offset++)
|
||||
{
|
||||
if (value[index + offset] != sequence[offset]) { matches = false; break; }
|
||||
}
|
||||
if (matches) return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static uint ReadUInt32(IReadOnlyList<byte> value, int offset) =>
|
||||
((uint)value[offset] << 24) | ((uint)value[offset + 1] << 16) | ((uint)value[offset + 2] << 8) | value[offset + 3];
|
||||
|
||||
private static void WriteUInt32(List<byte> value, uint number)
|
||||
{
|
||||
value.Add((byte)(number >> 24)); value.Add((byte)(number >> 16)); value.Add((byte)(number >> 8)); value.Add((byte)number);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public int ImportNewBacnetPoints(IReadOnlyList<CreatePointRequest> requests)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var known = ReadPoints(connection, transaction).Where(point => point.Protocol == PointProtocol.Bacnet)
|
||||
.Select(point => point.ExternalIdentity).ToHashSet(StringComparer.Ordinal);
|
||||
var created = 0;
|
||||
foreach (var request in requests)
|
||||
{
|
||||
if (!known.Add(request.ExternalIdentity)) continue;
|
||||
InsertPoint(connection, transaction, request);
|
||||
created++;
|
||||
}
|
||||
transaction.Commit();
|
||||
return created;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BacnetExternalPointService(GatewayStore store, BacnetBrowserService browser, ILogger<BacnetExternalPointService> logger) : BackgroundService
|
||||
{
|
||||
private readonly Dictionary<Guid, (string Address, DateTimeOffset Due)> _next = [];
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
var eligible = store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet &&
|
||||
point.Scope == PointScope.External && point.Readable && point.Address.TryGetProperty("objectType", out _) &&
|
||||
point.Address.TryGetProperty("host", out _)).ToDictionary(point => point.Id);
|
||||
foreach (var id in _next.Keys.Except(eligible.Keys).ToArray()) _next.Remove(id);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var due = eligible.Values
|
||||
.Select(point => (Point: point, Due: _next.TryGetValue(point.Id, out var next) &&
|
||||
next.Address == point.Address.GetRawText() ? next.Due : DateTimeOffset.MinValue))
|
||||
.Where(item => item.Due <= now).OrderBy(item => item.Due).Take(20).Select(item => item.Point).ToArray();
|
||||
if (due.Length == 0) continue;
|
||||
var values = store.ListPointValues().ToDictionary(value => value.PointId);
|
||||
foreach (var point in due)
|
||||
_next[point.Id] = (point.Address.GetRawText(), now.AddSeconds(Math.Clamp(ReadInt(point.Address, "pollIntervalSeconds") ?? 15, 2, 3600)));
|
||||
await Parallel.ForEachAsync(due, new ParallelOptions
|
||||
{
|
||||
CancellationToken = stoppingToken, MaxDegreeOfParallelism = 4
|
||||
}, async (point, token) => await ObserveAsync(point, values.GetValueOrDefault(point.Id), token));
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
catch (Microsoft.Data.Sqlite.SqliteException exception)
|
||||
{
|
||||
#pragma warning disable CA1848
|
||||
logger.LogWarning(exception, "BACnet polling could not read the gateway database.");
|
||||
#pragma warning restore CA1848
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ObserveAsync(GatewayPoint point, PointValue? previous, CancellationToken cancellationToken)
|
||||
{
|
||||
var address = point.Address;
|
||||
var host = ReadString(address, "host");
|
||||
var type = ReadInt(address, "objectType");
|
||||
var instance = ReadInt(address, "objectInstance");
|
||||
var device = ReadInt(address, "deviceInstance");
|
||||
if (host is null || type is null or < 0 or > 1023 || instance is null or < 0 or > 4_194_303 || device is null)
|
||||
return;
|
||||
JsonElement? value = null;
|
||||
try
|
||||
{
|
||||
value = await browser.ReadExternalValueAsync(new BacnetBrowseRequest(host, device.Value, ReadInt(address, "port"),
|
||||
Interface: ReadString(address, "interface"), Network: ReadInt(address, "network") ?? 0, Mac: ReadString(address, "mac")),
|
||||
type.Value, instance.Value, cancellationToken);
|
||||
}
|
||||
catch (Exception exception) when (exception is DomainValidationException or SocketException) { }
|
||||
var status = value.HasValue ? "Good" : "BadNotConnected";
|
||||
var effective = value ?? previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null);
|
||||
if (previous?.Status == status && previous.Value.GetRawText() == effective.GetRawText())
|
||||
{
|
||||
store.RecordPointObservation(point.Id, effective, PointProtocol.Bacnet, status, DateTimeOffset.UtcNow);
|
||||
return;
|
||||
}
|
||||
try { store.SetPointValue(point.Id, effective, PointProtocol.Bacnet, DateTimeOffset.UtcNow, status, expectedDefinition: point); }
|
||||
catch (DomainValidationException) { /* The source was edited or removed during polling. */ }
|
||||
}
|
||||
|
||||
private static string? ReadString(JsonElement address, string name) =>
|
||||
address.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
private static int? ReadInt(JsonElement address, string name) =>
|
||||
address.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var result) ? result : null;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public object GetBacnetNativeStatus()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
|
||||
var heartbeat = command.ExecuteScalar() as long?;
|
||||
command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE state='pending'";
|
||||
var pending = (long)command.ExecuteScalar()!;
|
||||
command.CommandText = "SELECT point_id,result,created_ms FROM bacnet_commands WHERE state='failed' ORDER BY id DESC LIMIT 10";
|
||||
using var reader = command.ExecuteReader();
|
||||
var failed = new List<object>();
|
||||
while (reader.Read()) failed.Add(new { pointId = reader.GetString(0), result = reader.GetString(1), occurredAtUtc = DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64(2)) });
|
||||
return new { connected = heartbeat.HasValue && DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - heartbeat.Value < 5000,
|
||||
heartbeatUtc = heartbeat.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(heartbeat.Value) : (DateTimeOffset?)null, pendingCommands = pending, failedCommands = failed,
|
||||
unsupportedPoints = ListPoints().Where(point => point.Scope == PointScope.Gateway && point.Protocol == PointProtocol.Bacnet && point.BacnetObjectKind is BacnetObjectKind.EventEnrollment or BacnetObjectKind.NotificationClass or BacnetObjectKind.TrendLog).Select(point => new { point.Id, point.DisplayName, point.BacnetObjectKind }).ToArray() };
|
||||
}
|
||||
|
||||
private static void EnqueueBacnetCommand(SqliteConnection connection, SqliteTransaction transaction, GatewayPoint point, PointValue value, int priority)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value.Status) && value.Status is not ("Good" or "ok")) return;
|
||||
if (priority is < 1 or > 16 or 6) throw new DomainValidationException("BACnet-Priorität muss 1 bis 16 sein; Priorität 6 ist reserviert.");
|
||||
var kind = point.BacnetObjectKind;
|
||||
var valid = kind switch
|
||||
{
|
||||
BacnetObjectKind.AnalogInput or BacnetObjectKind.AnalogOutput or BacnetObjectKind.AnalogValue => value.Value.ValueKind == JsonValueKind.Number && value.Value.TryGetSingle(out var real) && float.IsFinite(real),
|
||||
BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue => value.Value.ValueKind is JsonValueKind.True or JsonValueKind.False,
|
||||
BacnetObjectKind.MultiStateInput or BacnetObjectKind.MultiStateOutput or BacnetObjectKind.MultiStateValue => value.Value.ValueKind == JsonValueKind.Number && value.Value.TryGetUInt32(out var state) && state > 0,
|
||||
_ => false
|
||||
};
|
||||
var relinquish = value.Value.ValueKind == JsonValueKind.Null && kind is BacnetObjectKind.AnalogOutput or BacnetObjectKind.AnalogValue or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue or BacnetObjectKind.MultiStateOutput or BacnetObjectKind.MultiStateValue;
|
||||
if (!valid && !relinquish) throw new DomainValidationException("Der Wert passt nicht zum nativen BACnet-Objekt.");
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = "INSERT INTO bacnet_commands(point_id,value_json,priority,created_ms) VALUES($id,$value,$priority,$time)";
|
||||
command.Parameters.AddWithValue("$id", point.Id.ToString());
|
||||
command.Parameters.AddWithValue("$value", value.Value.GetRawText());
|
||||
command.Parameters.AddWithValue("$priority", priority);
|
||||
command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Only native effective values feed the shared mapping/trend store, never unarbitrated commands.</summary>
|
||||
public sealed class BacnetNativeBridgeService(GatewayDatabase database, GatewayStore store, ILogger<BacnetNativeBridgeService> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var observations = new List<(long Id, Guid Point, JsonElement Value, string Status, long Time)>();
|
||||
using var connection = database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT id,point_id,value_json,status,observed_ms FROM bacnet_observations ORDER BY id LIMIT 500";
|
||||
using (var reader = command.ExecuteReader())
|
||||
while (reader.Read()) observations.Add((reader.GetInt64(0), Guid.Parse(reader.GetString(1)), JsonSerializer.Deserialize<JsonElement>(reader.GetString(2)), reader.GetString(3), reader.GetInt64(4)));
|
||||
var points = store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.Scope == PointScope.Gateway).ToArray();
|
||||
foreach (var observation in observations)
|
||||
{
|
||||
if (points.Any(point => point.Id == observation.Point))
|
||||
{
|
||||
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == observation.Point);
|
||||
if (previous is null || previous.UpdatedAtUtc.ToUnixTimeMilliseconds() < observation.Time || previous.Status != observation.Status || previous.Value.GetRawText() != observation.Value.GetRawText())
|
||||
store.SetPointValue(observation.Point, observation.Value, PointProtocol.Bacnet, DateTimeOffset.FromUnixTimeMilliseconds(observation.Time), observation.Status);
|
||||
}
|
||||
command.CommandText = "DELETE FROM bacnet_observations WHERE id=$id";
|
||||
command.Parameters.Clear(); command.Parameters.AddWithValue("$id", observation.Id); command.ExecuteNonQuery();
|
||||
}
|
||||
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
|
||||
command.Parameters.Clear();
|
||||
var heartbeat = command.ExecuteScalar() as long? ?? 0;
|
||||
if (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - heartbeat > 5000)
|
||||
foreach (var point in points)
|
||||
{
|
||||
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == point.Id);
|
||||
if (previous?.Status != "BadNotConnected") store.SetPointValue(point.Id, previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null), PointProtocol.Bacnet, DateTimeOffset.UtcNow, "BadNotConnected");
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is SqliteException or JsonException or DomainValidationException)
|
||||
{
|
||||
#pragma warning disable CA1848
|
||||
logger.LogWarning("BACnet bridge read failed ({ErrorType}).", exception.GetType().Name);
|
||||
#pragma warning restore CA1848
|
||||
}
|
||||
try { await Task.Delay(100, stoppingToken); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record BacnetObjectsRequest(BacnetBrowseRequest Device, int Offset = 0, int Limit = 100);
|
||||
public sealed record BacnetObjectDetails(string ObjectType, int ObjectTypeCode, int ObjectInstance,
|
||||
string? Name, string? Description, JsonElement? Value, string? ValueType, Guid? PointId);
|
||||
public sealed record BacnetObjectPage(string? DeviceName, int Total, int NextOffset, IReadOnlyList<BacnetObjectDetails> Objects);
|
||||
public sealed record BacnetImportRequest(BacnetBrowseRequest Device, string[]? ObjectIds, bool All = false);
|
||||
public sealed record BacnetImportResult(int Created, int Existing, int Unsupported);
|
||||
|
||||
public sealed partial class BacnetBrowserService
|
||||
{
|
||||
private const int MaxInventory = 5000;
|
||||
private const int ObjectName = 77;
|
||||
private const int Description = 28;
|
||||
private const int PresentValue = 85;
|
||||
private const int OptionalReadTimeout = 950;
|
||||
|
||||
private static async Task<BacnetDiscoveredDevice[]> ReadDeviceNamesAsync(IReadOnlyList<BacnetDiscoveredDevice> devices,
|
||||
IPAddress local, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = devices.ToArray();
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(8));
|
||||
try
|
||||
{
|
||||
await Parallel.ForEachAsync(Enumerable.Range(0, result.Length), new ParallelOptions
|
||||
{
|
||||
CancellationToken = timeout.Token, MaxDegreeOfParallelism = 8
|
||||
}, async (index, token) =>
|
||||
{
|
||||
var device = result[index];
|
||||
var request = new BacnetBrowseRequest(device.Address, device.DeviceInstance, device.Port, Network: device.Network, Mac: device.Mac);
|
||||
try
|
||||
{
|
||||
using var socket = CreateSocket(local);
|
||||
var target = new IPEndPoint(IPAddress.Parse(device.Address), device.Port);
|
||||
var name = await ReadTextAsync(socket, target, 8, device.DeviceInstance, ObjectName, ReadRoute(request), token);
|
||||
result[index] = device with { DeviceName = name };
|
||||
}
|
||||
catch (Exception exception) when (exception is DomainValidationException or SocketException) { }
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { }
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<BacnetObjectPage> BrowseDetailsAsync(BacnetObjectsRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var (endpoint, local, route) = ResolveDevice(request.Device);
|
||||
using var socket = CreateSocket(local);
|
||||
var deviceName = await ReadTextAsync(socket, endpoint, 8, request.Device.DeviceInstance, ObjectName, route, cancellationToken);
|
||||
var count = await ReadObjectListCountAsync(socket, endpoint, request.Device.DeviceInstance, route, cancellationToken);
|
||||
var total = Math.Min(count, MaxInventory);
|
||||
var offset = Math.Clamp(request.Offset, 0, total);
|
||||
var end = Math.Min(total, offset + Math.Clamp(request.Limit, 1, 200));
|
||||
var ids = await ReadInventoryAsync(socket, endpoint, request.Device.DeviceInstance, route, offset, end, cancellationToken);
|
||||
var imports = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.ExternalIdentity is not null)
|
||||
.ToDictionary(point => point.ExternalIdentity!, point => point.Id, StringComparer.Ordinal);
|
||||
var objects = new BacnetObjectDetails[ids.Count];
|
||||
await Parallel.ForEachAsync(Enumerable.Range(0, ids.Count), new ParallelOptions
|
||||
{
|
||||
CancellationToken = cancellationToken, MaxDegreeOfParallelism = 4
|
||||
}, async (index, token) =>
|
||||
{
|
||||
using var worker = CreateSocket(local);
|
||||
var type = (int)(ids[index] >> 22);
|
||||
var instance = (int)(ids[index] & 0x3f_ffff);
|
||||
var name = await ReadTextAsync(worker, endpoint, type, instance, ObjectName, route, token);
|
||||
var description = await ReadTextAsync(worker, endpoint, type, instance, Description, route, token);
|
||||
var valueType = ScalarType(type);
|
||||
var value = valueType is null ? null : await ReadScalarAsync(worker, endpoint, type, instance, route, token);
|
||||
imports.TryGetValue(ExternalIdentity(endpoint, request.Device, type, instance), out var pointId);
|
||||
objects[index] = new(BacnetObjectTypeName(type), type, instance, name, description, value, valueType,
|
||||
pointId == Guid.Empty ? null : pointId);
|
||||
});
|
||||
return new(deviceName, count, end, objects);
|
||||
}
|
||||
|
||||
public async Task<BacnetImportResult> ImportAsync(BacnetImportRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var (endpoint, local, route) = ResolveDevice(request.Device);
|
||||
using var socket = CreateSocket(local);
|
||||
var count = await ReadObjectListCountAsync(socket, endpoint, request.Device.DeviceInstance, route, cancellationToken);
|
||||
if (count > MaxInventory) throw new DomainValidationException($"Geräte mit mehr als {MaxInventory} Objekten können nicht vollständig importiert werden.");
|
||||
var objects = await ReadInventoryAsync(socket, endpoint, request.Device.DeviceInstance, route, 0, count, cancellationToken);
|
||||
var desired = request.ObjectIds?.ToHashSet(StringComparer.Ordinal) ?? [];
|
||||
if (!request.All && desired.Count == 0) throw new DomainValidationException("Bitte mindestens ein BACnet-Objekt auswählen.");
|
||||
var selected = objects.Select(id => (Type: (int)(id >> 22), Instance: (int)(id & 0x3f_ffff)))
|
||||
.Where(obj => request.All || desired.Contains($"{obj.Type}:{obj.Instance}")).Distinct().ToArray();
|
||||
if (!request.All && selected.Length != desired.Count)
|
||||
throw new DomainValidationException("Die Auswahl enthält Objekte, die dieses Gerät nicht mehr meldet.");
|
||||
var create = new List<CreatePointRequest>();
|
||||
var existing = 0;
|
||||
var unsupported = 0;
|
||||
var known = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.ExternalIdentity is not null)
|
||||
.Select(point => point.ExternalIdentity!).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var (type, instance) in selected)
|
||||
{
|
||||
if (ScalarType(type) is not { } valueType) { unsupported++; continue; }
|
||||
var identity = ExternalIdentity(endpoint, request.Device, type, instance);
|
||||
if (!known.Add(identity)) { existing++; continue; }
|
||||
var name = await ReadTextAsync(socket, endpoint, type, instance, ObjectName, route, cancellationToken);
|
||||
var kind = Enum.Parse<BacnetObjectKind>(BacnetObjectTypeName(type));
|
||||
create.Add(new(ShortName(name, $"{BacnetObjectTypeName(type)} {instance}"), PointProtocol.Bacnet, PointScope.External,
|
||||
valueType, true, false, identity, JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
host = endpoint.Address.ToString(), port = endpoint.Port, deviceInstance = request.Device.DeviceInstance,
|
||||
@interface = request.Device.Interface, network = request.Device.Network, mac = request.Device.Mac,
|
||||
objectType = type, objectInstance = instance, pollIntervalSeconds = 15
|
||||
}), kind, (uint)instance));
|
||||
}
|
||||
var created = _store.ImportNewBacnetPoints(create);
|
||||
return new(created, existing + create.Count - created, unsupported);
|
||||
}
|
||||
|
||||
internal async Task<JsonElement?> ReadExternalValueAsync(BacnetBrowseRequest device, int type, int instance, CancellationToken token)
|
||||
{
|
||||
var (endpoint, local, route) = ResolveDevice(device);
|
||||
using var socket = CreateSocket(local);
|
||||
return await ReadScalarAsync(socket, endpoint, type, instance, route, token);
|
||||
}
|
||||
|
||||
private (IPEndPoint Endpoint, IPAddress Local, BacnetRoute? Route) ResolveDevice(BacnetBrowseRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!IPAddress.TryParse(request.Address, out var address) || address.AddressFamily != AddressFamily.InterNetwork ||
|
||||
address.Equals(IPAddress.Any) || request.DeviceInstance is < 0 or > 4_194_303)
|
||||
throw new DomainValidationException("BACnet-Gerät oder IPv4-Adresse ist ungültig.");
|
||||
var configuration = _store.GetGatewayConfiguration();
|
||||
var port = request.Port ?? configuration.Bacnet.IpPort;
|
||||
if (port is < 1 or > 65535) throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
|
||||
var local = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface).FirstOrDefault()?.Address
|
||||
?? throw new DomainValidationException("Für die BACnet-Schnittstelle wurde keine IPv4-Adresse gefunden.");
|
||||
return (new IPEndPoint(address, port), local, ReadRoute(request));
|
||||
}
|
||||
|
||||
private static async Task<List<uint>> ReadInventoryAsync(UdpClient socket, IPEndPoint endpoint, int device,
|
||||
BacnetRoute? route, int offset, int end, CancellationToken token)
|
||||
{
|
||||
var objects = new List<uint>(end - offset);
|
||||
for (var index = offset + 1; index <= end; index++)
|
||||
if (await ReadObjectListItemAsync(socket, endpoint, device, index, route, token) is { } id) objects.Add(id);
|
||||
return objects;
|
||||
}
|
||||
|
||||
private static string ExternalIdentity(IPEndPoint endpoint, BacnetBrowseRequest device, int type, int instance) =>
|
||||
$"bip:{endpoint}/{device.Network}/{device.Mac?.ToUpperInvariant()}/{type}:{instance}";
|
||||
|
||||
private static string ShortName(string? value, string fallback) =>
|
||||
string.IsNullOrWhiteSpace(value) ? fallback : value.Trim()[..Math.Min(value.Trim().Length, 160)];
|
||||
|
||||
private static string? ScalarType(int type) => type switch
|
||||
{
|
||||
0 or 1 or 2 => "Real",
|
||||
3 or 4 or 5 => "Boolean",
|
||||
13 or 14 or 19 => "UInt32",
|
||||
_ => null
|
||||
};
|
||||
|
||||
private static async Task<string?> ReadTextAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
|
||||
int property, BacnetRoute? route, CancellationToken token)
|
||||
{
|
||||
var bytes = await TryReadApplicationAsync(socket, endpoint, type, instance, property, route, token);
|
||||
if (bytes is not { Length: > 0 } || !TryApplicationValue(bytes, out var tag, out var data) || tag != 7 || data.Length < 1)
|
||||
return null;
|
||||
var encoding = data[0] switch
|
||||
{
|
||||
0 => Encoding.UTF8, 3 => new UTF32Encoding(true, false), 4 => Encoding.BigEndianUnicode, 5 => Encoding.Latin1, _ => null
|
||||
};
|
||||
return encoding?.GetString(data[1..]).TrimEnd('\0');
|
||||
}
|
||||
|
||||
private static async Task<JsonElement?> ReadScalarAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
|
||||
BacnetRoute? route, CancellationToken token)
|
||||
{
|
||||
var bytes = await TryReadApplicationAsync(socket, endpoint, type, instance, PresentValue, route, token);
|
||||
if (bytes is not { Length: > 0 }) return null;
|
||||
if (ScalarType(type) == "Boolean" && bytes[0] is 0x10 or 0x11)
|
||||
return JsonSerializer.SerializeToElement(bytes[0] == 0x11);
|
||||
if (!TryApplicationValue(bytes, out var tag, out var data)) return null;
|
||||
if (tag == 4 && data.Length == 4)
|
||||
{
|
||||
var value = BinaryPrimitives.ReadSingleBigEndian(data);
|
||||
return float.IsFinite(value) ? JsonSerializer.SerializeToElement(value) : null;
|
||||
}
|
||||
if (tag is 2 or 9 && data.Length is >= 1 and <= 4)
|
||||
{
|
||||
uint value = 0;
|
||||
foreach (var octet in data) value = (value << 8) | octet;
|
||||
return ScalarType(type) == "Boolean" ? JsonSerializer.SerializeToElement(value != 0) : JsonSerializer.SerializeToElement(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<byte[]?> TryReadApplicationAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
|
||||
int property, BacnetRoute? route, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await ReadPropertyAsync(socket, endpoint, type, instance, property, null, route, token, OptionalReadTimeout);
|
||||
// A scalar ReadProperty-ACK begins with object-id (5 bytes), property-id (2), then opening tag [3].
|
||||
return response.Length > 8 && response[0] == 0x0c && ReadUInt32(response, 1) == (uint)((type << 22) | instance) && response[5] == 0x19 &&
|
||||
response[6] == property && response[7] == 0x3e ? response[8..] : null;
|
||||
}
|
||||
catch (Exception exception) when (exception is DomainValidationException or SocketException) { return null; }
|
||||
}
|
||||
|
||||
private static bool TryApplicationValue(byte[] bytes, out int tag, out byte[] data)
|
||||
{
|
||||
tag = bytes[0] >> 4;
|
||||
data = [];
|
||||
if ((bytes[0] & 8) != 0) return false;
|
||||
var length = bytes[0] & 7;
|
||||
var offset = 1;
|
||||
if (length == 5)
|
||||
{
|
||||
if (bytes.Length < 2) return false;
|
||||
length = bytes[offset++];
|
||||
if (length == 254)
|
||||
{
|
||||
if (bytes.Length < 4) return false;
|
||||
length = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2, 2));
|
||||
offset = 4;
|
||||
}
|
||||
else if (length == 255) return false;
|
||||
}
|
||||
if (length > bytes.Length - offset - 1 || bytes[offset + length] != 0x3f) return false;
|
||||
data = bytes[offset..(offset + length)];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Globalization;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Gateway.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Gateway-native replacement for the LTD CSV runner. Exports a saved group of trend logs and may mail it through the fixed SE-Inno mail API.</summary>
|
||||
public sealed class CsvRunnerService : BackgroundService
|
||||
{
|
||||
private static readonly TimeZoneInfo BerlinTimeZone = ResolveBerlinTimeZone();
|
||||
private static readonly char[] MailRecipientSeparators = [';', ','];
|
||||
private readonly GatewayStore _store;
|
||||
private readonly NotificationTransport _transport;
|
||||
private readonly string _exportDirectory;
|
||||
private readonly SemaphoreSlim _executionLock = new(1, 1);
|
||||
private readonly ConcurrentDictionary<Guid, CsvRunnerExecution> _executions = new();
|
||||
|
||||
public IReadOnlyList<CsvRunnerExecution> ListExecutions() => _executions.Values.OrderBy(item => item.EnqueuedAtUtc).ToArray();
|
||||
|
||||
public CsvRunnerService(GatewayStore store, NotificationTransport transport, IOptions<GatewayOptions> options)
|
||||
{
|
||||
_store = store;
|
||||
_transport = transport;
|
||||
_exportDirectory = Path.Combine(Path.GetFullPath(options.Value.DataDirectory), "exports");
|
||||
}
|
||||
|
||||
public async Task<CsvRunnerJobResult> RunNowAsync(Guid jobId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var job = _store.GetCsvRunnerJob(jobId) ?? throw new DomainValidationException("Der CSV-Runner-Job existiert nicht.");
|
||||
return await ExecuteJobAsync(job, cancellationToken);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await CheckScheduleAsync(stoppingToken);
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
await CheckScheduleAsync(stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// Normal shutdown.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckScheduleAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, BerlinTimeZone);
|
||||
var time = now.ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
var date = now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
|
||||
foreach (var job in _store.ListCsvRunnerJobs().Where(job => job.Enabled && job.Time == time))
|
||||
{
|
||||
if (!_store.TryClaimScheduledCsvRunnerJob(job.Id, date)) continue;
|
||||
await ExecuteJobAsync(job, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<CsvRunnerJobResult> ExecuteJobAsync(CsvRunnerJob job, CancellationToken cancellationToken)
|
||||
{
|
||||
var execution = new CsvRunnerExecution(Guid.NewGuid(), job.Id, job.Name, "Pending", DateTimeOffset.UtcNow);
|
||||
_executions[execution.Id] = execution;
|
||||
var locked = false;
|
||||
try
|
||||
{
|
||||
await _executionLock.WaitAsync(cancellationToken);
|
||||
locked = true;
|
||||
_executions[execution.Id] = execution with { State = "Running" };
|
||||
var selection = _store.GetTrendSelection(job.SelectionId) ?? throw new DomainValidationException("Die Trend-Gruppe des CSV-Runner-Jobs existiert nicht mehr.");
|
||||
var filePath = await ExportSelectionAsync(job, selection, cancellationToken);
|
||||
if (job.MailEnabled) await MailExportAsync(job, filePath, cancellationToken);
|
||||
var result = new CsvRunnerJobResult(true, filePath, null, DateTimeOffset.UtcNow);
|
||||
_store.SetCsvRunnerJobResult(job.Id, result);
|
||||
return result;
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var result = new CsvRunnerJobResult(false, null, exception.Message, DateTimeOffset.UtcNow);
|
||||
_store.SetCsvRunnerJobResult(job.Id, result);
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_executions.TryRemove(execution.Id, out _);
|
||||
if (locked) _executionLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string> ExportSelectionAsync(CsvRunnerJob job, GatewayTrendSelection selection, CancellationToken cancellationToken)
|
||||
{
|
||||
var since = DateTimeOffset.UtcNow.AddHours(-job.RangeHours);
|
||||
var rows = _store.ListTrendExportRows(selection.TrendLogIds, since);
|
||||
var delimiter = job.Delimiter;
|
||||
var output = new StringBuilder("\uFEFFZeit");
|
||||
output.Append(delimiter).Append("Tabelle").Append(delimiter).Append("Wertnummer").Append(delimiter).Append("Alias").Append(delimiter).Append("Wert").Append(delimiter).Append("Einheit");
|
||||
foreach (var row in rows)
|
||||
{
|
||||
output.Append("\r\n");
|
||||
AppendCell(output, FormatTimestamp(row.TimestampUtc), delimiter);
|
||||
output.Append(delimiter); AppendCell(output, row.TrendLogName, delimiter);
|
||||
output.Append(delimiter); AppendCell(output, row.BacnetObjectInstance.ToString(CultureInfo.InvariantCulture), delimiter);
|
||||
output.Append(delimiter); AppendCell(output, row.PointName, delimiter);
|
||||
output.Append(delimiter); AppendCell(output, FormatValue(row.Value), delimiter);
|
||||
output.Append(delimiter); AppendCell(output, row.Unit, delimiter);
|
||||
}
|
||||
Directory.CreateDirectory(_exportDirectory);
|
||||
var stamp = DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH-mm-ssZ", CultureInfo.InvariantCulture);
|
||||
var fileName = $"{SafeFileName(selection.Name)}-{stamp}.csv";
|
||||
var filePath = Path.Combine(_exportDirectory, fileName);
|
||||
await File.WriteAllTextAsync(filePath, output.ToString(), new UTF8Encoding(true), cancellationToken);
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(filePath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async Task MailExportAsync(CsvRunnerJob job, string filePath, CancellationToken cancellationToken)
|
||||
{
|
||||
var apiKey = _store.GetMailApiKey();
|
||||
if (string.IsNullOrWhiteSpace(apiKey)) throw new DomainValidationException("Der Mail-API-Key ist nicht hinterlegt.");
|
||||
var recipients = (job.MailTo ?? string.Empty).Split(MailRecipientSeparators, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
if (recipients.Length == 0) throw new DomainValidationException("Für den CSV-Mailversand ist kein Empfänger hinterlegt.");
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
using var content = new MultipartFormDataContent();
|
||||
content.Add(new StringContent(apiKey), "api_key");
|
||||
content.Add(new StringContent(recipient), "address");
|
||||
content.Add(new StringContent(job.MailSubject), "subject");
|
||||
content.Add(new StringContent(job.MailMessage), "message");
|
||||
await using var file = File.OpenRead(filePath);
|
||||
using var attachment = new StreamContent(file);
|
||||
attachment.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/csv");
|
||||
content.Add(attachment, "attachment", Path.GetFileName(filePath));
|
||||
await _transport.PostAsync(NotificationChannel.Mail, content, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AppendCell(StringBuilder output, string value, string delimiter)
|
||||
{
|
||||
if (value.Contains('"') || value.Contains('\r') || value.Contains('\n') || value.Contains(delimiter, StringComparison.Ordinal))
|
||||
{
|
||||
output.Append('"').Append(value.Replace("\"", "\"\"", StringComparison.Ordinal)).Append('"');
|
||||
}
|
||||
else output.Append(value);
|
||||
}
|
||||
|
||||
private static string FormatValue(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number when value.TryGetDecimal(out var decimalValue) => decimalValue.ToString("0.##########", CultureInfo.GetCultureInfo("de-DE")),
|
||||
JsonValueKind.String => value.GetString() ?? string.Empty,
|
||||
JsonValueKind.True => "1",
|
||||
JsonValueKind.False => "0",
|
||||
JsonValueKind.Null => string.Empty,
|
||||
_ => value.GetRawText()
|
||||
};
|
||||
|
||||
private static string FormatTimestamp(DateTimeOffset timestamp) => TimeZoneInfo.ConvertTime(timestamp, BerlinTimeZone).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string SafeFileName(string value)
|
||||
{
|
||||
var invalid = Path.GetInvalidFileNameChars().ToHashSet();
|
||||
var safe = new string(value.Select(character => invalid.Contains(character) || !char.IsLetterOrDigit(character) && character is not '-' and not '_' and not '.' ? '_' : character).ToArray()).Trim('_');
|
||||
return string.IsNullOrWhiteSpace(safe) ? "trend-export" : safe[..Math.Min(safe.Length, 100)];
|
||||
}
|
||||
|
||||
private static TimeZoneInfo ResolveBerlinTimeZone()
|
||||
{
|
||||
try { return TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); }
|
||||
catch (TimeZoneNotFoundException) { return TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); }
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,45 @@ public sealed class GatewayDatabase
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
PRAGMA journal_mode = WAL;
|
||||
CREATE TABLE IF NOT EXISTS bacnet_commands (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL,
|
||||
priority INTEGER NOT NULL, created_ms INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'pending', result TEXT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bacnet_properties (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, property INTEGER NOT NULL,
|
||||
array_index INTEGER NOT NULL, priority INTEGER NOT NULL, payload BLOB NOT NULL,
|
||||
UNIQUE(point_id, property, array_index, priority)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bacnet_observations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL,
|
||||
status TEXT NOT NULL, observed_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bacnet_runtime (
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), heartbeat_ms INTEGER NOT NULL, state TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bacnet_discovery (
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), scan_id TEXT NOT NULL, target TEXT,
|
||||
port INTEGER NOT NULL, expires_ms INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bacnet_discovered_devices (
|
||||
scan_id TEXT NOT NULL, device_instance INTEGER NOT NULL, address TEXT NOT NULL,
|
||||
port INTEGER NOT NULL, vendor INTEGER NOT NULL, max_apdu INTEGER NOT NULL,
|
||||
network INTEGER NOT NULL DEFAULT 0, mac TEXT,
|
||||
PRIMARY KEY(scan_id, device_instance, address, port)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT NOT NULL PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS alarm_rules (
|
||||
id TEXT PRIMARY KEY, point_id TEXT NOT NULL REFERENCES points(id), enabled INTEGER NOT NULL,
|
||||
configuration_json TEXT NOT NULL, active INTEGER NULL, observed_at_utc TEXT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS notification_outbox (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, rule_id TEXT NOT NULL, title TEXT NOT NULL, message TEXT NOT NULL,
|
||||
destination_json TEXT NOT NULL, state TEXT NOT NULL, created_at_utc TEXT NOT NULL, result TEXT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notification_pending ON notification_outbox(state, id);
|
||||
CREATE TABLE IF NOT EXISTS admin_account (
|
||||
id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1),
|
||||
username TEXT NOT NULL UNIQUE CHECK(username = 'admin'),
|
||||
@@ -50,6 +85,34 @@ public sealed class GatewayDatabase
|
||||
password_iterations INTEGER NOT NULL,
|
||||
changed_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS app_roles (
|
||||
name TEXT NOT NULL PRIMARY KEY,
|
||||
label TEXT NOT NULL,
|
||||
permissions_json TEXT NOT NULL,
|
||||
is_system INTEGER NOT NULL,
|
||||
updated_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS app_users (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
email TEXT NULL UNIQUE,
|
||||
password_hash BLOB NOT NULL,
|
||||
password_salt BLOB NOT NULL,
|
||||
password_iterations INTEGER NOT NULL,
|
||||
role_name TEXT NOT NULL REFERENCES app_roles(name) ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
active INTEGER NOT NULL,
|
||||
created_at_utc TEXT NOT NULL,
|
||||
updated_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS app_user_preferences (
|
||||
user_id TEXT NOT NULL PRIMARY KEY REFERENCES app_users(id) ON DELETE CASCADE,
|
||||
theme TEXT NOT NULL DEFAULT 'system',
|
||||
csv_delimiter TEXT NOT NULL DEFAULT ';',
|
||||
sidebar_pinned INTEGER NOT NULL DEFAULT 1,
|
||||
trend_line_width REAL NOT NULL DEFAULT 1.8,
|
||||
updated_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS points (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
@@ -62,7 +125,8 @@ public sealed class GatewayDatabase
|
||||
address_json TEXT NOT NULL,
|
||||
created_at_utc TEXT NOT NULL,
|
||||
bacnet_object_kind TEXT NULL,
|
||||
bacnet_object_instance INTEGER NULL
|
||||
bacnet_object_instance INTEGER NULL,
|
||||
deleted_at_utc TEXT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_points_external_identity
|
||||
ON points(protocol, external_identity)
|
||||
@@ -117,6 +181,7 @@ public sealed class GatewayDatabase
|
||||
interval_seconds INTEGER NOT NULL,
|
||||
max_records INTEGER NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
public_access INTEGER NOT NULL DEFAULT 0,
|
||||
created_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS trend_records (
|
||||
@@ -130,18 +195,55 @@ public sealed class GatewayDatabase
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_trend_records_query
|
||||
ON trend_records(trend_log_id, sequence_number DESC);
|
||||
CREATE TABLE IF NOT EXISTS trend_selections (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NULL,
|
||||
owner_id TEXT NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
|
||||
shared INTEGER NOT NULL,
|
||||
trend_log_ids_json TEXT NOT NULL,
|
||||
created_at_utc TEXT NOT NULL,
|
||||
updated_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS csv_runner_jobs (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
selection_id TEXT NOT NULL REFERENCES trend_selections(id) ON DELETE RESTRICT,
|
||||
time TEXT NOT NULL,
|
||||
range_hours INTEGER NOT NULL,
|
||||
delimiter TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
mail_enabled INTEGER NOT NULL,
|
||||
mail_to TEXT NULL,
|
||||
mail_subject TEXT NOT NULL,
|
||||
mail_message TEXT NOT NULL,
|
||||
last_run_local_date TEXT NULL,
|
||||
last_result_json TEXT NULL,
|
||||
created_at_utc TEXT NOT NULL,
|
||||
updated_at_utc TEXT NOT NULL
|
||||
);
|
||||
""";
|
||||
command.ExecuteNonQuery();
|
||||
EnsureColumn(connection, "points", "bacnet_object_kind", "TEXT NULL");
|
||||
EnsureColumn(connection, "points", "bacnet_object_instance", "INTEGER NULL");
|
||||
using var bacnetObjectIndex = connection.CreateCommand();
|
||||
bacnetObjectIndex.CommandText = """
|
||||
EnsureColumn(connection, "points", "deleted_at_utc", "TEXT NULL");
|
||||
EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0");
|
||||
EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0");
|
||||
EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL");
|
||||
using var indexMigration = connection.BeginTransaction();
|
||||
using var pointIndexes = connection.CreateCommand();
|
||||
pointIndexes.Transaction = indexMigration;
|
||||
pointIndexes.CommandText = """
|
||||
DROP INDEX IF EXISTS idx_points_external_identity;
|
||||
CREATE UNIQUE INDEX idx_points_external_identity ON points(protocol, external_identity)
|
||||
WHERE external_identity IS NOT NULL AND deleted_at_utc IS NULL;
|
||||
DROP INDEX IF EXISTS idx_points_bacnet_object;
|
||||
CREATE UNIQUE INDEX idx_points_bacnet_object
|
||||
ON points(bacnet_object_kind, bacnet_object_instance)
|
||||
WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL;
|
||||
WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL AND deleted_at_utc IS NULL;
|
||||
""";
|
||||
bacnetObjectIndex.ExecuteNonQuery();
|
||||
pointIndexes.ExecuteNonQuery();
|
||||
indexMigration.Commit();
|
||||
}
|
||||
|
||||
private static void EnsureColumn(SqliteConnection connection, string tableName, string columnName, string definition)
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using StatusCodes = Opc.Ua.StatusCodes;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
#pragma warning disable CS0618 // Pinned SDK 1.5 compatibility API.
|
||||
|
||||
/// <summary>A real UA address space backed by the common point store, not a second writer.</summary>
|
||||
public sealed class GatewayOpcUaServer(GatewayStore store) : StandardServer
|
||||
{
|
||||
public const string PointsNamespace = "urn:se-inno:universalgateway:points";
|
||||
private GatewayNodeManager? _points;
|
||||
|
||||
protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration)
|
||||
{
|
||||
_points = new GatewayNodeManager(server, configuration, store);
|
||||
return new MasterNodeManager(server, configuration, null, _points);
|
||||
}
|
||||
|
||||
protected override void OnServerStarted(IServerInternal server)
|
||||
{
|
||||
base.OnServerStarted(server);
|
||||
server.SessionManager.ImpersonateUser += (_, args) =>
|
||||
{
|
||||
if (args.NewIdentity is AnonymousIdentityToken && store.GetGatewayConfiguration().OpcUa.AllowAnonymous)
|
||||
{
|
||||
args.Identity = new UserIdentity();
|
||||
return;
|
||||
}
|
||||
if (args.NewIdentity is UserNameIdentityToken token)
|
||||
{
|
||||
var user = token.DecryptedPassword is null ? null : store.Authenticate(token.UserName, Encoding.UTF8.GetString(token.DecryptedPassword));
|
||||
if (user is not null && (user.Permissions.Contains(GatewayPermissions.ViewDashboard) || user.Permissions.Contains(GatewayPermissions.ManageSources)))
|
||||
{
|
||||
args.Identity = new GatewayIdentity(user);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new ServiceResultException(StatusCodes.BadUserAccessDenied, "OPC-UA-Anmeldung abgewiesen.");
|
||||
};
|
||||
}
|
||||
|
||||
public void RefreshPoints(bool reconcile)
|
||||
{
|
||||
if (reconcile)
|
||||
{
|
||||
// Close revoked sessions including their monitored items. Checking writes
|
||||
// alone would leave already established subscriptions alive.
|
||||
foreach (var session in CurrentInstance.SessionManager.GetSessions())
|
||||
{
|
||||
if (session.Identity is not GatewayIdentity identity) continue;
|
||||
var current = store.GetAuthenticatedUser(identity.UserId);
|
||||
if (current is null || current.User.UpdatedAtUtc != identity.Revision || !current.Permissions.Order(StringComparer.Ordinal).SequenceEqual(identity.Permissions))
|
||||
CurrentInstance.CloseSession(null, session.Id, true);
|
||||
}
|
||||
}
|
||||
_points?.Refresh(reconcile);
|
||||
}
|
||||
|
||||
private sealed class GatewayIdentity(AuthenticatedGatewayUser user) : UserIdentity(new UserNameIdentityToken { UserName = user.User.Username })
|
||||
{
|
||||
public Guid UserId { get; } = user.User.Id;
|
||||
public DateTimeOffset Revision { get; } = user.User.UpdatedAtUtc;
|
||||
public string[] Permissions { get; } = user.Permissions.Order(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
private sealed class GatewayNodeManager : CustomNodeManager2
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly ConcurrentDictionary<Guid, PointValue> _pending = new();
|
||||
private readonly Dictionary<Guid, BaseDataVariableState> _variables = [];
|
||||
private FolderState? _folder;
|
||||
|
||||
public GatewayNodeManager(IServerInternal server, ApplicationConfiguration configuration, GatewayStore store)
|
||||
: base(server, configuration, PointsNamespace)
|
||||
{
|
||||
_store = store;
|
||||
_store.PointValueUpdated += OnPointValue;
|
||||
}
|
||||
|
||||
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
_folder = new FolderState(null)
|
||||
{
|
||||
NodeId = new NodeId("Gateway", NamespaceIndex),
|
||||
BrowseName = new QualifiedName("Gateway", NamespaceIndex),
|
||||
DisplayName = "SE-Inno Universalgateway",
|
||||
TypeDefinitionId = ObjectTypeIds.FolderType,
|
||||
ReferenceTypeId = ReferenceTypeIds.Organizes
|
||||
};
|
||||
_folder.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder);
|
||||
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references))
|
||||
{
|
||||
references = new List<IReference>();
|
||||
externalReferences[ObjectIds.ObjectsFolder] = references;
|
||||
}
|
||||
references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, _folder.NodeId));
|
||||
AddPredefinedNode(SystemContext, _folder);
|
||||
Refresh(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Never acquire the UA lock in a store callback: other protocol drivers may
|
||||
// already own their locks. Coalescing changes affects UA delivery only, not trends.
|
||||
private void OnPointValue(object? sender, PointValue value) => _pending[value.PointId] = value;
|
||||
|
||||
public void Refresh(bool reconcile)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (_folder is null) return;
|
||||
if (reconcile)
|
||||
{
|
||||
var points = _store.ListPoints().Where(point => point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.Gateway).ToArray();
|
||||
var values = _store.ListPointValues().ToDictionary(value => value.PointId);
|
||||
foreach (var point in points)
|
||||
{
|
||||
var type = OpcUaPointTypes.Resolve(point.ValueType);
|
||||
var access = (byte)((point.Readable ? AccessLevels.CurrentRead : 0) | (point.Writable && type != BuiltInType.Null ? AccessLevels.CurrentWrite : 0));
|
||||
var dataType = type == BuiltInType.Null ? DataTypeIds.BaseDataType : new NodeId((uint)type);
|
||||
if (_variables.TryGetValue(point.Id, out var existing))
|
||||
{
|
||||
existing.DisplayName = point.DisplayName;
|
||||
ConfigureVariable(existing, point, type, access, dataType);
|
||||
if (!values.ContainsKey(point.Id) && StatusCode.IsGood(existing.StatusCode))
|
||||
{
|
||||
existing.Value = null;
|
||||
existing.StatusCode = StatusCodes.BadWaitingForInitialData;
|
||||
existing.Timestamp = DateTime.UtcNow;
|
||||
}
|
||||
existing.ClearChangeMasks(SystemContext, false);
|
||||
continue;
|
||||
}
|
||||
var variable = new BaseDataVariableState(_folder)
|
||||
{
|
||||
NodeId = new NodeId(point.Id, NamespaceIndex),
|
||||
BrowseName = new QualifiedName(point.Id.ToString(), NamespaceIndex),
|
||||
DisplayName = point.DisplayName,
|
||||
ReferenceTypeId = ReferenceTypeIds.Organizes,
|
||||
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
|
||||
ValueRank = ValueRanks.Scalar,
|
||||
MinimumSamplingInterval = 100,
|
||||
StatusCode = type == BuiltInType.Null ? StatusCodes.BadNotSupported : StatusCodes.BadWaitingForInitialData,
|
||||
Timestamp = DateTime.UtcNow
|
||||
};
|
||||
ConfigureVariable(variable, point, type, access, dataType);
|
||||
_variables.Add(point.Id, variable);
|
||||
_folder.AddChild(variable);
|
||||
AddPredefinedNode(SystemContext, variable);
|
||||
if (values.TryGetValue(point.Id, out var current)) Apply(variable, current);
|
||||
}
|
||||
foreach (var removed in _variables.Keys.Except(points.Select(point => point.Id)).ToArray())
|
||||
{
|
||||
_folder.RemoveChild(_variables[removed]);
|
||||
DeleteNode(SystemContext, _variables[removed].NodeId);
|
||||
_variables.Remove(removed);
|
||||
}
|
||||
_folder.ClearChangeMasks(SystemContext, false);
|
||||
}
|
||||
foreach (var id in _pending.Keys)
|
||||
{
|
||||
if (_pending.TryRemove(id, out var value) && _variables.TryGetValue(id, out var variable)) Apply(variable, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ConfigureVariable(BaseDataVariableState variable, GatewayPoint point, BuiltInType type, byte access, NodeId dataType)
|
||||
{
|
||||
variable.DataType = dataType;
|
||||
variable.AccessLevel = access;
|
||||
variable.UserAccessLevel = access;
|
||||
variable.OnWriteValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding, ref object value, ref StatusCode status, ref DateTime timestamp) =>
|
||||
WriteValue(context, point, type, range, ref value, ref status, ref timestamp);
|
||||
variable.OnReadUserAccessLevel = (ISystemContext context, NodeState node, ref byte level) =>
|
||||
{
|
||||
level = AccessFor(context, access);
|
||||
return ServiceResult.Good;
|
||||
};
|
||||
variable.OnReadValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding, ref object value, ref StatusCode status, ref DateTime timestamp) =>
|
||||
(AccessFor(context, access) & AccessLevels.CurrentRead) != 0 ? ServiceResult.Good : StatusCodes.BadUserAccessDenied;
|
||||
}
|
||||
|
||||
private byte AccessFor(ISystemContext context, byte access)
|
||||
{
|
||||
var caller = (context as ServerSystemContext)?.UserIdentity;
|
||||
if (caller?.TokenType == UserTokenType.Anonymous)
|
||||
return _store.GetGatewayConfiguration().OpcUa.AllowAnonymous ? (byte)(access & AccessLevels.CurrentRead) : (byte)0;
|
||||
if (caller is not GatewayIdentity identity) return 0;
|
||||
var user = _store.GetAuthenticatedUser(identity.UserId);
|
||||
if (user is null || user.User.UpdatedAtUtc != identity.Revision) return 0;
|
||||
if (user.Permissions.Contains(GatewayPermissions.ManageSources)) return access;
|
||||
return user.Permissions.Contains(GatewayPermissions.ViewDashboard) ? (byte)(access & AccessLevels.CurrentRead) : (byte)0;
|
||||
}
|
||||
|
||||
private ServiceResult WriteValue(ISystemContext context, GatewayPoint point, BuiltInType type, NumericRange range, ref object value, ref StatusCode status, ref DateTime timestamp)
|
||||
{
|
||||
if (!point.Writable) return StatusCodes.BadNotWritable;
|
||||
if ((AccessFor(context, AccessLevels.CurrentWrite) & AccessLevels.CurrentWrite) == 0) return StatusCodes.BadUserAccessDenied;
|
||||
if (range != NumericRange.Empty) return StatusCodes.BadIndexRangeInvalid;
|
||||
if (value is null || TypeInfo.Construct(value).BuiltInType != type || value is Array) return StatusCodes.BadTypeMismatch;
|
||||
// UA writes carry the value, not an arbitrary client quality or source time.
|
||||
if (status != StatusCodes.Good || timestamp != DateTime.MinValue) return StatusCodes.BadWriteNotSupported;
|
||||
JsonElement json;
|
||||
try
|
||||
{
|
||||
json = JsonSerializer.SerializeToElement(value);
|
||||
_ = OpcUaPointTypes.Convert(json, type);
|
||||
}
|
||||
catch (Exception exception) when (exception is ArgumentException or FormatException or InvalidOperationException or OverflowException)
|
||||
{
|
||||
return StatusCodes.BadTypeMismatch;
|
||||
}
|
||||
var observed = DateTimeOffset.UtcNow;
|
||||
try { _store.SetPointValue(point.Id, json, PointProtocol.OpcUa, observed, "Good", expectedDefinition: point); }
|
||||
catch (DomainValidationException) { return StatusCodes.BadNodeIdUnknown; }
|
||||
status = StatusCodes.Good;
|
||||
timestamp = observed.UtcDateTime;
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
|
||||
private void Apply(BaseDataVariableState variable, PointValue value)
|
||||
{
|
||||
try
|
||||
{
|
||||
variable.Value = OpcUaPointTypes.Convert(value.Value, (BuiltInType)(uint)variable.DataType.Identifier);
|
||||
variable.StatusCode = string.IsNullOrWhiteSpace(value.Status) || value.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) || value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)
|
||||
? StatusCodes.Good : StatusCodes.BadNoCommunication;
|
||||
}
|
||||
catch (Exception exception) when (exception is FormatException or InvalidOperationException or OverflowException)
|
||||
{
|
||||
variable.StatusCode = StatusCodes.BadTypeMismatch;
|
||||
}
|
||||
variable.Timestamp = value.UpdatedAtUtc.UtcDateTime;
|
||||
variable.ClearChangeMasks(SystemContext, false);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) _store.PointValueUpdated -= OnPointValue;
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning restore CS0618
|
||||
@@ -0,0 +1,259 @@
|
||||
using System.Globalization;
|
||||
using System.Net.Mail;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public static string NotificationEndpoint(NotificationChannel channel) => channel switch
|
||||
{
|
||||
NotificationChannel.Mail => "https://mailapi.se-inno.de",
|
||||
NotificationChannel.WhatsApp => "https://whatsappapi.se-inno.de",
|
||||
NotificationChannel.Ntfy => "https://ntfy.api.se-inno.de",
|
||||
_ => throw new DomainValidationException("Unbekannter Nachrichtenkanal.")
|
||||
};
|
||||
|
||||
private static string NotificationKeyName(NotificationChannel channel)
|
||||
{
|
||||
_ = NotificationEndpoint(channel);
|
||||
return $"integration.{channel.ToString().ToLowerInvariant()}.api-key";
|
||||
}
|
||||
|
||||
public IReadOnlyList<NotificationIntegration> ListNotificationIntegrations()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return Enum.GetValues<NotificationChannel>().Select(channel => new NotificationIntegration(
|
||||
channel, NotificationEndpoint(channel), GetSetting(connection, NotificationKeyName(channel)) is not null)).ToArray();
|
||||
}
|
||||
|
||||
public void UpdateNotificationKey(NotificationChannel channel, UpdateNotificationKeyRequest request)
|
||||
{
|
||||
var name = NotificationKeyName(channel);
|
||||
var key = request.ApiKey?.Trim();
|
||||
if (!request.ClearApiKey && string.IsNullOrEmpty(key)) return;
|
||||
if (!request.ClearApiKey && (string.IsNullOrEmpty(key) || key.Length > 4096 || key.Any(char.IsControl)))
|
||||
throw new DomainValidationException("Bitte einen gültigen API-Key mit höchstens 4096 Zeichen eingeben.");
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
if (request.ClearApiKey) DeleteSetting(connection, name, transaction);
|
||||
else SetSetting(connection, name, _secretProtector.Protect(key!), transaction);
|
||||
WriteAudit(connection, "integration", $"{channel} API key {(request.ClearApiKey ? "removed" : "updated")}.", transaction);
|
||||
transaction.Commit();
|
||||
}
|
||||
|
||||
public string? GetNotificationKey(NotificationChannel channel)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var encrypted = GetSetting(connection, NotificationKeyName(channel));
|
||||
return encrypted is null ? null : _secretProtector.Unprotect(encrypted);
|
||||
}
|
||||
|
||||
public IReadOnlyList<AlarmRule> ListAlarmRules()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return ReadAlarmRules(connection);
|
||||
}
|
||||
|
||||
private static List<AlarmRule> ReadAlarmRules(SqliteConnection connection, SqliteTransaction? transaction = null)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = "SELECT configuration_json FROM alarm_rules ORDER BY rowid;";
|
||||
using var reader = command.ExecuteReader();
|
||||
var rules = new List<AlarmRule>();
|
||||
while (reader.Read()) rules.Add(JsonSerializer.Deserialize<AlarmRule>(reader.GetString(0), JsonOptions)!);
|
||||
return rules;
|
||||
}
|
||||
|
||||
public AlarmRule SaveAlarmRule(AlarmRule rule)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rule.Name) || rule.Name.Length > 120 || rule.Message is null || rule.Message.Length > 8000 || !Enum.IsDefined(rule.Condition))
|
||||
throw new DomainValidationException("Alarmname, Bedingung oder Nachricht ist ungültig.");
|
||||
if (!double.IsFinite(rule.Threshold) || !double.IsFinite(rule.Hysteresis) || rule.Hysteresis < 0)
|
||||
throw new DomainValidationException("Schwellwert und Hysterese müssen gültige Zahlen sein; Hysterese darf nicht negativ sein.");
|
||||
if (!ListPoints().Any(point => point.Id == rule.PointId && point.Readable))
|
||||
throw new DomainValidationException("Für den Alarm einen lesbaren Gateway-Datenpunkt auswählen.");
|
||||
if (rule.Destinations is not { Count: > 0 and <= 20 })
|
||||
throw new DomainValidationException("Ein Alarm benötigt 1 bis 20 Ziele.");
|
||||
foreach (var destination in rule.Destinations)
|
||||
{
|
||||
ValidateAlarmDestination(destination);
|
||||
if (destination.Channel == NotificationChannel.WhatsApp)
|
||||
_ = NotificationTransport.NormalizeTemplateText($"Entwarnung: {rule.Name}\n{rule.Message}\nWert: {double.MinValue.ToString("R", CultureInfo.InvariantCulture)}\nZeit: {DateTimeOffset.MaxValue:O}");
|
||||
if (rule.Enabled && GetNotificationKey(destination.Channel) is null)
|
||||
throw new DomainValidationException($"Für {destination.Channel} zuerst einen API-Key hinterlegen.");
|
||||
}
|
||||
if (rule.Destinations.Select(d => (d.Channel, d.Recipient)).Distinct().Count() != rule.Destinations.Count)
|
||||
throw new DomainValidationException("Dasselbe Alarmziel darf nicht mehrfach eingetragen werden.");
|
||||
rule = rule with { Id = rule.Id == Guid.Empty ? Guid.NewGuid() : rule.Id, Name = rule.Name.Trim() };
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
if (FindActivePoint(connection, transaction, rule.PointId) is not { Readable: true })
|
||||
throw new DomainValidationException("Der Alarm-Datenpunkt ist nicht mehr lesbar.");
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
// Keep edge state on descriptive edits. Only a changed condition/source or enable transition
|
||||
// establishes a fresh baseline, so merely editing a recipient does not repeat an alarm.
|
||||
var previousRule = ListAlarmRules().SingleOrDefault(item => item.Id == rule.Id);
|
||||
var keepState = previousRule is not null && previousRule.Enabled == rule.Enabled && previousRule.PointId == rule.PointId &&
|
||||
previousRule.Condition == rule.Condition && previousRule.Threshold == rule.Threshold && previousRule.Hysteresis == rule.Hysteresis;
|
||||
command.CommandText = """
|
||||
UPDATE notification_outbox SET state = 'Cancelled', result = 'Alarm rule changed.' WHERE rule_id = $id AND state = 'Pending';
|
||||
INSERT INTO alarm_rules(id, point_id, enabled, configuration_json) VALUES($id, $point, $enabled, $json)
|
||||
ON CONFLICT(id) DO UPDATE SET point_id = excluded.point_id, enabled = excluded.enabled,
|
||||
configuration_json = excluded.configuration_json,
|
||||
active = CASE WHEN $keepState = 1 THEN alarm_rules.active ELSE NULL END,
|
||||
observed_at_utc = CASE WHEN $keepState = 1 THEN alarm_rules.observed_at_utc ELSE NULL END;
|
||||
""";
|
||||
command.Parameters.AddWithValue("$id", rule.Id.ToString());
|
||||
command.Parameters.AddWithValue("$keepState", keepState ? 1 : 0);
|
||||
command.Parameters.AddWithValue("$point", rule.PointId.ToString());
|
||||
command.Parameters.AddWithValue("$enabled", rule.Enabled ? 1 : 0);
|
||||
command.Parameters.AddWithValue("$json", JsonSerializer.Serialize(rule, JsonOptions));
|
||||
command.ExecuteNonQuery();
|
||||
WriteAudit(connection, "alarm", $"Alarm '{rule.Name}' saved.", transaction);
|
||||
transaction.Commit();
|
||||
return rule;
|
||||
}
|
||||
|
||||
public void DeleteAlarmRule(Guid id)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
UPDATE notification_outbox SET state = 'Cancelled', result = 'Alarm rule removed.' WHERE rule_id = $id AND state = 'Pending';
|
||||
DELETE FROM alarm_rules WHERE id = $id;
|
||||
""";
|
||||
command.Parameters.AddWithValue("$id", id.ToString());
|
||||
command.ExecuteNonQuery();
|
||||
transaction.Commit();
|
||||
}
|
||||
|
||||
public static void ValidateAlarmDestination(AlarmDestination destination)
|
||||
{
|
||||
_ = NotificationEndpoint(destination.Channel);
|
||||
if (string.IsNullOrWhiteSpace(destination.Recipient) || destination.Recipient.Length > 254 || destination.Recipient.Any(char.IsControl))
|
||||
throw new DomainValidationException("Ein gültiges Alarmziel ist erforderlich.");
|
||||
if (destination.Channel == NotificationChannel.Mail && (!MailAddress.TryCreate(destination.Recipient, out var address) || address.Address != destination.Recipient))
|
||||
throw new DomainValidationException("Pro Mailziel eine einzelne E-Mail-Adresse eingeben.");
|
||||
if (destination.Channel == NotificationChannel.WhatsApp)
|
||||
{
|
||||
if (!Regex.IsMatch(destination.Recipient, @"^\+[1-9][0-9]{6,14}$", RegexOptions.CultureInvariant))
|
||||
throw new DomainValidationException("WhatsApp-Rufnummer im internationalen Format +49… eingeben.");
|
||||
if (!NotificationTransport.WhatsAppTemplates.Contains(destination.Template, StringComparer.Ordinal))
|
||||
throw new DomainValidationException("Ein unterstütztes, bei Meta freigegebenes WhatsApp-Template auswählen.");
|
||||
_ = NotificationTransport.NormalizeTemplateText(destination.PersonName, 60);
|
||||
}
|
||||
if (destination.Channel == NotificationChannel.Ntfy && (!Regex.IsMatch(destination.Recipient, @"^[A-Za-z0-9_-]{1,64}$", RegexOptions.CultureInvariant) || destination.Priority is < 0 or > 5 || destination.Tags is null || destination.Tags.Length > 200 || destination.Tags.Any(char.IsControl)))
|
||||
throw new DomainValidationException("ntfy-Topic, Priorität (0–5) oder Tags sind ungültig.");
|
||||
}
|
||||
|
||||
private static void EvaluateAlarms(SqliteConnection connection, SqliteTransaction transaction, PointValue value)
|
||||
{
|
||||
var numeric = value.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => 1d, JsonValueKind.False => 0d,
|
||||
JsonValueKind.Number when value.Value.TryGetDouble(out var number) && double.IsFinite(number) => number,
|
||||
_ => (double?)null
|
||||
};
|
||||
if (numeric is null || value.Status is not null && !value.Status.Equals("good", StringComparison.OrdinalIgnoreCase) && !value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) return;
|
||||
using var query = connection.CreateCommand();
|
||||
query.Transaction = transaction;
|
||||
query.CommandText = "SELECT configuration_json, active, observed_at_utc FROM alarm_rules WHERE point_id = $point AND enabled = 1;";
|
||||
query.Parameters.AddWithValue("$point", value.PointId.ToString());
|
||||
var records = new List<(AlarmRule Rule, bool? Active, DateTimeOffset? At)>();
|
||||
using (var reader = query.ExecuteReader())
|
||||
while (reader.Read()) records.Add((JsonSerializer.Deserialize<AlarmRule>(reader.GetString(0), JsonOptions)!, reader.IsDBNull(1) ? null : reader.GetBoolean(1), reader.IsDBNull(2) ? null : ParseTimestamp(reader.GetString(2))));
|
||||
foreach (var (rule, previous, observedAt) in records)
|
||||
{
|
||||
if (observedAt >= value.UpdatedAtUtc) continue;
|
||||
var active = rule.Condition switch
|
||||
{
|
||||
AlarmCondition.Active => numeric != 0, AlarmCondition.Inactive => numeric == 0,
|
||||
AlarmCondition.Above => previous == true ? numeric > rule.Threshold - rule.Hysteresis : numeric > rule.Threshold,
|
||||
AlarmCondition.Below => previous == true ? numeric < rule.Threshold + rule.Hysteresis : numeric < rule.Threshold,
|
||||
_ => false
|
||||
};
|
||||
using var update = connection.CreateCommand();
|
||||
update.Transaction = transaction;
|
||||
update.CommandText = "UPDATE alarm_rules SET active = $active, observed_at_utc = $at WHERE id = $id;";
|
||||
update.Parameters.AddWithValue("$active", active ? 1 : 0);
|
||||
update.Parameters.AddWithValue("$at", value.UpdatedAtUtc.ToString("O"));
|
||||
update.Parameters.AddWithValue("$id", rule.Id.ToString());
|
||||
update.ExecuteNonQuery();
|
||||
if (active == previous || !active && (previous is null || !rule.NotifyRecovery)) continue;
|
||||
var title = $"{(active ? "Alarm" : "Entwarnung")}: {rule.Name}";
|
||||
var message = $"{title}\n{rule.Message}\nWert: {numeric.Value.ToString(CultureInfo.InvariantCulture)}\nZeit: {value.UpdatedAtUtc:O}";
|
||||
foreach (var destination in rule.Destinations) EnqueueNotification(connection, transaction, rule.Id, title, message, destination);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnqueueNotification(SqliteConnection connection, SqliteTransaction transaction, Guid ruleId, string title, string message, AlarmDestination destination)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = "INSERT INTO notification_outbox(rule_id, title, message, destination_json, state, created_at_utc) VALUES($rule, $title, $message, $destination, 'Pending', $at);";
|
||||
command.Parameters.AddWithValue("$rule", ruleId.ToString());
|
||||
command.Parameters.AddWithValue("$title", title);
|
||||
command.Parameters.AddWithValue("$message", message);
|
||||
command.Parameters.AddWithValue("$destination", JsonSerializer.Serialize(destination, JsonOptions));
|
||||
command.Parameters.AddWithValue("$at", DateTimeOffset.UtcNow.ToString("O"));
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
public IReadOnlyList<NotificationDelivery> ListNotificationDeliveries()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT id, rule_id, title, message, destination_json, state, created_at_utc, result FROM notification_outbox ORDER BY id DESC LIMIT 200;";
|
||||
using var reader = command.ExecuteReader();
|
||||
var results = new List<NotificationDelivery>();
|
||||
while (reader.Read()) results.Add(ReadDelivery(reader));
|
||||
return results;
|
||||
}
|
||||
|
||||
public NotificationDelivery? ClaimNotification()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
UPDATE notification_outbox SET state = 'Sending'
|
||||
WHERE id = (SELECT id FROM notification_outbox WHERE state = 'Pending' ORDER BY id LIMIT 1)
|
||||
RETURNING id, rule_id, title, message, destination_json, state, created_at_utc, result;
|
||||
""";
|
||||
NotificationDelivery? delivery;
|
||||
using (var reader = command.ExecuteReader()) delivery = reader.Read() ? ReadDelivery(reader) : null;
|
||||
transaction.Commit();
|
||||
return delivery;
|
||||
}
|
||||
|
||||
private static NotificationDelivery ReadDelivery(SqliteDataReader reader) => new(reader.GetInt64(0), Guid.Parse(reader.GetString(1)), reader.GetString(2), reader.GetString(3),
|
||||
JsonSerializer.Deserialize<AlarmDestination>(reader.GetString(4), JsonOptions)!, reader.GetString(5), ParseTimestamp(reader.GetString(6)), reader.IsDBNull(7) ? null : reader.GetString(7));
|
||||
|
||||
public void CompleteNotification(long id, string state, string result)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "UPDATE notification_outbox SET state = $state, result = $result WHERE id = $id AND state = 'Sending';";
|
||||
command.Parameters.AddWithValue("$id", id);
|
||||
command.Parameters.AddWithValue("$state", state);
|
||||
command.Parameters.AddWithValue("$result", result);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
public void RecoverInterruptedNotifications()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "UPDATE notification_outbox SET state = 'Unknown', result = 'Dienst während Versand beendet; Zustellung unbekannt. Kein automatischer Doppelversand.' WHERE state = 'Sending';";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public enum BulkMappingTarget { Mqtt, Modbus, Bacnet, OpcUa }
|
||||
public sealed record BulkMappingRequest(Guid[] SourcePointIds, BulkMappingTarget Target,
|
||||
Guid? ModbusServerId = null, int? FirstRegister = null, string? MqttTopicPrefix = null,
|
||||
MqttMappingFormat? MqttFormat = null, MqttMonitoringSite? MqttSite = null);
|
||||
public sealed record BulkMappingResult(int Created, int Existing, IReadOnlyList<string> Assignments)
|
||||
{
|
||||
[JsonIgnore]
|
||||
public IReadOnlyList<Guid> NewMqttMappings { get; init; } = [];
|
||||
}
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public BulkMappingResult CreateBulkMappings(BulkMappingRequest request)
|
||||
{
|
||||
if (request.SourcePointIds is not { Length: >= 1 and <= 500 } || request.SourcePointIds.Distinct().Count() != request.SourcePointIds.Length ||
|
||||
!Enum.IsDefined(request.Target))
|
||||
throw new DomainValidationException("Bitte 1 bis 500 verschiedene Datenpunkte und ein gültiges Ziel auswählen.");
|
||||
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var points = ReadPoints(connection, transaction).ToDictionary(point => point.Id);
|
||||
var links = ReadMappings(connection, transaction);
|
||||
var mqtt = ReadMqttMappings(connection, transaction);
|
||||
var configuration = ReadGatewayConfiguration(connection, transaction);
|
||||
var server = request.Target == BulkMappingTarget.Modbus
|
||||
? configuration.ModbusServers.SingleOrDefault(item => item.Id == request.ModbusServerId) ??
|
||||
throw new DomainValidationException("Bitte zuerst eine Modbus-TCP-Serverinstanz auswählen.")
|
||||
: null;
|
||||
var prefix = request.MqttTopicPrefix?.Trim().TrimEnd('/');
|
||||
var mqttFormat = request.MqttFormat ?? (prefix is null ? MqttMappingFormat.SeMonitoring : MqttMappingFormat.Json);
|
||||
var site = request.MqttSite ?? DefaultMonitoringSite(configuration.Installation);
|
||||
var alarms = request.Target == BulkMappingTarget.Mqtt && mqttFormat == MqttMappingFormat.SeMonitoring
|
||||
? ReadMqttAlarmPoints(connection, transaction) : [];
|
||||
if (request.Target == BulkMappingTarget.Mqtt && mqttFormat != MqttMappingFormat.SeMonitoring &&
|
||||
(string.IsNullOrWhiteSpace(prefix) || !IsValidMqttTopic(prefix) || prefix.Length > 850))
|
||||
throw new DomainValidationException("Für MQTT ein gültiges Topic-Präfix ohne Wildcards eingeben.");
|
||||
|
||||
var usedRegisters = new HashSet<(ModbusArea Area, int Index)>();
|
||||
if (server is not null)
|
||||
{
|
||||
foreach (var point in points.Values)
|
||||
{
|
||||
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId != server.Id) continue;
|
||||
for (var offset = 0; offset < address.RegisterCount; offset++) usedRegisters.Add((address.Area, address.Address + offset));
|
||||
}
|
||||
}
|
||||
var nextRegister = request.FirstRegister ?? server?.FirstHoldingRegister ?? 0;
|
||||
var nextDiscrete = nextRegister;
|
||||
if (server is not null && (nextRegister < server.FirstHoldingRegister || nextRegister >= server.FirstHoldingRegister + server.HoldingRegisterCount))
|
||||
throw new DomainValidationException("Die Startadresse liegt außerhalb des Registerbereichs der Modbus-Instanz.");
|
||||
|
||||
var saved = new List<string>();
|
||||
var seed = new List<PointMapping>();
|
||||
var mqttCreated = new List<Guid>();
|
||||
var skipped = 0;
|
||||
foreach (var id in request.SourcePointIds)
|
||||
{
|
||||
if (!points.TryGetValue(id, out var source) || !source.Readable)
|
||||
throw new DomainValidationException("Die Auswahl enthält einen fehlenden oder nicht lesbaren Datenpunkt.");
|
||||
if (request.Target == BulkMappingTarget.Mqtt)
|
||||
{
|
||||
var slug = Regex.Replace(source.DisplayName.ToLowerInvariant(), "[^a-z0-9_-]+", "-").Trim('-');
|
||||
if (slug.Length > 80) slug = slug[..80];
|
||||
var pointDefaults = GetMqttPointDefaults(source, alarms);
|
||||
var monitoring = mqttFormat == MqttMappingFormat.SeMonitoring;
|
||||
if (monitoring && pointDefaults.Category is null)
|
||||
throw new DomainValidationException($"'{source.DisplayName}' benötigt das MQTT-Format JSON.");
|
||||
var topicName = pointDefaults.TopicName;
|
||||
var topic = monitoring ? BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName) :
|
||||
$"{prefix}/{(slug.Length == 0 ? "punkt" : slug)}-{source.Id:N}";
|
||||
var occupied = mqtt.Where(mapping => GetMqttTopic(mapping) == topic).ToArray();
|
||||
if (occupied.Any(mapping => mapping.PointId == source.Id && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (monitoring && occupied.Length > 0)
|
||||
{
|
||||
topicName = $"{topicName}-{source.Id:N}";
|
||||
topic = BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName);
|
||||
if (mqtt.Any(mapping => mapping.PointId == source.Id && GetMqttTopic(mapping) == topic &&
|
||||
mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (mqtt.Any(mapping => GetMqttTopic(mapping) == topic))
|
||||
throw new DomainValidationException($"Das erzeugte MQTT-Topic für '{source.DisplayName}' ist bereits belegt.");
|
||||
}
|
||||
var mqttMapping = SaveMqttMapping(connection, transaction, null, new CreateMqttMappingRequest(source.Id, mqttFormat,
|
||||
MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false,
|
||||
monitoring ? site.ProjectYear : null, monitoring ? site.ProjectNumber : null, monitoring ? site.IspNumber : null,
|
||||
monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null))!;
|
||||
mqtt.Add(mqttMapping);
|
||||
mqttCreated.Add(mqttMapping.Id);
|
||||
saved.Add($"{source.DisplayName} → {topic}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var protocol = request.Target switch
|
||||
{
|
||||
BulkMappingTarget.Modbus => PointProtocol.Modbus,
|
||||
BulkMappingTarget.Bacnet => PointProtocol.Bacnet,
|
||||
_ => PointProtocol.OpcUa
|
||||
};
|
||||
if (links.Any(link => link.Enabled && link.SourcePointId == source.Id &&
|
||||
points.TryGetValue(link.TargetPointId, out var target) && target.Protocol == protocol && target.Scope == PointScope.Gateway &&
|
||||
(server is null || ModbusAddressing.TryParse(target, out var bound) && bound.ServerId == server.Id)))
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = $"{source.DisplayName[..Math.Min(114, source.DisplayName.Length)]} [{source.Id:N}]";
|
||||
var type = OpcUaPointTypes.Resolve(source.ValueType);
|
||||
var binary = type == Opc.Ua.BuiltInType.Boolean;
|
||||
CreatePointRequest targetRequest;
|
||||
string? assignment = null;
|
||||
if (server is not null)
|
||||
{
|
||||
var dataType = type switch
|
||||
{
|
||||
Opc.Ua.BuiltInType.Boolean => ModbusDataType.Boolean,
|
||||
Opc.Ua.BuiltInType.Byte or Opc.Ua.BuiltInType.UInt16 => ModbusDataType.UInt16,
|
||||
Opc.Ua.BuiltInType.SByte or Opc.Ua.BuiltInType.Int16 => ModbusDataType.Int16,
|
||||
Opc.Ua.BuiltInType.Int32 => ModbusDataType.Int32,
|
||||
Opc.Ua.BuiltInType.UInt32 => ModbusDataType.UInt32,
|
||||
Opc.Ua.BuiltInType.Float or Opc.Ua.BuiltInType.Double => ModbusDataType.Float32,
|
||||
_ => throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten Modbus-Werttyp.")
|
||||
};
|
||||
var area = binary ? ModbusArea.DiscreteInput : ModbusArea.InputRegister;
|
||||
var width = dataType is ModbusDataType.UInt32 or ModbusDataType.Int32 or ModbusDataType.Float32 ? 2 : 1;
|
||||
ref var cursor = ref (binary ? ref nextDiscrete : ref nextRegister);
|
||||
var limit = server.FirstHoldingRegister + server.HoldingRegisterCount;
|
||||
while (cursor + width <= limit && Enumerable.Range(cursor, width).Any(index => usedRegisters.Contains((area, index)))) cursor++;
|
||||
if (cursor + width > limit)
|
||||
throw new DomainValidationException($"Für '{source.DisplayName}' ist im Modbus-Server kein freier Adressbereich mehr verfügbar.");
|
||||
var register = cursor;
|
||||
cursor += width;
|
||||
for (var offset = 0; offset < width; offset++) usedRegisters.Add((area, register + offset));
|
||||
targetRequest = new(name, protocol, PointScope.Gateway, dataType.ToString(), true, false, null,
|
||||
JsonSerializer.SerializeToElement(new { serverId = server.Id, unitId = server.UnitId, area = area.ToString(), address = register, dataType = dataType.ToString() }));
|
||||
assignment = $"{area} {register}" + (width > 1 ? $"–{register + width - 1}" : "");
|
||||
}
|
||||
else if (protocol == PointProtocol.Bacnet)
|
||||
{
|
||||
if (type is Opc.Ua.BuiltInType.Null or Opc.Ua.BuiltInType.String)
|
||||
throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten BACnet-Werttyp.");
|
||||
targetRequest = new(name, protocol, PointScope.Gateway, binary ? "Boolean" : "Real", true, false, null,
|
||||
EmptyObject(), binary ? BacnetObjectKind.BinaryValue : BacnetObjectKind.AnalogValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
targetRequest = new(name, protocol, PointScope.Gateway, source.ValueType, true, false, null, EmptyObject());
|
||||
}
|
||||
|
||||
var targetPoint = InsertPoint(connection, transaction, targetRequest);
|
||||
var mapping = SaveMapping(connection, transaction, null,
|
||||
new CreateMappingRequest(source.Id, targetPoint.Id, MappingDirection.OneWay, true, null, false, EmptyObject()))!.Mapping;
|
||||
seed.Add(mapping);
|
||||
saved.Add($"{source.DisplayName} → {assignment ?? (protocol == PointProtocol.Bacnet ? $"{targetPoint.BacnetObjectKind} {targetPoint.BacnetObjectInstance}" : targetPoint.DisplayName)}");
|
||||
}
|
||||
transaction.Commit();
|
||||
SeedNewMappings(seed);
|
||||
return new(saved.Count, skipped, saved) { NewMqttMappings = mqttCreated };
|
||||
}
|
||||
|
||||
private void SeedNewMappings(List<PointMapping> mappings)
|
||||
{
|
||||
if (mappings.Count == 0) return;
|
||||
var values = ListPointValues().ToDictionary(value => value.PointId);
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
if (!values.TryGetValue(mapping.SourcePointId, out var value) || value.Value.ValueKind == JsonValueKind.Null ||
|
||||
value.Status is not (null or "Good" or "ok")) continue;
|
||||
try
|
||||
{
|
||||
SetPointValue(mapping.TargetPointId, value.Value, value.SourceProtocol, DateTimeOffset.UtcNow, value.Status,
|
||||
mapping.SourcePointId, expectedMapping: mapping);
|
||||
}
|
||||
catch (DomainValidationException) { /* An edited route or incompatible first sample can wait for the next value. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.VisualBasic.FileIO;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public enum ConfigurationCsvKind { Points, Mappings, MqttMappings }
|
||||
public sealed record ConfigurationCsvRequest(string Csv);
|
||||
public sealed record ConfigurationCsvResult(int Created, int Updated);
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
private static readonly string[] PointColumns =
|
||||
["Id", "Name", "Protocol", "Scope", "ValueType", "Readable", "Writable", "ExternalIdentity", "Address", "BacnetObjectKind", "BacnetObjectInstance"];
|
||||
private static readonly string[] MappingColumns =
|
||||
["Id", "SourcePointId", "TargetPointId", "Direction", "Enabled", "BacnetPriority", "AcknowledgeMultipleExternalWriters", "Transform"];
|
||||
private static readonly string[] MqttMappingColumns =
|
||||
["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty"];
|
||||
|
||||
public string ExportConfigurationCsv(ConfigurationCsvKind kind)
|
||||
{
|
||||
IEnumerable<object?[]> records = kind switch
|
||||
{
|
||||
ConfigurationCsvKind.Points => ListPoints().Select(point => new object?[] { point.Id, point.DisplayName,
|
||||
point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable, point.ExternalIdentity,
|
||||
point.Address.GetRawText(), point.BacnetObjectKind, point.BacnetObjectInstance }),
|
||||
ConfigurationCsvKind.Mappings => ListMappings().Select(mapping => new object?[] { mapping.Id, mapping.SourcePointId,
|
||||
mapping.TargetPointId, mapping.Direction, mapping.Enabled, mapping.BacnetPriority,
|
||||
mapping.AcknowledgeMultipleExternalWriters, mapping.Transform.GetRawText() }),
|
||||
_ => ListMqttMappings().Select(mapping => new object?[] { mapping.Id, mapping.PointId, mapping.Format,
|
||||
mapping.Direction, mapping.QualityOfService, mapping.Retain, mapping.ProjectYear, mapping.ProjectNumber,
|
||||
mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty })
|
||||
};
|
||||
var output = new StringBuilder("\uFEFF");
|
||||
output.AppendJoin(';', CsvColumns(kind)).Append("\r\n");
|
||||
foreach (var record in records)
|
||||
{
|
||||
output.AppendJoin(';', record.Select(field =>
|
||||
{
|
||||
var value = Convert.ToString(field, CultureInfo.InvariantCulture) ?? "";
|
||||
if (NeedsCsvEscape(value)) value = "'" + value;
|
||||
return "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
|
||||
})).Append("\r\n");
|
||||
}
|
||||
return output.ToString();
|
||||
}
|
||||
|
||||
public ConfigurationCsvResult ImportConfigurationCsv(ConfigurationCsvKind kind, string csv)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(csv) || Encoding.UTF8.GetByteCount(csv) > 4 * 1024 * 1024)
|
||||
throw new DomainValidationException("CSV fehlt oder überschreitet 4 MB.");
|
||||
|
||||
var content = csv.TrimStart('\uFEFF');
|
||||
var endOfHeader = content.IndexOfAny(['\r', '\n']);
|
||||
var header = endOfHeader < 0 ? content : content[..endOfHeader];
|
||||
using var parser = new TextFieldParser(new StringReader(content))
|
||||
{
|
||||
HasFieldsEnclosedInQuotes = true,
|
||||
TrimWhiteSpace = false
|
||||
};
|
||||
parser.SetDelimiters(header.Contains(';') ? ";" : ",");
|
||||
var columns = CsvColumns(kind);
|
||||
try
|
||||
{
|
||||
if (!(parser.ReadFields() ?? []).Select(value => value.Trim()).SequenceEqual(columns, StringComparer.OrdinalIgnoreCase))
|
||||
throw new DomainValidationException("Die CSV-Spalten stimmen mit der exportierten Vorlage nicht überein.");
|
||||
}
|
||||
catch (MalformedLineException) { throw new DomainValidationException("Ungültiger CSV-Kopf."); }
|
||||
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var existing = kind switch
|
||||
{
|
||||
ConfigurationCsvKind.Points => ReadPoints(connection, transaction).Select(point => point.Id).ToHashSet(),
|
||||
ConfigurationCsvKind.Mappings => ReadMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet(),
|
||||
_ => ReadMqttMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet()
|
||||
};
|
||||
var seen = new HashSet<Guid>();
|
||||
var created = 0;
|
||||
var updated = 0;
|
||||
while (!parser.EndOfData)
|
||||
{
|
||||
var line = parser.LineNumber;
|
||||
try
|
||||
{
|
||||
if (created + updated >= 5000) throw new DomainValidationException("Maximal 5.000 Einträge pro Import.");
|
||||
var fields = parser.ReadFields() ?? [];
|
||||
if (fields.Length != columns.Length) throw new DomainValidationException($"Erwartet werden {columns.Length} Spalten.");
|
||||
for (var index = 0; index < fields.Length; index++)
|
||||
if (fields[index].StartsWith('\'') && NeedsCsvEscape(fields[index][1..])) fields[index] = fields[index][1..];
|
||||
|
||||
var id = string.IsNullOrWhiteSpace(fields[0]) ? (Guid?)null : CsvGuid(fields[0], columns[0]);
|
||||
if (id is { } entry && !seen.Add(entry)) throw new DomainValidationException("Diese ID kommt mehrfach in der Datei vor.");
|
||||
var update = id.HasValue && existing.Contains(id.Value);
|
||||
ImportCsvRow(connection, transaction, kind, fields, id, update);
|
||||
if (update) updated++;
|
||||
else created++;
|
||||
}
|
||||
catch (Exception exception) when (exception is DomainValidationException or MalformedLineException or JsonException)
|
||||
{
|
||||
var message = exception is DomainValidationException ? exception.Message : "Ungültige CSV- oder JSON-Syntax.";
|
||||
throw new DomainValidationException($"CSV-Zeile {line}: {message}");
|
||||
}
|
||||
}
|
||||
transaction.Commit();
|
||||
return new(created, updated);
|
||||
}
|
||||
|
||||
private void ImportCsvRow(SqliteConnection connection, SqliteTransaction transaction, ConfigurationCsvKind kind,
|
||||
string[] fields, Guid? id, bool update)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case ConfigurationCsvKind.Points:
|
||||
var point = new CreatePointRequest(fields[1], CsvEnum<PointProtocol>(fields[2], "Protocol"),
|
||||
CsvEnum<PointScope>(fields[3], "Scope"), fields[4], CsvBool(fields[5], "Readable"), CsvBool(fields[6], "Writable"),
|
||||
CsvOptional(fields[7]), JsonSerializer.Deserialize<JsonElement>(fields[8]),
|
||||
CsvOptional(fields[9]) is { } objectKind ? CsvEnum<BacnetObjectKind>(objectKind, "BacnetObjectKind") : null,
|
||||
CsvInteger(fields[10], "BacnetObjectInstance") is int instance and >= 0 ? (uint)instance :
|
||||
string.IsNullOrWhiteSpace(fields[10]) ? null : throw new DomainValidationException("BacnetObjectInstance erwartet eine nichtnegative Ganzzahl."));
|
||||
if (update) UpdatePoint(connection, transaction, id!.Value, point);
|
||||
else InsertPoint(connection, transaction, point, id);
|
||||
break;
|
||||
case ConfigurationCsvKind.Mappings:
|
||||
var mapping = new CreateMappingRequest(CsvGuid(fields[1], "SourcePointId"), CsvGuid(fields[2], "TargetPointId"),
|
||||
CsvEnum<MappingDirection>(fields[3], "Direction"), CsvBool(fields[4], "Enabled"),
|
||||
CsvInteger(fields[5], "BacnetPriority"), CsvBool(fields[6], "AcknowledgeMultipleExternalWriters"),
|
||||
JsonSerializer.Deserialize<JsonElement>(fields[7]));
|
||||
SaveMapping(connection, transaction, update ? id : null, mapping, update ? null : id);
|
||||
break;
|
||||
case ConfigurationCsvKind.MqttMappings:
|
||||
var mqtt = new CreateMqttMappingRequest(CsvGuid(fields[1], "PointId"), CsvEnum<MqttMappingFormat>(fields[2], "Format"),
|
||||
CsvEnum<MqttDirection>(fields[3], "Direction"), CsvEnum<MqttQualityOfService>(fields[4], "QualityOfService"),
|
||||
CsvBool(fields[5], "Retain"), CsvInteger(fields[6], "ProjectYear"), CsvOptional(fields[7]), CsvOptional(fields[8]),
|
||||
CsvOptional(fields[9]) is { } category ? CsvEnum<SeMonitoringCategory>(category, "SeCategory") : null,
|
||||
CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12]));
|
||||
SaveMqttMapping(connection, transaction, update ? id : null, mqtt, update ? null : id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static string[] CsvColumns(ConfigurationCsvKind kind) => kind switch
|
||||
{
|
||||
ConfigurationCsvKind.Points => PointColumns,
|
||||
ConfigurationCsvKind.Mappings => MappingColumns,
|
||||
_ => MqttMappingColumns
|
||||
};
|
||||
|
||||
private static string? CsvOptional(string text) => string.IsNullOrWhiteSpace(text) ? null : text;
|
||||
private static Guid CsvGuid(string text, string field) => Guid.TryParse(text, out var value) && value != Guid.Empty
|
||||
? value : throw new DomainValidationException($"{field} erwartet eine gültige ID.");
|
||||
private static int? CsvInteger(string text, string field) => string.IsNullOrWhiteSpace(text) ? null :
|
||||
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)
|
||||
? value : throw new DomainValidationException($"{field} erwartet eine Ganzzahl.");
|
||||
private static bool CsvBool(string text, string field) => text.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"true" or "1" => true,
|
||||
"false" or "0" => false,
|
||||
_ => throw new DomainValidationException($"{field} erwartet True oder False.")
|
||||
};
|
||||
private static T CsvEnum<T>(string text, string field) where T : struct, Enum =>
|
||||
Enum.TryParse<T>(text, true, out var value) && Enum.IsDefined(value)
|
||||
? value : throw new DomainValidationException($"{field} enthält einen unbekannten Wert.");
|
||||
|
||||
private static bool NeedsCsvEscape(string value) => value.AsSpan().TrimStart(' ') is ['=' or '+' or '-' or '@' or '\t' or '\r' or '\n' or '\'', ..];
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Globalization;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public MqttMappingDefaults GetMqttMappingDefaults()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection).Installation);
|
||||
var alarms = ReadMqttAlarmPoints(connection);
|
||||
return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray());
|
||||
}
|
||||
|
||||
internal GatewayPoint? GetMqttPoint(Guid id)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return FindActivePoint(connection, null, id);
|
||||
}
|
||||
|
||||
internal static bool IsBooleanMqttPoint(GatewayPoint point) =>
|
||||
point.BacnetObjectKind is BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue ||
|
||||
OpcUaPointTypes.Resolve(point.ValueType) == Opc.Ua.BuiltInType.Boolean;
|
||||
|
||||
private static MqttMonitoringSite DefaultMonitoringSite(InstallationIdentity? installation)
|
||||
{
|
||||
var project = installation?.ProjectNumber;
|
||||
var year = project is { Length: >= 7 } && IsProjectNumber(project) &&
|
||||
int.TryParse(project.AsSpan(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out var projectYear)
|
||||
? 2000 + projectYear : (int?)null;
|
||||
return new(year, project, installation is null ? null : $"ISP{installation.IspNumber}");
|
||||
}
|
||||
|
||||
private static HashSet<Guid> ReadMqttAlarmPoints(SqliteConnection connection, SqliteTransaction? transaction = null) =>
|
||||
ReadAlarmRules(connection, transaction).Where(rule => rule.Enabled).Select(rule => rule.PointId).ToHashSet();
|
||||
|
||||
private static MqttPointDefaults GetMqttPointDefaults(GatewayPoint point, HashSet<Guid> alarms)
|
||||
{
|
||||
var category = GetMqttPointClassification(point) switch
|
||||
{
|
||||
MqttPointClassification.Analog => SeMonitoringCategory.Analog,
|
||||
MqttPointClassification.Digital => alarms.Contains(point.Id) ? SeMonitoringCategory.Alarms : SeMonitoringCategory.Notify,
|
||||
_ => (SeMonitoringCategory?)null
|
||||
};
|
||||
var name = new string(point.DisplayName.Select(character => char.IsLetterOrDigit(character) || character is '_' or '-' ? character : '_').ToArray()).Trim('_');
|
||||
if (name.EndsWith("_Wert", StringComparison.OrdinalIgnoreCase)) name = name[..^5];
|
||||
return new(point.Id, category, name.Length == 0 ? "Punkt" : name);
|
||||
}
|
||||
|
||||
private static string BuildMonitoringTopic(MqttMonitoringSite site, SeMonitoringCategory category, string name) =>
|
||||
$"Projekte{site.ProjectYear}/{site.ProjectNumber}/{site.IspNumber}/{GetCategorySegment(category)}/{name}_Wert";
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
internal List<GatewayPoint> ListMqttExternalPoints()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return ReadMqttExternalPoints(connection);
|
||||
}
|
||||
|
||||
private static List<GatewayPoint> ReadMqttExternalPoints(SqliteConnection connection, SqliteTransaction? transaction = null)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = PointSelect + " WHERE deleted_at_utc IS NULL AND protocol = 'Mqtt' AND scope = 'External';";
|
||||
using var reader = command.ExecuteReader();
|
||||
var points = new List<GatewayPoint>();
|
||||
while (reader.Read())
|
||||
{
|
||||
var point = ReadPoint(reader);
|
||||
if (MqttExternalTopics.Address(point) is not null) points.Add(point);
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
internal MqttTopicImportResult ImportMqttExternalPoints(MqttConfiguration broker, ObservedMqttTopic[] topics, int unavailable)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
if (ReadGatewayConfiguration(connection, transaction).Mqtt != broker)
|
||||
throw new DomainValidationException("Die MQTT-Broker-Konfiguration wurde während des Imports geändert.");
|
||||
var known = ReadMqttExternalPoints(connection, transaction).Select(MqttExternalTopics.Address).ToHashSet(StringComparer.Ordinal);
|
||||
var created = 0;
|
||||
var existing = 0;
|
||||
foreach (var topic in topics)
|
||||
{
|
||||
if (!known.Add(topic.Topic)) { existing++; continue; }
|
||||
var leaf = topic.Topic[(topic.Topic.LastIndexOf('/') + 1)..].Trim();
|
||||
if (leaf.Length == 0) leaf = topic.Topic.Trim();
|
||||
if (leaf.Length == 0) leaf = "MQTT-Datenpunkt";
|
||||
var identity = "mqtt-topic:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(topic.Topic)));
|
||||
var point = InsertPoint(connection, transaction, new CreatePointRequest(leaf[..Math.Min(leaf.Length, 160)],
|
||||
PointProtocol.Mqtt, PointScope.External, topic.ValueType!, true, false, identity,
|
||||
JsonSerializer.SerializeToElement(new { topic = topic.Topic })));
|
||||
WritePointValue(connection, transaction, new(point.Id, topic.Value!.Value, PointProtocol.Mqtt,
|
||||
topic.ReceivedAtUtc, "Good", point.Id));
|
||||
created++;
|
||||
}
|
||||
transaction.Commit();
|
||||
return new(created, existing, unavailable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Opc.Ua;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record SaveOpcUaClientRequest(OpcUaClientConfiguration Configuration, string? Password = null, bool ClearPassword = false);
|
||||
public sealed record OpcUaClientView(OpcUaClientConfiguration Configuration, bool HasPassword);
|
||||
public sealed record OpcUaImportPoint(string NodeId, string DisplayName, string ValueType, bool Readable, bool Writable);
|
||||
public sealed record OpcUaImportRequest(Guid ClientId, IReadOnlyList<OpcUaImportPoint> Points);
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
public IReadOnlyList<OpcUaClientView> ListOpcUaClients()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return (GetGatewayConfiguration().OpcUa.Clients ?? []).Select(client => new OpcUaClientView(client, GetSetting(connection, $"opcua.password.{client.Id}") is not null)).ToArray();
|
||||
}
|
||||
|
||||
public OpcUaClientView SaveOpcUaClient(SaveOpcUaClientRequest request)
|
||||
{
|
||||
var client = request.Configuration with { Id = request.Configuration.Id == Guid.Empty ? Guid.NewGuid() : request.Configuration.Id, Name = request.Configuration.Name.Trim(), EndpointUrl = request.Configuration.EndpointUrl.Trim() };
|
||||
if (client.AuthenticationMode is not (OpcUaAuthenticationMode.Anonymous or OpcUaAuthenticationMode.Username))
|
||||
throw new DomainValidationException("Der OPC-UA-Client unterstützt derzeit Anonym oder Benutzer/Passwort.");
|
||||
if (client.AuthenticationMode == OpcUaAuthenticationMode.Username && !client.UseSecurity)
|
||||
throw new DomainValidationException("Benutzer/Passwort erfordert einen gesicherten Kanal.");
|
||||
if (client.PublishingIntervalMilliseconds is < 100 or > 60_000)
|
||||
throw new DomainValidationException("OPC-UA-Publishing-Intervall: 100 bis 60000 ms.");
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var configuration = JsonSerializer.Deserialize<GatewayConfiguration>(GetSetting(connection, GatewayConfigurationKey)!, JsonOptions)!;
|
||||
var clients = (configuration.OpcUa.Clients ?? []).Where(item => item.Id != client.Id).Append(client).ToArray();
|
||||
configuration = configuration with { OpcUa = configuration.OpcUa with { Clients = clients } };
|
||||
ValidateGatewayConfiguration(configuration);
|
||||
var key = $"opcua.password.{client.Id}";
|
||||
if (request.ClearPassword) DeleteSetting(connection, key, transaction);
|
||||
else if (request.Password is not null) SetSetting(connection, key, _secretProtector.Protect(request.Password), transaction);
|
||||
if (client.AuthenticationMode == OpcUaAuthenticationMode.Username && GetSetting(connection, key) is null)
|
||||
throw new DomainValidationException("Bitte ein OPC-UA-Passwort hinterlegen.");
|
||||
SetSetting(connection, GatewayConfigurationKey, JsonSerializer.Serialize(configuration, JsonOptions), transaction);
|
||||
// Password rotations also invalidate running client sessions, without exposing a secret in status.
|
||||
SetSetting(connection, $"opcua.revision.{client.Id}", Guid.NewGuid().ToString(), transaction);
|
||||
WriteAudit(connection, "opcua", $"Client '{client.Name}' saved.", transaction);
|
||||
transaction.Commit();
|
||||
return new OpcUaClientView(client, GetSetting(connection, key) is not null);
|
||||
}
|
||||
|
||||
public (string? Password, string Revision) GetOpcUaClientCredentials(Guid id)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var encrypted = GetSetting(connection, $"opcua.password.{id}");
|
||||
return (encrypted is null ? null : _secretProtector.Unprotect(encrypted), GetSetting(connection, $"opcua.revision.{id}") ?? "");
|
||||
}
|
||||
|
||||
public IReadOnlyList<GatewayPoint> ImportOpcUaPoints(OpcUaImportRequest request)
|
||||
{
|
||||
var client = (GetGatewayConfiguration().OpcUa.Clients ?? []).SingleOrDefault(item => item.Id == request.ClientId)
|
||||
?? throw new DomainValidationException("Bitte zuerst eine OPC-UA-Verbindung speichern.");
|
||||
if (request.Points.Count is < 1 or > 5000) throw new DomainValidationException("Zwischen 1 und 5000 Punkte je Import sind erlaubt.");
|
||||
foreach (var item in request.Points)
|
||||
{
|
||||
if (OpcUaPointTypes.Resolve(item.ValueType) == BuiltInType.Null || !item.Readable || string.IsNullOrWhiteSpace(item.DisplayName))
|
||||
throw new DomainValidationException("Nur lesbare skalare OPC-UA-Variablen können importiert werden.");
|
||||
try { _ = ExpandedNodeId.Parse(item.NodeId); }
|
||||
catch (Exception exception) when (exception is ServiceResultException or FormatException) { throw new DomainValidationException("Ungültige OPC-UA-NodeId."); }
|
||||
}
|
||||
var points = ListPoints();
|
||||
var imported = new List<GatewayPoint>();
|
||||
foreach (var item in request.Points.DistinctBy(item => item.NodeId))
|
||||
{
|
||||
var identity = $"opcua:{new Uri(client.EndpointUrl).AbsoluteUri}:{item.NodeId}";
|
||||
if (points.Any(point => point.ExternalIdentity == identity)) continue;
|
||||
imported.Add(CreatePoint(new CreatePointRequest(item.DisplayName, PointProtocol.OpcUa, PointScope.External, item.ValueType, true, item.Writable, identity,
|
||||
JsonSerializer.SerializeToElement(new { clientId = client.Id, nodeId = item.NodeId }))));
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Gateway.Api.Domain;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
private const string PointSelect = """
|
||||
SELECT id, display_name, protocol, scope, value_type, readable, writable, external_identity,
|
||||
address_json, created_at_utc, bacnet_object_kind, bacnet_object_instance FROM points
|
||||
""";
|
||||
|
||||
private static GatewayPoint? FindActivePoint(SqliteConnection connection, SqliteTransaction? transaction, Guid id)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = PointSelect + " WHERE id = $id AND deleted_at_utc IS NULL;";
|
||||
command.Parameters.AddWithValue("$id", id.ToString());
|
||||
using var reader = command.ExecuteReader();
|
||||
return reader.Read() ? ReadPoint(reader) : null;
|
||||
}
|
||||
|
||||
private static bool MatchesPointDefinition(GatewayPoint current, GatewayPoint expected) =>
|
||||
current.Protocol == expected.Protocol && current.Scope == expected.Scope &&
|
||||
current.Readable == expected.Readable && current.Writable == expected.Writable &&
|
||||
string.Equals(current.ValueType, expected.ValueType, StringComparison.OrdinalIgnoreCase) &&
|
||||
current.ExternalIdentity == expected.ExternalIdentity && current.BacnetObjectKind == expected.BacnetObjectKind &&
|
||||
current.BacnetObjectInstance == expected.BacnetObjectInstance &&
|
||||
current.Address.GetRawText() == expected.Address.GetRawText();
|
||||
|
||||
public bool IsPointDefinitionCurrent(GatewayPoint expected)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
return FindActivePoint(connection, null, expected.Id) is { } current && MatchesPointDefinition(current, expected);
|
||||
}
|
||||
|
||||
private static GatewayPoint PreparePoint(SqliteConnection connection, SqliteTransaction transaction,
|
||||
CreatePointRequest request, GatewayPoint? existing)
|
||||
{
|
||||
ValidatePointRequest(request);
|
||||
var name = request.DisplayName.Trim();
|
||||
var instance = request.BacnetObjectKind is null ? null : request.BacnetObjectInstance;
|
||||
if (request.Protocol == PointProtocol.Bacnet && request.Scope == PointScope.Gateway)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
SELECT EXISTS(SELECT 1 FROM points WHERE deleted_at_utc IS NULL AND protocol = 'Bacnet'
|
||||
AND scope = 'Gateway' AND display_name = $name AND id <> $id);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$name", name);
|
||||
command.Parameters.AddWithValue("$id", existing?.Id.ToString() ?? "");
|
||||
if ((long)command.ExecuteScalar()! != 0 || ReadGatewayConfiguration(connection, transaction).DeviceName == name)
|
||||
throw new DomainValidationException("BACnet-Object_Name muss innerhalb des Gateway-Geräts eindeutig sein.");
|
||||
|
||||
var kind = request.BacnetObjectKind!.Value;
|
||||
instance ??= existing is { Protocol: PointProtocol.Bacnet, Scope: PointScope.Gateway } && existing.BacnetObjectKind == kind
|
||||
? existing.BacnetObjectInstance : null;
|
||||
instance ??= GetNextBacnetObjectInstance(connection, transaction, kind);
|
||||
}
|
||||
return new GatewayPoint(existing?.Id ?? Guid.NewGuid(), name, request.Protocol, request.Scope,
|
||||
request.ValueType.Trim(), request.Readable, request.Writable, NormalizeNullable(request.ExternalIdentity),
|
||||
request.Address.Clone(), existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow, request.BacnetObjectKind, instance);
|
||||
}
|
||||
|
||||
private static void BindPoint(SqliteCommand command, GatewayPoint point)
|
||||
{
|
||||
command.Parameters.AddWithValue("$id", point.Id.ToString());
|
||||
command.Parameters.AddWithValue("$displayName", point.DisplayName);
|
||||
command.Parameters.AddWithValue("$protocol", point.Protocol.ToString());
|
||||
command.Parameters.AddWithValue("$scope", point.Scope.ToString());
|
||||
command.Parameters.AddWithValue("$valueType", point.ValueType);
|
||||
command.Parameters.AddWithValue("$readable", point.Readable ? 1 : 0);
|
||||
command.Parameters.AddWithValue("$writable", point.Writable ? 1 : 0);
|
||||
command.Parameters.AddWithValue("$externalIdentity", (object?)point.ExternalIdentity ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$address", point.Address.GetRawText());
|
||||
command.Parameters.AddWithValue("$bacnetObjectKind", (object?)point.BacnetObjectKind?.ToString() ?? DBNull.Value);
|
||||
command.Parameters.AddWithValue("$bacnetObjectInstance", (object?)point.BacnetObjectInstance ?? DBNull.Value);
|
||||
}
|
||||
|
||||
private static DomainValidationException PointIdentityConflict(GatewayPoint point) =>
|
||||
new(point.Scope == PointScope.Gateway && point.BacnetObjectKind is not null
|
||||
? "BACnet-Objekttyp und -instanz sind bereits vergeben."
|
||||
: "Die externe Punktadresse existiert bereits.");
|
||||
|
||||
public GatewayPoint? UpdatePoint(Guid id, CreatePointRequest request)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var updated = UpdatePoint(connection, transaction, id, request);
|
||||
transaction.Commit();
|
||||
return updated;
|
||||
}
|
||||
|
||||
private static GatewayPoint? UpdatePoint(SqliteConnection connection, SqliteTransaction transaction, Guid id, CreatePointRequest request)
|
||||
{
|
||||
var current = FindActivePoint(connection, transaction, id);
|
||||
if (current is null) return null;
|
||||
var updated = PreparePoint(connection, transaction, request, current);
|
||||
bool signalChanged = current.Protocol != updated.Protocol || current.Scope != updated.Scope ||
|
||||
!string.Equals(current.ValueType, updated.ValueType, StringComparison.OrdinalIgnoreCase) ||
|
||||
current.ExternalIdentity != updated.ExternalIdentity || current.BacnetObjectKind != updated.BacnetObjectKind ||
|
||||
current.BacnetObjectInstance != updated.BacnetObjectInstance ||
|
||||
!JsonNode.DeepEquals(JsonNode.Parse(current.Address.GetRawText()), JsonNode.Parse(updated.Address.GetRawText()));
|
||||
var dependencies = ReadPointDependencies(connection, transaction, id);
|
||||
if ((signalChanged || current.Readable != updated.Readable || current.Writable != updated.Writable) &&
|
||||
(dependencies.Mappings + dependencies.MqttMappings + dependencies.Alarms > 0))
|
||||
throw new DomainValidationException("Der Punkt ist mit Mappings oder Alarmen verknüpft. Seine Adresse, sein Typ und seine Zugriffe sind in dieser Zuordnung fest. Der Name kann geändert werden.");
|
||||
if (!updated.Readable && current.Readable && dependencies.TrendLogs > 0)
|
||||
throw new DomainValidationException("Der Datenpunkt wird von einem Trendlog gelesen.");
|
||||
|
||||
// Preserve identical address JSON so a formatting-only edit never recreates a native object.
|
||||
if (!signalChanged) updated = updated with { Address = current.Address };
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
UPDATE points SET display_name=$displayName, protocol=$protocol, scope=$scope, value_type=$valueType,
|
||||
readable=$readable, writable=$writable, external_identity=$externalIdentity,
|
||||
address_json=$address, bacnet_object_kind=$bacnetObjectKind, bacnet_object_instance=$bacnetObjectInstance
|
||||
WHERE id=$id AND deleted_at_utc IS NULL;
|
||||
""";
|
||||
BindPoint(command, updated);
|
||||
try { command.ExecuteNonQuery(); }
|
||||
catch (SqliteException exception) when (exception.SqliteErrorCode == 19) { throw PointIdentityConflict(updated); }
|
||||
if (signalChanged) ClearPointRuntime(connection, transaction, id);
|
||||
else if (current.Writable && !updated.Writable)
|
||||
ExecutePointSql(connection, transaction, id, "DELETE FROM bacnet_commands WHERE point_id=$id AND state='pending';");
|
||||
WriteAudit(connection, "point", $"Point '{updated.DisplayName}' updated ({id}).", transaction);
|
||||
return updated;
|
||||
}
|
||||
|
||||
public PointDependencies? GetPointDependencies(Guid id)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction(deferred: true);
|
||||
if (FindActivePoint(connection, transaction, id) is null) return null;
|
||||
return ReadPointDependencies(connection, transaction, id);
|
||||
}
|
||||
|
||||
private static PointDependencies ReadPointDependencies(SqliteConnection connection, SqliteTransaction transaction, Guid id)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
SELECT (SELECT COUNT(*) FROM mappings WHERE source_point_id=$id OR target_point_id=$id),
|
||||
(SELECT COUNT(*) FROM mqtt_mappings WHERE point_id=$id),
|
||||
(SELECT COUNT(*) FROM alarm_rules WHERE point_id=$id),
|
||||
(SELECT COUNT(*) FROM trend_logs WHERE source_point_id=$id);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$id", id.ToString());
|
||||
using var reader = command.ExecuteReader();
|
||||
reader.Read();
|
||||
return new(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3));
|
||||
}
|
||||
|
||||
public bool DeletePoint(Guid id, string? confirmation)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var point = FindActivePoint(connection, transaction, id);
|
||||
if (point is null) return false;
|
||||
var dependencies = ReadPointDependencies(connection, transaction, id);
|
||||
if (!string.Equals(confirmation, dependencies.Confirmation, StringComparison.Ordinal) &&
|
||||
(confirmation is not null || dependencies is not { Mappings: 0, MqttMappings: 0, Alarms: 0, TrendLogs: 0 }))
|
||||
throw new DomainValidationException("Der Punkt wird verwendet. Bitte prüfe die Verknüpfungen und bestätige das Löschen erneut.");
|
||||
|
||||
ExecutePointSql(connection, transaction, id, """
|
||||
DELETE FROM mappings WHERE source_point_id=$id OR target_point_id=$id;
|
||||
DELETE FROM mqtt_mappings WHERE point_id=$id;
|
||||
UPDATE notification_outbox SET state='Cancelled', result='Alarm point removed.'
|
||||
WHERE state='Pending' AND rule_id IN (SELECT id FROM alarm_rules WHERE point_id=$id);
|
||||
DELETE FROM alarm_rules WHERE point_id=$id;
|
||||
UPDATE trend_logs SET enabled=0 WHERE source_point_id=$id;
|
||||
UPDATE points SET deleted_at_utc=$now WHERE id=$id;
|
||||
""");
|
||||
ClearPointRuntime(connection, transaction, id);
|
||||
WriteAudit(connection, "point", $"Point '{point.DisplayName}' deleted ({id}).", transaction);
|
||||
transaction.Commit();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void ClearPointRuntime(SqliteConnection connection, SqliteTransaction transaction, Guid id) =>
|
||||
ExecutePointSql(connection, transaction, id, """
|
||||
DELETE FROM point_values WHERE point_id=$id;
|
||||
DELETE FROM bacnet_commands WHERE point_id=$id;
|
||||
DELETE FROM bacnet_properties WHERE point_id=$id;
|
||||
DELETE FROM bacnet_observations WHERE point_id=$id;
|
||||
""");
|
||||
|
||||
private static void ExecutePointSql(SqliteConnection connection, SqliteTransaction transaction, Guid id, string sql)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = sql;
|
||||
command.Parameters.AddWithValue("$id", id.ToString());
|
||||
command.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow.ToString("O"));
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed partial class GatewayStore
|
||||
{
|
||||
private static readonly DisplayUnit[] DefaultUnits =
|
||||
[new("%", "Prozent", true), new("°C", "Grad Celsius", true), new("A", "Ampere", true),
|
||||
new("bool", "Digital / Bool", true), new("K", "Kelvin", true), new("Pa", "Pascal", true), new("V", "Volt", true)];
|
||||
|
||||
public IReadOnlyList<DisplayUnit> ListDisplayUnits()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var json = GetSetting(connection, "presentation.units");
|
||||
return json is null ? DefaultUnits : JsonSerializer.Deserialize<DisplayUnit[]>(json, JsonOptions)!;
|
||||
}
|
||||
|
||||
public DisplayUnit SaveDisplayUnit(DisplayUnit unit)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(unit.Symbol) || unit.Symbol.Length > 24 || unit.Symbol.Any(char.IsControl) ||
|
||||
string.IsNullOrWhiteSpace(unit.Name) || unit.Name.Length > 100)
|
||||
throw new DomainValidationException("Symbol (1–24 Zeichen) und Bezeichnung (1–100 Zeichen) angeben.");
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var json = GetSetting(connection, "presentation.units");
|
||||
var units = (json is null ? DefaultUnits : JsonSerializer.Deserialize<DisplayUnit[]>(json, JsonOptions)!).ToList();
|
||||
var saved = unit with { Symbol = unit.Symbol.Trim(), Name = unit.Name.Trim(), IsSystem = DefaultUnits.Any(item => item.Symbol == unit.Symbol.Trim()) };
|
||||
units.RemoveAll(item => item.Symbol == saved.Symbol);
|
||||
units.Add(saved);
|
||||
SetSetting(connection, "presentation.units", JsonSerializer.Serialize(units.OrderBy(item => item.Symbol), JsonOptions), transaction);
|
||||
transaction.Commit();
|
||||
return saved;
|
||||
}
|
||||
|
||||
public IReadOnlyList<PointPresentation> ListPointPresentations()
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var json = GetSetting(connection, "presentation.points");
|
||||
return json is null ? [] : JsonSerializer.Deserialize<PointPresentation[]>(json, JsonOptions)!;
|
||||
}
|
||||
|
||||
public void SavePointPresentations(IReadOnlyList<PointPresentation> updates)
|
||||
{
|
||||
if (updates.Count > 10000 || updates.Select(item => item.PointId).Distinct().Count() != updates.Count)
|
||||
throw new DomainValidationException("Maximal 10000 eindeutige Datenpunkte gleichzeitig bearbeiten.");
|
||||
var points = ListPoints().Select(point => point.Id).ToHashSet();
|
||||
var units = ListDisplayUnits().Select(unit => unit.Symbol).Append("").ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var item in updates)
|
||||
{
|
||||
if (!points.Contains(item.PointId) || string.IsNullOrWhiteSpace(item.Alias) || item.Alias.Length > 160 ||
|
||||
!units.Contains(item.Unit) || !double.IsFinite(item.Factor) || item.Factor == 0 ||
|
||||
item.Kind is not ("analog" or "digital") || !Regex.IsMatch(item.Color ?? "", "^#[0-9a-fA-F]{6}$"))
|
||||
throw new DomainValidationException("Alias, Einheit, Faktor, Typ oder Farbe ist ungültig.");
|
||||
}
|
||||
using var connection = _database.OpenConnection();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var json = GetSetting(connection, "presentation.points");
|
||||
var existing = (json is null ? [] : JsonSerializer.Deserialize<PointPresentation[]>(json, JsonOptions)!).ToDictionary(item => item.PointId);
|
||||
foreach (var item in updates) existing[item.PointId] = item;
|
||||
SetSetting(connection, "presentation.points", JsonSerializer.Serialize(existing.Values, JsonOptions), transaction);
|
||||
WriteAudit(connection, "aliases", $"Updated presentation for {updates.Count} points.", transaction);
|
||||
transaction.Commit();
|
||||
}
|
||||
|
||||
public IReadOnlyList<DashboardWidget> GetDashboard(Guid userId)
|
||||
{
|
||||
using var connection = _database.OpenConnection();
|
||||
var json = GetSetting(connection, $"dashboard.{userId}");
|
||||
return json is null ? [] : JsonSerializer.Deserialize<DashboardWidget[]>(json, JsonOptions)!;
|
||||
}
|
||||
|
||||
public void SaveDashboard(Guid userId, bool isAdministrator, IReadOnlyList<DashboardWidget> widgets)
|
||||
{
|
||||
var visible = ListTrendSelections(userId, isAdministrator).Select(selection => selection.Id).ToHashSet();
|
||||
if (widgets.Count > 24 || widgets.Select(widget => widget.Id).Distinct().Count() != widgets.Count ||
|
||||
widgets.Any(widget => widget.Id == Guid.Empty || string.IsNullOrWhiteSpace(widget.Title) || widget.Title.Length > 120 ||
|
||||
!visible.Contains(widget.SelectionId) || widget.RangeHours is < 1 or > 720 || widget.Type is not ("Graph" or "Values")))
|
||||
throw new DomainValidationException("Ungültiges Widget: Titel, sichtbare Auswahl, Typ und Zeitraum prüfen (maximal 24 Widgets).");
|
||||
using var connection = _database.OpenConnection();
|
||||
SetSetting(connection, $"dashboard.{userId}", JsonSerializer.Serialize(widgets, JsonOptions));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,81 @@
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Read-only inventory of interfaces that are visible to the local gateway process.</summary>
|
||||
public sealed class HardwareDiscoveryService
|
||||
{
|
||||
public GatewayHardwareInventory GetInventory()
|
||||
{
|
||||
var interfaces = NetworkInterface.GetAllNetworkInterfaces()
|
||||
.Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Loopback)
|
||||
.Select(network => new GatewayNetworkInterface(
|
||||
network.Name,
|
||||
network.Description,
|
||||
network.OperationalStatus == OperationalStatus.Up,
|
||||
network.GetPhysicalAddress().ToString(),
|
||||
network.GetIPProperties().UnicastAddresses
|
||||
.Where(address => address.Address.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6)
|
||||
.Select(address => address.Address.ToString())
|
||||
.OrderBy(address => address, StringComparer.Ordinal)
|
||||
.ToArray()))
|
||||
.OrderBy(network => network.Name, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
var serialPaths = new HashSet<string>(StringComparer.Ordinal);
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
if (Directory.Exists("/dev/serial/by-id"))
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFileSystemEntries("/dev/serial/by-id"))
|
||||
{
|
||||
serialPaths.Add(path);
|
||||
}
|
||||
}
|
||||
|
||||
if (Directory.Exists("/dev"))
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFiles("/dev", "tty*"))
|
||||
{
|
||||
var name = Path.GetFileName(path);
|
||||
if (name.StartsWith("ttyUSB", StringComparison.Ordinal) ||
|
||||
name.StartsWith("ttyACM", StringComparison.Ordinal) ||
|
||||
name.StartsWith("ttyS", StringComparison.Ordinal) ||
|
||||
name.StartsWith("ttyAMA", StringComparison.Ordinal))
|
||||
{
|
||||
serialPaths.Add(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new GatewayHardwareInventory(
|
||||
interfaces,
|
||||
serialPaths.OrderBy(path => path, StringComparer.Ordinal).Select(path => new GatewaySerialDevice(path, GetSerialTarget(path))).ToArray());
|
||||
}
|
||||
|
||||
private static string? GetSerialTarget(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.ResolveLinkTarget(path, false)?.FullName;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record GatewayHardwareInventory(
|
||||
IReadOnlyList<GatewayNetworkInterface> NetworkInterfaces,
|
||||
IReadOnlyList<GatewaySerialDevice> SerialDevices);
|
||||
|
||||
public sealed record GatewayNetworkInterface(string Name, string Description, bool IsUp, string MacAddress, IReadOnlyList<string> Addresses);
|
||||
|
||||
public sealed record GatewaySerialDevice(string DevicePath, string? TargetPath);
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record HostNetworkProfile(string Interface, string Mode, string? Address, int? PrefixLength,
|
||||
string? Gateway, string[]? Dns, int? Metric);
|
||||
public sealed record HostNetworkConfirmation(string Id);
|
||||
|
||||
public sealed class HostNetworkService
|
||||
{
|
||||
private const string SocketPath = "/run/seiugw-network/control.sock";
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public async Task<IResult> SendAsync(object request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
return Results.Json(new { error = "Die Netzwerkkonfiguration benötigt den NixOS-Netzwerkdienst." }, statusCode: 503);
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(8));
|
||||
try
|
||||
{
|
||||
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
await socket.ConnectAsync(new UnixDomainSocketEndPoint(SocketPath), timeout.Token);
|
||||
using var stream = new NetworkStream(socket);
|
||||
await stream.WriteAsync(JsonSerializer.SerializeToUtf8Bytes(request, JsonOptions), timeout.Token);
|
||||
socket.Shutdown(SocketShutdown.Send);
|
||||
using var response = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token);
|
||||
var result = response.RootElement;
|
||||
return Results.Json(result.Clone(), statusCode: result.TryGetProperty("error", out _) ? 400 : 200);
|
||||
}
|
||||
catch (Exception ex) when (ex is SocketException or IOException or JsonException ||
|
||||
ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Results.Json(new { error = "Der NixOS-Netzwerkdienst ist gerade nicht erreichbar." }, statusCode: 503);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Xml.Linq;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record KnxEtsImportRequest(string FileName, string ContentBase64);
|
||||
|
||||
public sealed record KnxEtsImportResult(int Imported, IReadOnlyList<string> Errors);
|
||||
|
||||
/// <summary>Imports ETS group-address exports (.knxproj ZIP or XML) without trusting project metadata as executable content.</summary>
|
||||
public static class KnxEtsImporter
|
||||
{
|
||||
public static KnxEtsImportResult Import(KnxEtsImportRequest request, GatewayStore store)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.FileName) || request.FileName.Length > 260)
|
||||
{
|
||||
throw new DomainValidationException("Eine ETS-Datei mit gültigem Dateinamen wird benötigt.");
|
||||
}
|
||||
byte[] content;
|
||||
try { content = Convert.FromBase64String(request.ContentBase64); }
|
||||
catch (FormatException) { throw new DomainValidationException("Die ETS-Datei ist nicht gültig kodiert."); }
|
||||
if (content.Length is 0 or > 25 * 1024 * 1024)
|
||||
{
|
||||
throw new DomainValidationException("Die ETS-Datei darf maximal 25 MiB groß sein.");
|
||||
}
|
||||
|
||||
var documents = ReadXmlDocuments(request.FileName, content);
|
||||
var imported = 0;
|
||||
var errors = new List<string>();
|
||||
foreach (var document in documents)
|
||||
{
|
||||
foreach (var element in document.Descendants().Where(item => item.Name.LocalName == "GroupAddress"))
|
||||
{
|
||||
var name = element.Attribute("Name")?.Value?.Trim();
|
||||
var address = NormalizeAddress(element.Attribute("Address")?.Value);
|
||||
if (string.IsNullOrWhiteSpace(name) || address is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var dpt = element.Attribute("DatapointType")?.Value?.Trim() ?? element.Attribute("DPT")?.Value?.Trim();
|
||||
var identity = $"knx:{address}";
|
||||
try
|
||||
{
|
||||
using var addressJson = JsonDocument.Parse(JsonSerializer.Serialize(new { groupAddress = address, datapointType = dpt }));
|
||||
store.CreatePoint(new CreatePointRequest(
|
||||
name,
|
||||
PointProtocol.Knx,
|
||||
PointScope.External,
|
||||
GetValueType(dpt),
|
||||
true,
|
||||
IsWritableDpt(dpt),
|
||||
identity,
|
||||
addressJson.RootElement.Clone()));
|
||||
imported++;
|
||||
}
|
||||
catch (DomainValidationException exception)
|
||||
{
|
||||
errors.Add($"{address}: {exception.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new KnxEtsImportResult(imported, errors);
|
||||
}
|
||||
|
||||
private static List<XDocument> ReadXmlDocuments(string fileName, byte[] content)
|
||||
{
|
||||
if (fileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return [XDocument.Parse(Encoding.UTF8.GetString(content), LoadOptions.None)];
|
||||
}
|
||||
if (!fileName.EndsWith(".knxproj", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new DomainValidationException("Unterstützt werden ETS-Projekte (.knxproj) und ETS-XML-Exporte (.xml).");
|
||||
}
|
||||
try
|
||||
{
|
||||
using var memory = new MemoryStream(content, writable: false);
|
||||
using var archive = new ZipArchive(memory, ZipArchiveMode.Read, leaveOpen: false);
|
||||
var documents = new List<XDocument>();
|
||||
foreach (var entry in archive.Entries.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && entry.Length <= 10 * 1024 * 1024))
|
||||
{
|
||||
using var stream = entry.Open();
|
||||
documents.Add(XDocument.Load(stream, LoadOptions.None));
|
||||
}
|
||||
if (documents.Count == 0)
|
||||
{
|
||||
throw new DomainValidationException("Das ETS-Projekt enthält keine lesbare XML-Datei.");
|
||||
}
|
||||
return documents;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
throw new DomainValidationException("Die .knxproj-Datei ist kein gültiges ETS-ZIP-Archiv.");
|
||||
}
|
||||
catch (System.Xml.XmlException)
|
||||
{
|
||||
throw new DomainValidationException("Die ETS-XML-Datei ist ungültig.");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? NormalizeAddress(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return null;
|
||||
var trimmed = value.Trim();
|
||||
if (trimmed.Split('/').Length == 3 && trimmed.Split('/').All(part => int.TryParse(part, out _))) return trimmed;
|
||||
if (!ushort.TryParse(trimmed, out var encoded)) return null;
|
||||
return $"{(encoded >> 11) & 31}/{(encoded >> 8) & 7}/{encoded & 255}";
|
||||
}
|
||||
|
||||
private static string GetValueType(string? dpt) => dpt?.StartsWith("DPT-1", StringComparison.OrdinalIgnoreCase) == true ? "Boolean" : "Real";
|
||||
|
||||
private static bool IsWritableDpt(string? dpt) => !string.IsNullOrWhiteSpace(dpt);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Executes the configured mapping graph in-process. A journal entry is made
|
||||
/// before every forwarded value so the reverse edge of a bidirectional mapping
|
||||
/// consumes exactly the returning update instead of writing it back again.
|
||||
/// </summary>
|
||||
public sealed class MappingRuntimeService : IHostedService, IDisposable
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly WriteJournal _journal;
|
||||
private int _running;
|
||||
|
||||
public MappingRuntimeService(GatewayStore store, WriteJournal journal)
|
||||
{
|
||||
_store = store;
|
||||
_journal = journal;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_store.PointValueUpdated += OnPointValueUpdated;
|
||||
Interlocked.Exchange(ref _running, 1);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Exchange(ref _running, 0);
|
||||
_store.PointValueUpdated -= OnPointValueUpdated;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose() => _store.PointValueUpdated -= OnPointValueUpdated;
|
||||
|
||||
private void OnPointValueUpdated(object? sender, PointValue update)
|
||||
{
|
||||
if (Volatile.Read(ref _running) == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Configurations are intentionally read for every update. This keeps a
|
||||
// newly saved mapping live without requiring a process restart.
|
||||
Dictionary<Guid, GatewayPoint>? points = null;
|
||||
foreach (var mapping in _store.ListMappings().Where(candidate => candidate.Enabled))
|
||||
{
|
||||
var targetId = mapping.SourcePointId == update.PointId
|
||||
? mapping.TargetPointId
|
||||
: mapping.Direction == MappingDirection.Bidirectional && mapping.TargetPointId == update.PointId
|
||||
? mapping.SourcePointId
|
||||
: Guid.Empty;
|
||||
if (targetId == Guid.Empty)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var valueText = update.Value.GetRawText();
|
||||
var journalPrefix = $"mapping:{mapping.Id}:{mapping.SourcePointId}:{mapping.TargetPointId}:{mapping.Direction}:{mapping.BacnetPriority}";
|
||||
var reflectionKey = $"{journalPrefix}:{update.PointId}";
|
||||
if (_journal.ConsumeReflection(reflectionKey, valueText))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
points ??= _store.ListPoints().ToDictionary(point => point.Id);
|
||||
if (!points.ContainsKey(update.PointId) || !points.TryGetValue(targetId, out var target)) continue;
|
||||
if (target.Scope == PointScope.External && !string.IsNullOrWhiteSpace(update.Status) && !update.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) && !update.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
_journal.Register($"{journalPrefix}:{targetId}", valueText, TimeSpan.FromSeconds(15));
|
||||
_store.SetPointValue(targetId, update.Value, update.SourceProtocol, update.UpdatedAtUtc, update.Status,
|
||||
update.OriginPointId ?? update.PointId, mapping.BacnetPriority, expectedDefinition: target, expectedMapping: mapping);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A broken external mapping must not bring down the protocol
|
||||
// adapters. It remains visible in the audit trail on its next
|
||||
// configuration validation/update.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
internal enum ModbusArea
|
||||
{
|
||||
Coil,
|
||||
DiscreteInput,
|
||||
InputRegister,
|
||||
HoldingRegister
|
||||
}
|
||||
|
||||
internal enum ModbusDataType
|
||||
{
|
||||
Boolean,
|
||||
UInt16,
|
||||
Int16,
|
||||
UInt32,
|
||||
Int32,
|
||||
Float32,
|
||||
Float32WordSwap
|
||||
}
|
||||
|
||||
internal sealed record ModbusAddress(
|
||||
string Transport,
|
||||
Guid? ServerId,
|
||||
string? Host,
|
||||
int Port,
|
||||
byte UnitId,
|
||||
string? SerialPortAlias,
|
||||
ModbusArea Area,
|
||||
ushort Address,
|
||||
ModbusDataType DataType,
|
||||
int PollIntervalSeconds)
|
||||
{
|
||||
public int RegisterCount => Area is ModbusArea.Coil or ModbusArea.DiscreteInput ? 1 : DataType is ModbusDataType.UInt32 or ModbusDataType.Int32 or ModbusDataType.Float32 or ModbusDataType.Float32WordSwap ? 2 : 1;
|
||||
}
|
||||
|
||||
internal static class ModbusAddressing
|
||||
{
|
||||
public static bool TryParse(GatewayPoint point, out ModbusAddress address)
|
||||
{
|
||||
address = null!;
|
||||
if (point.Protocol != PointProtocol.Modbus || point.Address.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var transport = GetString(point.Address, "transport")?.ToLowerInvariant() ?? "tcp";
|
||||
var serverIdText = GetString(point.Address, "serverId");
|
||||
var serverId = Guid.TryParse(serverIdText, out var parsedServerId) ? parsedServerId : (Guid?)null;
|
||||
var host = GetString(point.Address, "host");
|
||||
var port = GetInt(point.Address, "port") ?? 502;
|
||||
var unitId = GetInt(point.Address, "unitId") ?? 1;
|
||||
var serialPortAlias = GetString(point.Address, "serialPortAlias");
|
||||
var area = ParseArea(GetString(point.Address, "area"));
|
||||
var register = GetInt(point.Address, "address") ?? GetInt(point.Address, "register") ?? -1;
|
||||
var dataType = ParseDataType(GetString(point.Address, "dataType"), area);
|
||||
var interval = GetInt(point.Address, "pollIntervalSeconds") ?? 5;
|
||||
if (transport is not ("tcp" or "rtu") || port is < 1 or > 65_535 || unitId is < 1 or > 247 || register is < 0 or > 65_535 || interval is < 1 or > 86_400)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (transport == "tcp" && serverId is null && string.IsNullOrWhiteSpace(host))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (transport == "rtu" && string.IsNullOrWhiteSpace(serialPortAlias))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
address = new ModbusAddress(transport, serverId, host, port, (byte)unitId, serialPortAlias, area, (ushort)register, dataType, interval);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonElement Encode(ushort[] registers, bool? coil, ModbusAddress address)
|
||||
{
|
||||
object value = address.Area is ModbusArea.Coil or ModbusArea.DiscreteInput
|
||||
? coil ?? false
|
||||
: address.DataType switch
|
||||
{
|
||||
ModbusDataType.UInt16 => registers[0],
|
||||
ModbusDataType.Int16 => unchecked((short)registers[0]),
|
||||
ModbusDataType.UInt32 => ((uint)registers[0] << 16) | registers[1],
|
||||
ModbusDataType.Int32 => unchecked((int)(((uint)registers[0] << 16) | registers[1])),
|
||||
ModbusDataType.Float32 => BitConverter.Int32BitsToSingle((int)(((uint)registers[0] << 16) | registers[1])),
|
||||
ModbusDataType.Float32WordSwap => BitConverter.Int32BitsToSingle((int)(((uint)registers[1] << 16) | registers[0])),
|
||||
_ => registers[0]
|
||||
};
|
||||
return JsonSerializer.SerializeToElement(value);
|
||||
}
|
||||
|
||||
public static (ushort[] Registers, bool? Coil) Decode(JsonElement value, ModbusAddress address)
|
||||
{
|
||||
if (address.Area is ModbusArea.Coil or ModbusArea.DiscreteInput)
|
||||
{
|
||||
var coil = value.ValueKind == JsonValueKind.True || value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && Math.Abs(number) > double.Epsilon ||
|
||||
value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed;
|
||||
return ([], coil);
|
||||
}
|
||||
|
||||
var numberValue = value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var numeric)
|
||||
? numeric
|
||||
: value.ValueKind == JsonValueKind.String && double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedNumber)
|
||||
? parsedNumber
|
||||
: throw new DomainValidationException("Der Modbus-Wert muss numerisch sein.");
|
||||
return address.DataType switch
|
||||
{
|
||||
ModbusDataType.UInt16 => ([checked((ushort)Math.Round(numberValue))], null),
|
||||
ModbusDataType.Int16 => ([unchecked((ushort)checked((short)Math.Round(numberValue)))], null),
|
||||
ModbusDataType.UInt32 => ToRegisters(checked((uint)Math.Round(numberValue)), false),
|
||||
ModbusDataType.Int32 => ToRegisters(unchecked((uint)checked((int)Math.Round(numberValue))), false),
|
||||
ModbusDataType.Float32 => ToRegisters(unchecked((uint)BitConverter.SingleToInt32Bits(checked((float)numberValue))), false),
|
||||
ModbusDataType.Float32WordSwap => ToRegisters(unchecked((uint)BitConverter.SingleToInt32Bits(checked((float)numberValue))), true),
|
||||
_ => ([checked((ushort)Math.Round(numberValue))], null)
|
||||
};
|
||||
}
|
||||
|
||||
private static (ushort[] Registers, bool? Coil) ToRegisters(uint value, bool wordSwap)
|
||||
{
|
||||
var high = (ushort)(value >> 16);
|
||||
var low = (ushort)value;
|
||||
return (wordSwap ? [low, high] : [high, low], null);
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var property) && property.ValueKind == JsonValueKind.String ? property.GetString()?.Trim() : null;
|
||||
|
||||
private static int? GetInt(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var property) && property.TryGetInt32(out var value) ? value : null;
|
||||
|
||||
private static ModbusArea ParseArea(string? raw) => raw?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"coil" or "coils" => ModbusArea.Coil,
|
||||
"discrete" or "discreteinput" or "discrete-input" => ModbusArea.DiscreteInput,
|
||||
"input" or "inputregister" or "input-register" => ModbusArea.InputRegister,
|
||||
_ => ModbusArea.HoldingRegister
|
||||
};
|
||||
|
||||
private static ModbusDataType ParseDataType(string? raw, ModbusArea area)
|
||||
{
|
||||
if (area is ModbusArea.Coil or ModbusArea.DiscreteInput)
|
||||
{
|
||||
return ModbusDataType.Boolean;
|
||||
}
|
||||
return raw?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"int16" => ModbusDataType.Int16,
|
||||
"uint32" => ModbusDataType.UInt32,
|
||||
"int32" => ModbusDataType.Int32,
|
||||
"float32" or "real" => ModbusDataType.Float32,
|
||||
"float32wordswap" or "float32-swap" or "float32_swap" => ModbusDataType.Float32WordSwap,
|
||||
_ => ModbusDataType.UInt16
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record ModbusCsvImportRequest(string Csv, bool ReplaceExisting = false);
|
||||
|
||||
public sealed record ModbusCsvImportResult(int Imported, IReadOnlyList<string> Errors);
|
||||
|
||||
/// <summary>Imports an intentionally small, documented CSV dialect for field Modbus point lists.</summary>
|
||||
public static class ModbusCsvImporter
|
||||
{
|
||||
public const string Example = """
|
||||
Name;Transport;Host;Port;SerialPortAlias;UnitId;Area;Address;DataType;Writable;PollIntervalSeconds
|
||||
Zulufttemperatur;tcp;192.168.10.20;502;;1;InputRegister;0;Float32;false;10
|
||||
Zuluft Sollwert;tcp;192.168.10.20;502;;1;HoldingRegister;20;Float32WordSwap;true;5
|
||||
Anlage Freigabe;rtu;;;RS485-Hauptstrang;1;Coil;0;Boolean;true;5
|
||||
""";
|
||||
|
||||
public static ModbusCsvImportResult Import(string csv, GatewayStore store)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(csv))
|
||||
{
|
||||
throw new DomainValidationException("Die Modbus-CSV ist leer.");
|
||||
}
|
||||
var rows = ReadRows(csv).ToArray();
|
||||
if (rows.Length < 2)
|
||||
{
|
||||
throw new DomainValidationException("Die Modbus-CSV benötigt eine Kopfzeile und mindestens einen Datenpunkt.");
|
||||
}
|
||||
var header = rows[0].Select((value, index) => new { Key = value.Trim(), index })
|
||||
.Where(item => item.Key.Length > 0)
|
||||
.ToDictionary(item => item.Key, item => item.index, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var required in new[] { "Name", "Transport", "UnitId", "Area", "Address" })
|
||||
{
|
||||
if (!header.ContainsKey(required))
|
||||
{
|
||||
throw new DomainValidationException($"Der CSV-Header '{required}' fehlt.");
|
||||
}
|
||||
}
|
||||
|
||||
var errors = new List<string>();
|
||||
var imported = 0;
|
||||
for (var rowIndex = 1; rowIndex < rows.Length; rowIndex++)
|
||||
{
|
||||
var row = rows[rowIndex];
|
||||
if (row.All(string.IsNullOrWhiteSpace))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var get = new Func<string, string>(name => header.TryGetValue(name, out var index) && index < row.Length ? row[index].Trim() : string.Empty);
|
||||
var transport = get("Transport").ToLowerInvariant();
|
||||
var port = ParseInt(get("Port"), 502);
|
||||
var unitId = ParseInt(get("UnitId"), 1);
|
||||
var address = ParseInt(get("Address"), -1);
|
||||
var pollInterval = ParseInt(get("PollIntervalSeconds"), 5);
|
||||
var area = string.IsNullOrWhiteSpace(get("Area")) ? "HoldingRegister" : get("Area");
|
||||
var dataType = string.IsNullOrWhiteSpace(get("DataType")) ? "UInt16" : get("DataType");
|
||||
var writable = bool.TryParse(get("Writable"), out var parsedWritable) && parsedWritable;
|
||||
if (transport is not ("tcp" or "rtu") || unitId is < 1 or > 247 || address is < 0 or > 65_535 || pollInterval is < 1 or > 86_400)
|
||||
{
|
||||
throw new DomainValidationException("Transport, UnitId, Adresse oder Pollintervall ist ungültig.");
|
||||
}
|
||||
var host = get("Host");
|
||||
var alias = get("SerialPortAlias");
|
||||
if (transport == "tcp" && string.IsNullOrWhiteSpace(host)) throw new DomainValidationException("Für Modbus TCP fehlt Host.");
|
||||
if (transport == "rtu" && string.IsNullOrWhiteSpace(alias)) throw new DomainValidationException("Für Modbus RTU fehlt SerialPortAlias.");
|
||||
|
||||
var addressJson = JsonSerializer.SerializeToElement(new Dictionary<string, object?>
|
||||
{
|
||||
["transport"] = transport,
|
||||
["host"] = transport == "tcp" ? host : null,
|
||||
["port"] = transport == "tcp" ? port : null,
|
||||
["serialPortAlias"] = transport == "rtu" ? alias : null,
|
||||
["unitId"] = unitId,
|
||||
["area"] = area,
|
||||
["address"] = address,
|
||||
["dataType"] = dataType,
|
||||
["pollIntervalSeconds"] = pollInterval
|
||||
});
|
||||
var externalIdentity = transport == "tcp"
|
||||
? $"tcp:{host}:{port}:{unitId}:{area}:{address}:{dataType}"
|
||||
: $"rtu:{alias}:{unitId}:{area}:{address}:{dataType}";
|
||||
store.CreatePoint(new CreatePointRequest(
|
||||
get("Name"), PointProtocol.Modbus, PointScope.External,
|
||||
dataType, true, writable, externalIdentity, addressJson));
|
||||
imported++;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
errors.Add($"Zeile {rowIndex + 1}: {exception.Message}");
|
||||
}
|
||||
}
|
||||
return new ModbusCsvImportResult(imported, errors);
|
||||
}
|
||||
|
||||
private static int ParseInt(string value, int fallback) => string.IsNullOrWhiteSpace(value) ? fallback : int.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
private static IEnumerable<string[]> ReadRows(string csv)
|
||||
{
|
||||
var delimiter = csv.Contains(';') ? ';' : ',';
|
||||
using var reader = new StringReader(csv.Replace("\r\n", "\n", StringComparison.Ordinal));
|
||||
string? line;
|
||||
while ((line = reader.ReadLine()) is not null)
|
||||
{
|
||||
var values = new List<string>();
|
||||
var cell = new StringBuilder();
|
||||
var quoted = false;
|
||||
for (var index = 0; index < line.Length; index++)
|
||||
{
|
||||
var current = line[index];
|
||||
if (current == '"' && index + 1 < line.Length && line[index + 1] == '"' && quoted)
|
||||
{
|
||||
cell.Append('"'); index++; continue;
|
||||
}
|
||||
if (current == '"') { quoted = !quoted; continue; }
|
||||
if (current == delimiter && !quoted) { values.Add(cell.ToString()); cell.Clear(); continue; }
|
||||
cell.Append(current);
|
||||
}
|
||||
if (quoted) throw new DomainValidationException("Die CSV enthält ein nicht geschlossenes Anführungszeichen.");
|
||||
values.Add(cell.ToString());
|
||||
yield return values.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO.Ports;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using NModbus;
|
||||
using NModbus.Serial;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record ModbusRuntimeIssue(Guid Id, string Error, DateTimeOffset OccurredAtUtc);
|
||||
|
||||
#pragma warning disable CA1848 // This adapter logs rare field-bus failures; source-generated log methods add no operational value here.
|
||||
|
||||
/// <summary>
|
||||
/// Native Modbus TCP server/client and RTU client. TCP listeners deliberately
|
||||
/// parse MBAP frames here instead of accepting the library's default listener:
|
||||
/// this is what makes a per-instance IP allow-list enforceable before a Modbus
|
||||
/// request is ever processed.
|
||||
/// </summary>
|
||||
public sealed class ModbusProtocolService : BackgroundService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly WriteJournal _journal;
|
||||
private readonly ILogger<ModbusProtocolService> _logger;
|
||||
private readonly ConcurrentDictionary<Guid, TcpServerRuntime> _servers = new();
|
||||
private readonly ConcurrentDictionary<Guid, ModbusRuntimeIssue> _serverErrors = new();
|
||||
private readonly ConcurrentDictionary<Guid, ModbusRuntimeIssue> _pointErrors = new();
|
||||
private readonly ConcurrentDictionary<Guid, DateTimeOffset> _nextPollAt = new();
|
||||
private readonly ModbusFactory _factory = new();
|
||||
private CancellationToken _serviceStopping;
|
||||
private int _disposed;
|
||||
|
||||
public ModbusProtocolService(GatewayStore store, WriteJournal journal, ILogger<ModbusProtocolService> logger)
|
||||
{
|
||||
_store = store;
|
||||
_journal = journal;
|
||||
_logger = logger;
|
||||
_store.PointValueUpdated += OnPointValueUpdated;
|
||||
}
|
||||
|
||||
public bool IsTcpListening(ModbusServerConfiguration configuration) =>
|
||||
_servers.TryGetValue(configuration.Id, out var runtime) && runtime.ConfigurationEquals(configuration);
|
||||
public ModbusRuntimeIssue? GetTcpError(Guid id) => _serverErrors.GetValueOrDefault(id);
|
||||
public ModbusRuntimeIssue[] GetPointErrors() => _pointErrors.Values.ToArray();
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_store.PointValueUpdated -= OnPointValueUpdated;
|
||||
foreach (var server in _servers.Values)
|
||||
{
|
||||
server.Dispose();
|
||||
}
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_serviceStopping = stoppingToken;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ReconcileServersAsync(stoppingToken);
|
||||
await PollExternalPointsAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(exception, "Modbus scheduling cycle failed.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(250), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Task ReconcileServersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var configured = _store.GetGatewayConfiguration().ModbusServers;
|
||||
var desired = configured.ToDictionary(server => server.Id);
|
||||
foreach (var id in _serverErrors.Keys)
|
||||
if (!desired.ContainsKey(id)) _serverErrors.TryRemove(id, out _);
|
||||
foreach (var (id, existing) in _servers)
|
||||
{
|
||||
if (!desired.TryGetValue(id, out var next) || !existing.ConfigurationEquals(next))
|
||||
{
|
||||
if (_servers.TryRemove(id, out var removed))
|
||||
{
|
||||
removed.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var server in configured)
|
||||
{
|
||||
if (_servers.ContainsKey(server.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var runtime = new TcpServerRuntime(server, _store, _logger);
|
||||
try
|
||||
{
|
||||
runtime.Start(cancellationToken);
|
||||
if (!_servers.TryAdd(server.Id, runtime)) runtime.Dispose();
|
||||
_serverErrors.TryRemove(server.Id, out _);
|
||||
}
|
||||
catch (SocketException exception)
|
||||
{
|
||||
runtime.Dispose();
|
||||
_serverErrors[server.Id] = new(server.Id, exception.Message, DateTimeOffset.UtcNow);
|
||||
_logger.LogDebug(exception, "Modbus server {Server} could not bind.", server.Name);
|
||||
}
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task PollExternalPointsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var points = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Modbus && point.Scope == PointScope.External && point.Readable).ToArray();
|
||||
foreach (var id in _pointErrors.Keys.Except(points.Select(point => point.Id)))
|
||||
_pointErrors.TryRemove(id, out _);
|
||||
foreach (var point in points)
|
||||
{
|
||||
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId is not null)
|
||||
{
|
||||
_pointErrors[point.Id] = new(point.Id, "Ungültige Modbus-Adresse.", now);
|
||||
continue;
|
||||
}
|
||||
if (_nextPollAt.TryGetValue(point.Id, out var next) && next > now)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
_nextPollAt[point.Id] = now.AddSeconds(address.PollIntervalSeconds);
|
||||
try
|
||||
{
|
||||
var value = address.Transport == "rtu"
|
||||
? await ReadRtuAsync(point, address, cancellationToken)
|
||||
: await ReadTcpAsync(point, address, cancellationToken);
|
||||
var identity = GetEndpointIdentity(point);
|
||||
if (!_journal.ConsumeReflection(identity, value.GetRawText()))
|
||||
{
|
||||
_store.SetPointValue(point.Id, value, PointProtocol.Modbus, DateTimeOffset.UtcNow, expectedDefinition: point);
|
||||
}
|
||||
_pointErrors.TryRemove(point.Id, out _);
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_pointErrors[point.Id] = new(point.Id, exception.Message, DateTimeOffset.UtcNow);
|
||||
_logger.LogDebug(exception, "Modbus read failed for {Point}.", point.DisplayName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonElement> ReadTcpAsync(GatewayPoint point, ModbusAddress address, CancellationToken cancellationToken)
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(address.Host!, address.Port, cancellationToken);
|
||||
var master = _factory.CreateMaster(client);
|
||||
try
|
||||
{
|
||||
return await ReadValueAsync(master, address);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (master is IDisposable disposable)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonElement> ReadRtuAsync(GatewayPoint point, ModbusAddress address, CancellationToken cancellationToken)
|
||||
{
|
||||
var serial = ResolveSerialPort(address.SerialPortAlias!);
|
||||
using var port = CreateSerialPort(serial);
|
||||
port.Open();
|
||||
var master = _factory.CreateRtuMaster(port);
|
||||
try
|
||||
{
|
||||
return await ReadValueAsync(master, address);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (master is IDisposable disposable)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<JsonElement> ReadValueAsync(IModbusMaster master, ModbusAddress address)
|
||||
{
|
||||
if (address.Area == ModbusArea.Coil)
|
||||
{
|
||||
return ModbusAddressing.Encode([], (await master.ReadCoilsAsync(address.UnitId, address.Address, 1))[0], address);
|
||||
}
|
||||
if (address.Area == ModbusArea.DiscreteInput)
|
||||
{
|
||||
return ModbusAddressing.Encode([], (await master.ReadInputsAsync(address.UnitId, address.Address, 1))[0], address);
|
||||
}
|
||||
var registers = address.Area == ModbusArea.InputRegister
|
||||
? await master.ReadInputRegistersAsync(address.UnitId, address.Address, (ushort)address.RegisterCount)
|
||||
: await master.ReadHoldingRegistersAsync(address.UnitId, address.Address, (ushort)address.RegisterCount);
|
||||
return ModbusAddressing.Encode(registers, null, address);
|
||||
}
|
||||
|
||||
private void OnPointValueUpdated(object? sender, PointValue update)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(update.Status) && !update.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) && !update.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) return;
|
||||
var point = _store.ListPoints().SingleOrDefault(candidate => candidate.Id == update.PointId);
|
||||
if (point is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (point.Protocol == PointProtocol.Modbus && ModbusAddressing.TryParse(point, out var address))
|
||||
{
|
||||
if (address.ServerId is not null && _servers.TryGetValue(address.ServerId.Value, out var server))
|
||||
{
|
||||
server.WriteGatewayValue(point, address, update.Value);
|
||||
}
|
||||
else if (point.Scope == PointScope.External && point.Writable && !(update.SourceProtocol == PointProtocol.Modbus && update.OriginPointId == point.Id))
|
||||
{
|
||||
_ = WriteExternalSafelyAsync(point, address, update.Value, _serviceStopping);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WriteExternalSafelyAsync(GatewayPoint point, ModbusAddress address, JsonElement value, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var identity = GetEndpointIdentity(point);
|
||||
var valueText = value.GetRawText();
|
||||
_journal.Register(identity, valueText, TimeSpan.FromSeconds(15));
|
||||
if (address.Transport == "rtu")
|
||||
{
|
||||
var serial = ResolveSerialPort(address.SerialPortAlias!);
|
||||
using var port = CreateSerialPort(serial);
|
||||
port.Open();
|
||||
var master = _factory.CreateRtuMaster(port);
|
||||
try { if (_store.IsPointDefinitionCurrent(point)) await WriteValueAsync(master, address, value); }
|
||||
finally { if (master is IDisposable disposable) disposable.Dispose(); }
|
||||
}
|
||||
else
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(address.Host!, address.Port, cancellationToken);
|
||||
var master = _factory.CreateMaster(client);
|
||||
try { if (_store.IsPointDefinitionCurrent(point)) await WriteValueAsync(master, address, value); }
|
||||
finally { if (master is IDisposable disposable) disposable.Dispose(); }
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(exception, "Modbus write failed for {Point}.", point.DisplayName);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteValueAsync(IModbusMaster master, ModbusAddress address, JsonElement value)
|
||||
{
|
||||
var encoded = ModbusAddressing.Decode(value, address);
|
||||
if (address.Area == ModbusArea.Coil)
|
||||
{
|
||||
await master.WriteSingleCoilAsync(address.UnitId, address.Address, encoded.Coil ?? false);
|
||||
return;
|
||||
}
|
||||
if (address.Area != ModbusArea.HoldingRegister)
|
||||
{
|
||||
throw new DomainValidationException("Auf Input-Register und Discrete Inputs kann nicht geschrieben werden.");
|
||||
}
|
||||
if (encoded.Registers.Length == 1)
|
||||
{
|
||||
await master.WriteSingleRegisterAsync(address.UnitId, address.Address, encoded.Registers[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
await master.WriteMultipleRegistersAsync(address.UnitId, address.Address, encoded.Registers);
|
||||
}
|
||||
}
|
||||
|
||||
private SerialPortConfiguration ResolveSerialPort(string alias) =>
|
||||
(_store.GetGatewayConfiguration().SerialPorts ?? []).SingleOrDefault(port => string.Equals(port.Alias, alias, StringComparison.OrdinalIgnoreCase))
|
||||
?? throw new DomainValidationException($"Der serielle Port-Alias '{alias}' ist nicht konfiguriert.");
|
||||
|
||||
private static SerialPort CreateSerialPort(SerialPortConfiguration configuration) => new(
|
||||
configuration.DevicePath,
|
||||
configuration.BaudRate,
|
||||
Enum.Parse<Parity>(configuration.Parity, true),
|
||||
configuration.DataBits,
|
||||
Enum.Parse<StopBits>(configuration.StopBits == 2 ? "Two" : "One", true))
|
||||
{
|
||||
ReadTimeout = 2_000,
|
||||
WriteTimeout = 2_000
|
||||
};
|
||||
|
||||
private static string GetEndpointIdentity(GatewayPoint point) => $"modbus:{point.ExternalIdentity ?? point.Id.ToString()}";
|
||||
|
||||
private sealed class TcpServerRuntime : IDisposable
|
||||
{
|
||||
private readonly ModbusServerConfiguration _configuration;
|
||||
private readonly GatewayStore _store;
|
||||
private readonly ILogger _logger;
|
||||
private readonly TcpListener _listener;
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private int _disposed;
|
||||
private readonly object _gate = new();
|
||||
private readonly ushort[] _holding;
|
||||
private readonly ushort[] _input;
|
||||
private readonly bool[] _coils;
|
||||
private readonly bool[] _discretes;
|
||||
private Task? _acceptTask;
|
||||
|
||||
public TcpServerRuntime(ModbusServerConfiguration configuration, GatewayStore store, ILogger logger)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_store = store;
|
||||
_logger = logger;
|
||||
_listener = new TcpListener(IPAddress.Parse(configuration.BindAddress), configuration.Port);
|
||||
_holding = new ushort[configuration.HoldingRegisterCount];
|
||||
_input = new ushort[configuration.HoldingRegisterCount];
|
||||
_coils = new bool[configuration.HoldingRegisterCount];
|
||||
_discretes = new bool[configuration.HoldingRegisterCount];
|
||||
}
|
||||
|
||||
public bool ConfigurationEquals(ModbusServerConfiguration other) =>
|
||||
_configuration.Id == other.Id &&
|
||||
string.Equals(_configuration.Name, other.Name, StringComparison.Ordinal) &&
|
||||
string.Equals(_configuration.BindAddress, other.BindAddress, StringComparison.Ordinal) &&
|
||||
_configuration.Port == other.Port &&
|
||||
_configuration.UnitId == other.UnitId &&
|
||||
_configuration.FirstHoldingRegister == other.FirstHoldingRegister &&
|
||||
_configuration.HoldingRegisterCount == other.HoldingRegisterCount &&
|
||||
_configuration.AllowedClientIps.SequenceEqual(other.AllowedClientIps, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void Start(CancellationToken applicationStopping)
|
||||
{
|
||||
_listener.Start();
|
||||
_acceptTask = Task.Run(() => AcceptLoopAsync(_stopping.Token), applicationStopping);
|
||||
}
|
||||
|
||||
public void WriteGatewayValue(GatewayPoint point, ModbusAddress address, JsonElement value)
|
||||
{
|
||||
if (address.Address < _configuration.FirstHoldingRegister || address.Address - _configuration.FirstHoldingRegister + address.RegisterCount > _holding.Length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var offset = address.Address - _configuration.FirstHoldingRegister;
|
||||
var encoded = ModbusAddressing.Decode(value, address);
|
||||
lock (_gate)
|
||||
{
|
||||
switch (address.Area)
|
||||
{
|
||||
case ModbusArea.Coil: _coils[offset] = encoded.Coil ?? false; break;
|
||||
case ModbusArea.DiscreteInput: _discretes[offset] = encoded.Coil ?? false; break;
|
||||
case ModbusArea.InputRegister: Array.Copy(encoded.Registers, 0, _input, offset, encoded.Registers.Length); break;
|
||||
default: Array.Copy(encoded.Registers, 0, _holding, offset, encoded.Registers.Length); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(cancellationToken);
|
||||
_ = Task.Run(() => HandleClientAsync(client, cancellationToken), cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogWarning(exception, "Modbus TCP listener {Name} stopped unexpectedly.", _configuration.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken)
|
||||
{
|
||||
using (client)
|
||||
{
|
||||
var remote = (client.Client.RemoteEndPoint as IPEndPoint)?.Address;
|
||||
if (remote is null || !IsAllowed(remote))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var stream = client.GetStream();
|
||||
var header = new byte[7];
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await stream.ReadExactlyAsync(header, cancellationToken);
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var length = (header[4] << 8) | header[5];
|
||||
if (header[2] != 0 || header[3] != 0 || length is < 2 or > 254)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var pdu = new byte[length - 1];
|
||||
try
|
||||
{
|
||||
await stream.ReadExactlyAsync(pdu, cancellationToken);
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var response = HandleRequest(header[6], pdu);
|
||||
var responseHeader = new byte[7];
|
||||
responseHeader[0] = header[0]; responseHeader[1] = header[1];
|
||||
responseHeader[4] = (byte)(((response.Length + 1) >> 8) & 0xff);
|
||||
responseHeader[5] = (byte)((response.Length + 1) & 0xff);
|
||||
responseHeader[6] = header[6];
|
||||
await stream.WriteAsync(responseHeader, cancellationToken);
|
||||
await stream.WriteAsync(response, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] HandleRequest(byte unitId, byte[] request)
|
||||
{
|
||||
if (unitId != _configuration.UnitId || request.Length < 5)
|
||||
{
|
||||
return ExceptionResponse(request.FirstOrDefault(), 2);
|
||||
}
|
||||
var function = request[0];
|
||||
var address = (ushort)((request[1] << 8) | request[2]);
|
||||
var quantity = (ushort)((request[3] << 8) | request[4]);
|
||||
return function switch
|
||||
{
|
||||
1 or 2 => ReadBits(function, address, quantity),
|
||||
3 or 4 => ReadRegisters(function, address, quantity),
|
||||
5 => WriteSingleCoil(address, quantity == 0xff00),
|
||||
6 => WriteSingleRegister(address, quantity),
|
||||
15 => WriteMultipleCoils(address, quantity, request),
|
||||
16 => WriteMultipleRegisters(address, quantity, request),
|
||||
_ => ExceptionResponse(function, 1)
|
||||
};
|
||||
}
|
||||
|
||||
private byte[] ReadBits(byte function, ushort address, ushort quantity)
|
||||
{
|
||||
if (!IsInRange(address, quantity) || quantity is < 1 or > 2_000) return ExceptionResponse(function, 2);
|
||||
var data = new byte[(quantity + 7) / 8];
|
||||
var offset = address - _configuration.FirstHoldingRegister;
|
||||
lock (_gate)
|
||||
{
|
||||
var source = function == 1 ? _coils : _discretes;
|
||||
for (var index = 0; index < quantity; index++) if (source[offset + index]) data[index / 8] |= (byte)(1 << (index % 8));
|
||||
}
|
||||
return [function, (byte)data.Length, .. data];
|
||||
}
|
||||
|
||||
private byte[] ReadRegisters(byte function, ushort address, ushort quantity)
|
||||
{
|
||||
if (!IsInRange(address, quantity) || quantity is < 1 or > 125) return ExceptionResponse(function, 2);
|
||||
var data = new byte[quantity * 2];
|
||||
var offset = address - _configuration.FirstHoldingRegister;
|
||||
lock (_gate)
|
||||
{
|
||||
var source = function == 3 ? _holding : _input;
|
||||
for (var index = 0; index < quantity; index++)
|
||||
{
|
||||
data[index * 2] = (byte)(source[offset + index] >> 8);
|
||||
data[index * 2 + 1] = (byte)source[offset + index];
|
||||
}
|
||||
}
|
||||
return [function, (byte)data.Length, .. data];
|
||||
}
|
||||
|
||||
private byte[] WriteSingleCoil(ushort address, bool value)
|
||||
{
|
||||
if (!IsInRange(address, 1)) return ExceptionResponse(5, 2);
|
||||
lock (_gate) _coils[address - _configuration.FirstHoldingRegister] = value;
|
||||
PropagateWrites(ModbusArea.Coil, address, 1);
|
||||
return [5, (byte)(address >> 8), (byte)address, value ? (byte)0xff : (byte)0, 0];
|
||||
}
|
||||
|
||||
private byte[] WriteSingleRegister(ushort address, ushort value)
|
||||
{
|
||||
if (!IsInRange(address, 1)) return ExceptionResponse(6, 2);
|
||||
lock (_gate) _holding[address - _configuration.FirstHoldingRegister] = value;
|
||||
PropagateWrites(ModbusArea.HoldingRegister, address, 1);
|
||||
return [6, (byte)(address >> 8), (byte)address, (byte)(value >> 8), (byte)value];
|
||||
}
|
||||
|
||||
private byte[] WriteMultipleCoils(ushort address, ushort quantity, byte[] request)
|
||||
{
|
||||
if (!IsInRange(address, quantity) || quantity is < 1 or > 1_968 || request.Length < 6 || request[5] != (quantity + 7) / 8 || request.Length != 6 + request[5]) return ExceptionResponse(15, 3);
|
||||
lock (_gate) for (var index = 0; index < quantity; index++) _coils[address - _configuration.FirstHoldingRegister + index] = (request[6 + index / 8] & (1 << (index % 8))) != 0;
|
||||
PropagateWrites(ModbusArea.Coil, address, quantity);
|
||||
return [15, (byte)(address >> 8), (byte)address, (byte)(quantity >> 8), (byte)quantity];
|
||||
}
|
||||
|
||||
private byte[] WriteMultipleRegisters(ushort address, ushort quantity, byte[] request)
|
||||
{
|
||||
if (!IsInRange(address, quantity) || quantity is < 1 or > 123 || request.Length < 6 || request[5] != quantity * 2 || request.Length != 6 + request[5]) return ExceptionResponse(16, 3);
|
||||
lock (_gate) for (var index = 0; index < quantity; index++) _holding[address - _configuration.FirstHoldingRegister + index] = (ushort)((request[6 + index * 2] << 8) | request[7 + index * 2]);
|
||||
PropagateWrites(ModbusArea.HoldingRegister, address, quantity);
|
||||
return [16, (byte)(address >> 8), (byte)address, (byte)(quantity >> 8), (byte)quantity];
|
||||
}
|
||||
|
||||
private void PropagateWrites(ModbusArea area, ushort start, ushort count)
|
||||
{
|
||||
foreach (var point in _store.ListPoints().Where(point => point.Protocol == PointProtocol.Modbus && point.Writable))
|
||||
{
|
||||
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId != _configuration.Id || address.Area != area || address.Address < start || address.Address + address.RegisterCount > start + count)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var offset = address.Address - _configuration.FirstHoldingRegister;
|
||||
JsonElement value;
|
||||
lock (_gate)
|
||||
{
|
||||
value = area == ModbusArea.Coil
|
||||
? ModbusAddressing.Encode([], _coils[offset], address)
|
||||
: ModbusAddressing.Encode(_holding[offset..(offset + address.RegisterCount)], null, address);
|
||||
}
|
||||
_store.SetPointValue(point.Id, value, PointProtocol.Modbus, DateTimeOffset.UtcNow, expectedDefinition: point);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_logger.LogWarning(exception, "Could not apply Modbus server write to {Point}.", point.DisplayName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsAllowed(IPAddress remote) => _configuration.AllowedClientIps.Count == 0 || _configuration.AllowedClientIps.Any(value => IPAddress.TryParse(value, out var allowed) && allowed.Equals(remote));
|
||||
|
||||
private bool IsInRange(ushort address, ushort quantity) => address >= _configuration.FirstHoldingRegister && quantity > 0 && (uint)(address - _configuration.FirstHoldingRegister) + quantity <= _holding.Length;
|
||||
|
||||
private static byte[] ExceptionResponse(byte function, byte code) => [(byte)(function | 0x80), code];
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_stopping.Cancel();
|
||||
_listener.Stop();
|
||||
_stopping.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning restore CA1848
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
@@ -10,14 +11,16 @@ namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// One outbound MQTT client for the appliance. It intentionally does not host an MQTT broker.
|
||||
/// Mappings are exact topics only; wildcard subscriptions are deliberately not created.
|
||||
/// Mapping and external point subscriptions use exact topics.
|
||||
/// </summary>
|
||||
public sealed class MqttClientService : BackgroundService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly MqttClientFactory _factory = new();
|
||||
private readonly SemaphoreSlim _publishGate = new(1, 1);
|
||||
private readonly ConcurrentDictionary<Guid, byte> _initialPublications = new();
|
||||
private readonly object _clientLock = new();
|
||||
private Dictionary<string, GatewayPoint[]> _externalPoints = new(StringComparer.Ordinal);
|
||||
private IMqttClient? _client;
|
||||
private MqttClientStatus _status = new(false, false, null, null, null, null, null);
|
||||
private int _reconfigureRequested = 1;
|
||||
@@ -34,6 +37,11 @@ public sealed class MqttClientService : BackgroundService
|
||||
/// <summary>Applies changed broker or subscription configuration without a process restart.</summary>
|
||||
public void RequestReconfigure() => Interlocked.Exchange(ref _reconfigureRequested, 1);
|
||||
|
||||
public void QueueInitialPublications(IReadOnlyList<Guid> mappingIds)
|
||||
{
|
||||
foreach (var id in mappingIds) _initialPublications.TryAdd(id, 0);
|
||||
}
|
||||
|
||||
public async Task<int> PublishPointValueAsync(PointValue pointValue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var client = GetConnectedClient();
|
||||
@@ -42,25 +50,20 @@ public sealed class MqttClientService : BackgroundService
|
||||
return 0;
|
||||
}
|
||||
|
||||
var mappings = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)
|
||||
.ToArray();
|
||||
var published = 0;
|
||||
await _publishGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var mappings = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional);
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
var payload = CreateOutboundPayload(mapping, pointValue);
|
||||
var message = _factory.CreateApplicationMessageBuilder()
|
||||
.WithTopic(GatewayStore.GetMqttTopic(mapping))
|
||||
.WithPayload(payload)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService))
|
||||
.WithRetainFlag(mapping.Retain)
|
||||
.Build();
|
||||
await client.PublishAsync(message, cancellationToken);
|
||||
published++;
|
||||
UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
try
|
||||
{
|
||||
await PublishMappedValueAsync(client, mapping, pointValue, cancellationToken);
|
||||
published++;
|
||||
}
|
||||
catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); }
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
@@ -84,20 +87,33 @@ public sealed class MqttClientService : BackgroundService
|
||||
try
|
||||
{
|
||||
var (configuration, password) = _store.GetMqttConnectionConfiguration();
|
||||
if (configuration.Enabled)
|
||||
{
|
||||
var sources = _store.ListMqttExternalPoints()
|
||||
.Where(point => point.Readable)
|
||||
.GroupBy(point => MqttExternalTopics.Address(point)!, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal);
|
||||
var previous = Interlocked.Exchange(ref _externalPoints, sources);
|
||||
if (sources.Count != previous.Count || sources.Keys.Any(topic => !previous.ContainsKey(topic)))
|
||||
RequestReconfigure();
|
||||
}
|
||||
if (!configuration.Enabled)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
SetStatus(new MqttClientStatus(false, false, null, null, null, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
|
||||
UpdateStatus(status => status with { Enabled = false, Connected = false, Endpoint = null, ConnectedAtUtc = null, LastError = null });
|
||||
}
|
||||
else if (Interlocked.Exchange(ref _reconfigureRequested, 0) == 1 || GetConnectedClient() is null)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
UpdateStatus(status => status with { Enabled = true, Connected = false, Endpoint = $"{configuration.Host}:{configuration.Port}", ConnectedAtUtc = null });
|
||||
await ConnectAsync(configuration, password, stoppingToken);
|
||||
}
|
||||
if (configuration.Enabled && !_initialPublications.IsEmpty && GetConnectedClient() is not null)
|
||||
await PublishInitialValuesAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false, LastError = exception.Message });
|
||||
UpdateStatus(status => status with { Connected = GetConnectedClient() is not null, LastError = exception.Message });
|
||||
}
|
||||
|
||||
try
|
||||
@@ -113,6 +129,46 @@ public sealed class MqttClientService : BackgroundService
|
||||
await DisconnectCurrentAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
private async Task PublishInitialValuesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _publishGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (GetConnectedClient() is not { } client) return;
|
||||
var mappings = _store.ListMqttMappings().Where(mapping => mapping.Direction == MqttDirection.Publish)
|
||||
.ToDictionary(mapping => mapping.Id);
|
||||
var values = _store.ListPointValues().ToDictionary(value => value.PointId);
|
||||
foreach (var id in _initialPublications.Keys)
|
||||
{
|
||||
if (mappings.TryGetValue(id, out var mapping) && values.TryGetValue(mapping.PointId, out var value) &&
|
||||
value.SourceProtocol != PointProtocol.Mqtt && IsGoodValue(value))
|
||||
{
|
||||
try
|
||||
{
|
||||
await PublishMappedValueAsync(client, mapping, value, cancellationToken);
|
||||
continue;
|
||||
}
|
||||
catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); }
|
||||
}
|
||||
_initialPublications.TryRemove(id, out _);
|
||||
}
|
||||
}
|
||||
finally { _publishGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task PublishMappedValueAsync(IMqttClient client, MqttMapping mapping, PointValue pointValue, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = _factory.CreateApplicationMessageBuilder()
|
||||
.WithTopic(GatewayStore.GetMqttTopic(mapping))
|
||||
.WithPayload(CreateOutboundPayload(mapping, pointValue))
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService))
|
||||
.WithRetainFlag(mapping.Retain)
|
||||
.Build();
|
||||
await client.PublishAsync(message, cancellationToken);
|
||||
_initialPublications.TryRemove(mapping.Id, out _);
|
||||
UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_store.PointValueUpdated -= OnPointValueUpdated;
|
||||
@@ -120,10 +176,10 @@ public sealed class MqttClientService : BackgroundService
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
|
||||
internal static MqttClientOptions BuildClientOptions(MqttClientFactory factory, MqttConfiguration configuration, string? password, string clientId)
|
||||
{
|
||||
var builder = _factory.CreateClientOptionsBuilder()
|
||||
.WithClientId(configuration.ClientId)
|
||||
var builder = factory.CreateClientOptionsBuilder()
|
||||
.WithClientId(clientId)
|
||||
.WithTcpServer(configuration.Host, configuration.Port)
|
||||
// MQTT 3.1.1 gives the widest compatibility with existing field brokers.
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311);
|
||||
@@ -145,25 +201,39 @@ public sealed class MqttClientService : BackgroundService
|
||||
});
|
||||
}
|
||||
|
||||
return builder.Build();
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
|
||||
{
|
||||
var client = _factory.CreateMqttClient();
|
||||
client.ApplicationMessageReceivedAsync += HandleReceivedMessageAsync;
|
||||
client.DisconnectedAsync += HandleDisconnectedAsync;
|
||||
await client.ConnectAsync(builder.Build(), cancellationToken);
|
||||
lock (_clientLock)
|
||||
{
|
||||
_client = client;
|
||||
}
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
SetStatus(new MqttClientStatus(true, true, $"{configuration.Host}:{configuration.Port}", null, now, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
|
||||
await SubscribeMappedTopicsAsync(client, cancellationToken);
|
||||
client.DisconnectedAsync += arguments => HandleDisconnectedAsync(client, arguments);
|
||||
try
|
||||
{
|
||||
var result = await client.ConnectAsync(BuildClientOptions(_factory, configuration, password, configuration.ClientId), cancellationToken);
|
||||
if (!client.IsConnected) throw new DomainValidationException($"Broker-Verbindung abgewiesen ({result.ResultCode}).");
|
||||
var subscriptionError = await SubscribeMappedTopicsAsync(client, cancellationToken);
|
||||
UpdateStatus(status => status with { Connected = client.IsConnected, LastError = subscriptionError, ConnectedAtUtc = DateTimeOffset.UtcNow });
|
||||
}
|
||||
catch
|
||||
{
|
||||
await DisconnectCurrentAsync(cancellationToken);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken)
|
||||
private async Task<string?> SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken)
|
||||
{
|
||||
var subscriptions = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
|
||||
.GroupBy(GatewayStore.GetMqttTopic, StringComparer.Ordinal)
|
||||
.Select(mapping => (Topic: GatewayStore.GetMqttTopic(mapping), mapping.QualityOfService))
|
||||
.Concat(Volatile.Read(ref _externalPoints).Keys.Select(topic => (Topic: topic, QualityOfService: MqttQualityOfService.AtLeastOnce)))
|
||||
.GroupBy(subscription => subscription.Topic, StringComparer.Ordinal)
|
||||
.Select(group => new
|
||||
{
|
||||
Topic = group.Key,
|
||||
@@ -172,18 +242,21 @@ public sealed class MqttClientService : BackgroundService
|
||||
.ToArray();
|
||||
if (subscriptions.Length == 0)
|
||||
{
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
var builder = _factory.CreateSubscribeOptionsBuilder();
|
||||
foreach (var subscription in subscriptions)
|
||||
var rejected = new List<string>();
|
||||
foreach (var batch in subscriptions.Chunk(100))
|
||||
{
|
||||
builder.WithTopicFilter(filter => filter
|
||||
.WithTopic(subscription.Topic)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService)));
|
||||
var builder = _factory.CreateSubscribeOptionsBuilder();
|
||||
foreach (var subscription in batch)
|
||||
builder.WithTopicFilter(filter => filter.WithTopic(subscription.Topic)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService)));
|
||||
var result = await client.SubscribeAsync(builder.Build(), cancellationToken);
|
||||
rejected.AddRange(result.Items.Where(item => (int)item.ResultCode >= 128).Select(item => item.TopicFilter.Topic));
|
||||
}
|
||||
|
||||
await client.SubscribeAsync(builder.Build(), cancellationToken);
|
||||
return rejected.Count == 0 ? null :
|
||||
$"Broker hat {rejected.Count} Abonnement(s) abgelehnt · {string.Join(", ", rejected.Take(3))}";
|
||||
}
|
||||
|
||||
private async Task HandleReceivedMessageAsync(MqttApplicationMessageReceivedEventArgs arguments)
|
||||
@@ -191,27 +264,57 @@ public sealed class MqttClientService : BackgroundService
|
||||
try
|
||||
{
|
||||
var topic = arguments.ApplicationMessage.Topic;
|
||||
var payload = arguments.ApplicationMessage.Payload;
|
||||
var receivedAt = DateTimeOffset.UtcNow;
|
||||
var stored = false;
|
||||
if (Volatile.Read(ref _externalPoints).TryGetValue(topic, out var sources))
|
||||
{
|
||||
var sample = MqttExternalTopics.Read(topic, payload, inferDigital: false);
|
||||
foreach (var source in sources)
|
||||
{
|
||||
if (sample.Value is not { } value || MqttExternalTopics.ConvertToPoint(value, source.ValueType) is not { } converted)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Empfang · {topic} · Wert passt nicht zum Typ '{source.ValueType}'." });
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
_store.SetPointValue(source.Id, converted, PointProtocol.Mqtt, receivedAt, "Good", expectedDefinition: source);
|
||||
stored = true;
|
||||
}
|
||||
catch (DomainValidationException exception)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Empfang · {topic} · {exception.Message}" });
|
||||
}
|
||||
}
|
||||
}
|
||||
var mappings = _store.ListMqttMappings()
|
||||
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
|
||||
.Where(mapping => string.Equals(GatewayStore.GetMqttTopic(mapping), topic, StringComparison.Ordinal))
|
||||
.ToArray();
|
||||
if (mappings.Length == 0)
|
||||
{
|
||||
if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt });
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = arguments.ApplicationMessage.Payload;
|
||||
var payloadBytes = new byte[checked((int)payload.Length)];
|
||||
payload.CopyTo(payloadBytes);
|
||||
var rawPayload = Encoding.UTF8.GetString(payloadBytes);
|
||||
using var document = ParsePayload(rawPayload);
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
var value = ExtractInboundValue(document.RootElement, mapping);
|
||||
_store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, DateTimeOffset.UtcNow);
|
||||
try
|
||||
{
|
||||
var point = _store.GetMqttPoint(mapping.PointId);
|
||||
if (point is not { Writable: true }) continue;
|
||||
var value = ExtractInboundValue(document.RootElement, mapping, point);
|
||||
_store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, receivedAt, expectedDefinition: point);
|
||||
stored = true;
|
||||
}
|
||||
catch (DomainValidationException exception) { RecordPayloadError("Empfang", mapping, exception); }
|
||||
}
|
||||
|
||||
UpdateStatus(status => status with { LastReceivedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt });
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
@@ -221,11 +324,11 @@ public sealed class MqttClientService : BackgroundService
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs arguments)
|
||||
private Task HandleDisconnectedAsync(IMqttClient client, MqttClientDisconnectedEventArgs arguments)
|
||||
{
|
||||
lock (_clientLock)
|
||||
{
|
||||
_client = null;
|
||||
if (!ReferenceEquals(client, _client)) return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (arguments.Exception is not null)
|
||||
@@ -275,8 +378,9 @@ public sealed class MqttClientService : BackgroundService
|
||||
|
||||
private void OnPointValueUpdated(object? sender, PointValue pointValue)
|
||||
{
|
||||
if (!IsGoodValue(pointValue)) return;
|
||||
// MQTT-originated values must not be reflected to the same broker again.
|
||||
if (pointValue.SourceProtocol == PointProtocol.Mqtt || !GetStatus().Connected)
|
||||
if ((pointValue.SourceProtocol == PointProtocol.Mqtt && pointValue.OriginPointId == pointValue.PointId) || !GetStatus().Connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -284,6 +388,9 @@ public sealed class MqttClientService : BackgroundService
|
||||
_ = PublishPointValueSafelyAsync(pointValue);
|
||||
}
|
||||
|
||||
private static bool IsGoodValue(PointValue value) => string.IsNullOrWhiteSpace(value.Status) ||
|
||||
value.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) || value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private async Task PublishPointValueSafelyAsync(PointValue pointValue)
|
||||
{
|
||||
try
|
||||
@@ -299,7 +406,7 @@ public sealed class MqttClientService : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument ParsePayload(string rawPayload)
|
||||
internal static JsonDocument ParsePayload(string rawPayload)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -311,7 +418,7 @@ public sealed class MqttClientService : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping)
|
||||
internal static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping, GatewayPoint point)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.Json && !string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
{
|
||||
@@ -323,14 +430,30 @@ public sealed class MqttClientService : BackgroundService
|
||||
return property.Clone();
|
||||
}
|
||||
|
||||
return payload.Clone();
|
||||
if (mapping.Format == MqttMappingFormat.Json) return payload.Clone();
|
||||
if (GatewayStore.IsBooleanMqttPoint(point))
|
||||
{
|
||||
if (payload.ValueKind is JsonValueKind.True or JsonValueKind.False) return payload.Clone();
|
||||
if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var digital) && digital is 0 or 1)
|
||||
return JsonSerializer.SerializeToElement(digital == 1);
|
||||
throw new DomainValidationException("Der digitale Datenpunkt erwartet 0 oder 1.");
|
||||
}
|
||||
if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var analog) && double.IsFinite(analog))
|
||||
return payload.Clone();
|
||||
throw new DomainValidationException("Der Datenpunkt erwartet eine endliche Zahl.");
|
||||
}
|
||||
|
||||
private static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
|
||||
internal static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.SeMonitoring)
|
||||
if (mapping.Format is MqttMappingFormat.SeMonitoring or MqttMappingFormat.SingleTopic)
|
||||
{
|
||||
return pointValue.Value.GetRawText();
|
||||
return pointValue.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => "1",
|
||||
JsonValueKind.False => "0",
|
||||
JsonValueKind.Number when pointValue.Value.TryGetDouble(out var number) && double.IsFinite(number) => pointValue.Value.GetRawText(),
|
||||
_ => throw new DomainValidationException("Das Topic erwartet eine endliche Zahl oder einen digitalen Zustand.")
|
||||
};
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
@@ -354,7 +477,19 @@ public sealed class MqttClientService : BackgroundService
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(qualityOfService))
|
||||
};
|
||||
|
||||
private void SetStatus(MqttClientStatus status) => Volatile.Write(ref _status, status);
|
||||
private void RecordPayloadError(string direction, MqttMapping mapping, DomainValidationException exception) =>
|
||||
UpdateStatus(status => status with { LastError = $"{direction} · {GatewayStore.GetMqttTopic(mapping)} · {exception.Message}" });
|
||||
|
||||
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update) => SetStatus(update(GetStatus()));
|
||||
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update)
|
||||
{
|
||||
MqttClientStatus before;
|
||||
MqttClientStatus after;
|
||||
do
|
||||
{
|
||||
before = GetStatus();
|
||||
after = update(before);
|
||||
if (after.LastError is { } error && error != before.LastError)
|
||||
after = after with { LastFailure = error, LastFailureAtUtc = DateTimeOffset.UtcNow };
|
||||
} while (!ReferenceEquals(Interlocked.CompareExchange(ref _status, after, before), before));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Buffers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
internal static class MqttExternalTopics
|
||||
{
|
||||
internal const int MaxTopicLength = 1024;
|
||||
private const int MaxPayloadLength = 16 * 1024;
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
|
||||
internal static bool IsTopic(string topic) =>
|
||||
topic.Length is > 0 and <= MaxTopicLength && topic.IndexOfAny(['+', '#', '\0']) < 0;
|
||||
|
||||
internal static string? Address(GatewayPoint point) =>
|
||||
point is { Protocol: PointProtocol.Mqtt, Scope: PointScope.External } &&
|
||||
point.Address.TryGetProperty("topic", out var topic) && topic.ValueKind == JsonValueKind.String &&
|
||||
topic.GetString() is { } address && IsTopic(address) ? address : null;
|
||||
|
||||
internal static (JsonElement? Value, string? Type, string Preview) Read(string topic, ReadOnlySequence<byte> payload, bool inferDigital = true)
|
||||
{
|
||||
if (payload.IsEmpty) return (null, null, "Leere Nachricht");
|
||||
if (payload.Length > MaxPayloadLength) return (null, null, $"Nachricht zu groß ({payload.Length} Bytes)");
|
||||
string text;
|
||||
try { text = StrictUtf8.GetString(payload.IsSingleSegment ? payload.FirstSpan : payload.ToArray()); }
|
||||
catch (DecoderFallbackException) { return (null, null, $"Binärdaten ({payload.Length} Bytes)"); }
|
||||
|
||||
var preview = text.Length > 240 ? text[..240] + "…" : text;
|
||||
using var document = MqttClientService.ParsePayload(text);
|
||||
var value = document.RootElement;
|
||||
var type = value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True or JsonValueKind.False => "Boolean",
|
||||
JsonValueKind.Number when value.TryGetDouble(out var number) && double.IsFinite(number) => "Double",
|
||||
JsonValueKind.String => "String",
|
||||
JsonValueKind.Object or JsonValueKind.Array => "Json",
|
||||
_ => null
|
||||
};
|
||||
if (inferDigital && type == "Double" && IsSeDigitalTopic(topic) && value.GetDouble() is 0 or 1)
|
||||
return (JsonSerializer.SerializeToElement(value.GetDouble() == 1), "Boolean", preview);
|
||||
return (type is null ? null : value.Clone(), type, preview);
|
||||
}
|
||||
|
||||
private static bool IsSeDigitalTopic(string topic)
|
||||
{
|
||||
var levels = topic.Split('/');
|
||||
return levels is [var projectYear, var project, var isp, "Notify" or "Alarm" or "Alarms", _] &&
|
||||
projectYear.StartsWith("Projekte", StringComparison.Ordinal) &&
|
||||
project.StartsWith('P') && isp.StartsWith("ISP", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
internal static JsonElement? ConvertToPoint(JsonElement value, string type)
|
||||
{
|
||||
if (OpcUaPointTypes.Resolve(type) == Opc.Ua.BuiltInType.Boolean)
|
||||
{
|
||||
if (value.ValueKind is JsonValueKind.True or JsonValueKind.False) return value;
|
||||
if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var state) && state is 0 or 1)
|
||||
return JsonSerializer.SerializeToElement(state == 1);
|
||||
return null;
|
||||
}
|
||||
return OpcUaPointTypes.Resolve(type) switch
|
||||
{
|
||||
>= Opc.Ua.BuiltInType.SByte and <= Opc.Ua.BuiltInType.Double when value.ValueKind == JsonValueKind.Number => value,
|
||||
Opc.Ua.BuiltInType.String when value.ValueKind == JsonValueKind.String => value,
|
||||
_ when type.Equals("Json", StringComparison.OrdinalIgnoreCase) && value.ValueKind is JsonValueKind.Object or JsonValueKind.Array => value,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record MqttTopicBrowseRequest(string? Filter);
|
||||
public sealed record MqttTopicImportRequest(Guid SessionId, string[] Topics);
|
||||
public sealed record MqttTopicImportResult(int Created, int Existing, int Unavailable);
|
||||
public sealed record MqttTopicBrowserItem(string Topic, string Preview, string? ValueType, DateTimeOffset ReceivedAtUtc, bool Retained, Guid? PointId);
|
||||
public sealed record MqttTopicBrowserView(Guid SessionId, string Filter, bool Connected, bool LimitReached, string? Error, IReadOnlyList<MqttTopicBrowserItem> Topics);
|
||||
internal sealed record ObservedMqttTopic(string Topic, string Preview, string? ValueType, JsonElement? Value, DateTimeOffset ReceivedAtUtc, bool Retained);
|
||||
|
||||
public sealed class MqttTopicBrowserService(GatewayStore store) : BackgroundService
|
||||
{
|
||||
private const int MaxTopics = 3000;
|
||||
private readonly MqttClientFactory _factory = new();
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
private BrowserSession? _current;
|
||||
|
||||
public async Task<MqttTopicBrowserView> StartBrowseAsync(MqttTopicBrowseRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var filter = string.IsNullOrEmpty(request.Filter) ? "#" : request.Filter;
|
||||
ValidateFilter(filter);
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var (configuration, password) = store.GetMqttConnectionConfiguration();
|
||||
if (!configuration.Enabled) throw new DomainValidationException("Zuerst den MQTT-Client aktivieren und den Broker speichern.");
|
||||
if (_current is { } active && active.Client.IsConnected && active.Filter == filter && active.Configuration == configuration)
|
||||
return ReadView(active);
|
||||
|
||||
await StopCurrentAsync();
|
||||
var session = new BrowserSession(configuration, filter, _factory.CreateMqttClient());
|
||||
session.Client.ApplicationMessageReceivedAsync += message =>
|
||||
{
|
||||
var publish = message.ApplicationMessage;
|
||||
Capture(session, publish.Topic, publish.Payload, publish.Retain);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
session.Client.DisconnectedAsync += notification =>
|
||||
{
|
||||
lock (session.Topics) session.Error = notification.Exception?.Message ?? "Die Broker-Verbindung wurde getrennt.";
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(12));
|
||||
try
|
||||
{
|
||||
var clientId = "seiugwBrowse" + session.Id.ToString("N")[..10];
|
||||
var result = await session.Client.ConnectAsync(MqttClientService.BuildClientOptions(_factory, configuration, password, clientId), timeout.Token);
|
||||
if (!session.Client.IsConnected)
|
||||
throw new DomainValidationException($"Broker-Verbindung abgewiesen ({result.ResultCode}).");
|
||||
var options = _factory.CreateSubscribeOptionsBuilder()
|
||||
.WithTopicFilter(topic => topic.WithTopic(filter).WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)).Build();
|
||||
var subscription = await session.Client.SubscribeAsync(options, timeout.Token);
|
||||
if (subscription.Items.Count != 1 || subscription.Items.Any(item => (int)item.ResultCode >= 128))
|
||||
throw new DomainValidationException($"Der Broker hat den Topic-Filter '{filter}' abgelehnt.");
|
||||
Volatile.Write(ref _current, session);
|
||||
return ReadView(session);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
await CloseAsync(session);
|
||||
if (cancellationToken.IsCancellationRequested || exception is DomainValidationException) throw;
|
||||
throw new DomainValidationException(exception is OperationCanceledException
|
||||
? "Der Broker hat beim Öffnen des Topic-Browsers nicht rechtzeitig geantwortet."
|
||||
: $"MQTT-Topic-Browser: {exception.Message}");
|
||||
}
|
||||
}
|
||||
finally { _lifecycle.Release(); }
|
||||
}
|
||||
|
||||
public MqttTopicBrowserView GetBrowse(Guid id) => ReadView(RequireSession(id));
|
||||
|
||||
public async Task<MqttTopicImportResult> ImportAsync(MqttTopicImportRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.Topics is not { Length: >= 1 and <= MaxTopics } || request.Topics.Any(topic => topic is null || !MqttExternalTopics.IsTopic(topic)))
|
||||
throw new DomainValidationException($"Bitte 1 bis {MaxTopics} beobachtete MQTT-Topics auswählen.");
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var session = RequireSession(request.SessionId);
|
||||
ObservedMqttTopic[] samples;
|
||||
var selection = request.Topics.ToHashSet(StringComparer.Ordinal);
|
||||
lock (session.Topics)
|
||||
samples = session.Topics.Values.Where(sample => selection.Contains(sample.Topic) && sample.Value.HasValue).ToArray();
|
||||
return store.ImportMqttExternalPoints(session.Configuration, samples, selection.Count - samples.Length);
|
||||
}
|
||||
finally { _lifecycle.Release(); }
|
||||
}
|
||||
|
||||
public async Task ResetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
try { await StopCurrentAsync(); }
|
||||
finally { _lifecycle.Release(); }
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
if (Volatile.Read(ref _current) is not { } session || !session.IsIdle) continue;
|
||||
await _lifecycle.WaitAsync(stoppingToken);
|
||||
try
|
||||
{
|
||||
if (ReferenceEquals(session, _current) && session.IsIdle) await StopCurrentAsync();
|
||||
}
|
||||
finally { _lifecycle.Release(); }
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
|
||||
finally { await ResetAsync(CancellationToken.None); }
|
||||
}
|
||||
|
||||
private BrowserSession RequireSession(Guid id)
|
||||
{
|
||||
if (Volatile.Read(ref _current) is not { } session || session.Id != id || session.IsIdle)
|
||||
throw new DomainValidationException("Die Topic-Beobachtung ist abgelaufen. Bitte erneut starten.");
|
||||
if (store.GetGatewayConfiguration().Mqtt != session.Configuration)
|
||||
throw new DomainValidationException("Die Broker-Konfiguration wurde geändert. Bitte die Topic-Beobachtung neu starten.");
|
||||
session.Touch();
|
||||
return session;
|
||||
}
|
||||
|
||||
private MqttTopicBrowserView ReadView(BrowserSession session)
|
||||
{
|
||||
var points = store.ListMqttExternalPoints()
|
||||
.ToLookup(point => MqttExternalTopics.Address(point)!, StringComparer.Ordinal);
|
||||
session.Touch();
|
||||
lock (session.Topics)
|
||||
{
|
||||
var topics = session.Topics.Values.OrderBy(sample => sample.Topic, StringComparer.Ordinal)
|
||||
.Select(sample => new MqttTopicBrowserItem(sample.Topic, sample.Preview, sample.ValueType, sample.ReceivedAtUtc,
|
||||
sample.Retained, points[sample.Topic].FirstOrDefault()?.Id)).ToArray();
|
||||
return new(session.Id, session.Filter, session.Client.IsConnected, session.LimitReached, session.Error, topics);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Capture(BrowserSession session, string topic, System.Buffers.ReadOnlySequence<byte> payload, bool retained)
|
||||
{
|
||||
if (!MqttExternalTopics.IsTopic(topic)) return;
|
||||
lock (session.Topics)
|
||||
{
|
||||
if (!session.Topics.ContainsKey(topic) && session.Topics.Count >= MaxTopics)
|
||||
{
|
||||
session.LimitReached = true;
|
||||
return;
|
||||
}
|
||||
var (value, type, preview) = MqttExternalTopics.Read(topic, payload);
|
||||
session.Topics[topic] = new(topic, preview, type, value, DateTimeOffset.UtcNow, retained);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateFilter(string filter)
|
||||
{
|
||||
if (filter.Length > MqttExternalTopics.MaxTopicLength || filter.Contains('\0'))
|
||||
throw new DomainValidationException("Der MQTT-Topic-Filter ist ungültig.");
|
||||
var levels = filter.Split('/');
|
||||
for (var index = 0; index < levels.Length; index++)
|
||||
{
|
||||
var level = levels[index];
|
||||
if ((level.Contains('#') && (level != "#" || index != levels.Length - 1)) ||
|
||||
(level.Contains('+') && level != "+"))
|
||||
throw new DomainValidationException("MQTT-Wildcards müssen ganze Ebenen belegen. # gehört ans Ende des Filters.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopCurrentAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _current, null) is { } session) await CloseAsync(session);
|
||||
}
|
||||
|
||||
private async Task CloseAsync(BrowserSession session)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
if (session.Client.IsConnected)
|
||||
await session.Client.DisconnectAsync(_factory.CreateClientDisconnectOptionsBuilder().Build(), timeout.Token);
|
||||
}
|
||||
catch (Exception) { /* The client still has to release its broker connection. */ }
|
||||
finally { session.Client.Dispose(); }
|
||||
}
|
||||
|
||||
private sealed class BrowserSession(MqttConfiguration configuration, string filter, IMqttClient client)
|
||||
{
|
||||
private long _lastAccess = Environment.TickCount64;
|
||||
public Guid Id { get; } = Guid.NewGuid();
|
||||
public MqttConfiguration Configuration { get; } = configuration;
|
||||
public string Filter { get; } = filter;
|
||||
public IMqttClient Client { get; } = client;
|
||||
public Dictionary<string, ObservedMqttTopic> Topics { get; } = new(StringComparer.Ordinal);
|
||||
public bool LimitReached { get; set; }
|
||||
public string? Error { get; set; }
|
||||
public bool IsIdle => Environment.TickCount64 - Interlocked.Read(ref _lastAccess) >= 45000;
|
||||
public void Touch() => Interlocked.Exchange(ref _lastAccess, Environment.TickCount64);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>SE-Inno APIs use PHP-style multipart form fields, not Meta's direct JSON API.</summary>
|
||||
public sealed class NotificationTransport(IHttpClientFactory clients)
|
||||
{
|
||||
public static readonly IReadOnlyList<string> WhatsAppTemplates = ["infomessagegroup", "infoapp", "meldung", "stoerung", "se_portal_admin", "contact_form", "se_portal_manage", "se_portal"];
|
||||
|
||||
// Template variables cannot contain line breaks/tabs or runs of more than four spaces.
|
||||
// Keep Unicode letters, punctuation and emoji; normalize whitespace instead of stripping umlauts.
|
||||
public static string NormalizeTemplateText(string text, int maximumLength = 1024)
|
||||
{
|
||||
if (text is null) throw new DomainValidationException("WhatsApp-Template-Text fehlt.");
|
||||
var output = new StringBuilder();
|
||||
var space = false;
|
||||
foreach (var rune in text.Normalize(NormalizationForm.FormC).EnumerateRunes())
|
||||
{
|
||||
if (Rune.IsWhiteSpace(rune) || Rune.IsControl(rune)) { space = output.Length > 0; continue; }
|
||||
if (space) output.Append(' ');
|
||||
space = false;
|
||||
output.Append(rune);
|
||||
}
|
||||
var normalized = output.ToString();
|
||||
if (normalized.Length == 0 || normalized.Length > maximumLength)
|
||||
throw new DomainValidationException($"WhatsApp-Template-Text muss nach Bereinigung 1 bis {maximumLength} Zeichen enthalten. Bitte die Nachricht kürzen.");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public static MultipartFormDataContent BuildAlarmForm(string key, NotificationDelivery delivery)
|
||||
{
|
||||
GatewayStore.ValidateAlarmDestination(delivery.Destination);
|
||||
if (string.IsNullOrWhiteSpace(key)) throw new DomainValidationException("Für diesen Versandkanal ist kein API-Key hinterlegt.");
|
||||
var fields = new Dictionary<string, string> { ["api_key"] = key };
|
||||
var destination = delivery.Destination;
|
||||
switch (destination.Channel)
|
||||
{
|
||||
case NotificationChannel.Mail:
|
||||
fields["address"] = destination.Recipient;
|
||||
fields["subject"] = delivery.Title;
|
||||
fields["message"] = delivery.Message;
|
||||
break;
|
||||
case NotificationChannel.WhatsApp:
|
||||
fields["number"] = destination.Recipient;
|
||||
fields["message"] = NormalizeTemplateText(delivery.Message);
|
||||
fields["template"] = destination.Template;
|
||||
fields["pn"] = NormalizeTemplateText(destination.PersonName, 60);
|
||||
break;
|
||||
case NotificationChannel.Ntfy:
|
||||
fields["topic"] = destination.Recipient;
|
||||
fields["message"] = delivery.Message;
|
||||
fields["title"] = delivery.Title;
|
||||
fields["priority"] = destination.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
fields["tags"] = destination.Tags;
|
||||
break;
|
||||
}
|
||||
var form = new MultipartFormDataContent();
|
||||
foreach (var (name, value) in fields) form.Add(new StringContent(value, Encoding.UTF8), name);
|
||||
return form;
|
||||
}
|
||||
|
||||
public async Task SendAlarmAsync(string key, NotificationDelivery delivery, CancellationToken cancellationToken)
|
||||
{
|
||||
using var form = BuildAlarmForm(key, delivery);
|
||||
await PostAsync(delivery.Destination.Channel, form, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task PostAsync(NotificationChannel channel, MultipartFormDataContent form, CancellationToken cancellationToken)
|
||||
{
|
||||
using var client = clients.CreateClient("seiugw-notifications");
|
||||
using var response = await client.PostAsync(GatewayStore.NotificationEndpoint(channel), form, cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new DomainValidationException($"{channel}-API: HTTP {(int)response.StatusCode}.");
|
||||
// Do not persist or echo arbitrary API bodies: they can contain credentials and personal data.
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
using var json = JsonDocument.Parse(body);
|
||||
if (json.RootElement.ValueKind == JsonValueKind.Object &&
|
||||
((json.RootElement.TryGetProperty("success", out var success) && success.ValueKind == JsonValueKind.False) ||
|
||||
(json.RootElement.TryGetProperty("error", out var error) && error.ValueKind is not (JsonValueKind.Null or JsonValueKind.False) && error.ToString().Length > 0)))
|
||||
throw new DomainValidationException($"{channel}-API meldet einen Fehler trotz HTTP-Erfolg.");
|
||||
}
|
||||
catch (JsonException) { /* The supplied APIs may respond with plain text. HTTP remains the available acceptance signal. */ }
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AlarmNotificationService(GatewayStore store, NotificationTransport transport) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
store.RecoverInterruptedNotifications();
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var delivery = store.ClaimNotification();
|
||||
if (delivery is null)
|
||||
{
|
||||
try { await Task.Delay(500, stoppingToken); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var key = store.GetNotificationKey(delivery.Destination.Channel);
|
||||
if (key is null)
|
||||
{
|
||||
store.CompleteNotification(delivery.Id, "Blocked", "API-Key fehlt; Kanal gesperrt.");
|
||||
continue;
|
||||
}
|
||||
await transport.SendAlarmAsync(key, delivery, stoppingToken);
|
||||
store.CompleteNotification(delivery.Id, "Accepted", "Von API angenommen; Endzustellung nicht bestätigt.");
|
||||
}
|
||||
catch (DomainValidationException exception)
|
||||
{
|
||||
store.CompleteNotification(delivery.Id, "Failed", exception.Message);
|
||||
}
|
||||
catch (Exception exception) when (exception is HttpRequestException or OperationCanceledException)
|
||||
{
|
||||
store.CompleteNotification(delivery.Id, "Unknown", "Verbindung unterbrochen oder Zeitlimit erreicht; Zustellung unbekannt. Kein automatischer Doppelversand.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
#pragma warning disable CS0618 // OPC UA 1.5 retains this constructor while its telemetry migration is in progress.
|
||||
|
||||
/// <summary>Creates one persistent PKI layout for both OPC UA client and server roles.</summary>
|
||||
public sealed class OpcUaApplicationFactory
|
||||
{
|
||||
private static readonly SemaphoreSlim CertificateGate = new(1, 1);
|
||||
private readonly GatewayDatabase _database;
|
||||
|
||||
public OpcUaApplicationFactory(GatewayDatabase database)
|
||||
{
|
||||
_database = database;
|
||||
}
|
||||
|
||||
public async Task<ApplicationConfiguration> CreateClientConfigurationAsync()
|
||||
{
|
||||
var configuration = CreateBaseConfiguration(ApplicationType.Client);
|
||||
await configuration.ValidateAsync(ApplicationType.Client);
|
||||
await EnsureCertificateAsync(configuration);
|
||||
return configuration;
|
||||
}
|
||||
|
||||
public async Task<ApplicationConfiguration> CreateServerConfigurationAsync(int port, bool allowAnonymous)
|
||||
{
|
||||
var configuration = CreateBaseConfiguration(ApplicationType.Server);
|
||||
configuration.ServerConfiguration = new ServerConfiguration
|
||||
{
|
||||
BaseAddresses = [$"opc.tcp://0.0.0.0:{port}"],
|
||||
SecurityPolicies = [
|
||||
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.Sign, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 },
|
||||
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.SignAndEncrypt, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }
|
||||
],
|
||||
UserTokenPolicies = allowAnonymous
|
||||
? [new UserTokenPolicy(UserTokenType.UserName), new UserTokenPolicy(UserTokenType.Anonymous)]
|
||||
: [new UserTokenPolicy(UserTokenType.UserName)],
|
||||
DiagnosticsEnabled = false,
|
||||
MaxSessionCount = 100,
|
||||
MaxChannelCount = 100
|
||||
};
|
||||
await configuration.ValidateAsync(ApplicationType.Server);
|
||||
await EnsureCertificateAsync(configuration);
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private ApplicationConfiguration CreateBaseConfiguration(ApplicationType type)
|
||||
{
|
||||
var pkiDirectory = Path.Combine(_database.DataDirectory, "pki", "opcua");
|
||||
Directory.CreateDirectory(pkiDirectory);
|
||||
return new ApplicationConfiguration
|
||||
{
|
||||
ApplicationName = "SE-Inno Universalgateway",
|
||||
ApplicationUri = $"urn:{Utils.GetHostName()}:se-inno:universalgateway" + (type == ApplicationType.Server ? ":server" : ""),
|
||||
ApplicationType = type,
|
||||
ProductUri = "urn:se-inno:universalgateway",
|
||||
SecurityConfiguration = new SecurityConfiguration
|
||||
{
|
||||
ApplicationCertificate = new CertificateIdentifier
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
// Client certificates can lack server DNS names. Keep the existing
|
||||
// client identity, and create a separate server identity without deleting it.
|
||||
StorePath = Path.Combine(pkiDirectory, type == ApplicationType.Server ? "server-own" : "own"),
|
||||
SubjectName = $"CN=SE-Inno Universalgateway{(type == ApplicationType.Server ? " Server" : "")}, DC={Utils.GetHostName()}"
|
||||
},
|
||||
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "trusted") },
|
||||
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "issuers") },
|
||||
RejectedCertificateStore = new CertificateStoreIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "rejected") },
|
||||
AutoAcceptUntrustedCertificates = false,
|
||||
AddAppCertToTrustedStore = true
|
||||
},
|
||||
ClientConfiguration = new ClientConfiguration
|
||||
{
|
||||
DefaultSessionTimeout = 60_000,
|
||||
WellKnownDiscoveryUrls = []
|
||||
},
|
||||
TransportQuotas = new TransportQuotas { OperationTimeout = 15_000, MaxMessageSize = 4 * 1024 * 1024 },
|
||||
TransportConfigurations = []
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task EnsureCertificateAsync(ApplicationConfiguration configuration)
|
||||
{
|
||||
await CertificateGate.WaitAsync();
|
||||
try
|
||||
{
|
||||
var identity = configuration.SecurityConfiguration.ApplicationCertificate;
|
||||
if (configuration.ApplicationType == ApplicationType.Server && await identity.Find(false) is null)
|
||||
{
|
||||
// A wildcard listener address is not the address clients connect to.
|
||||
// Include real local addresses in the first server certificate. Existing
|
||||
// certificates are never silently replaced after a network change.
|
||||
var names = configuration.GetServerDomainNames().Concat([Utils.GetHostName(), "localhost", "127.0.0.1", "::1"])
|
||||
.Concat(NetworkInterface.GetAllNetworkInterfaces().Where(adapter => adapter.OperationalStatus == OperationalStatus.Up)
|
||||
.SelectMany(adapter => adapter.GetIPProperties().UnicastAddresses)
|
||||
.Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork || address.Address.AddressFamily == AddressFamily.InterNetworkV6 && !address.Address.IsIPv6LinkLocal)
|
||||
.Select(address => address.Address.ToString())).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
using var certificate = CertificateFactory.CreateCertificate(configuration.ApplicationUri, configuration.ApplicationName, identity.SubjectName, names)
|
||||
.SetLifeTime(24).SetRSAKeySize(2048).CreateForRSA();
|
||||
using var certificateStore = identity.OpenStore();
|
||||
await certificateStore.AddAsync(certificate);
|
||||
}
|
||||
var application = new ApplicationInstance(configuration);
|
||||
if (!await application.CheckApplicationInstanceCertificatesAsync(false, null, CancellationToken.None))
|
||||
throw new DomainValidationException("Das OPC-UA-Anwendungszertifikat konnte nicht erzeugt oder geladen werden.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
CertificateGate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning restore CS0618
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Text.Json;
|
||||
using System.Text;
|
||||
using Gateway.Api.Domain;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
#pragma warning disable CS0618 // The OPC Foundation 1.5 fluent/async replacement is still evolving; these stable calls remain supported.
|
||||
|
||||
public sealed record OpcUaBrowseRequest(
|
||||
string EndpointUrl,
|
||||
string? NodeId = null,
|
||||
bool UseSecurity = true,
|
||||
OpcUaAuthenticationMode AuthenticationMode = OpcUaAuthenticationMode.Anonymous,
|
||||
string? Username = null,
|
||||
string? Password = null,
|
||||
bool AcceptUntrustedServerCertificate = false,
|
||||
Guid? ClientId = null);
|
||||
|
||||
public sealed record OpcUaBrowseItem(string NodeId, string BrowseName, string DisplayName, string NodeClass, bool HasChildren, JsonElement? Value,
|
||||
string? StableNodeId = null, string? ValueType = null, bool Readable = false, bool Writable = false);
|
||||
|
||||
public sealed class OpcUaBrowserService
|
||||
{
|
||||
private readonly OpcUaApplicationFactory _applications;
|
||||
private readonly GatewayStore? _store;
|
||||
|
||||
public OpcUaBrowserService(OpcUaApplicationFactory applications, GatewayStore? store = null)
|
||||
{
|
||||
_applications = applications;
|
||||
_store = store;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<OpcUaBrowseItem>> BrowseAsync(OpcUaBrowseRequest request)
|
||||
{
|
||||
try { return await BrowseCoreAsync(request); }
|
||||
catch (OperationCanceledException) { throw new DomainValidationException("OPC-UA-Abfrage nach 15 Sekunden abgebrochen. Bitte einen kleineren Teilbaum öffnen."); }
|
||||
catch (ServiceResultException exception) { throw new DomainValidationException($"OPC-UA-Abfrage fehlgeschlagen: {exception.StatusCode}. Anmeldung, Endpunkt und Zertifikatsvertrauen prüfen."); }
|
||||
catch (FormatException) { throw new DomainValidationException("Die OPC-UA-NodeId ist ungültig."); }
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<OpcUaBrowseItem>> BrowseCoreAsync(OpcUaBrowseRequest request)
|
||||
{
|
||||
if (request.ClientId is { } clientId)
|
||||
{
|
||||
var saved = _store?.ListOpcUaClients().SingleOrDefault(item => item.Configuration.Id == clientId)?.Configuration
|
||||
?? throw new DomainValidationException("OPC-UA-Verbindung nicht gefunden.");
|
||||
request = request with { EndpointUrl = saved.EndpointUrl, UseSecurity = saved.UseSecurity, AuthenticationMode = saved.AuthenticationMode,
|
||||
Username = saved.Username, Password = _store!.GetOpcUaClientCredentials(clientId).Password, AcceptUntrustedServerCertificate = saved.AcceptUntrustedServerCertificate };
|
||||
}
|
||||
if (!Uri.TryCreate(request.EndpointUrl, UriKind.Absolute, out var endpointUri) || endpointUri.Scheme != "opc.tcp")
|
||||
{
|
||||
throw new DomainValidationException("Die OPC-UA-Endpunktadresse muss mit opc.tcp:// beginnen.");
|
||||
}
|
||||
if (request.AuthenticationMode == OpcUaAuthenticationMode.Username && (string.IsNullOrWhiteSpace(request.Username) || request.Password is null))
|
||||
{
|
||||
throw new DomainValidationException("Für OPC-UA-Benutzeranmeldung werden Benutzername und Passwort benötigt.");
|
||||
}
|
||||
if (request.AuthenticationMode is not (OpcUaAuthenticationMode.Anonymous or OpcUaAuthenticationMode.Username))
|
||||
throw new DomainValidationException("Benutzerzertifikate werden im Browser noch nicht unterstützt. Bitte Anonym oder Benutzer/Passwort wählen.");
|
||||
if (request.AuthenticationMode == OpcUaAuthenticationMode.Username && !request.UseSecurity)
|
||||
throw new DomainValidationException("Benutzer/Passwort erfordert einen gesicherten OPC-UA-Kanal.");
|
||||
|
||||
var configuration = await _applications.CreateClientConfigurationAsync();
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
if (request.AcceptUntrustedServerCertificate)
|
||||
{
|
||||
// Explicit per-request exception, never a global trust relaxation.
|
||||
configuration.CertificateValidator.CertificateValidation += (_, args) => args.Accept = args.Error.StatusCode == Opc.Ua.StatusCodes.BadCertificateUntrusted;
|
||||
}
|
||||
|
||||
EndpointDescription selected;
|
||||
try
|
||||
{
|
||||
selected = await CoreClientUtils.SelectEndpointAsync(configuration, request.EndpointUrl, request.UseSecurity, 15_000, timeout.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new DomainValidationException("Der OPC-UA-Endpunkt hat nicht innerhalb von 15 Sekunden geantwortet.");
|
||||
}
|
||||
var endpoint = new ConfiguredEndpoint(null, selected, EndpointConfiguration.Create(configuration));
|
||||
if (request.UseSecurity && selected.SecurityMode is not (MessageSecurityMode.Sign or MessageSecurityMode.SignAndEncrypt))
|
||||
throw new DomainValidationException("Der Server bietet keinen gesicherten OPC-UA-Endpunkt an.");
|
||||
var identity = request.AuthenticationMode == OpcUaAuthenticationMode.Username
|
||||
? new UserIdentity(request.Username!, Encoding.UTF8.GetBytes(request.Password!))
|
||||
: new UserIdentity();
|
||||
Session session;
|
||||
try
|
||||
{
|
||||
session = await Session.Create(configuration, endpoint, false, true, "SE-Inno Universalgateway Browser", 60_000, identity, null, timeout.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new DomainValidationException("Der OPC-UA-Endpunkt hat keine Sitzung innerhalb von 15 Sekunden aufgebaut.");
|
||||
}
|
||||
try
|
||||
{
|
||||
var node = string.IsNullOrWhiteSpace(request.NodeId) ? ObjectIds.ObjectsFolder : ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(request.NodeId), session.NamespaceUris);
|
||||
var browser = new Browser(session)
|
||||
{
|
||||
BrowseDirection = BrowseDirection.Forward,
|
||||
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
|
||||
IncludeSubtypes = true,
|
||||
NodeClassMask = 0,
|
||||
MaxReferencesReturned = 250,
|
||||
ContinueUntilDone = true
|
||||
};
|
||||
var references = await browser.BrowseAsync(node, timeout.Token);
|
||||
if (references.Count > 5000) throw new DomainValidationException("Mehr als 5000 Nodes in einer Ebene. Bitte den Teilbaum gezielt eingrenzen.");
|
||||
var readableNodes = references.Where(reference => reference.NodeClass == NodeClass.Variable && !reference.NodeId.IsAbsolute)
|
||||
.Select(reference => ExpandedNodeId.ToNodeId(reference.NodeId, session.NamespaceUris)).Distinct().ToArray();
|
||||
var values = new Dictionary<NodeId, DataValue>();
|
||||
var metadata = new Dictionary<NodeId, (string? Type, byte Access)>();
|
||||
foreach (var batch in readableNodes.Chunk(25))
|
||||
{
|
||||
var reads = new ReadValueIdCollection(batch.SelectMany(id => new[] { Attributes.Value, Attributes.DataType, Attributes.ValueRank, Attributes.UserAccessLevel }
|
||||
.Select(attribute => new ReadValueId { NodeId = id, AttributeId = attribute })));
|
||||
var result = await session.ReadAsync(null, 0, TimestampsToReturn.Both, reads, timeout.Token);
|
||||
for (var i = 0; i < batch.Length; i++)
|
||||
{
|
||||
values[batch[i]] = result.Results[i * 4];
|
||||
var type = result.Results[i * 4 + 1].Value is NodeId typeId ? TypeInfo.GetBuiltInType(typeId, session.TypeTree).ToString() : null;
|
||||
if (result.Results[i * 4 + 2].Value is not int rank || rank != ValueRanks.Scalar || type is null || OpcUaPointTypes.Resolve(type) == BuiltInType.Null) type = null;
|
||||
metadata[batch[i]] = (type, result.Results[i * 4 + 3].Value is byte access ? access : (byte)0);
|
||||
}
|
||||
}
|
||||
var items = new List<OpcUaBrowseItem>();
|
||||
foreach (var reference in references)
|
||||
{
|
||||
timeout.Token.ThrowIfCancellationRequested();
|
||||
var localId = ExpandedNodeId.ToNodeId(reference.NodeId, session.NamespaceUris);
|
||||
var meta = localId is not null && metadata.TryGetValue(localId, out var found) ? found : default;
|
||||
JsonElement? value = null;
|
||||
if (localId is not null && values.TryGetValue(localId, out var dataValue))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (StatusCode.IsGood(dataValue.StatusCode) && dataValue.Value is not null)
|
||||
{
|
||||
value = JsonSerializer.SerializeToElement(dataValue.Value);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is NotSupportedException or JsonException)
|
||||
{
|
||||
// Browsing should remain usable if one variable rejects a read.
|
||||
}
|
||||
}
|
||||
items.Add(new OpcUaBrowseItem(
|
||||
localId?.ToString() ?? reference.NodeId.ToString(),
|
||||
reference.BrowseName?.Name ?? reference.NodeId.ToString(),
|
||||
reference.DisplayName?.Text ?? reference.BrowseName?.Name ?? reference.NodeId.ToString(),
|
||||
reference.NodeClass.ToString(),
|
||||
reference.NodeClass is NodeClass.Object or NodeClass.Variable,
|
||||
value,
|
||||
localId is null ? null : NodeId.ToExpandedNodeId(localId, session.NamespaceUris).ToString(),
|
||||
meta.Type, (meta.Access & AccessLevels.CurrentRead) != 0, (meta.Access & AccessLevels.CurrentWrite) != 0));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await session.CloseAsync();
|
||||
session.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning restore CS0618
|
||||
@@ -0,0 +1,229 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using Gateway.Api.Domain;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using StatusCodes = Opc.Ua.StatusCodes;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
#pragma warning disable CA1848
|
||||
|
||||
public sealed record OpcUaClientStatus(Guid ClientId, bool Connected, int SubscribedPoints, string State, DateTimeOffset UpdatedAtUtc);
|
||||
|
||||
/// <summary>One long-lived secure session/subscription per connection. Writes are never retried after an ambiguous result.</summary>
|
||||
public sealed class OpcUaClientService(GatewayStore store, OpcUaApplicationFactory applications, ILogger<OpcUaClientService> logger) : BackgroundService
|
||||
{
|
||||
private readonly ConcurrentDictionary<Guid, OpcUaClientStatus> _status = new();
|
||||
private readonly ConcurrentDictionary<Guid, Worker> _workers = new();
|
||||
private int _disposed;
|
||||
|
||||
public IReadOnlyList<OpcUaClientStatus> GetStatus() => _status.Values.ToArray();
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
store.PointValueUpdated += OnPointValue;
|
||||
try
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var configuration = store.GetGatewayConfiguration().OpcUa;
|
||||
var clients = configuration.ClientEnabled ? (configuration.Clients ?? []).Where(client => client.Enabled).ToArray() : [];
|
||||
var points = store.ListPoints();
|
||||
foreach (var id in _workers.Keys.Except(clients.Select(client => client.Id))) await RemoveAsync(id);
|
||||
foreach (var client in clients)
|
||||
{
|
||||
var selected = points.Where(point => point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.External && ClientId(point) == client.Id).ToArray();
|
||||
var credentials = store.GetOpcUaClientCredentials(client.Id);
|
||||
var signature = JsonSerializer.Serialize(new { client, selected, credentials.Revision });
|
||||
if (_workers.TryGetValue(client.Id, out var current) && current.Signature == signature) continue;
|
||||
await RemoveAsync(client.Id);
|
||||
var worker = new Worker(signature, CancellationTokenSource.CreateLinkedTokenSource(stoppingToken));
|
||||
_workers[client.Id] = worker;
|
||||
worker.Task = RunClientAsync(client, selected, credentials.Password, worker);
|
||||
}
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
|
||||
finally
|
||||
{
|
||||
store.PointValueUpdated -= OnPointValue;
|
||||
foreach (var id in _workers.Keys) await RemoveAsync(id);
|
||||
}
|
||||
}
|
||||
|
||||
private static Guid? ClientId(GatewayPoint point) => point.Address.TryGetProperty("clientId", out var id) && id.ValueKind == JsonValueKind.String && id.TryGetGuid(out var result) ? result : null;
|
||||
|
||||
private void OnPointValue(object? sender, PointValue value)
|
||||
{
|
||||
if (value.OriginPointId == value.PointId || !IsGood(value.Status)) return;
|
||||
var point = store.ListPoints().SingleOrDefault(point => point.Id == value.PointId && point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.External && point.Writable);
|
||||
if (point is null || ClientId(point) is not { } clientId) return;
|
||||
if (!_workers.TryGetValue(clientId, out var worker) || !worker.Connected || !worker.Writes.Writer.TryWrite(value))
|
||||
MarkPoint(point, "BadNotConnected");
|
||||
}
|
||||
|
||||
private async Task RunClientAsync(OpcUaClientConfiguration client, GatewayPoint[] points, string? password, Worker worker)
|
||||
{
|
||||
var token = worker.Cancellation.Token;
|
||||
var retrySeconds = 1;
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
Session? session = null;
|
||||
try
|
||||
{
|
||||
SetStatus(client.Id, false, 0, "Verbindungsaufbau");
|
||||
var configuration = await applications.CreateClientConfigurationAsync();
|
||||
if (client.AcceptUntrustedServerCertificate)
|
||||
configuration.CertificateValidator.CertificateValidation += (_, args) => args.Accept = args.Error.StatusCode == StatusCodes.BadCertificateUntrusted;
|
||||
using var connectTimeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
connectTimeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
var endpoint = await CoreClientUtils.SelectEndpointAsync(configuration, client.EndpointUrl, client.UseSecurity, 15_000, connectTimeout.Token);
|
||||
if (client.UseSecurity && endpoint.SecurityMode is not (MessageSecurityMode.Sign or MessageSecurityMode.SignAndEncrypt)) throw new ServiceResultException(StatusCodes.BadSecurityModeInsufficient);
|
||||
var identity = client.AuthenticationMode switch
|
||||
{
|
||||
OpcUaAuthenticationMode.Anonymous => new UserIdentity(),
|
||||
OpcUaAuthenticationMode.Username when client.UseSecurity && password is not null => new UserIdentity(client.Username!, Encoding.UTF8.GetBytes(password)),
|
||||
_ => throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected)
|
||||
};
|
||||
session = await Session.Create(configuration, new ConfiguredEndpoint(null, endpoint, EndpointConfiguration.Create(configuration)), false, true, $"SE-UGW {client.Name}", 60_000, identity, null, connectTimeout.Token);
|
||||
session.KeepAliveInterval = 5000;
|
||||
var faulted = 0;
|
||||
session.KeepAlive += (_, args) => { if (ServiceResult.IsBad(args.Status)) Interlocked.Exchange(ref faulted, 1); };
|
||||
var observations = new ConcurrentQueue<(GatewayPoint Point, DataValue Value)>();
|
||||
var nodes = points.ToDictionary(point => point.Id, point => ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(point.Address.GetProperty("nodeId").GetString()!), session.NamespaceUris)
|
||||
?? throw new ServiceResultException(StatusCodes.BadNodeIdUnknown));
|
||||
using var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = client.PublishingIntervalMilliseconds, KeepAliveCount = 10, LifetimeCount = 60 };
|
||||
foreach (var point in points.Where(point => point.Readable))
|
||||
{
|
||||
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodes[point.Id], AttributeId = Attributes.Value, SamplingInterval = client.PublishingIntervalMilliseconds, QueueSize = 100, DiscardOldest = true };
|
||||
item.Notification += (_, _) => { foreach (var value in item.DequeueValues()) observations.Enqueue((point, value)); };
|
||||
subscription.AddItem(item);
|
||||
}
|
||||
session.AddSubscription(subscription);
|
||||
await subscription.CreateAsync(token);
|
||||
var rejected = subscription.MonitoredItems.Count(item => ServiceResult.IsBad(item.Status.Error));
|
||||
var echoes = new Dictionary<Guid, List<(string Value, DateTimeOffset Expires)>>();
|
||||
var seen = new Dictionary<Guid, (DateTime Time, string Value, uint Status)>();
|
||||
// Drop queued commands from an old connection. Reconnect is a fresh read, never a replay of writes.
|
||||
while (worker.Writes.Reader.TryRead(out _)) { }
|
||||
worker.Connected = true;
|
||||
retrySeconds = 1;
|
||||
SetStatus(client.Id, true, points.Length - rejected, rejected == 0 ? "Abonniert" : $"{rejected} Nodes abgewiesen");
|
||||
while (!token.IsCancellationRequested && Volatile.Read(ref faulted) == 0 && session.Connected)
|
||||
{
|
||||
// Process a bounded batch so ongoing notifications cannot starve writes.
|
||||
for (var i = 0; i < 1000 && observations.TryDequeue(out var observation); i++)
|
||||
{
|
||||
var point = observation.Point;
|
||||
var value = observation.Value;
|
||||
if (!StatusCode.IsGood(value.StatusCode) || value.Value is null) { MarkPoint(point, value.Value is null && StatusCode.IsGood(value.StatusCode) ? "BadWaitingForInitialData" : value.StatusCode.ToString()); continue; }
|
||||
JsonElement json;
|
||||
try { json = JsonSerializer.SerializeToElement(value.Value); _ = OpcUaPointTypes.Convert(json, OpcUaPointTypes.Resolve(point.ValueType)); }
|
||||
catch (Exception exception) when (exception is FormatException or InvalidOperationException or JsonException or NotSupportedException or OverflowException) { MarkPoint(point, "BadTypeMismatch"); continue; }
|
||||
var text = json.GetRawText();
|
||||
var timestamp = value.SourceTimestamp == DateTime.MinValue ? value.ServerTimestamp : value.SourceTimestamp;
|
||||
if (timestamp == DateTime.MinValue) timestamp = DateTime.UtcNow;
|
||||
if (seen.TryGetValue(point.Id, out var prior) && timestamp <= prior.Time && text == prior.Value && value.StatusCode.Code == prior.Status) continue;
|
||||
seen[point.Id] = (timestamp, text, value.StatusCode.Code);
|
||||
if (echoes.TryGetValue(point.Id, out var pending))
|
||||
{
|
||||
pending.RemoveAll(entry => entry.Expires < DateTimeOffset.UtcNow);
|
||||
var match = pending.FindIndex(entry => entry.Value == text);
|
||||
if (match >= 0) { pending.RemoveAt(match); continue; }
|
||||
}
|
||||
try
|
||||
{
|
||||
store.SetPointValue(point.Id, json, PointProtocol.OpcUa, new DateTimeOffset(DateTime.SpecifyKind(timestamp, DateTimeKind.Utc)), "Good", expectedDefinition: point);
|
||||
}
|
||||
catch (DomainValidationException) { /* The subscription will reconcile the edited point. */ }
|
||||
}
|
||||
if (worker.Writes.Reader.TryRead(out var write))
|
||||
{
|
||||
var point = points.SingleOrDefault(candidate => candidate.Id == write.PointId);
|
||||
if (point is null || !store.IsPointDefinitionCurrent(point)) continue;
|
||||
var converted = OpcUaPointTypes.Convert(write.Value, OpcUaPointTypes.Resolve(point.ValueType));
|
||||
var text = JsonSerializer.Serialize(converted);
|
||||
if (!echoes.TryGetValue(point.Id, out var pending)) echoes[point.Id] = pending = [];
|
||||
pending.Add((text, DateTimeOffset.UtcNow.AddSeconds(30)));
|
||||
try
|
||||
{
|
||||
var response = await session.WriteAsync(null, [new WriteValue { NodeId = nodes[point.Id], AttributeId = Attributes.Value, Value = new DataValue(new Variant(converted)) }], token);
|
||||
if (StatusCode.IsBad(response.Results[0])) { pending.RemoveAll(entry => entry.Value == text); MarkPoint(point, response.Results[0].ToString()); }
|
||||
}
|
||||
catch (Exception exception) when (exception is ServiceResultException or OperationCanceledException)
|
||||
{
|
||||
MarkPoint(point, "BadWriteOutcomeUnknown");
|
||||
throw; // May already have reached the server. Never retry this command.
|
||||
}
|
||||
}
|
||||
else await Task.Delay(25, token);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
|
||||
catch (Exception exception)
|
||||
{
|
||||
SetStatus(client.Id, false, 0, exception is ServiceResultException ua ? new StatusCode(ua.StatusCode).ToString() : "Verbindung unterbrochen");
|
||||
logger.LogWarning("OPC UA client {ClientId} disconnected ({ErrorType}).", client.Id, exception.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
worker.Connected = false;
|
||||
if (_status.TryGetValue(client.Id, out var state) && state.Connected) SetStatus(client.Id, false, 0, "Verbindung unterbrochen");
|
||||
foreach (var point in points) MarkPoint(point, "BadNotConnected");
|
||||
while (worker.Writes.Reader.TryRead(out _)) { }
|
||||
if (session is not null)
|
||||
{
|
||||
try { using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); await session.CloseAsync(closeTimeout.Token); }
|
||||
catch (Exception exception) when (exception is ServiceResultException or OperationCanceledException) { }
|
||||
session.Dispose();
|
||||
}
|
||||
}
|
||||
try { await Task.Delay(TimeSpan.FromSeconds(retrySeconds), token); }
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { break; }
|
||||
retrySeconds = Math.Min(30, retrySeconds * 2);
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkPoint(GatewayPoint point, string status)
|
||||
{
|
||||
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == point.Id);
|
||||
if (previous?.Status == status) return;
|
||||
try
|
||||
{
|
||||
store.SetPointValue(point.Id, previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null), PointProtocol.OpcUa,
|
||||
DateTimeOffset.UtcNow, status, expectedDefinition: point);
|
||||
}
|
||||
catch (DomainValidationException) { /* The point was edited or removed while this session was connected. */ }
|
||||
}
|
||||
private void SetStatus(Guid id, bool connected, int count, string state) => _status[id] = new(id, connected, count, state, DateTimeOffset.UtcNow);
|
||||
private static bool IsGood(string? status) => string.IsNullOrWhiteSpace(status) || status.Equals("Good", StringComparison.OrdinalIgnoreCase) || status.Equals("ok", StringComparison.OrdinalIgnoreCase);
|
||||
private async Task RemoveAsync(Guid id)
|
||||
{
|
||||
if (!_workers.TryRemove(id, out var worker)) return;
|
||||
await worker.Cancellation.CancelAsync();
|
||||
await worker.Task;
|
||||
worker.Cancellation.Dispose();
|
||||
_status.TryRemove(id, out _);
|
||||
}
|
||||
public override void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
store.PointValueUpdated -= OnPointValue;
|
||||
base.Dispose();
|
||||
}
|
||||
private sealed class Worker(string signature, CancellationTokenSource cancellation)
|
||||
{
|
||||
public string Signature { get; } = signature;
|
||||
public CancellationTokenSource Cancellation { get; } = cancellation;
|
||||
public Channel<PointValue> Writes { get; } = Channel.CreateBounded<PointValue>(new BoundedChannelOptions(128) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true });
|
||||
public Task Task { get; set; } = Task.CompletedTask;
|
||||
public volatile bool Connected;
|
||||
}
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
#pragma warning restore CA1848
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
using Opc.Ua;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Explicit scalar conversions; no implicit Boolean/numeric or string/numeric coercion.</summary>
|
||||
public static class OpcUaPointTypes
|
||||
{
|
||||
public static BuiltInType Resolve(string valueType) => valueType.ToUpperInvariant() switch
|
||||
{
|
||||
"BOOL" or "BOOLEAN" => BuiltInType.Boolean,
|
||||
"REAL" or "FLOAT" or "SINGLE" or "FLOAT32" or "FLOAT32WORDSWAP" or "FLOAT32-SWAP" or "FLOAT32_SWAP" => BuiltInType.Float,
|
||||
"DOUBLE" => BuiltInType.Double,
|
||||
"SBYTE" => BuiltInType.SByte,
|
||||
"BYTE" => BuiltInType.Byte,
|
||||
"INT16" => BuiltInType.Int16,
|
||||
"UINT16" => BuiltInType.UInt16,
|
||||
"INTEGER" or "INT32" => BuiltInType.Int32,
|
||||
"UNSIGNED" or "UINT32" => BuiltInType.UInt32,
|
||||
"INT64" => BuiltInType.Int64,
|
||||
"UINT64" => BuiltInType.UInt64,
|
||||
"STRING" => BuiltInType.String,
|
||||
_ => BuiltInType.Null
|
||||
};
|
||||
|
||||
public static object? Convert(JsonElement value, BuiltInType type) => type switch
|
||||
{
|
||||
BuiltInType.Boolean => value.GetBoolean(),
|
||||
BuiltInType.Float => Finite(value.GetSingle()),
|
||||
BuiltInType.Double => Finite(value.GetDouble()),
|
||||
BuiltInType.SByte => value.GetSByte(),
|
||||
BuiltInType.Byte => value.GetByte(),
|
||||
BuiltInType.Int16 => value.GetInt16(),
|
||||
BuiltInType.UInt16 => value.GetUInt16(),
|
||||
BuiltInType.Int32 => value.GetInt32(),
|
||||
BuiltInType.UInt32 => value.GetUInt32(),
|
||||
BuiltInType.Int64 => value.GetInt64(),
|
||||
BuiltInType.UInt64 => value.GetUInt64(),
|
||||
BuiltInType.String => value.ValueKind == JsonValueKind.String ? value.GetString() : throw new FormatException("String required."),
|
||||
_ => throw new FormatException("Unsupported OPC UA scalar type.")
|
||||
};
|
||||
|
||||
private static float Finite(float value) => float.IsFinite(value) ? value : throw new FormatException("Finite value required.");
|
||||
private static double Finite(double value) => double.IsFinite(value) ? value : throw new FormatException("Finite value required.");
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Gateway.Api.Domain;
|
||||
using Opc.Ua.Configuration;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed record OpcUaServerStatus(bool Listening, int? Port, string? LastError);
|
||||
|
||||
#pragma warning disable CS0618 // OPC Foundation 1.5 keeps this constructor during its telemetry migration.
|
||||
#pragma warning disable CA1848 // Server lifecycle messages are rare and intentionally simple.
|
||||
|
||||
/// <summary>
|
||||
/// Hosts the native OPC UA endpoint with persistent application certificate and
|
||||
/// trust stores. Anonymous sessions are opt-in; otherwise the server exposes
|
||||
/// username authentication over secured channels.
|
||||
/// </summary>
|
||||
public sealed class OpcUaServerService : BackgroundService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly OpcUaApplicationFactory _applications;
|
||||
private readonly ILogger<OpcUaServerService> _logger;
|
||||
private ApplicationInstance? _application;
|
||||
private OpcUaServerStatus _status = new(false, null, null);
|
||||
|
||||
public OpcUaServerStatus GetStatus() => Volatile.Read(ref _status);
|
||||
|
||||
public OpcUaServerService(GatewayStore store, OpcUaApplicationFactory applications, ILogger<OpcUaServerService> logger)
|
||||
{
|
||||
_store = store;
|
||||
_applications = applications;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var configuration = _store.GetGatewayConfiguration().OpcUa;
|
||||
if (!configuration.ServerEnabled)
|
||||
{
|
||||
Volatile.Write(ref _status, new(false, null, null));
|
||||
await DelayAsync(stoppingToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var applicationConfiguration = await _applications.CreateServerConfigurationAsync(configuration.Port, configuration.AllowAnonymous);
|
||||
var application = new ApplicationInstance(applicationConfiguration);
|
||||
_application = application;
|
||||
var server = new GatewayOpcUaServer(_store);
|
||||
await application.StartAsync(server);
|
||||
Volatile.Write(ref _status, new(true, configuration.Port, null));
|
||||
_logger.LogInformation("OPC UA server listening on TCP {Port}.", configuration.Port);
|
||||
|
||||
// Configuration changes are picked up by a controlled restart.
|
||||
var ticks = 0;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(100), stoppingToken);
|
||||
server.RefreshPoints(++ticks % 20 == 0);
|
||||
if (ticks % 20 != 0) continue;
|
||||
var next = _store.GetGatewayConfiguration().OpcUa;
|
||||
if (!next.ServerEnabled || next.Port != configuration.Port || next.AllowAnonymous != configuration.AllowAnonymous)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Volatile.Write(ref _status, new(false, configuration.Port, exception.Message));
|
||||
_logger.LogWarning(exception, "OPC UA server start failed.");
|
||||
await DelayAsync(stoppingToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (GetStatus().Listening) Volatile.Write(ref _status, new(false, configuration.Port, null));
|
||||
var application = Interlocked.Exchange(ref _application, null);
|
||||
if (application is not null)
|
||||
{
|
||||
await application.StopAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DelayAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#pragma warning restore CS0618
|
||||
#pragma warning restore CA1848
|
||||
@@ -25,13 +25,17 @@ public sealed class SecretProtector
|
||||
else
|
||||
{
|
||||
_key = RandomNumberGenerator.GetBytes(KeyLength);
|
||||
File.WriteAllBytes(keyPath, _key);
|
||||
var fileOptions = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None };
|
||||
if (!OperatingSystem.IsWindows()) fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
using var file = new FileStream(keyPath, fileOptions);
|
||||
file.Write(_key);
|
||||
}
|
||||
|
||||
if (_key.Length != KeyLength)
|
||||
{
|
||||
throw new InvalidOperationException("The gateway secret key is invalid.");
|
||||
}
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(keyPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
|
||||
public string Protect(string secret)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class SessionService
|
||||
public sealed class SessionService(GatewayStore store)
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, SessionEntry> _sessions = new(StringComparer.Ordinal);
|
||||
|
||||
public string Create()
|
||||
public string Create(AuthenticatedGatewayUser user)
|
||||
{
|
||||
PruneExpired();
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
_sessions[token] = DateTimeOffset.UtcNow.AddHours(12);
|
||||
_sessions[token] = new SessionEntry(user, DateTimeOffset.UtcNow.AddHours(12));
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -22,10 +23,30 @@ public sealed class SessionService
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = authorizationHeader[7..];
|
||||
return _sessions.TryGetValue(token, out var expiresAt) && expiresAt > DateTimeOffset.UtcNow;
|
||||
return GetUser(authorizationHeader) is not null;
|
||||
}
|
||||
|
||||
public AuthenticatedGatewayUser? GetUser(string? authorizationHeader)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader) || !authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var token = authorizationHeader[7..];
|
||||
if (!_sessions.TryGetValue(token, out var entry) || entry.ExpiresAtUtc <= DateTimeOffset.UtcNow) return null;
|
||||
var current = store.GetAuthenticatedUser(entry.User.User.Id);
|
||||
if (current is null || current.User.UpdatedAtUtc != entry.User.User.UpdatedAtUtc)
|
||||
{
|
||||
_sessions.TryRemove(token, out _);
|
||||
return null;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
public bool HasPermission(string? authorizationHeader, string permission) =>
|
||||
GetUser(authorizationHeader)?.Permissions.Contains(permission, StringComparer.Ordinal) == true;
|
||||
|
||||
public void Remove(string? authorizationHeader)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
@@ -37,12 +58,14 @@ public sealed class SessionService
|
||||
private void PruneExpired()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var (token, expiresAt) in _sessions)
|
||||
foreach (var (token, entry) in _sessions)
|
||||
{
|
||||
if (expiresAt <= now)
|
||||
if (entry.ExpiresAtUtc <= now)
|
||||
{
|
||||
_sessions.TryRemove(token, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record SessionEntry(AuthenticatedGatewayUser User, DateTimeOffset ExpiresAtUtc);
|
||||
}
|
||||
+721
-50
@@ -1,12 +1,41 @@
|
||||
const app = document.querySelector('#app');
|
||||
const state = { token: sessionStorage.getItem('seiugw-token'), view: 'overview', points: [], mappings: [], trendLogs: [], configuration: null, mqtt: null, mqttMappings: [], mqttStatus: null };
|
||||
const state = { token: sessionStorage.getItem('seiugw-token'), user: null, preferences: null, view: 'overview', points: [], mappings: [], trendLogs: [], trendSelections: [], runnerJobs: [], mailIntegration: null, configuration: null, hardware: { networkInterfaces: [], serialDevices: [] }, mqtt: null, mqttMappings: [], mqttStatus: null, users: [], roles: [], permissionCatalog: [], userEditId: null };
|
||||
const can = permission => state.user?.permissions?.includes(permission);
|
||||
Object.assign(state, { adminTab: 'aliases', pointsTab: 'points', presentation: { points: [], units: [] }, dashboard: [], notifications: [], alarms: [], deliveries: [], komari: null, alarmPointId: null, alarmEditId: null, alarmSource: '', aliasSource: '', runnerEditId: null });
|
||||
|
||||
function resolveTheme(theme) {
|
||||
return theme === 'system' ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme;
|
||||
}
|
||||
|
||||
function applyTheme(theme) {
|
||||
const selected = ['system', 'light', 'dark'].includes(theme) ? theme : 'system';
|
||||
document.documentElement.dataset.theme = resolveTheme(selected);
|
||||
document.documentElement.dataset.themeMode = selected;
|
||||
try { localStorage.setItem('seiugw-theme', selected); } catch { /* Private browsers may disable storage. */ }
|
||||
document.querySelectorAll('button[data-theme]').forEach(button => {
|
||||
const active = button.dataset.theme === selected;
|
||||
button.classList.toggle('active', active);
|
||||
button.setAttribute('aria-pressed', String(active));
|
||||
});
|
||||
}
|
||||
|
||||
function applyStoredTheme() {
|
||||
let theme = 'dark';
|
||||
try { theme = localStorage.getItem('seiugw-theme') || theme; } catch { /* Use the dark default. */ }
|
||||
applyTheme(theme);
|
||||
}
|
||||
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
if (document.documentElement.dataset.themeMode === 'system') applyTheme('system');
|
||||
});
|
||||
applyStoredTheme();
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const headers = { ...(options.headers || {}) };
|
||||
if (state.token) headers.Authorization = `Bearer ${state.token}`;
|
||||
if (options.body) headers['Content-Type'] = 'application/json';
|
||||
const response = await fetch(path, { ...options, headers });
|
||||
if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); throw new Error('Sitzung abgelaufen.'); }
|
||||
if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); throw new Error('Sitzung abgelaufen.'); }
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
throw new Error(body.error || `Anfrage fehlgeschlagen (${response.status})`);
|
||||
@@ -29,12 +58,20 @@ async function boot() {
|
||||
const setup = await api('/api/setup');
|
||||
if (!setup.adminConfigured) return renderSetup();
|
||||
if (!state.token) return renderLogin();
|
||||
if (!state.user) state.user = (await api('/api/auth/me')).user;
|
||||
if (!state.preferences) {
|
||||
state.preferences = await api('/api/auth/preferences');
|
||||
applyTheme(state.preferences.theme);
|
||||
}
|
||||
state.view = can('view_dashboard') ? 'overview' : can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system';
|
||||
await loadData();
|
||||
if (!can('view_dashboard')) state.view = can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system';
|
||||
if (can('manage_gateway') && new URLSearchParams(location.search).has('network-confirm')) state.view = 'system';
|
||||
renderShell();
|
||||
}
|
||||
|
||||
function renderSetup() {
|
||||
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><h1>Erstinbetriebnahme</h1><p>Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.</p><form id="setup-form" class="form"><div class="row"><label>Projektnummer<input id="setup-project" value="P" maxlength="33" pattern="P[A-Za-z0-9_-]{1,32}" placeholder="P190726" required autofocus></label><label>ISP<input id="setup-isp" type="number" min="1" max="99" value="1" required></label></div><div class="notice blue">Der Rechner wird als <code id="setup-hostname">SE-UGW-P-ISP01</code> in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.</div><label>Neues Passwort<input id="setup-password" type="password" minlength="12" autocomplete="new-password" required></label><label>Passwort wiederholen<input id="setup-confirm" type="password" minlength="12" autocomplete="new-password" required></label><div class="buttons"><button class="btn primary">Einrichten</button></div><div id="setup-message"></div></form></div></section>`;
|
||||
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><h1>Erstinbetriebnahme</h1><p>Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.</p><form id="setup-form" class="form"><div class="row"><label>Projektnummer<input id="setup-project" value="P" maxlength="33" pattern="P[A-Za-z0-9_-]{1,32}" placeholder="P190726" required autofocus></label><label>ISP<input id="setup-isp" type="number" min="1" max="99" value="1" required></label></div><div class="notice blue">Der Rechner wird als <code id="setup-hostname">SE-UGW-P-ISP01</code> in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.</div><label>Neues Passwort<input id="setup-password" type="password" minlength="12" autocomplete="new-password" required></label><label>Passwort wiederholen<input id="setup-confirm" type="password" minlength="12" autocomplete="new-password" required></label><div class="buttons"><button class="btn primary">Einrichten</button></div><div id="setup-message"></div></form></div></section>`;
|
||||
const updateHostName = () => {
|
||||
const project = document.querySelector('#setup-project').value.trim().toUpperCase() || 'P';
|
||||
const isp = String(document.querySelector('#setup-isp').value || '1').padStart(2, '0');
|
||||
@@ -52,40 +89,69 @@ function renderSetup() {
|
||||
}
|
||||
|
||||
function renderLogin() {
|
||||
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><h1>Anmelden</h1><p>Lokaler Administrationszugang.</p><form id="login-form" class="form"><label>Benutzer<input value="admin" disabled></label><label>Passwort<input id="login-password" type="password" autocomplete="current-password" required autofocus></label><div class="buttons"><button class="btn primary">Anmelden</button></div><div id="login-message"></div></form></div></section>`;
|
||||
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><h1>Anmelden</h1><p>Lokaler Zugang zum Gateway.</p><form id="login-form" class="form"><label>Benutzer<input id="login-username" value="admin" autocomplete="username" required autofocus></label><label>Passwort<input id="login-password" type="password" autocomplete="current-password" required></label><div class="buttons"><button class="btn primary">Anmelden</button></div><div id="login-message"></div></form></div></section>`;
|
||||
document.querySelector('#login-form').addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
const result = await api('/api/auth/login', { method: 'POST', body: JSON.stringify({ username: 'admin', password: document.querySelector('#login-password').value }) });
|
||||
state.token = result.accessToken; sessionStorage.setItem('seiugw-token', state.token); await boot();
|
||||
const result = await api('/api/auth/login', { method: 'POST', body: JSON.stringify({ username: document.querySelector('#login-username').value, password: document.querySelector('#login-password').value }) });
|
||||
state.token = result.accessToken; state.user = result.user; sessionStorage.setItem('seiugw-token', state.token); await boot();
|
||||
} catch (error) { errorTarget('login-message', 'Anmeldung fehlgeschlagen.'); }
|
||||
});
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
[state.configuration, state.points, state.mappings, state.trendLogs, state.mqtt, state.mqttMappings, state.mqttStatus] = await Promise.all([
|
||||
api('/api/gateway/configuration'), api('/api/points'), api('/api/mappings'), api('/api/trend-logs'), api('/api/mqtt/configuration'), api('/api/mqtt/mappings'), api('/api/mqtt/status')
|
||||
]);
|
||||
if (!can('manage_sources')) { state.points = []; state.mappings = []; }
|
||||
if (!can('manage_gateway')) { state.configuration = null; state.komari = null; }
|
||||
if (!can('manage_users')) state.users = [];
|
||||
if (!can('manage_roles') && !can('manage_users')) { state.roles = []; state.permissionCatalog = []; }
|
||||
if (!can('manage_alarms')) { state.alarms = []; state.deliveries = []; }
|
||||
if (!can('view_trends')) { state.trendLogs = []; state.trendSelections = []; }
|
||||
if (!can('manage_runner')) state.runnerJobs = [];
|
||||
const jobs = [];
|
||||
jobs.push(api('/api/presentation').then(value => { state.presentation = value; }));
|
||||
if (can('view_dashboard')) jobs.push(api('/api/dashboard').then(value => { state.dashboard = value; }));
|
||||
if (!can('manage_sources') && (can('edit_aliases') || can('manage_alarms') || can('manage_integrations'))) jobs.push(api('/api/points/catalog').then(value => { state.points = value; }));
|
||||
if (can('manage_gateway')) jobs.push(api('/api/system/komari').then(value => { state.komari = value; }));
|
||||
if (can('manage_integrations') || can('manage_alarms')) jobs.push(api('/api/integrations/notifications').then(value => { state.notifications = value; }));
|
||||
if (can('manage_alarms')) jobs.push(api('/api/alarms').then(value => { state.alarms = value; }), api('/api/alarms/deliveries').then(value => { state.deliveries = value; }));
|
||||
if (can('manage_gateway')) jobs.push(api('/api/gateway/configuration').then(value => { state.configuration = value; }), api('/api/gateway/hardware').then(value => { state.hardware = value; }));
|
||||
if (can('manage_sources')) jobs.push(api('/api/points').then(value => { state.points = value; }), api('/api/mappings').then(value => { state.mappings = value; }));
|
||||
if (can('manage_sources')) jobs.push(api('/api/opcua/clients').then(value => { state.opcuaClients = value; }));
|
||||
if (can('view_trends')) jobs.push(api('/api/trend-logs').then(value => { state.trendLogs = value; }), api('/api/trend-selections').then(value => { state.trendSelections = value; }));
|
||||
if (can('manage_runner')) jobs.push(api('/api/runner/jobs').then(value => { state.runnerJobs = value; }));
|
||||
if (can('manage_integrations')) jobs.push(api('/api/mqtt/configuration').then(value => { state.mqtt = value; }), api('/api/mqtt/mappings').then(value => { state.mqttMappings = value; }), api('/api/mqtt/status').then(value => { state.mqttStatus = value; }), api('/api/mqtt/mapping-defaults').then(value => { state.mqttMappingDefaults = value; }));
|
||||
if (can('manage_integrations')) jobs.push(api('/api/integrations/mail').then(value => { state.mailIntegration = value; }));
|
||||
if (can('manage_users')) jobs.push(api('/api/users').then(value => { state.users = value; }));
|
||||
if (can('manage_roles') || can('manage_users')) jobs.push(api('/api/roles').then(value => { state.roles = value.roles; state.permissionCatalog = value.permissions; }));
|
||||
await Promise.all(jobs);
|
||||
}
|
||||
|
||||
function themeControls(theme) {
|
||||
return `<div class="theme-control"><span class="theme-caption">Darstellung</span><div class="theme-toggle" role="group" aria-label="Farbschema">${[['light','Hell'],['dark','Dunkel'],['system','System']].map(([value, label]) => `<button class="theme-option ${value === theme ? 'active' : ''}" type="button" data-theme="${value}" aria-pressed="${value === theme}">${label}</button>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
function renderShell() {
|
||||
app.innerHTML = `<section class="shell"><aside class="sidebar"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><nav class="nav">
|
||||
<button data-view="overview">Übersicht</button><button data-view="points">Datenpunkte</button><button data-view="mappings">Mappings</button><button data-view="mqtt">MQTT</button><button data-view="trends">Trend Logs</button><button data-view="protocols">Protokolle</button><button data-view="system">System</button>
|
||||
</nav><div class="sidebar-foot">Vendor ID 815<br>Linux / Hostnetz</div></aside><section id="content" class="content"></section></section>`;
|
||||
const nav = `${can('view_dashboard') ? '<button data-view="overview">Dashboard</button>' : ''}${can('view_trends') ? '<button data-view="trends">Trend</button>' : ''}${can('manage_sources') || can('manage_gateway') || can('manage_integrations') ? '<button data-view="points">Datenpunkte</button>' : ''}${can('manage_sources') ? '<button data-view="mappings">Mappings</button>' : ''}${adminTabs().length ? '<button data-view="admin">Admin</button>' : ''}<button data-view="system">Einstellungen</button>`;
|
||||
const theme = state.preferences?.theme || 'system';
|
||||
app.innerHTML = `<section class="shell"><aside class="sidebar"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"><div><span class="eyebrow">SE-INNO</span><br>Universal­gateway</div><button class="btn pin" id="sidebar-pin" title="Seitenleiste anheften" aria-pressed="${state.preferences?.sidebarPinned !== false}">⌖</button></div><nav class="nav">${nav}</nav><div class="sidebar-foot">${themeControls(theme)}<div id="theme-message" role="status"></div><div class="user-caption"><strong>${escapeHtml(state.user?.user?.displayName || '')} · @${escapeHtml(state.user?.user?.username || '')}</strong><span>${escapeHtml(state.user?.user?.role || '')}</span></div><button class="btn" id="sidebar-logout">Abmelden</button><small>by J.H. | SE Inno GmbH</small></div></aside><section id="content" class="content"></section></section>`;
|
||||
document.querySelector('#sidebar-logout').addEventListener('click', logout);
|
||||
document.querySelector('.shell').classList.toggle('unpinned', state.preferences?.sidebarPinned === false);
|
||||
document.querySelector('#sidebar-pin').addEventListener('click', async () => { try { state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ sidebarPinned: state.preferences?.sidebarPinned === false }) }); renderShell(); } catch (error) { window.alert(error.message); } });
|
||||
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => { state.view = button.dataset.view; renderView(); }));
|
||||
document.querySelectorAll('button[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme)));
|
||||
renderView();
|
||||
}
|
||||
|
||||
function renderView() {
|
||||
document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view));
|
||||
const content = document.querySelector('#content');
|
||||
const views = { overview: viewOverview, points: viewPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, protocols: viewProtocols, system: viewSystem };
|
||||
const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem };
|
||||
content.innerHTML = views[state.view]();
|
||||
bindView(state.view);
|
||||
}
|
||||
|
||||
function header(title, status = 'Konfiguration geladen') {
|
||||
return `<header class="topline"><h1>${title}</h1><span class="status"><i class="dot"></i>${status}</span></header>`;
|
||||
return `<header class="topline"><div><span class="eyebrow">ANSICHT</span><h1>${title}</h1></div><span class="status">SE-Inno Universalgateway · ${escapeHtml(status)}</span></header>`;
|
||||
}
|
||||
|
||||
function viewOverview() {
|
||||
@@ -98,78 +164,437 @@ function viewOverview() {
|
||||
<article class="card"><div class="metric-label">Datenpunkte</div><div class="metric-value">${state.points.length}</div><div class="metric-sub">${state.points.filter(point => point.scope === 'External').length} extern</div></article>
|
||||
<article class="card"><div class="metric-label">Mappings</div><div class="metric-value">${state.mappings.length}</div><div class="metric-sub">Schreibownership geprüft</div></article>
|
||||
<article class="card"><div class="metric-label">MQTT-Mappings</div><div class="metric-value">${state.mqttMappings.length}</div><div class="metric-sub">${escapeHtml(mqttStatus)}</div></article>
|
||||
</section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Inbetriebnahme</h2></div><table><tbody><tr><td>Projekt / ISP</td><td>${installation}</td></tr><tr><td>Rechnername</td><td><code>${hostName}</code></td></tr></tbody></table><div class="notice blue" style="margin-top:12px">Der MQTT-Client kann Daten an einen vorhandenen Broker senden und von exakt gemappten Topics annehmen. Die nativen BACnet-, OPC-UA- und Modbus-Adapter werden separat aktiviert; bis dahin wird keine externe Steuerung simuliert.</div></article><article class="card"><div class="card-head"><h2>Schreibregeln</h2></div><p class="note">Ein externes Ziel erhält grundsätzlich genau einen schreibenden Pfad. Mehrere BACnet-Prioritäten sind nur bei ausdrücklich quittierter Konfiguration zulässig. MQTT-Echo wird nicht erneut an denselben Broker gespiegelt.</p></article></section>`;
|
||||
</section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Inbetriebnahme</h2></div><table><tbody><tr><td>Projekt / ISP</td><td>${installation}</td></tr><tr><td>Rechnername</td><td><code>${hostName}</code></td></tr></tbody></table><div class="notice blue" style="margin-top:12px">Der native BACnet/IP-Dienst läuft mit Vendor-ID 815. Aktuell stellt er ausschließlich Device und Network-Port bereit; freigegebene Gateway-Datenpunkte werden mit dem Mapping-Adapter als BACnet-Objekte materialisiert.</div></article><article class="card"><div class="card-head"><h2>Schreibregeln</h2></div><p class="note">Ein externes Ziel erhält grundsätzlich genau einen schreibenden Pfad. Mehrere BACnet-Prioritäten sind nur bei ausdrücklich quittierter Konfiguration zulässig. MQTT-Echo wird nicht erneut an denselben Broker gespiegelt.</p></article></section>`;
|
||||
}
|
||||
|
||||
function viewPoints() {
|
||||
const rows = state.points.map(point => `<tr><td>${escapeHtml(point.displayName)}</td><td><span class="tag">${point.protocol}</span></td><td><span class="tag gray">${point.scope}</span></td><td>${escapeHtml(point.valueType)}</td><td>${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance !== null && point.bacnetObjectInstance !== undefined ? ` · ${point.bacnetObjectInstance}` : ''}</td><td>${point.writable ? 'R/W' : 'R'}</td><td>${escapeHtml(point.externalIdentity || '—')}</td></tr>`).join('');
|
||||
return `${header('Datenpunkte')}<section class="grid two"><article class="card"><div class="card-head"><h2>Neuer Datenpunkt</h2></div><form id="point-form" class="form"><label>Name<input name="displayName" required maxlength="160" placeholder="z. B. Zuluft Sollwert"></label><div class="row"><label>Protokoll<select name="protocol"><option>Bacnet</option><option>OpcUa</option><option>Modbus</option><option>Knx</option><option>Mqtt</option><option>Internal</option></select></label><label>Bereich<select name="scope"><option>External</option><option>Gateway</option><option>Internal</option></select></label></div><div class="row"><label>Werttyp<input name="valueType" value="Real" required></label><label>Externe Identität<input name="externalIdentity" placeholder="device:23/av:1"></label></div><div class="row"><label>BACnet-Objekttyp<select name="bacnetObjectKind"><option value="">— nur Gateway/BACnet —</option><option>AnalogInput</option><option>AnalogOutput</option><option>AnalogValue</option><option>BinaryInput</option><option>BinaryOutput</option><option>BinaryValue</option><option>MultiStateInput</option><option>MultiStateOutput</option><option>MultiStateValue</option><option>Schedule</option><option>Calendar</option><option>EventEnrollment</option><option>NotificationClass</option></select></label><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" placeholder="z. B. 1"></label></div><label>Adresse (JSON)<textarea name="address" required>{}</textarea></label><label class="switch"><input type="checkbox" name="writable"> Beschreibbar</label><div class="buttons"><button class="btn primary">Punkt anlegen</button></div><div id="point-message"></div></form></article><article class="card"><div class="card-head"><h2>Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2></div>${state.points.length ? `<table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th><th>BACnet-Objekt</th><th>Zugriff</th><th>Identität</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Datenpunkte.</div>'}</article></section>`;
|
||||
const editing = state.points.find(point => point.id === state.pointEditId);
|
||||
const select = (options, value) => options.map(option =>
|
||||
`<option ${option === value ? 'selected' : ''}>${option}</option>`).join('');
|
||||
const bacnetKinds = ['AnalogInput', 'AnalogOutput', 'AnalogValue', 'BinaryInput', 'BinaryOutput', 'BinaryValue',
|
||||
'MultiStateInput', 'MultiStateOutput', 'MultiStateValue', 'Schedule', 'Calendar', 'EventEnrollment', 'NotificationClass'];
|
||||
if (editing?.bacnetObjectKind === 'TrendLog') bacnetKinds.push('TrendLog');
|
||||
const rows = state.points.map(point => `<tr>
|
||||
<td>${escapeHtml(point.displayName)}</td>
|
||||
<td><span class="tag">${escapeHtml(point.protocol)}</span></td>
|
||||
<td><span class="tag gray">${escapeHtml(point.scope)}</span></td>
|
||||
<td>${escapeHtml(point.valueType)}</td>
|
||||
<td>${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance == null ? '' : ` · ${point.bacnetObjectInstance}`}</td>
|
||||
<td>${(point.readable ? 'R' : '') + (point.readable && point.writable ? '/' : '') + (point.writable ? 'W' : '') || '—'}</td>
|
||||
<td>${escapeHtml((point.protocol === 'Mqtt' && point.address?.topic) || point.externalIdentity || '—')}</td>
|
||||
<td><div class="buttons"><button type="button" class="btn" data-edit-point="${point.id}">Bearbeiten</button>
|
||||
<button type="button" class="btn danger" data-delete-point="${point.id}">Löschen</button></div></td>
|
||||
</tr>`).join('');
|
||||
return `${header('Datenpunkte')}<section class="grid two">
|
||||
<article class="card"><div class="card-head"><h2>${editing ? 'Datenpunkt bearbeiten' : 'Neuer Datenpunkt'}</h2></div>
|
||||
<form id="point-form" class="form">
|
||||
<label>Name<input name="displayName" required maxlength="160" value="${escapeHtml(editing?.displayName || '')}" placeholder="z. B. Zuluft Sollwert"></label>
|
||||
<div class="row">
|
||||
<label>Protokoll<select name="protocol">${select(['Bacnet', 'OpcUa', 'Modbus', 'Knx', 'Mqtt', 'Internal'], editing?.protocol)}</select></label>
|
||||
<label>Bereich<select name="scope">${select(['External', 'Gateway', 'Internal'], editing?.scope)}</select></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Werttyp<input name="valueType" value="${escapeHtml(editing?.valueType || 'Real')}" required maxlength="80"></label>
|
||||
<label data-point-external>Externe Identität<input name="externalIdentity" value="${escapeHtml(editing?.externalIdentity || '')}" placeholder="device:23/av:1"></label>
|
||||
</div>
|
||||
<div class="row" data-point-bacnet>
|
||||
<label>BACnet-Objekttyp<select name="bacnetObjectKind"><option value="">—</option>${select(bacnetKinds, editing?.bacnetObjectKind)}</select></label>
|
||||
<label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" value="${editing?.bacnetObjectInstance ?? ''}" placeholder="automatisch"></label>
|
||||
</div>
|
||||
<label>Adresse (JSON)<textarea name="address" required>${escapeHtml(JSON.stringify(editing?.address ?? {}, null, 2))}</textarea></label>
|
||||
<div class="row">
|
||||
<label class="switch"><input type="checkbox" name="readable" ${(editing?.readable ?? true) ? 'checked' : ''}> Lesbar</label>
|
||||
<label class="switch"><input type="checkbox" name="writable" ${editing?.writable ? 'checked' : ''}> Beschreibbar</label>
|
||||
</div>
|
||||
<div class="buttons"><button type="submit" class="btn primary">${editing ? 'Änderungen speichern' : 'Punkt anlegen'}</button>
|
||||
${editing ? '<button type="button" class="btn" id="cancel-point-edit">Abbrechen</button>' : ''}</div>
|
||||
<div id="point-message" role="status"></div>
|
||||
</form>
|
||||
</article>
|
||||
<article class="card"><div class="card-head"><h2>Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2>${configurationCsvButtons('points')}</div>
|
||||
<div id="point-list-message" role="status"></div>
|
||||
${rows ? `<div class="table-scroll"><table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th>
|
||||
<th>BACnet-Objekt</th><th>Zugriff</th><th>Identität</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>`
|
||||
: '<div class="empty">Noch keine Datenpunkte.</div>'}
|
||||
</article>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function mappingPointOptions(selected, detail) {
|
||||
const options = state.points.map(point =>
|
||||
`<option value="${point.id}" ${point.id === selected ? 'selected' : ''}>${escapeHtml(point.displayName)} · ${escapeHtml(point[detail])}</option>`);
|
||||
if (selected && !state.points.some(point => point.id === selected))
|
||||
options.unshift(`<option value="${escapeHtml(selected)}" selected>${escapeHtml(selected)}</option>`);
|
||||
return options.join('');
|
||||
}
|
||||
|
||||
function mappingActions(id, kind) {
|
||||
return `<div class="buttons">
|
||||
<button type="button" class="btn" data-edit-${kind}="${id}">Bearbeiten</button>
|
||||
<button type="button" class="btn danger" data-delete-${kind}="${id}">Löschen</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function viewMappings() {
|
||||
const pointOptions = state.points.map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${point.protocol}</option>`).join('');
|
||||
const editing = state.mappings.find(mapping => mapping.id === state.mappingEditId);
|
||||
const names = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
|
||||
const rows = state.mappings.map(mapping => `<tr><td>${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)}</td><td>${mapping.direction === 'Bidirectional' ? '⇄' : '→'}</td><td>${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)}</td><td>${mapping.bacnetPriority || '—'}</td><td>${mapping.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
|
||||
return `${header('Mappings')}<section class="grid two"><article class="card"><div class="card-head"><h2>Mapping anlegen</h2></div>${state.points.length < 2 ? '<div class="notice">Mindestens zwei Punkte anlegen, bevor ein Mapping erzeugt werden kann.</div>' : `<form id="mapping-form" class="form"><label>Quelle<select name="sourcePointId">${pointOptions}</select></label><label>Ziel<select name="targetPointId">${pointOptions}</select></label><div class="row"><label>Richtung<select name="direction"><option value="OneWay">Einweg</option><option value="Bidirectional">Bidirektional</option></select></label><label>BACnet-Priorität (optional)<input type="number" name="bacnetPriority" min="1" max="16" placeholder="z. B. 16"></label></div><label class="switch"><input type="checkbox" name="acknowledge"> Mehrfachschreiben bei unterschiedlichen BACnet-Prioritäten bewusst zulassen</label><label>Transformation (JSON)<textarea name="transform">{}</textarea></label><div class="buttons"><button class="btn primary">Mapping speichern</button></div><div id="mapping-message"></div></form>`}</article><article class="card"><div class="card-head"><h2>Aktive Mapping-Tabelle</h2></div>${state.mappings.length ? `<table><thead><tr><th>Quelle</th><th></th><th>Ziel</th><th>Prio</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Mappings.</div>'}</article></section>`;
|
||||
const rows = state.mappings.map(mapping => `<tr>
|
||||
<td>${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)}</td>
|
||||
<td>${mapping.direction === 'Bidirectional' ? '⇄' : '→'}</td>
|
||||
<td>${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)}</td>
|
||||
<td>${mapping.bacnetPriority ?? '—'}</td>
|
||||
<td>${mapping.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td>
|
||||
<td>${mappingActions(mapping.id, 'mapping')}</td>
|
||||
</tr>`).join('');
|
||||
const form = state.points.length < 2 && !editing ? '<div class="notice">Für ein Mapping werden zwei Datenpunkte benötigt.</div>' : `
|
||||
<form id="mapping-form" class="form">
|
||||
<label>Quelle<select name="sourcePointId" required>${mappingPointOptions(editing?.sourcePointId, 'protocol')}</select></label>
|
||||
<label>Ziel<select name="targetPointId" required>${mappingPointOptions(editing?.targetPointId ?? state.points[1]?.id, 'protocol')}</select></label>
|
||||
<div class="row">
|
||||
<label>Richtung<select name="direction"><option value="OneWay">Einweg</option><option value="Bidirectional" ${editing?.direction === 'Bidirectional' ? 'selected' : ''}>Bidirektional</option></select></label>
|
||||
<label>BACnet-Priorität (optional)<input type="number" name="bacnetPriority" min="1" max="16" value="${editing?.bacnetPriority ?? ''}" placeholder="z. B. 16"></label>
|
||||
</div>
|
||||
<label class="switch"><input type="checkbox" name="enabled" ${(editing?.enabled ?? true) ? 'checked' : ''}> Mapping aktiv</label>
|
||||
<label class="switch"><input type="checkbox" name="acknowledge" ${editing?.acknowledgeMultipleExternalWriters ? 'checked' : ''}> Mehrfachschreiben bei unterschiedlichen BACnet-Prioritäten bewusst zulassen</label>
|
||||
<label>Transformation (JSON)<textarea name="transform">${escapeHtml(JSON.stringify(editing ? editing.transform : {}, null, 2))}</textarea></label>
|
||||
<div class="buttons"><button class="btn primary">Mapping speichern</button>
|
||||
${editing ? '<button type="button" class="btn" id="cancel-mapping-edit">Abbrechen</button>' : ''}</div>
|
||||
<div id="mapping-message" role="status"></div>
|
||||
</form>`;
|
||||
return `${header('Mappings')}${viewMappingBatch()}<section class="grid two">
|
||||
<article class="card"><div class="card-head"><h2>${editing ? 'Mapping bearbeiten' : 'Mapping anlegen'}</h2></div>${form}</article>
|
||||
<article class="card"><div class="card-head"><h2>Mapping-Tabelle</h2>${configurationCsvButtons('mappings')}</div><div id="mapping-list-message" role="status"></div>
|
||||
${rows ? `<div class="table-scroll"><table><thead><tr><th>Quelle</th><th></th><th>Ziel</th><th>Prio</th><th>Status</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>`
|
||||
: '<div class="empty">Noch keine Mappings.</div>'}
|
||||
</article>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function viewMqtt() {
|
||||
const broker = state.mqtt.configuration;
|
||||
const status = state.mqttStatus;
|
||||
const pointNames = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
|
||||
const pointOptions = state.points.map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${escapeHtml(point.valueType)}</option>`).join('');
|
||||
const editing = state.mqttMappings.find(entry => entry.mapping.id === state.mqttMappingEditId)?.mapping;
|
||||
const connection = status.connected ? `verbunden · ${escapeHtml(status.endpoint || '')}` : broker.enabled ? `nicht verbunden${status.lastError ? ` · ${escapeHtml(status.lastError)}` : ''}` : 'deaktiviert';
|
||||
const rows = state.mqttMappings.map(entry => {
|
||||
const mapping = entry.mapping;
|
||||
return `<tr><td>${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}</td><td>${mapping.format === 'SeMonitoring' ? 'SE-Monitoring' : 'JSON'}</td><td>${escapeHtml(mapping.direction)}</td><td><code>${escapeHtml(entry.topic)}</code></td><td>${escapeHtml(mapping.qualityOfService)}</td><td>${mapping.retain ? 'ja' : 'nein'}</td></tr>`;
|
||||
return `<tr><td>${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}</td><td>${escapeHtml(mqttMappingFormatLabel(mapping.format))}</td><td>${escapeHtml(mapping.direction)}</td><td><code>${escapeHtml(entry.topic)}</code></td><td>${escapeHtml(mapping.qualityOfService)}</td><td>${mapping.retain ? 'ja' : 'nein'}</td><td>${mappingActions(mapping.id, 'mqtt-mapping')}</td></tr>`;
|
||||
}).join('');
|
||||
return `${header('MQTT / MQTTS', connection)}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarm</td><td>Nur digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>MQTT-Mapping anlegen</h2></div>${pointOptions ? `<form id="mqtt-mapping-form" class="form"><label>Datenpunkt<select name="pointId">${pointOptions}</select></label><div class="row"><label>Format<select name="format"><option value="SeMonitoring">SE-Monitoring</option><option value="Json">JSON</option></select></label><label>Richtung<select name="direction"><option value="Publish">Nur senden</option><option value="Subscribe">Nur empfangen</option><option value="Bidirectional">Senden und empfangen</option></select></label></div><div class="row"><label>QoS<select name="qualityOfService"><option value="AtMostOnce">0 · höchstens einmal</option><option value="AtLeastOnce" selected>1 · mindestens einmal</option><option value="ExactlyOnce">2 · genau einmal</option></select></label><label class="switch"><input type="checkbox" name="retain"> Retained Message</label></div><div class="card-head" style="margin-top:4px"><h2>SE-Monitoring</h2></div><div class="row three"><label>Jahr<input name="projectYear" type="number" min="2000" max="2100" value="2019"></label><label>Projekt<input name="projectNumber" value="P1909015"></label><label>ISP<input name="ispNumber" value="ISP1"></label></div><div class="row"><label>Kategorie<select name="seCategory"><option>Analog</option><option>Notify</option><option>Alarm</option><option>Setpoints</option></select></label><label>Punktname<input name="topicName" placeholder="iVlTempFuehler4Speicher"></label></div><div class="card-head" style="margin-top:4px"><h2>JSON</h2></div><div class="row"><label>Topic<input name="jsonTopic" placeholder="site/plant/telemetry"></label><label>Eigenschaft (optional)<input name="jsonProperty" placeholder="supplyTemperature"></label></div><div class="buttons"><button class="btn primary">MQTT-Mapping speichern</button></div><div id="mqtt-mapping-message"></div></form>` : '<div class="notice">Zuerst einen Datenpunkt anlegen.</div>'}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2></div>${state.mqttMappings.length ? `<table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
|
||||
return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarms</td><td>Digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}</h2></div>${mqttMappingForm(editing)}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2>${configurationCsvButtons('mqtt')}</div><div id="mqtt-mapping-list-message" role="status"></div>${state.mqttMappings.length ? `<div class="table-scroll"><table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
|
||||
}
|
||||
|
||||
function viewTrends() {
|
||||
const pointNames = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
|
||||
const sourceOptions = state.points.filter(point => point.readable).map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${point.protocol}</option>`).join('');
|
||||
const rows = state.trendLogs.map(log => `<tr><td>${escapeHtml(log.name)}</td><td>${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}</td><td>${log.bacnetObjectInstance}</td><td>${log.intervalSeconds}s</td><td>${log.maxRecords.toLocaleString('de-DE')}</td><td>${log.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
|
||||
return `${header('Trend Logs')}<section class="grid two"><article class="card"><div class="card-head"><h2>Internes Trend Log</h2></div>${sourceOptions ? `<form id="trend-form" class="form"><label>Quellpunkt<select name="sourcePointId">${sourceOptions}</select></label><label>Name<input name="name" required maxlength="160" placeholder="z. B. Zuluft Sollwert Verlauf"></label><div class="row three"><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" required></label><label>Intervall (s)<input name="intervalSeconds" type="number" min="1" max="86400" value="60" required></label><label>Max. Werte<input name="maxRecords" type="number" min="1" max="1000000" value="10000" required></label></div><div class="notice blue">Die Historie wird bei eingehenden Werten höchstens einmal je Intervall ergänzt. Sie ist schreibgeschützt und kann später als BACnet Trend Log bereitgestellt werden.</div><div class="buttons"><button class="btn primary">Trend Log anlegen</button></div><div id="trend-message"></div></form>` : '<div class="notice">Zuerst mindestens einen lesbaren Datenpunkt anlegen.</div>'}</article><article class="card"><div class="card-head"><h2>Konfigurierte Trend Logs</h2></div>${state.trendLogs.length ? `<table><thead><tr><th>Name</th><th>Quelle</th><th>BACnet</th><th>Intervall</th><th>Retention</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Trend Logs.</div>'}</article></section>`;
|
||||
const rows = state.trendLogs.map(log => `<tr><td>${escapeHtml(log.name)}</td><td>${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}</td><td>${log.bacnetObjectInstance}</td><td>${log.intervalSeconds}s</td><td>${log.maxRecords.toLocaleString('de-DE')}</td><td>${log.isPublic ? `<a class="tag" href="/public-trends.html?log=${encodeURIComponent(log.id)}" target="_blank" rel="noopener">öffentlich</a>` : '<span class="tag gray">intern</span>'}</td><td>${log.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
|
||||
const createPanel = can('manage_sources') ? (sourceOptions ? `<form id="trend-form" class="form"><label>Quellpunkt<select name="sourcePointId">${sourceOptions}</select></label><label>Name<input name="name" required maxlength="160" placeholder="z. B. Zuluft Sollwert Verlauf"></label><div class="row three"><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" required></label><label>Intervall (s)<input name="intervalSeconds" type="number" min="1" max="86400" value="60" required></label><label>Max. Werte<input name="maxRecords" type="number" min="1" max="1000000" value="10000" required></label></div><label class="switch"><input name="isPublic" type="checkbox"> Ohne Anmeldung veröffentlichen</label><div class="notice blue">Die Freigabe gilt nur für dieses Log und veröffentlicht ausschließlich die aufgezeichneten Werte. Die Historie wird bei eingehenden Werten höchstens einmal je Intervall ergänzt.</div><div class="buttons"><button class="btn primary">Trend Log anlegen</button></div><div id="trend-message"></div></form>` : '<div class="notice">Zuerst mindestens einen lesbaren Datenpunkt anlegen.</div>') : '<div class="notice blue">Ihre Rolle darf Trenddaten ansehen, aber keine Trend Logs anlegen oder verändern.</div>';
|
||||
const selectionOptions = state.trendLogs.map(log => `<option value="${log.id}">${escapeHtml(log.name)} · BACnet TL ${log.bacnetObjectInstance}</option>`).join('');
|
||||
const selectionRows = state.trendSelections.map(selection => `<tr><td>${escapeHtml(selection.name)}</td><td>${selection.trendLogIds.length}</td><td>${selection.shared ? '<span class="tag">geteilt</span>' : '<span class="tag gray">privat</span>'}</td><td>${selection.ownerId === state.user?.user?.id || state.user?.user?.role === 'admin' ? `<button class="btn danger" data-delete-selection="${selection.id}">Löschen</button>` : '—'}</td></tr>`).join('');
|
||||
const selectionPanel = state.trendLogs.length ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Trend-Gruppe speichern</h2></div><form id="trend-selection-form" class="form"><label>Name<input name="name" required maxlength="120" placeholder="Tagesexport Lüftung"></label><label>Beschreibung (optional)<input name="description" maxlength="600"></label><label>Trend Logs<select name="trendLogIds" multiple size="6" required>${selectionOptions}</select></label><label class="switch"><input name="shared" type="checkbox"> Mit anderen Benutzern teilen</label><div class="buttons"><button class="btn primary">Gruppe speichern</button></div><div id="trend-selection-message"></div></form></article><article class="card"><div class="card-head"><h2>Gespeicherte Gruppen</h2><span class="tag gray">${state.trendSelections.length}</span></div>${selectionRows ? `<table><thead><tr><th>Name</th><th>Logs</th><th>Zugriff</th><th></th></tr></thead><tbody>${selectionRows}</tbody></table>` : '<div class="empty">Noch keine Trend-Gruppe gespeichert.</div>'}</article></section>` : '';
|
||||
return `${header('Trend Logs')}<section class="grid two"><article class="card"><div class="card-head"><h2>Internes Trend Log</h2></div>${createPanel}</article><article class="card"><div class="card-head"><h2>Konfigurierte Trend Logs</h2></div>${state.trendLogs.length ? `<table><thead><tr><th>Name</th><th>Quelle</th><th>BACnet</th><th>Intervall</th><th>Retention</th><th>Freigabe</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Trend Logs.</div>'}</article></section>${selectionPanel}`;
|
||||
}
|
||||
|
||||
function viewRunner() {
|
||||
const selections = state.trendSelections;
|
||||
const selectionOptions = selections.map(selection => `<option value="${selection.id}">${escapeHtml(selection.name)} · ${selection.trendLogIds.length} Trend Logs</option>`).join('');
|
||||
const rows = state.runnerJobs.map(job => `<tr><td>${escapeHtml(job.name)}</td><td>${escapeHtml(selections.find(selection => selection.id === job.selectionId)?.name || job.selectionId)}</td><td>${escapeHtml(job.time)} · ${job.rangeHours}h</td><td>${job.mailEnabled ? escapeHtml(job.mailTo || '—') : 'kein Mailversand'}</td><td>${job.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td><td>${job.lastResult ? (job.lastResult.success ? `<span class="tag">${escapeHtml(new Date(job.lastResult.ranAtUtc).toLocaleString())}</span>` : `<span class="tag warn">${escapeHtml(job.lastResult.error || 'Fehler')}</span>`) : 'noch nicht gelaufen'}</td><td><div class="buttons"><button class="btn" data-test-runner="${job.id}">Test</button><button class="btn danger" data-delete-runner="${job.id}">Löschen</button></div></td></tr>`).join('');
|
||||
const mail = state.mailIntegration || { mailConfigured: false, endpoint: 'https://mailapi.se-inno.de' };
|
||||
const mailPanel = can('manage_integrations') ? `<article class="card"><div class="card-head"><h2>Mail-API</h2><span class="tag ${mail.mailConfigured ? '' : 'gray'}">${mail.mailConfigured ? 'Key gespeichert' : 'kein Key'}</span></div><form id="mail-integration-form" class="form"><label>API-Key<input name="apiKey" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><label class="switch"><input name="clearApiKey" type="checkbox"> Gespeicherten API-Key löschen</label><p class="note">Endpoint: <code>${escapeHtml(mail.endpoint)}</code>. Der Key wird verschlüsselt in der lokalen Datenbank abgelegt.</p><div class="buttons"><button class="btn primary">Mail-API speichern</button></div><div id="mail-integration-message"></div></form></article>` : '';
|
||||
const create = selections.length ? `<form id="runner-form" class="form"><label>Name<input name="name" required maxlength="120" placeholder="Tagesexport Lüftung"></label><label>Auswahl<select name="selectionId">${selectionOptions}</select></label><div class="row"><label>Uhrzeit (Europe/Berlin)<input name="time" type="time" value="06:00" required></label><label>Zeitraum<select name="rangeHours"><option value="24">letzte 24 h</option><option value="48">letzte 48 h</option><option value="168">letzte 7 Tage</option><option value="720">letzte 30 Tage</option></select></label></div><div class="row"><label>CSV-Trennzeichen<select name="delimiter"><option value=";">Semikolon ;</option><option value=",">Komma ,</option><option value="\t">Tabulator</option></select></label><label class="switch"><input name="enabled" type="checkbox" checked> aktiv</label></div><label class="switch"><input name="mailEnabled" type="checkbox"> CSV per Mail verschicken</label><label>Mail an (Komma oder Semikolon)<input name="mailTo" placeholder="kunde@example.com; service@example.com"></label><label>Betreff<input name="mailSubject" value="SE-Inno Universalgateway CSV Export"></label><label>Nachricht<textarea name="mailMessage">Automatischer CSV Export aus dem SE-Inno Universalgateway.</textarea></label><div class="buttons"><button class="btn primary">Runner-Job anlegen</button></div><div id="runner-message"></div></form>` : '<div class="notice">Zuerst in Trend Logs eine gespeicherte Trend-Gruppe anlegen.</div>';
|
||||
return `${header('CSV Runner')}<section class="grid two"><article class="card"><div class="card-head"><h2>Neuer Job</h2></div>${create}</article>${mailPanel}</section><section class="card" style="margin-top:14px"><div class="card-head"><h2>Vorhandene Runner</h2><span class="tag gray">${state.runnerJobs.length}</span></div>${rows ? `<table><thead><tr><th>Name</th><th>Auswahl</th><th>Laufzeit</th><th>Mail</th><th>Status</th><th>Letztes Ergebnis</th><th></th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Keine Runner-Jobs angelegt.</div>'}</section>`;
|
||||
}
|
||||
|
||||
function bacnetInterfaceOptions(selected) {
|
||||
const interfaces = state.hardware.networkInterfaces;
|
||||
const missing = selected && !interfaces.some(card => card.name === selected)
|
||||
? `<option value="" selected disabled>${escapeHtml(selected)} · nicht verfügbar</option>` : '';
|
||||
return missing + interfaces.map(card =>
|
||||
`<option value="${escapeHtml(card.name)}" ${card.name === selected ? 'selected' : ''}>${escapeHtml(card.name)} · ${escapeHtml(card.addresses.join(', ') || 'keine IP')} · ${card.isUp ? 'aktiv' : 'inaktiv'}</option>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
function viewProtocols() {
|
||||
const c = state.configuration;
|
||||
return `${header('Protokolle')}<section class="grid two"><article class="card"><div class="card-head"><h2>BACnet/IP</h2><span class="tag">B-BC</span></div><form id="bacnet-form" class="form"><label>Linux-Interface<input name="interface" value="${escapeHtml(c.bacnet.interface)}" required></label><div class="row"><label>UDP-Port<input name="ipPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label><label>Device-Instance<input name="deviceInstance" type="number" min="0" max="4194303" value="${c.deviceInstance}"></label></div><label>BBMD-Modus<select name="bbmdMode"><option ${c.bacnet.bbmdMode === 'Disabled' ? 'selected' : ''}>Disabled</option><option ${c.bacnet.bbmdMode === 'Bbmd' ? 'selected' : ''}>Bbmd</option><option ${c.bacnet.bbmdMode === 'ForeignDevice' ? 'selected' : ''}>ForeignDevice</option></select></label><label>BBMD-Adresse (bei Foreign Device)<input name="bbmdAddress" value="${escapeHtml(c.bacnet.bbmdAddress || '')}"></label><label>Foreign-Device TTL in Sekunden<input name="ttl" type="number" min="1" max="65535" value="${c.bacnet.foreignDeviceTtlSeconds || ''}"></label><div class="buttons"><button class="btn primary">BACnet speichern</button></div><div id="bacnet-message"></div></form></article><article class="card"><div class="card-head"><h2>OPC UA & Modbus</h2></div><p class="notice blue">OPC UA ist als Client und Server mit persistentem Zertifikatsspeicher vorgesehen. Modbus-TCP wird mehrere Serverinstanzen, frei wählbare Bind-Adressen, Ports und Registerbereiche sowie eine optionale Client-IP-Allowlist unterstützen.</p><div class="card-head" style="margin-top:18px"><h2>KNXnet/IP</h2><span class="tag gray">vorgesehen</span></div><p class="note">Routing, Tunneling und KNX Secure bleiben vorbereitet, werden aber erst nach BACnet, OPC UA und Modbus aktiviert.</p></article></section>`;
|
||||
const servers = c.modbusServers || [];
|
||||
const serialPorts = c.serialPorts || [];
|
||||
const aliases = serialPorts.map(port => `<option value="${escapeHtml(port.alias)}">${escapeHtml(port.alias)} · ${escapeHtml(port.devicePath)}</option>`).join('');
|
||||
const serialDeviceOptions = (state.hardware?.serialDevices || []).map(device => `<option value="${escapeHtml(device.devicePath)}">${escapeHtml(device.targetPath || device.devicePath)}</option>`).join('');
|
||||
const serverRows = servers.map(server => `<tr><td>${escapeHtml(server.name)}</td><td><code>${escapeHtml(server.bindAddress)}:${server.port}</code></td><td>${server.unitId}</td><td>${server.firstHoldingRegister}–${server.firstHoldingRegister + server.holdingRegisterCount - 1}</td><td>${server.allowedClientIps?.length ? escapeHtml(server.allowedClientIps.join(', ')) : 'alle'}</td><td><button class="btn danger" data-remove-modbus-server="${server.id}">Entfernen</button></td></tr>`).join('');
|
||||
const serialRows = serialPorts.map(port => `<tr><td>${escapeHtml(port.alias)}</td><td><code>${escapeHtml(port.devicePath)}</code></td><td>${port.baudRate}, ${escapeHtml(port.parity)}, ${port.dataBits}/${port.stopBits}</td><td><button class="btn danger" data-remove-serial-port="${port.id}">Entfernen</button></td></tr>`).join('');
|
||||
return `${header('Protokolle')}<datalist id="serial-device-list">${serialDeviceOptions}</datalist>
|
||||
${pointPanel('bacnet', `<div class="bacnet-layout"><article class="card bacnet-settings"><div class="card-head"><h2>BACnet/IP</h2><span class="tag">Native Objekte</span></div><form id="bacnet-form" class="form"><label>Netzwerkkarte<select name="interface" required>${bacnetInterfaceOptions(c.bacnet.interface)}</select></label><div class="row"><label>UDP-Port<input name="ipPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label><label>Device-Instance<input name="deviceInstance" type="number" min="0" max="4194303" value="${c.deviceInstance}"></label></div><label>BBMD-Modus<select name="bbmdMode"><option ${c.bacnet.bbmdMode === 'Disabled' ? 'selected' : ''}>Disabled</option><option ${c.bacnet.bbmdMode === 'Bbmd' ? 'selected' : ''}>Bbmd</option><option ${c.bacnet.bbmdMode === 'ForeignDevice' ? 'selected' : ''}>ForeignDevice</option></select></label><label>BBMD-Adresse (bei Foreign Device)<input name="bbmdAddress" value="${escapeHtml(c.bacnet.bbmdAddress || '')}"></label><label>Foreign-Device TTL in Sekunden<input name="ttl" type="number" min="1" max="65535" value="${c.bacnet.foreignDeviceTtlSeconds || ''}"></label><p class="note">Die Liste bietet alle auf diesem Gateway sichtbaren Netzwerkschnittstellen an.</p><div class="buttons"><button class="btn primary">BACnet speichern</button></div><div id="bacnet-message"></div></form></article><div id="bacnet-browser"></div></div>`)}
|
||||
${pointPanel('opcua', `<section class="grid equal"><article class="card"><div class="card-head"><h2>OPC UA</h2><span class="tag">Client + Server</span></div><form id="opcua-form" class="form"><label>Server-Port<input name="port" type="number" min="1" max="65535" value="${c.opcUa.port}"></label><div class="row"><label class="switch"><input name="clientEnabled" type="checkbox" ${c.opcUa.clientEnabled ? 'checked' : ''}> OPC-UA-Client aktiv</label><label class="switch"><input name="serverEnabled" type="checkbox" ${c.opcUa.serverEnabled ? 'checked' : ''}> OPC-UA-Server aktiv</label></div><label class="switch"><input name="allowAnonymous" type="checkbox" ${c.opcUa.allowAnonymous ? 'checked' : ''}> Anonymer Serverzugriff</label><div class="notice blue">Serverzertifikat, Trustlist und Clientzertifikate liegen persistent unter <code>/var/lib/seiugw/pki</code>. Für den Produktivbetrieb bleibt anonymer Zugriff deaktiviert.</div><div class="buttons"><button class="btn primary">OPC UA speichern</button></div><div id="opcua-message"></div></form></article></section><div id="opcua-browser"></div>`)}
|
||||
${pointPanel('modbus', `<section class="grid equal"><article class="card"><div class="card-head"><h2>Modbus-TCP-Server</h2><span class="tag">${servers.length}</span></div><form id="modbus-server-form" class="form"><label>Name<input name="name" required placeholder="GLT Server"></label><div class="row three"><label>Bind-IP<input name="bindAddress" value="0.0.0.0" required></label><label>Port<input name="port" type="number" min="1" max="65535" value="502" required></label><label>Unit-ID<input name="unitId" type="number" min="1" max="247" value="1" required></label></div><div class="row"><label>Erstes Holding-Register<input name="firstHoldingRegister" type="number" min="0" max="65535" value="0" required></label><label>Anzahl Register<input name="holdingRegisterCount" type="number" min="1" max="65536" value="1000" required></label></div><label>Erlaubte Client-IPs (eine je Zeile, leer = alle)<textarea name="allowedClientIps"></textarea></label><div class="buttons"><button class="btn primary">TCP-Server hinzufügen</button></div><div id="modbus-server-message"></div></form></article>
|
||||
<article class="card"><div class="card-head"><h2>TCP-Serverinstanzen</h2></div>${servers.length ? `<table><thead><tr><th>Name</th><th>Bindung</th><th>Unit</th><th>Holding</th><th>Client-Allowlist</th><th></th></tr></thead><tbody>${serverRows}</tbody></table>` : '<div class="empty">Keine Modbus-TCP-Serverinstanz angelegt.</div>'}</article>
|
||||
<article class="card"><div class="card-head"><h2>Modbus-Datenpunkte importieren</h2></div><form id="modbus-import-form" class="form"><label>CSV-Datei<input name="csvFile" type="file" accept=".csv,text/csv" required></label><p class="note">Unterstützt TCP und RTU, Coil, Discrete Input, Input/Holding Register sowie UInt16/Int16/UInt32/Int32/Float32/Word-Swap.</p><div class="buttons"><button type="button" class="btn" id="download-modbus-example">Beispiel-CSV laden</button><button class="btn primary">CSV importieren</button></div><div id="modbus-import-message"></div></form></article></section>`)}
|
||||
${pointPanel('knx', `<section class="grid equal"><article class="card"><div class="card-head"><h2>KNX</h2></div><form id="knx-form" class="form"><label class="switch"><input name="enabled" type="checkbox" ${c.knx.enabled ? 'checked' : ''}> KNX aktivieren</label><div class="row"><label>Transport<select name="transport"><option value="Ip" ${c.knx.transport !== 'Tp' ? 'selected' : ''}>KNX IP</option><option value="Tp" ${c.knx.transport === 'Tp' ? 'selected' : ''}>KNX TP via USB</option></select></label><label>TP-Alias<select name="serialPortAlias"><option value="">—</option>${aliases}</select></label></div><label class="switch"><input name="secure" type="checkbox" ${c.knx.secure ? 'checked' : ''}> KNX Secure</label><label>ETS-Projekt oder XML-Export<input id="knx-ets-file" type="file" accept=".knxproj,.xml,application/zip,text/xml,application/xml"></label><div class="buttons"><button class="btn primary">KNX speichern</button><button id="knx-ets-import" type="button" class="btn">ETS importieren</button></div><div id="knx-message"></div><div id="knx-import-message"></div></form><p class="note">Der Import übernimmt Gruppenadresse und DPT als externe KNX-Datenpunkte. Bereits vorhandene Gruppenadressen werden übersprungen.</p></article></section>`)}
|
||||
${pointPanel('serial', `<section class="grid equal"><article class="card"><div class="card-head"><h2>USB / COM-Aliase</h2></div><form id="serial-port-form" class="form"><div class="row"><label>Alias<input name="alias" required placeholder="RS485-Hauptstrang" pattern="[A-Za-z0-9_-]{1,64}"></label><label>Linux-Gerät<input name="devicePath" list="serial-device-list" required placeholder="/dev/ttyUSB0"></label></div><div class="row three"><label>Baud<input name="baudRate" type="number" value="9600" min="1200" max="921600"></label><label>Parity<select name="parity"><option>None</option><option>Even</option><option>Odd</option></select></label><label>Bits<input name="dataBits" type="number" value="8" min="5" max="8"></label></div><label>Stop-Bits<select name="stopBits"><option value="1">1</option><option value="2">2</option></select></label><p class="note">Die Liste enthält die aktuell sichtbaren USB-/COM-Geräte. Ein stabiler <code>/dev/serial/by-id/…</code>-Pfad ist vorzuziehen.</p><div class="buttons"><button class="btn primary">Alias anlegen</button></div><div id="serial-port-message"></div></form></article>
|
||||
<article class="card"><div class="card-head"><h2>Serielle Schnittstellen</h2></div>${serialPorts.length ? `<table><thead><tr><th>Alias</th><th>Gerät</th><th>Parameter</th><th></th></tr></thead><tbody>${serialRows}</tbody></table>` : '<div class="empty">Noch kein USB-/COM-Port aliasiert.</div>'}<div class="notice blue" style="margin-top:12px">Modbus RTU verwendet diese Aliase direkt in der CSV (<code>SerialPortAlias</code>). KNX TP verwendet denselben Alias für einen USB-TP-Adapter.</div></article></section>`)}`;
|
||||
}
|
||||
|
||||
function viewSystem() {
|
||||
return `${header('System')}<section class="grid two"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" required></label><label>Neues Passwort<input type="password" name="next" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button><button id="logout" type="button" class="btn danger">Abmelden</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Audit</h2></div><div id="audit-content" class="empty">Wird geladen …</div></article></section>`;
|
||||
function viewSystem(section = 'settings') {
|
||||
const theme = state.preferences?.theme || 'system';
|
||||
const roleOptions = state.roles.map(role => `<option value="${escapeHtml(role.name)}">${escapeHtml(role.label)} · ${escapeHtml(role.name)}</option>`).join('');
|
||||
const editUser = state.users.find(user => user.id === state.userEditId) || null;
|
||||
const userRows = state.users.map(user => `<tr><td>${escapeHtml(user.username)}</td><td>${escapeHtml(user.displayName)}</td><td>${escapeHtml(user.email || '—')}</td><td><span class="tag gray">${escapeHtml(user.role)}</span></td><td>${user.active ? '<span class="tag">aktiv</span>' : '<span class="tag gray">deaktiviert</span>'}</td><td><div class="buttons"><button class="btn" data-edit-user="${user.id}">Bearbeiten</button>${user.id === state.user?.user?.id ? '' : `<button class="btn" data-toggle-user="${user.id}" data-active="${user.active}">${user.active ? 'Deaktivieren' : 'Aktivieren'}</button>`}</div></td></tr>`).join('');
|
||||
const roleRows = state.roles.map(role => `<tr><td>${escapeHtml(role.label)}</td><td><code>${escapeHtml(role.name)}</code></td><td>${role.permissions.map(permission => `<span class="tag gray">${escapeHtml(permission)}</span>`).join(' ')}</td><td>${role.isSystem ? 'System' : 'Benutzerdefiniert'}</td></tr>`).join('');
|
||||
const auditPanel = can('view_debug') ? '<article class="card"><div class="card-head"><h2>Audit</h2></div><div id="audit-content" class="empty">Wird geladen …</div></article>' : '';
|
||||
const userPanel = can('manage_users') ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editUser ? `Benutzer bearbeiten · ${escapeHtml(editUser.username)}` : 'Benutzer anlegen'}</h2></div><form id="user-form" class="form"><div class="row"><label>Benutzername<input name="username" value="${escapeHtml(editUser?.username || '')}" required minlength="3" maxlength="80" pattern="[A-Za-z0-9._-]+"></label><label>Anzeigename<input name="displayName" value="${escapeHtml(editUser?.displayName || '')}" required maxlength="120"></label></div><div class="row"><label>E-Mail (optional)<input name="email" value="${escapeHtml(editUser?.email || '')}" type="email" maxlength="160"></label><label>Rolle<select name="role">${state.roles.map(role => `<option value="${escapeHtml(role.name)}" ${role.name === editUser?.role ? 'selected' : ''}>${escapeHtml(role.label)} · ${escapeHtml(role.name)}</option>`).join('')}</select></label></div><label>${editUser ? 'Neues Passwort (leer lassen = unverändert)' : 'Startpasswort'}<input name="password" type="password" minlength="12" ${editUser ? '' : 'required'}></label>${editUser ? '<label>Neues Passwort wiederholen<input name="passwordConfirmation" type="password" autocomplete="new-password" minlength="12"></label>' : ''}<label class="switch"><input name="active" type="checkbox" ${editUser ? (editUser.active ? 'checked' : '') : 'checked'}> Konto aktiv</label><div class="buttons"><button class="btn primary">${editUser ? 'Änderungen speichern' : 'Benutzer anlegen'}</button>${editUser ? '<button id="cancel-user-edit" type="button" class="btn">Abbrechen</button>' : ''}</div><div id="user-message"></div></form></article><article class="card"><div class="card-head"><h2>Konten</h2><span class="tag gray">${state.users.length}</span></div>${userRows ? `<table><thead><tr><th>Benutzer</th><th>Name</th><th>E-Mail</th><th>Rolle</th><th>Status</th><th></th></tr></thead><tbody>${userRows}</tbody></table>` : '<div class="empty">Keine Konten.</div>'}</article></section>` : '';
|
||||
const rolePanel = can('manage_roles') ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Benutzerdefinierte Rolle</h2></div><form id="role-form" class="form"><label>Name<input name="name" required pattern="[A-Za-z0-9_-]+" placeholder="service"></label><label>Bezeichnung<input name="label" required placeholder="Service"></label><label>Berechtigungen (kommagetrennt)<textarea name="permissions" placeholder="view_trends,manage_sources"></textarea></label><p class="note">Verfügbar: ${state.permissionCatalog.map(permission => `<code>${escapeHtml(permission)}</code>`).join(', ')}</p><div class="buttons"><button class="btn primary">Rolle speichern</button></div><div id="role-message"></div></form></article><article class="card"><div class="card-head"><h2>Rollen</h2></div><table><thead><tr><th>Bezeichnung</th><th>Name</th><th>Berechtigungen</th><th>Typ</th></tr></thead><tbody>${roleRows}</tbody></table></article></section>` : '';
|
||||
if (section === 'users') return userPanel;
|
||||
if (section === 'roles') return rolePanel;
|
||||
if (section === 'debug') return auditPanel;
|
||||
return `${header('Einstellungen')}<section class="grid equal"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" autocomplete="current-password" required></label><label>Neues Passwort<input type="password" name="next" autocomplete="new-password" minlength="12" required></label><label>Neues Passwort wiederholen<input type="password" name="confirmation" autocomplete="new-password" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Darstellung</h2></div><div class="theme-toggle settings-theme" aria-label="Farbschema"><button class="theme-option ${theme === 'system' ? 'active' : ''}" data-theme="system" type="button">System</button><button class="theme-option ${theme === 'light' ? 'active' : ''}" data-theme="light" type="button">Hell</button><button class="theme-option ${theme === 'dark' ? 'active' : ''}" data-theme="dark" type="button">Dunkel</button></div><div id="system-message"></div></article>${can('manage_gateway') ? viewInstallationSettings() : ''}</section>${can('manage_gateway') ? '<section class="card" id="host-network" style="margin-top:10px"><h2>Netzwerk · IPv4</h2><p class="note">Netzwerkstatus wird geladen …</p></section>' : ''}`;
|
||||
}
|
||||
|
||||
function bindView(view) {
|
||||
if (view === 'points') document.querySelector('#point-form')?.addEventListener('submit', submitPoint);
|
||||
if (view === 'mappings') document.querySelector('#mapping-form')?.addEventListener('submit', submitMapping);
|
||||
if (view === 'mqtt') { document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration); document.querySelector('#mqtt-mapping-form')?.addEventListener('submit', submitMqttMapping); }
|
||||
if (view === 'trends') document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog);
|
||||
if (view === 'protocols') document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet);
|
||||
if (view === 'system') { document.querySelector('#password-form').addEventListener('submit', submitPassword); document.querySelector('#logout').addEventListener('click', logout); loadAudit(); }
|
||||
if (view === 'overview') return bindDashboard();
|
||||
if (view === 'admin') return bindAdmin();
|
||||
if (view === 'points') {
|
||||
bindPointTabs();
|
||||
bindGatewayStatus();
|
||||
// Keep each panel mounted: tab/theme changes must not discard forms or browse results.
|
||||
if (can('manage_gateway')) bindView('protocols');
|
||||
if (can('manage_integrations')) bindView('mqtt');
|
||||
}
|
||||
if (view === 'points' && can('manage_sources')) {
|
||||
bindPointEditor();
|
||||
bindConfigurationCsv('points', 'point-list-message');
|
||||
}
|
||||
if (view === 'mappings') {
|
||||
bindMappingEditor('mapping', submitMapping);
|
||||
bindMappingBatch();
|
||||
bindConfigurationCsv('mappings', 'mapping-list-message');
|
||||
}
|
||||
if (view === 'mqtt') {
|
||||
bindMqttTopicBrowser();
|
||||
document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration);
|
||||
bindMqttMappingOptions(document.querySelector('#mqtt-mapping-form'));
|
||||
bindMappingEditor('mqtt-mapping', submitMqttMapping);
|
||||
bindConfigurationCsv('mqtt', 'mqtt-mapping-list-message');
|
||||
}
|
||||
if (view === 'trends') {
|
||||
bindTrendViewer();
|
||||
document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog);
|
||||
document.querySelector('#trend-selection-form')?.addEventListener('submit', submitTrendSelection);
|
||||
document.querySelectorAll('[data-delete-selection]').forEach(button => button.addEventListener('click', deleteTrendSelection));
|
||||
}
|
||||
if (view === 'runner') {
|
||||
document.querySelector('#runner-form')?.addEventListener('submit', submitRunnerJob);
|
||||
document.querySelector('#mail-integration-form')?.addEventListener('submit', submitMailIntegration);
|
||||
document.querySelectorAll('[data-test-runner]').forEach(button => button.addEventListener('click', testRunnerJob));
|
||||
document.querySelectorAll('[data-delete-runner]').forEach(button => button.addEventListener('click', deleteRunnerJob));
|
||||
}
|
||||
if (view === 'protocols') {
|
||||
if (can('manage_sources')) { renderBacnetBrowser(); renderOpcUaBrowser(); }
|
||||
document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet);
|
||||
document.querySelector('#bacnet-scan-form')?.addEventListener('submit', submitBacnetScan);
|
||||
document.querySelector('#opcua-form')?.addEventListener('submit', submitOpcUa);
|
||||
document.querySelector('#opcua-browse-form')?.addEventListener('submit', submitOpcUaBrowse);
|
||||
document.querySelector('#modbus-server-form')?.addEventListener('submit', submitModbusServer);
|
||||
document.querySelector('#serial-port-form')?.addEventListener('submit', submitSerialPort);
|
||||
document.querySelector('#modbus-import-form')?.addEventListener('submit', submitModbusImport);
|
||||
document.querySelector('#download-modbus-example')?.addEventListener('click', downloadModbusExample);
|
||||
document.querySelector('#knx-form')?.addEventListener('submit', submitKnx);
|
||||
document.querySelector('#knx-ets-import')?.addEventListener('click', submitKnxEtsImport);
|
||||
document.querySelectorAll('[data-remove-modbus-server]').forEach(button => button.addEventListener('click', removeModbusServer));
|
||||
document.querySelectorAll('[data-remove-serial-port]').forEach(button => button.addEventListener('click', removeSerialPort));
|
||||
}
|
||||
if (view === 'system') {
|
||||
document.querySelector('#password-form')?.addEventListener('submit', submitPassword);
|
||||
bindInstallationSettings();
|
||||
const networkPanel = document.querySelector('#host-network');
|
||||
if (networkPanel) bindHostNetwork(networkPanel);
|
||||
document.querySelector('#content').querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme)));
|
||||
document.querySelector('#user-form')?.addEventListener('submit', submitUser);
|
||||
const userPassword = document.querySelector('#user-form [name=password]');
|
||||
const userConfirmation = document.querySelector('#user-form [name=passwordConfirmation]');
|
||||
if (userConfirmation) userPassword.addEventListener('input', () => {
|
||||
userConfirmation.required = Boolean(userPassword.value);
|
||||
});
|
||||
document.querySelector('#cancel-user-edit')?.addEventListener('click', () => { state.userEditId = null; renderView(); });
|
||||
document.querySelector('#role-form')?.addEventListener('submit', submitRole);
|
||||
document.querySelectorAll('[data-edit-user]').forEach(button => button.addEventListener('click', () => { state.userEditId = button.dataset.editUser; renderView(); }));
|
||||
document.querySelectorAll('[data-toggle-user]').forEach(button => button.addEventListener('click', toggleUser));
|
||||
if (document.querySelector('#audit-content')) loadAudit();
|
||||
}
|
||||
}
|
||||
|
||||
function renderBacnetBrowser() {
|
||||
const card = document.querySelector('#bacnet-form')?.closest('article');
|
||||
if (card) {
|
||||
card.querySelector('.tag').textContent = 'Native Objekte';
|
||||
card.insertAdjacentHTML('beforeend', '<p class="note" id="bacnet-runtime-status">Laufzeitstatus wird gelesen …</p>');
|
||||
api('/api/bacnet/status').then(status => {
|
||||
const target = document.querySelector('#bacnet-runtime-status');
|
||||
if (target) target.textContent = `${status.connected ? 'Nativer BACnet-Dienst verbunden' : 'Nativer BACnet-Dienst nicht verbunden'} · ${status.pendingCommands} offene Befehle · ${status.failedCommands.length} zuletzt abgewiesene/abgelaufene Befehle${status.unsupportedPoints.length ? ` · ${status.unsupportedPoints.length} noch nicht unterstützte Objekte` : ''}`;
|
||||
}).catch(error => errorTarget('bacnet-runtime-status', error.message));
|
||||
}
|
||||
const c = state.configuration;
|
||||
document.querySelector('#bacnet-browser').insertAdjacentHTML('beforeend', `<article class="card bacnet-search"><div class="card-head"><h2>BACnet/IP-Browser</h2></div><form id="bacnet-scan-form" class="form"><div class="row"><label>Direkte Ziel-IP (optional)<input name="targetAddress" placeholder="leer = Broadcast auf der BACnet-Schnittstelle"></label><label>UDP-Port<input name="targetPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label></div><div class="row"><label>Netzwerkkarte<select name="interface" required>${bacnetInterfaceOptions(c.bacnet.interface)}</select></label><label>Antwortfenster (Sekunden)<input name="timeoutSeconds" type="number" min="1" max="30" value="5"></label></div><p class="note">Auf der konfigurierten BACnet-Netzwerkkarte sucht der native Dienst über seinen UDP-Port ${c.bacnet.ipPort}. Für Geräte in einem anderen Subnetz eine direkte Ziel-IP oder einen BBMD verwenden.</p><div class="buttons"><button class="btn primary">BACnet-Geräte suchen</button></div><div id="bacnet-scan-message"></div></form></article><aside class="card bacnet-devices"><div class="card-head"><h2 id="bacnet-device-heading">Gefundene Geräte</h2><button id="bacnet-back-to-devices" class="btn" type="button" hidden>Geräteliste öffnen</button></div><div id="bacnet-scan-results" class="bacnet-device-scroll" tabindex="0" role="region" aria-labelledby="bacnet-device-heading"><div class="empty">Noch keine Suche gestartet.</div></div><section id="bacnet-object-panel" class="bacnet-object-panel" hidden></section></aside>`);
|
||||
}
|
||||
|
||||
function renderOpcUaBrowser() {
|
||||
document.querySelector('#opcua-browser').insertAdjacentHTML('beforeend', `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>OPC-UA-Browser</h2></div><form id="opcua-browse-form" class="form"><label>Endpunkt<input name="endpointUrl" placeholder="opc.tcp://192.168.10.10:4840" required></label><div class="row"><label>Sicherheit<select name="useSecurity"><option value="true">Gesicherter Kanal erforderlich</option><option value="false">Ohne Kanalsicherheit</option></select></label><label>Start-NodeId (optional)<input name="nodeId" placeholder="leer = ObjectsFolder"></label></div><div class="row three"><label>Anmeldung<select name="authenticationMode"><option value="Username">Benutzer / Passwort</option><option value="Anonymous">Anonym</option></select></label><label>Benutzer<input name="username" autocomplete="off"></label><label>Passwort<input name="password" type="password" autocomplete="off"></label></div><label class="switch"><input name="acceptUntrusted" type="checkbox"> Unbekanntes Serverzertifikat für diese Abfrage akzeptieren</label><p class="note">Gültigkeit und Zertifikatsangaben werden weiterhin geprüft. Gateway-Server: Web-Benutzer verwenden; Schreiben erfordert „Quellen verwalten“. Anonymer Zugriff ist nur lesend.</p><div class="buttons"><button class="btn primary">Durchsuchen</button><button class="btn" id="opcua-browse-root" type="button">Zur Wurzel</button></div><div id="opcua-browse-message"></div></form></article><article class="card"><div class="card-head"><h2>Gefundene Nodes</h2></div><div id="opcua-browse-results" class="empty">Noch keine Abfrage.</div></article></section>`);
|
||||
document.querySelector('#opcua-browse-root').addEventListener('click', () => { const form = document.querySelector('#opcua-browse-form'); form.elements.nodeId.value = ''; form.requestSubmit(); });
|
||||
const form = document.querySelector('#opcua-browse-form');
|
||||
form.insertAdjacentHTML('afterbegin', `<label>Gespeicherte Verbindung<select name="clientId"><option value="">Neue Verbindung / einmalig browsen</option>${(state.opcuaClients?.clients || []).map(item => `<option value="${item.configuration.id}">${escapeHtml(item.configuration.name)}</option>`).join('')}</select></label><div class="row"><label>Verbindungsname<input name="connectionName" placeholder="GLT Hauptanlage"></label><label>Abonnement-Intervall (ms)<input name="publishingInterval" type="number" min="100" max="60000" value="1000"></label></div><label class="switch"><input name="enabled" type="checkbox" checked> Dauerhafte Verbindung aktiv</label><div id="opcua-client-status" class="note"></div>`);
|
||||
form.querySelector('.buttons').insertAdjacentHTML('beforeend', '<button type="button" class="btn" id="opcua-client-save">Verbindung speichern</button>');
|
||||
const select = form.elements.clientId;
|
||||
select.addEventListener('change', () => {
|
||||
const saved = state.opcuaClients.clients.find(item => item.configuration.id === select.value);
|
||||
form.elements.password.value = ''; form.elements.nodeId.value = '';
|
||||
document.querySelector('#opcua-browse-results').textContent = 'Noch keine Abfrage.';
|
||||
if (!saved) { document.querySelector('#opcua-client-status').textContent = ''; return; }
|
||||
const c = saved.configuration;
|
||||
form.elements.connectionName.value = c.name; form.elements.endpointUrl.value = c.endpointUrl;
|
||||
form.elements.useSecurity.value = String(c.useSecurity); form.elements.authenticationMode.value = c.authenticationMode;
|
||||
form.elements.username.value = c.username || ''; form.elements.publishingInterval.value = c.publishingIntervalMilliseconds;
|
||||
form.elements.acceptUntrusted.checked = c.acceptUntrustedServerCertificate; form.elements.enabled.checked = c.enabled;
|
||||
form.elements.password.placeholder = saved.hasPassword ? 'Gespeichert – leer lassen zum Beibehalten' : '';
|
||||
const status = state.opcuaClients.status.find(item => item.clientId === c.id);
|
||||
document.querySelector('#opcua-client-status').textContent = status ? `${status.state} · ${status.subscribedPoints} abonnierte Punkte` : 'Deaktiviert / startet';
|
||||
});
|
||||
document.querySelector('#opcua-client-save').addEventListener('click', async () => {
|
||||
try {
|
||||
if (!form.reportValidity()) return;
|
||||
const f = new FormData(form);
|
||||
const configuration = { id: select.value || uuid(), name: String(f.get('connectionName')).trim(), endpointUrl: String(f.get('endpointUrl')).trim(), authenticationMode: f.get('authenticationMode'), username: String(f.get('username')).trim(), useSecurity: f.get('useSecurity') === 'true', acceptUntrustedServerCertificate: f.get('acceptUntrusted') === 'on', enabled: f.get('enabled') === 'on', publishingIntervalMilliseconds: Number(f.get('publishingInterval')) };
|
||||
const saved = await api('/api/opcua/clients', { method: 'POST', body: JSON.stringify({ configuration, password: String(f.get('password')) || null }) });
|
||||
await loadData();
|
||||
if (![...select.options].some(option => option.value === saved.configuration.id)) select.add(new Option(saved.configuration.name, saved.configuration.id));
|
||||
select.value = saved.configuration.id; select.dispatchEvent(new Event('change'));
|
||||
errorTarget('opcua-browse-message', 'Gespeichert. Importierte Punkte werden automatisch abonniert.', true);
|
||||
} catch (error) { errorTarget('opcua-browse-message', error.message); }
|
||||
});
|
||||
}
|
||||
|
||||
function bindPointEditor() {
|
||||
const form = document.querySelector('#point-form');
|
||||
if (!form) return;
|
||||
function syncFields() {
|
||||
const external = form.elements.scope.value === 'External';
|
||||
const bacnet = form.elements.protocol.value === 'Bacnet' && form.elements.scope.value !== 'Internal';
|
||||
form.querySelector('[data-point-external]').hidden = !external;
|
||||
form.elements.externalIdentity.disabled = !external;
|
||||
form.elements.externalIdentity.required = external;
|
||||
form.querySelector('[data-point-bacnet]').hidden = !bacnet;
|
||||
form.elements.bacnetObjectKind.disabled = form.elements.bacnetObjectInstance.disabled = !bacnet;
|
||||
form.elements.bacnetObjectKind.required = bacnet && form.elements.scope.value === 'Gateway';
|
||||
}
|
||||
syncFields();
|
||||
form.elements.protocol.addEventListener('change', syncFields);
|
||||
form.elements.scope.addEventListener('change', syncFields);
|
||||
form.addEventListener('submit', submitPoint);
|
||||
document.querySelectorAll('[data-edit-point]').forEach(button => button.addEventListener('click', () => {
|
||||
state.pointEditId = button.dataset.editPoint;
|
||||
renderView();
|
||||
document.querySelector('#point-form input[name="displayName"]')?.focus();
|
||||
}));
|
||||
document.querySelector('#cancel-point-edit')?.addEventListener('click', () => {
|
||||
state.pointEditId = null;
|
||||
renderView();
|
||||
});
|
||||
document.querySelectorAll('[data-delete-point]').forEach(button => button.addEventListener('click', () => deletePoint(button)));
|
||||
}
|
||||
|
||||
async function submitPoint(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const id = state.pointEditId;
|
||||
const submit = event.currentTarget.querySelector('button[type="submit"]');
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const address = JSON.parse(form.get('address'));
|
||||
const scope = form.get('scope');
|
||||
const objectInstance = form.get('bacnetObjectInstance');
|
||||
await api('/api/points', { method: 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: true, writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) });
|
||||
await api(id ? `/api/points/${encodeURIComponent(id)}` : '/api/points', { method: id ? 'PUT' : 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: form.get('readable') === 'on', writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) });
|
||||
state.pointEditId = null;
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('point-message', error.message); }
|
||||
errorTarget('point-list-message', id ? 'Änderungen gespeichert.' : 'Datenpunkt angelegt.', true);
|
||||
} catch (error) {
|
||||
errorTarget('point-message', error instanceof SyntaxError ? 'Die Adresse enthält ungültiges JSON.' : error.message);
|
||||
} finally { submit.disabled = false; }
|
||||
}
|
||||
|
||||
async function deletePoint(button) {
|
||||
const id = button.dataset.deletePoint;
|
||||
const point = state.points.find(item => item.id === id);
|
||||
if (!point) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const path = `/api/points/${encodeURIComponent(id)}`;
|
||||
const usage = await api(path + '/dependencies');
|
||||
const effects = [
|
||||
usage.mappings && `${usage.mappings} Mapping(s) werden entfernt.`,
|
||||
usage.mqttMappings && `${usage.mqttMappings} MQTT-Zuordnung(en) werden entfernt.`,
|
||||
usage.alarms && `${usage.alarms} Alarmregel(n) werden entfernt.`,
|
||||
usage.trendLogs && `${usage.trendLogs} Trendlog(s) werden gestoppt. Aufzeichnungen bleiben abrufbar.`
|
||||
].filter(Boolean);
|
||||
if (!window.confirm([`Datenpunkt „${point.displayName}“ löschen?`, ...effects].join('\n'))) return;
|
||||
await api(path + '?confirmation=' + encodeURIComponent(usage.confirmation), { method: 'DELETE' });
|
||||
if (state.pointEditId === id) state.pointEditId = null;
|
||||
await loadData(); renderView();
|
||||
errorTarget('point-list-message', 'Datenpunkt gelöscht.', true);
|
||||
} catch (error) {
|
||||
errorTarget('point-list-message', error.message);
|
||||
} finally { button.disabled = false; }
|
||||
}
|
||||
|
||||
function bindMappingEditor(kind, submit) {
|
||||
const mqtt = kind === 'mqtt-mapping';
|
||||
const editKey = mqtt ? 'mqttMappingEditId' : 'mappingEditId';
|
||||
const endpoint = mqtt ? '/api/mqtt/mappings' : '/api/mappings';
|
||||
const form = document.querySelector(`#${kind}-form`);
|
||||
form?.addEventListener('submit', submit);
|
||||
document.querySelectorAll(`[data-edit-${kind}]`).forEach(button => button.addEventListener('click', () => {
|
||||
state[editKey] = button.getAttribute(`data-edit-${kind}`);
|
||||
renderView();
|
||||
document.querySelector(`#${kind}-form select`)?.focus();
|
||||
}));
|
||||
document.querySelector(`#cancel-${kind}-edit`)?.addEventListener('click', () => {
|
||||
state[editKey] = null;
|
||||
renderView();
|
||||
});
|
||||
document.querySelectorAll(`[data-delete-${kind}]`).forEach(button => button.addEventListener('click', async () => {
|
||||
const id = button.getAttribute(`data-delete-${kind}`);
|
||||
if (!window.confirm(mqtt ? 'MQTT-Verknüpfung löschen?' : 'Verknüpfung zwischen diesen Datenpunkten löschen?')) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await api(`${endpoint}/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
if (state[editKey] === id) state[editKey] = null;
|
||||
await loadData();
|
||||
renderView();
|
||||
errorTarget(`${kind}-list-message`, 'Verknüpfung gelöscht.', true);
|
||||
} catch (error) {
|
||||
errorTarget(`${kind}-list-message`, error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
async function submitMapping(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const id = state.mappingEditId;
|
||||
const submit = event.currentTarget.querySelector('button[type="submit"], button:not([type])');
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const priority = form.get('bacnetPriority'); const transform = JSON.parse(form.get('transform'));
|
||||
const response = await api('/api/mappings', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'), direction: form.get('direction'), enabled: true, bacnetPriority: priority ? Number(priority) : null, acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform }) });
|
||||
const priority = form.get('bacnetPriority');
|
||||
const transform = JSON.parse(form.get('transform'));
|
||||
const response = await api(id ? `/api/mappings/${encodeURIComponent(id)}` : '/api/mappings', {
|
||||
method: id ? 'PUT' : 'POST',
|
||||
body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'),
|
||||
direction: form.get('direction'), enabled: form.get('enabled') === 'on', bacnetPriority: priority ? Number(priority) : null,
|
||||
acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform })
|
||||
});
|
||||
state.mappingEditId = null;
|
||||
await loadData(); renderView();
|
||||
if (response.warnings?.length) window.alert(response.warnings.join('\n'));
|
||||
} catch (error) { errorTarget('mapping-message', error.message); }
|
||||
errorTarget('mapping-list-message', response.warnings?.length ? response.warnings.join(' ') : 'Mapping gespeichert.', !response.warnings?.length);
|
||||
} catch (error) {
|
||||
errorTarget('mapping-message', error instanceof SyntaxError ? 'Die Transformation enthält ungültiges JSON.' : error.message);
|
||||
} finally { submit.disabled = false; }
|
||||
}
|
||||
|
||||
async function submitMqttConfiguration(event) {
|
||||
@@ -179,46 +604,292 @@ async function submitMqttConfiguration(event) {
|
||||
try {
|
||||
const password = String(form.get('password') || '');
|
||||
await api('/api/mqtt/configuration', { method: 'PUT', body: JSON.stringify({ configuration: { enabled: form.get('enabled') === 'on', host: String(form.get('host') || '').trim(), port: Number(form.get('port')), useTls: form.get('useTls') === 'on', ignoreCertificateErrors, clientId: String(form.get('clientId') || '').trim(), username: String(form.get('username') || '').trim() || null }, password: password || null, clearPassword: form.get('clearPassword') === 'on' }) });
|
||||
state.mqttBrowser = null;
|
||||
await loadData(); renderView(); errorTarget('mqtt-configuration-message', 'Gespeichert; die Verbindung wird neu aufgebaut.', true);
|
||||
} catch (error) { errorTarget('mqtt-configuration-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitMqttMapping(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const id = state.mqttMappingEditId;
|
||||
const submit = event.currentTarget.querySelector('button[type="submit"]');
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const format = form.get('format');
|
||||
await api('/api/mqtt/mappings', { method: 'POST', body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'), qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on', projectYear: format === 'SeMonitoring' ? Number(form.get('projectYear')) : null, projectNumber: format === 'SeMonitoring' ? form.get('projectNumber') : null, ispNumber: format === 'SeMonitoring' ? form.get('ispNumber') : null, seCategory: format === 'SeMonitoring' ? form.get('seCategory') : null, topicName: format === 'SeMonitoring' ? form.get('topicName') : null, jsonTopic: format === 'Json' ? form.get('jsonTopic') : null, jsonProperty: format === 'Json' ? form.get('jsonProperty') : null }) });
|
||||
const format = form.has('seMonitoring') ? 'SeMonitoring' : form.get('freeFormat');
|
||||
const monitoring = format === 'SeMonitoring';
|
||||
await api(id ? `/api/mqtt/mappings/${encodeURIComponent(id)}` : '/api/mqtt/mappings', {
|
||||
method: id ? 'PUT' : 'POST',
|
||||
body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'),
|
||||
qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on',
|
||||
...(monitoring ? mqttSiteFromForm(form) : {}), seCategory: monitoring ? form.get('seCategory') : null,
|
||||
topicName: monitoring ? form.get('topicName') : null, jsonTopic: monitoring ? null : form.get('jsonTopic'),
|
||||
jsonProperty: format === 'Json' ? form.get('jsonProperty') : null })
|
||||
});
|
||||
state.mqttMappingEditId = null;
|
||||
await loadData(); renderView();
|
||||
errorTarget('mqtt-mapping-list-message', 'MQTT-Mapping gespeichert.', true);
|
||||
} catch (error) { errorTarget('mqtt-mapping-message', error.message); }
|
||||
finally { submit.disabled = false; }
|
||||
}
|
||||
|
||||
async function submitTrendLog(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true }) });
|
||||
await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true, isPublic: form.get('isPublic') === 'on' }) });
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('trend-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitTrendSelection(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
await api('/api/trend-selections', { method: 'POST', body: JSON.stringify({ name: form.get('name'), description: String(form.get('description') || '').trim() || null, shared: form.get('shared') === 'on', trendLogIds: form.getAll('trendLogIds') }) });
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('trend-selection-message', error.message); }
|
||||
}
|
||||
|
||||
async function deleteTrendSelection(event) {
|
||||
const id = event.currentTarget.dataset.deleteSelection;
|
||||
if (!window.confirm('Diese gespeicherte Trend-Gruppe löschen?')) return;
|
||||
try { await api(`/api/trend-selections/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); }
|
||||
catch (error) { errorTarget('trend-selection-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitRunnerJob(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
await api('/api/runner/jobs', { method: 'POST', body: JSON.stringify({ name: form.get('name'), selectionId: form.get('selectionId'), time: form.get('time'), rangeHours: Number(form.get('rangeHours')), delimiter: form.get('delimiter'), enabled: form.get('enabled') === 'on', mailEnabled: form.get('mailEnabled') === 'on', mailTo: String(form.get('mailTo') || '').trim() || null, mailSubject: String(form.get('mailSubject') || '').trim() || null, mailMessage: String(form.get('mailMessage') || '').trim() || null }) });
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('runner-message', error.message); }
|
||||
}
|
||||
|
||||
async function testRunnerJob(event) {
|
||||
const button = event.currentTarget;
|
||||
try {
|
||||
const result = await api(`/api/runner/jobs/${encodeURIComponent(button.dataset.testRunner)}/test`, { method: 'POST' });
|
||||
await loadData(); renderView();
|
||||
window.alert(result.success ? `CSV erzeugt: ${result.filePath}${result.filePath && state.runnerJobs.find(job => job.id === button.dataset.testRunner)?.mailEnabled ? '\nMailversand abgeschlossen.' : ''}` : `CSV-Runner fehlgeschlagen: ${result.error}`);
|
||||
} catch (error) { window.alert(`CSV-Runner fehlgeschlagen: ${error.message}`); }
|
||||
}
|
||||
|
||||
async function deleteRunnerJob(event) {
|
||||
const id = event.currentTarget.dataset.deleteRunner;
|
||||
if (!window.confirm('Diesen CSV-Runner-Job löschen?')) return;
|
||||
try { await api(`/api/runner/jobs/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); }
|
||||
catch (error) { window.alert(error.message); }
|
||||
}
|
||||
|
||||
async function submitMailIntegration(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
const apiKey = String(form.get('apiKey') || '').trim(); const clearApiKey = form.get('clearApiKey') === 'on';
|
||||
if (!apiKey && !clearApiKey) throw new Error('Bitte einen neuen API-Key eintragen oder das Löschen auswählen.');
|
||||
await api('/api/integrations/mail', { method: 'PUT', body: JSON.stringify({ apiKey: apiKey || null, clearApiKey }) });
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('mail-integration-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitBacnet(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
|
||||
try {
|
||||
c.deviceInstance = Number(form.get('deviceInstance')); c.deviceName = `SEIU-Gateway-${c.deviceInstance}`;
|
||||
c.bacnet.interface = form.get('interface'); c.bacnet.ipPort = Number(form.get('ipPort')); c.bacnet.bbmdMode = form.get('bbmdMode'); c.bacnet.bbmdAddress = form.get('bbmdAddress') || null; c.bacnet.foreignDeviceTtlSeconds = form.get('ttl') ? Number(form.get('ttl')) : null;
|
||||
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Aktivierung erfolgt beim nächsten Adapter-Start.', true);
|
||||
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Der native Dienst übernimmt die Änderung automatisch; Netzwerkänderungen lösen einen kurzen Neustart aus. Abweichende Ports müssen auch in der NixOS-Firewall freigegeben sein.', true);
|
||||
} catch (error) { errorTarget('bacnet-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitBacnetScan(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
const devices = await api('/api/bacnet/scan', { method: 'POST', body: JSON.stringify({ interface: String(form.get('interface') || '').trim() || null, targetAddress: String(form.get('targetAddress') || '').trim() || null, targetPort: Number(form.get('targetPort')), timeoutSeconds: Number(form.get('timeoutSeconds')) }) });
|
||||
renderBacnetDevices(devices, form.get('interface'));
|
||||
errorTarget('bacnet-scan-message', `${devices.length} Gerät(e) gefunden.`, true);
|
||||
} catch (error) { errorTarget('bacnet-scan-message', error.message); }
|
||||
}
|
||||
|
||||
async function saveGatewayConfiguration(messageTarget, message) {
|
||||
try {
|
||||
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(state.configuration) });
|
||||
await loadData(); renderView(); errorTarget(messageTarget, message, true);
|
||||
} catch (error) { errorTarget(messageTarget, error.message); }
|
||||
}
|
||||
|
||||
async function submitOpcUa(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
|
||||
c.opcUa.port = Number(form.get('port')); c.opcUa.clientEnabled = form.get('clientEnabled') === 'on'; c.opcUa.serverEnabled = form.get('serverEnabled') === 'on'; c.opcUa.allowAnonymous = form.get('allowAnonymous') === 'on';
|
||||
await saveGatewayConfiguration('opcua-message', 'Gespeichert. Der OPC-UA-Dienst übernimmt die Änderung automatisch.');
|
||||
}
|
||||
|
||||
async function submitOpcUaBrowse(event) {
|
||||
event.preventDefault(); const element = event.currentTarget; const form = new FormData(element);
|
||||
const submit = element.querySelector('button[type="submit"], button:not([type])'); submit.disabled = true;
|
||||
errorTarget('opcua-browse-message', 'Verbindung wird aufgebaut …', true);
|
||||
try {
|
||||
const clientId = form.get('clientId') || null;
|
||||
if (clientId) {
|
||||
const saved = state.opcuaClients.clients.find(item => item.configuration.id === clientId)?.configuration;
|
||||
if (!saved || String(form.get('endpointUrl')).trim() !== saved.endpointUrl || form.get('authenticationMode') !== saved.authenticationMode || String(form.get('username')).trim() !== (saved.username || '') || (form.get('useSecurity') === 'true') !== saved.useSecurity || (form.get('acceptUntrusted') === 'on') !== saved.acceptUntrustedServerCertificate || form.get('password'))
|
||||
throw new Error('Geänderte Verbindungsdaten bitte zuerst speichern. Browsen verwendet die gespeicherten Zugangsdaten.');
|
||||
}
|
||||
const items = await api('/api/opcua/browse', { method: 'POST', body: JSON.stringify({ clientId, endpointUrl: String(form.get('endpointUrl')).trim(), nodeId: String(form.get('nodeId') || '').trim() || null, useSecurity: form.get('useSecurity') === 'true', authenticationMode: form.get('authenticationMode'), username: String(form.get('username') || '').trim(), password: String(form.get('password') || ''), acceptUntrustedServerCertificate: form.get('acceptUntrusted') === 'on' }) });
|
||||
const target = document.querySelector('#opcua-browse-results');
|
||||
target.innerHTML = items.length ? `<table><thead><tr><th>Name</th><th>Klasse</th><th>NodeId</th><th>Wert</th><th></th></tr></thead><tbody>${items.map(item => `<tr><td>${escapeHtml(item.displayName)}</td><td>${escapeHtml(item.nodeClass)}</td><td><code>${escapeHtml(item.nodeId)}</code></td><td>${item.value === null || item.value === undefined ? '—' : escapeHtml(typeof item.value === 'string' ? item.value : JSON.stringify(item.value))}</td><td>${item.hasChildren ? `<button class="btn" type="button" data-opcua-node="${escapeHtml(item.nodeId)}">Öffnen</button>` : ''}</td></tr>`).join('')}</tbody></table>` : '<div class="empty">Keine untergeordneten Nodes.</div>';
|
||||
target.querySelectorAll('[data-opcua-node]').forEach(button => button.addEventListener('click', () => { element.elements.nodeId.value = button.dataset.opcuaNode; element.requestSubmit(); }));
|
||||
const importable = items.filter(item => item.stableNodeId && item.valueType && item.readable);
|
||||
async function importPoints(selected, button) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
const imported = await api('/api/opcua/import', { method: 'POST', body: JSON.stringify({ clientId, points: selected.map(item => ({ nodeId: item.stableNodeId, displayName: item.displayName, valueType: item.valueType, readable: item.readable, writable: item.writable })) }) });
|
||||
await loadData(); errorTarget('opcua-browse-message', `${imported.length} Punkte übernommen. Bereits vorhandene Punkte übersprungen.`, true);
|
||||
} catch (error) { errorTarget('opcua-browse-message', error.message); }
|
||||
finally { button.disabled = false; }
|
||||
}
|
||||
if (clientId && importable.length) {
|
||||
const all = document.createElement('button'); all.type = 'button'; all.className = 'btn primary'; all.textContent = 'Alle lesbaren Skalare dieser Ebene hinzufügen';
|
||||
target.prepend(all); all.addEventListener('click', () => importPoints(importable, all));
|
||||
target.querySelectorAll('tbody tr').forEach((row, index) => {
|
||||
const item = items[index]; if (!importable.includes(item)) return;
|
||||
const add = document.createElement('button'); add.type = 'button'; add.className = 'btn'; add.textContent = 'Hinzufügen';
|
||||
row.lastElementChild.append(add); add.addEventListener('click', () => importPoints([item], add));
|
||||
});
|
||||
}
|
||||
errorTarget('opcua-browse-message', `${items.length} Nodes gelesen.${clientId ? '' : ' Verbindung speichern, um Punkte dauerhaft zu übernehmen.'}`, true);
|
||||
} catch (error) { errorTarget('opcua-browse-message', error.message); }
|
||||
finally { submit.disabled = false; }
|
||||
}
|
||||
|
||||
async function submitModbusServer(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
|
||||
c.modbusServers = c.modbusServers || [];
|
||||
c.modbusServers.push({ id: uuid(), name: String(form.get('name')).trim(), bindAddress: String(form.get('bindAddress')).trim(), port: Number(form.get('port')), unitId: Number(form.get('unitId')), firstHoldingRegister: Number(form.get('firstHoldingRegister')), holdingRegisterCount: Number(form.get('holdingRegisterCount')), allowedClientIps: String(form.get('allowedClientIps') || '').split(/[\s,;]+/).map(value => value.trim()).filter(Boolean) });
|
||||
await saveGatewayConfiguration('modbus-server-message', 'TCP-Server gespeichert und aktiviert.');
|
||||
}
|
||||
|
||||
async function removeModbusServer(event) {
|
||||
const id = event.currentTarget.dataset.removeModbusServer;
|
||||
if (!window.confirm('Diese Modbus-TCP-Serverinstanz entfernen?')) return;
|
||||
state.configuration.modbusServers = (state.configuration.modbusServers || []).filter(server => server.id !== id);
|
||||
await saveGatewayConfiguration('modbus-server-message', 'TCP-Server entfernt.');
|
||||
}
|
||||
|
||||
async function submitSerialPort(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
|
||||
c.serialPorts = c.serialPorts || [];
|
||||
c.serialPorts.push({ id: uuid(), alias: String(form.get('alias')).trim(), devicePath: String(form.get('devicePath')).trim(), baudRate: Number(form.get('baudRate')), parity: form.get('parity'), dataBits: Number(form.get('dataBits')), stopBits: Number(form.get('stopBits')) });
|
||||
await saveGatewayConfiguration('serial-port-message', 'Serieller Port gespeichert.');
|
||||
}
|
||||
|
||||
async function removeSerialPort(event) {
|
||||
const id = event.currentTarget.dataset.removeSerialPort;
|
||||
if (!window.confirm('Diesen COM-/USB-Alias entfernen?')) return;
|
||||
state.configuration.serialPorts = (state.configuration.serialPorts || []).filter(port => port.id !== id);
|
||||
await saveGatewayConfiguration('serial-port-message', 'Serieller Port entfernt.');
|
||||
}
|
||||
|
||||
async function submitKnx(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
|
||||
c.knx.enabled = form.get('enabled') === 'on'; c.knx.secure = form.get('secure') === 'on'; c.knx.transport = form.get('transport'); c.knx.serialPortAlias = String(form.get('serialPortAlias') || '').trim() || null;
|
||||
await saveGatewayConfiguration('knx-message', 'KNX-Konfiguration gespeichert.');
|
||||
}
|
||||
|
||||
async function submitKnxEtsImport() {
|
||||
const file = document.querySelector('#knx-ets-file')?.files?.[0];
|
||||
try {
|
||||
if (!file) throw new Error('Bitte zuerst eine ETS-Projektdatei oder XML-Export auswählen.');
|
||||
const bytes = new Uint8Array(await file.arrayBuffer()); let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
const result = await api('/api/imports/knx-ets', { method: 'POST', body: JSON.stringify({ fileName: file.name, contentBase64: btoa(binary) }) });
|
||||
await loadData(); errorTarget('knx-import-message', `${result.imported} Gruppenadresse(n) importiert${result.errors?.length ? `, ${result.errors.length} übersprungen.` : '.'}`, true);
|
||||
} catch (error) { errorTarget('knx-import-message', error.message); }
|
||||
}
|
||||
|
||||
async function downloadModbusExample() {
|
||||
try {
|
||||
const response = await fetch('/api/imports/modbus-example.csv', { headers: { Authorization: `Bearer ${state.token}` } });
|
||||
if (!response.ok) throw new Error('Beispieldatei konnte nicht geladen werden.');
|
||||
const href = URL.createObjectURL(await response.blob()); const link = document.createElement('a'); link.href = href; link.download = 'seiugw-modbus-beispiel.csv'; link.click(); URL.revokeObjectURL(href);
|
||||
} catch (error) { errorTarget('modbus-import-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitModbusImport(event) {
|
||||
event.preventDefault(); const file = new FormData(event.currentTarget).get('csvFile');
|
||||
try {
|
||||
if (!(file instanceof File) || !file.size) throw new Error('Bitte eine CSV-Datei auswählen.');
|
||||
const result = await api('/api/imports/modbus-csv', { method: 'POST', body: JSON.stringify({ csv: await file.text() }) });
|
||||
await loadData(); errorTarget('modbus-import-message', `${result.imported} Datenpunkte importiert${result.errors?.length ? `, ${result.errors.length} Zeile(n) übersprungen.` : '.'}`, true);
|
||||
} catch (error) { errorTarget('modbus-import-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitPassword(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try { await api('/api/auth/password', { method: 'POST', body: JSON.stringify({ currentPassword: form.get('current'), newPassword: form.get('next') }) }); sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); }
|
||||
const newPassword = form.get('next');
|
||||
const newPasswordConfirmation = form.get('confirmation');
|
||||
if (newPassword !== newPasswordConfirmation)
|
||||
return errorTarget('password-message', 'Die neuen Passwörter müssen übereinstimmen.');
|
||||
try { await api('/api/auth/password', { method: 'POST', body: JSON.stringify({ currentPassword: form.get('current'), newPassword, newPasswordConfirmation }) }); sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); }
|
||||
catch (error) { errorTarget('password-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitUser(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
const payload = { username: form.get('username'), displayName: form.get('displayName'), email: String(form.get('email') || '').trim() || null, role: form.get('role'), active: form.get('active') === 'on' };
|
||||
const password = String(form.get('password') || '');
|
||||
if (state.userEditId) {
|
||||
if (password) {
|
||||
const confirmation = form.get('passwordConfirmation');
|
||||
if (password !== confirmation) throw new Error('Die neuen Passwörter müssen übereinstimmen.');
|
||||
payload.password = password;
|
||||
payload.passwordConfirmation = confirmation;
|
||||
}
|
||||
await api(`/api/users/${encodeURIComponent(state.userEditId)}`, { method: 'PATCH', body: JSON.stringify(payload) });
|
||||
state.userEditId = null;
|
||||
} else {
|
||||
await api('/api/users', { method: 'POST', body: JSON.stringify({ ...payload, password }) });
|
||||
}
|
||||
await loadData(); renderView(); errorTarget('user-message', 'Benutzer angelegt.', true);
|
||||
} catch (error) { errorTarget('user-message', error.message); }
|
||||
}
|
||||
|
||||
async function toggleUser(event) {
|
||||
const button = event.currentTarget;
|
||||
const active = button.dataset.active !== 'true';
|
||||
if (!window.confirm(active ? 'Konto aktivieren?' : 'Konto deaktivieren?')) return;
|
||||
try { await api(`/api/users/${encodeURIComponent(button.dataset.toggleUser)}`, { method: 'PATCH', body: JSON.stringify({ active }) }); await loadData(); renderView(); }
|
||||
catch (error) { errorTarget('user-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitRole(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
try {
|
||||
const permissions = String(form.get('permissions') || '').split(/[\s,;]+/).map(value => value.trim()).filter(Boolean);
|
||||
await api('/api/roles', { method: 'POST', body: JSON.stringify({ name: form.get('name'), label: form.get('label'), permissions }) });
|
||||
await loadData(); renderView(); errorTarget('role-message', 'Rolle gespeichert.', true);
|
||||
} catch (error) { errorTarget('role-message', error.message); }
|
||||
}
|
||||
|
||||
async function loadAudit() {
|
||||
try { const entries = await api('/api/audit?limit=8'); const target = document.querySelector('#audit-content'); target.innerHTML = entries.length ? `<table><tbody>${entries.map(entry => `<tr><td>${escapeHtml(new Date(entry.occurredAtUtc).toLocaleString())}</td><td><span class="tag gray">${escapeHtml(entry.category)}</span></td><td>${escapeHtml(entry.message)}</td></tr>`).join('')}</tbody></table>` : 'Noch keine Ereignisse.'; }
|
||||
catch (error) { errorTarget('audit-content', error.message); }
|
||||
}
|
||||
|
||||
async function logout() { await api('/api/auth/logout', { method: 'POST' }); sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); }
|
||||
boot().catch(error => { app.innerHTML = `<section class="auth"><div class="auth-card"><h1>Startfehler</h1><p>${escapeHtml(error.message)}</p></div></section>`; });
|
||||
async function setTheme(theme) {
|
||||
if (!['system', 'light', 'dark'].includes(theme)) return;
|
||||
applyTheme(theme);
|
||||
state.preferences = { ...(state.preferences || {}), theme };
|
||||
try {
|
||||
state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ theme }) });
|
||||
errorTarget('theme-message', 'Darstellung gespeichert.', true);
|
||||
errorTarget('system-message', 'Darstellung gespeichert.', true);
|
||||
} catch (error) {
|
||||
errorTarget('theme-message', `Nur lokal geändert: ${error.message}`);
|
||||
errorTarget('system-message', `Farbschema wurde nur lokal gesetzt: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() { await api('/api/auth/logout', { method: 'POST' }); sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); }
|
||||
boot().catch(error => {
|
||||
if (!state.token && error.message === 'Sitzung abgelaufen.') return renderLogin();
|
||||
app.innerHTML = `<section class="auth"><div class="auth-card"><h1>Startfehler</h1><p>${escapeHtml(error.message)}</p></div></section>`;
|
||||
});
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.8 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
@@ -0,0 +1,119 @@
|
||||
let activeBacnetDevice;
|
||||
|
||||
function showBacnetDevices() {
|
||||
const heading = document.querySelector('#bacnet-device-heading');
|
||||
if (!heading) return;
|
||||
heading.textContent = 'Gefundene Geräte';
|
||||
document.querySelector('#bacnet-back-to-devices').hidden = true;
|
||||
document.querySelector('#bacnet-object-panel').hidden = true;
|
||||
document.querySelector('#bacnet-scan-results').hidden = false;
|
||||
}
|
||||
|
||||
function renderBacnetDevices(devices, networkInterface) {
|
||||
activeBacnetDevice = null;
|
||||
showBacnetDevices();
|
||||
const list = document.querySelector('#bacnet-scan-results');
|
||||
list.innerHTML = devices.length ? `<table><thead><tr><th>Gerät</th><th>Instanz</th><th>Adresse</th><th>Vendor</th><th></th></tr></thead>
|
||||
<tbody>${devices.map(device => `<tr>
|
||||
<td>${escapeHtml(device.deviceName || '—')}</td><td>${device.deviceInstance}</td>
|
||||
<td><code>${escapeHtml(device.address)}:${device.port}</code>${device.network ? `<div class="note">BACnet-Netz ${device.network} · ${escapeHtml(device.mac || '—')}</div>` : ''}</td>
|
||||
<td>${device.vendorId ?? '—'}</td>
|
||||
<td><button type="button" class="btn" data-bacnet-device="${device.deviceInstance}">Objekte lesen</button></td>
|
||||
</tr>`).join('')}</tbody></table>` : '<div class="empty">Keine BACnet-Geräte gefunden.</div>';
|
||||
list.querySelectorAll('[data-bacnet-device]').forEach((button, index) => button.addEventListener('click', () =>
|
||||
openBacnetObjects(button, { ...devices[index], interface: networkInterface })));
|
||||
}
|
||||
|
||||
async function openBacnetObjects(button, device) {
|
||||
if (!device) return;
|
||||
const panel = document.querySelector('#bacnet-object-panel');
|
||||
const selected = { device, rows: [], offset: 0, total: 0 };
|
||||
activeBacnetDevice = selected;
|
||||
button.disabled = true;
|
||||
errorTarget('bacnet-scan-message', 'BACnet-Objekte werden gelesen …', true);
|
||||
try {
|
||||
const result = await requestBacnetObjectPage(selected);
|
||||
if (!panel.isConnected || selected !== activeBacnetDevice) return;
|
||||
document.querySelector('#bacnet-scan-results').hidden = true;
|
||||
document.querySelector('#bacnet-device-heading').textContent = result.deviceName || device.deviceName || `BACnet-Gerät ${device.deviceInstance}`;
|
||||
const back = document.querySelector('#bacnet-back-to-devices');
|
||||
back.hidden = false;
|
||||
back.onclick = () => { activeBacnetDevice = null; showBacnetDevices(); };
|
||||
panel.hidden = false;
|
||||
panel.innerHTML = `<div class="note">Device-Instanz ${device.deviceInstance} · ${escapeHtml(device.address)}</div>
|
||||
<div class="buttons">
|
||||
<button class="btn primary" type="button" id="bacnet-import-selected" disabled>Auswahl anlegen</button>
|
||||
<button class="btn" type="button" id="bacnet-import-all">Alle importierbaren anlegen</button>
|
||||
<button class="btn" type="button" id="bacnet-load-more" hidden>Weitere Objekte laden</button>
|
||||
</div>
|
||||
<div id="bacnet-object-message" role="status"></div>
|
||||
<div id="bacnet-object-results" class="bacnet-device-scroll" tabindex="0" role="region" aria-label="BACnet-Objekte">
|
||||
<table><thead><tr><th></th><th>Typ / Instanz</th><th>Objektname</th><th>Beschreibung</th><th>Aktueller Wert</th></tr></thead><tbody></tbody></table>
|
||||
</div>`;
|
||||
panel.querySelector('#bacnet-import-selected').onclick = () => importBacnetObjects(panel, selected, false);
|
||||
panel.querySelector('#bacnet-import-all').onclick = () => importBacnetObjects(panel, selected, true);
|
||||
panel.querySelector('#bacnet-load-more').onclick = async event => {
|
||||
const more = event.currentTarget;
|
||||
more.disabled = true;
|
||||
try {
|
||||
await requestBacnetObjectPage(selected);
|
||||
if (selected === activeBacnetDevice) paintBacnetObjects(panel, selected);
|
||||
} catch (error) { errorTarget('bacnet-object-message', error.message); }
|
||||
finally { more.disabled = false; }
|
||||
};
|
||||
panel.addEventListener('change', syncBacnetImportSelection);
|
||||
paintBacnetObjects(panel, selected);
|
||||
errorTarget('bacnet-scan-message', `${selected.total} Objekt(e) gefunden.`, true);
|
||||
} catch (error) {
|
||||
errorTarget('bacnet-scan-message', error.message);
|
||||
} finally { button.disabled = false; }
|
||||
}
|
||||
|
||||
function syncBacnetImportSelection(event) {
|
||||
const panel = event.currentTarget;
|
||||
panel.querySelector('#bacnet-import-selected').disabled = !panel.querySelector('[data-bacnet-object]:checked');
|
||||
}
|
||||
|
||||
async function requestBacnetObjectPage(selection) {
|
||||
const result = await api('/api/bacnet/objects', { method:'POST',
|
||||
body:JSON.stringify({device:selection.device, offset:selection.offset, limit:100}) });
|
||||
selection.rows.push(...result.objects);
|
||||
selection.total = result.total;
|
||||
selection.offset = result.nextOffset;
|
||||
return result;
|
||||
}
|
||||
|
||||
function paintBacnetObjects(panel, selection) {
|
||||
const selectedIds = new Set([...panel.querySelectorAll('[data-bacnet-object]:checked')].map(input => input.value));
|
||||
panel.querySelector('tbody').innerHTML = selection.rows.map(object => {
|
||||
const id = `${object.objectTypeCode}:${object.objectInstance}`;
|
||||
const label = object.name || `${object.objectType} ${object.objectInstance}`;
|
||||
const pick = object.pointId ? '<span class="tag">angelegt</span>' : object.valueType
|
||||
? `<input type="checkbox" aria-label="${escapeHtml(label)} auswählen" data-bacnet-object value="${id}" ${selectedIds.has(id) ? 'checked' : ''}>` : '—';
|
||||
return `<tr><td>${pick}</td><td>${escapeHtml(object.objectType)} · ${object.objectInstance}</td>
|
||||
<td>${escapeHtml(object.name || '—')}</td><td>${escapeHtml(object.description || '—')}</td>
|
||||
<td>${escapeHtml(object.value == null ? '—' : String(object.value))}</td></tr>`;
|
||||
}).join('');
|
||||
panel.querySelector('#bacnet-load-more').hidden = selection.offset >= Math.min(5000, selection.total);
|
||||
panel.querySelector('#bacnet-import-all').disabled = selection.total === 0 || selection.total > 5000;
|
||||
syncBacnetImportSelection({ currentTarget:panel });
|
||||
}
|
||||
|
||||
async function importBacnetObjects(panel, selection, all) {
|
||||
const objectIds = [...panel.querySelectorAll('[data-bacnet-object]:checked')].map(input => input.value);
|
||||
const selected = new Set(objectIds);
|
||||
const buttons = [...panel.querySelectorAll('button')];
|
||||
buttons.forEach(button => { button.disabled = true; });
|
||||
try {
|
||||
const result = await api('/api/bacnet/import', { method:'POST', body:JSON.stringify({device:selection.device, objectIds, all}) });
|
||||
for (const object of selection.rows) {
|
||||
if (object.valueType && (all || selected.has(`${object.objectTypeCode}:${object.objectInstance}`))) object.pointId = 'imported';
|
||||
}
|
||||
await loadData();
|
||||
errorTarget('bacnet-object-message', `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unsupported} ohne unterstützten Live-Wert`, true);
|
||||
} catch (error) { errorTarget('bacnet-object-message', error.message); }
|
||||
finally {
|
||||
buttons.forEach(button => { button.disabled = false; });
|
||||
if (activeBacnetDevice === selection) paintBacnetObjects(panel, selection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
function canViewGatewayStatus() {
|
||||
return can('manage_sources') || can('manage_gateway') || can('manage_integrations');
|
||||
}
|
||||
|
||||
function viewGatewayStatus() {
|
||||
return `<div id="gateway-status">
|
||||
<div class="card-head"><span class="note" data-status-time></span><button class="btn" type="button" data-status-refresh>Aktualisieren</button></div>
|
||||
<div data-status-error role="status"></div>
|
||||
<div data-status-content class="grid equal"></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function connectionStatusTag(text, tone = '') {
|
||||
return `<span class="tag ${tone}">${escapeHtml(text)}</span>`;
|
||||
}
|
||||
|
||||
function statusTime(date) {
|
||||
if (!date) return '—';
|
||||
return new Intl.DateTimeFormat('de-DE', { dateStyle:'short', timeStyle:'medium', timeZone:'Europe/Berlin' }).format(new Date(date));
|
||||
}
|
||||
|
||||
function connectionStatusCard(name, tag, content) {
|
||||
return `<article class="card connection-status-card"><div class="card-head"><h2>${name}</h2>${tag}</div>${content}</article>`;
|
||||
}
|
||||
|
||||
function statusError(text) {
|
||||
return text ? `<p class="notice red">${escapeHtml(text)}</p>` : '';
|
||||
}
|
||||
|
||||
function renderGatewayStatus(snapshot) {
|
||||
const cards = [];
|
||||
const mqtt = snapshot.mqtt;
|
||||
const bacnet = snapshot.bacnet;
|
||||
const opc = snapshot.opcUa;
|
||||
const modbus = snapshot.modbus;
|
||||
if (mqtt) {
|
||||
const stateTag = mqtt.connected ? connectionStatusTag('Verbunden') : mqtt.enabled
|
||||
? connectionStatusTag('Nicht verbunden', 'warn') : connectionStatusTag('Deaktiviert', 'gray');
|
||||
const lastFailure = mqtt.lastFailure || mqtt.lastError;
|
||||
cards.push(connectionStatusCard('MQTT', stateTag, `<dl class="connection-facts">
|
||||
<dt>Broker</dt><dd>${escapeHtml(mqtt.endpoint || '—')}</dd>
|
||||
<dt>Verbunden seit</dt><dd>${statusTime(mqtt.connectedAtUtc)}</dd>
|
||||
<dt>Letzter Empfang</dt><dd>${statusTime(mqtt.lastReceivedAtUtc)}</dd>
|
||||
<dt>Zuletzt gesendet</dt><dd>${statusTime(mqtt.lastPublishedAtUtc)}</dd>
|
||||
</dl>${lastFailure ? `<p class="note">Letzter Fehler · ${statusTime(mqtt.lastFailureAtUtc)}</p>${statusError(lastFailure)}` : ''}`));
|
||||
}
|
||||
if (bacnet) {
|
||||
cards.push(connectionStatusCard('BACnet/IP', bacnet.connected ? connectionStatusTag('Dienst aktiv') : connectionStatusTag('Dienst nicht erreichbar', 'warn'),
|
||||
`<dl class="connection-facts"><dt>Letztes Lebenszeichen</dt><dd>${statusTime(bacnet.heartbeatUtc)}</dd>
|
||||
<dt>Offene Befehle</dt><dd>${bacnet.pendingCommands}</dd></dl>
|
||||
${bacnet.failedCommands.length ? `<p class="note">Fehlgeschlagene Befehle</p><ul class="connection-issues">${bacnet.failedCommands.map(command => {
|
||||
const name = state.points.find(point => point.id === command.pointId)?.displayName || command.pointId;
|
||||
return `<li>${escapeHtml(name)} · ${escapeHtml(command.result)} · ${statusTime(command.occurredAtUtc)}</li>`;
|
||||
}).join('')}</ul>` : ''}
|
||||
${bacnet.unsupportedPoints.length ? statusError(`Native Objekte ohne Unterstützung · ${bacnet.unsupportedPoints.map(point => point.displayName).join(', ')}`) : ''}`));
|
||||
}
|
||||
if (opc) {
|
||||
const server = opc.server;
|
||||
const serverTag = server.listening ? connectionStatusTag(`Server aktiv · TCP ${server.port}`) : opc.serverEnabled
|
||||
? connectionStatusTag('Server nicht bereit', 'warn') : connectionStatusTag('Server deaktiviert', 'gray');
|
||||
cards.push(connectionStatusCard('OPC UA', serverTag, `${statusError(server.lastError)}
|
||||
${opc.clients.length ? `<ul class="connection-issues">${opc.clients.map(client => {
|
||||
const enabled = opc.clientsEnabled && client.enabled;
|
||||
const clientState = enabled ? client.status?.state || 'Verbindungsaufbau' : 'Deaktiviert';
|
||||
const detail = enabled && client.status?.connected ? ` · ${client.status.subscribedPoints} abonniert` : '';
|
||||
return `<li>${escapeHtml(client.name)} · ${escapeHtml(clientState)}${detail}</li>`;
|
||||
}).join('')}</ul>` : '<p class="note">Keine Client-Verbindung eingerichtet.</p>'}`));
|
||||
}
|
||||
if (modbus) {
|
||||
cards.push(connectionStatusCard('Modbus TCP / RTU', '', `
|
||||
${modbus.servers.length ? `<ul class="connection-issues">${modbus.servers.map(server => `<li>
|
||||
${escapeHtml(server.name)} · TCP ${server.port} · ${server.listening ? 'Lauscht' : 'Nicht bereit'}
|
||||
${statusError(server.error?.error)}</li>`).join('')}</ul>` : '<p class="note">Kein TCP-Server eingerichtet.</p>'}
|
||||
${modbus.pointErrors.length ? `<p class="note">Lesefehler</p><ul class="connection-issues">${modbus.pointErrors.map(issue =>
|
||||
`<li>${escapeHtml(issue.name)} · ${escapeHtml(issue.error)} · ${statusTime(issue.occurredAtUtc)}</li>`).join('')}</ul>` : ''}`));
|
||||
}
|
||||
if (snapshot.pointErrors) {
|
||||
cards.push(connectionStatusCard('Datenpunktqualität', connectionStatusTag(`${snapshot.pointErrors.length} auffällig`, snapshot.pointErrors.length ? 'warn' : 'gray'),
|
||||
snapshot.pointErrors.length ? `<div class="table-scroll connection-issues"><table><thead><tr><th>Datenpunkt</th><th>Treiber</th><th>Qualität</th><th>Zeit</th></tr></thead>
|
||||
<tbody>${snapshot.pointErrors.map(point => `<tr><td>${escapeHtml(point.name)}</td><td>${escapeHtml(point.sourceProtocol)}</td><td>${escapeHtml(point.status)}</td><td>${statusTime(point.updatedAtUtc)}</td></tr>`).join('')}</tbody></table></div>`
|
||||
: '<p class="note">Keine schlechte Qualität gemeldet.</p>'));
|
||||
}
|
||||
return cards.join('');
|
||||
}
|
||||
|
||||
function refreshGatewayStatus(panel) {
|
||||
if (!panel || panel.hidden || !panel.isConnected) return;
|
||||
panel.dispatchEvent(new Event('refresh-gateway-status'));
|
||||
}
|
||||
|
||||
function bindGatewayStatus() {
|
||||
const panel = document.querySelector('#point-panel-status');
|
||||
if (!panel) return;
|
||||
const button = panel.querySelector('[data-status-refresh]');
|
||||
const message = panel.querySelector('[data-status-error]');
|
||||
let timer;
|
||||
async function refresh() {
|
||||
clearTimeout(timer);
|
||||
if (panel.hidden || !panel.isConnected || button.disabled) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const snapshot = await api('/api/points/status');
|
||||
panel.querySelector('[data-status-content]').innerHTML = renderGatewayStatus(snapshot);
|
||||
panel.querySelector('[data-status-time]').textContent = `Stand ${statusTime(snapshot.checkedAtUtc)}`;
|
||||
message.textContent = '';
|
||||
} catch (error) {
|
||||
message.textContent = error.message;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
if (!panel.hidden && panel.isConnected) timer = setTimeout(refresh, 10000);
|
||||
}
|
||||
}
|
||||
panel.addEventListener('refresh-gateway-status', refresh);
|
||||
button.addEventListener('click', refresh);
|
||||
refresh();
|
||||
}
|
||||
|
||||
function viewInstallationSettings() {
|
||||
const identity = state.configuration?.installation;
|
||||
return `<article class="card"><div class="card-head"><h2>Projekt und ISP</h2></div>
|
||||
<form id="installation-form" class="form">
|
||||
<div class="row">
|
||||
<label>Projektnummer<input name="projectNumber" value="${escapeHtml(identity?.projectNumber || 'P')}" maxlength="33" pattern="[Pp][A-Za-z0-9_\\-]{1,32}" required></label>
|
||||
<label>ISP-Nummer<input name="ispNumber" type="number" min="1" max="99" value="${identity?.ispNumber ?? 1}" required></label>
|
||||
</div>
|
||||
<div>Rechnername <code data-installation-host></code></div>
|
||||
<div class="buttons"><button type="submit" class="btn primary">Projekt und ISP speichern</button></div>
|
||||
<div id="installation-message" role="status"></div>
|
||||
</form>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function bindInstallationSettings() {
|
||||
const form = document.querySelector('#installation-form');
|
||||
if (!form) return;
|
||||
const fields = form.elements;
|
||||
const hostname = form.querySelector('[data-installation-host]');
|
||||
const preview = () => {
|
||||
hostname.textContent = `SE-UGW-${fields.projectNumber.value.trim().toUpperCase()}-ISP${String(fields.ispNumber.value || '1').padStart(2, '0')}`;
|
||||
};
|
||||
form.addEventListener('input', preview);
|
||||
preview();
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const save = form.querySelector('button[type=submit]');
|
||||
save.disabled = true;
|
||||
try {
|
||||
const installation = await api('/api/gateway/installation', { method:'PUT', body:JSON.stringify({
|
||||
projectNumber: fields.projectNumber.value, ispNumber: Number(fields.ispNumber.value)
|
||||
}) });
|
||||
state.configuration.installation = installation;
|
||||
fields.projectNumber.value = installation.projectNumber;
|
||||
fields.ispNumber.value = installation.ispNumber;
|
||||
preview();
|
||||
if (can('manage_integrations')) state.mqttMappingDefaults = await api('/api/mqtt/mapping-defaults');
|
||||
errorTarget('installation-message', 'Projekt und ISP gespeichert.', true);
|
||||
} catch (error) { errorTarget('installation-message', error.message); }
|
||||
finally { save.disabled = false; }
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,27 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<html lang="de" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>SEIU Gateway</title>
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
<title>SE-Inno Universalgateway</title>
|
||||
<script>
|
||||
try {
|
||||
const theme = localStorage.getItem('seiugw-theme') || 'dark';
|
||||
document.documentElement.dataset.theme = theme === 'system' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme === 'light' ? 'light' : 'dark';
|
||||
} catch { /* Dark is the default when browser storage is unavailable. */ }
|
||||
</script>
|
||||
<link rel="stylesheet" href="/styles.css?v=20261009-tabs-1">
|
||||
<link rel="stylesheet" href="/ltd.css?v=20261119-mqtt-browser-1">
|
||||
</head>
|
||||
<body>
|
||||
<main id="app" aria-live="polite"></main>
|
||||
<script src="/app.js" defer></script>
|
||||
<script src="/ltd.js?v=20261119-status-1" defer></script>
|
||||
<script src="/network-settings.js?v=20261119-network-1" defer></script>
|
||||
<script src="/bacnet-browser.js?v=20261119-batch-2" defer></script>
|
||||
<script src="/mqtt-mapping-form.js?v=20261119-status-1" defer></script>
|
||||
<script src="/gateway-status.js?v=20261119-status-1" defer></script>
|
||||
<script src="/mapping-batch.js?v=20261119-status-1" defer></script>
|
||||
<script src="/mqtt-topic-browser.js?v=20261119-mqtt-browser-1" defer></script>
|
||||
<script src="/app.js?v=20261119-mqtt-browser-1" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,151 @@
|
||||
/* Layout and palette from SE-LTD, with gateway screens sharing the same shell. */
|
||||
/* Theme colors live in styles.css only; layout must not overwrite the palette. */
|
||||
:root { font-family: "Segoe UI", Tahoma, sans-serif; font-size: 12px; }
|
||||
body { min-width:360px; font-size:12px; }
|
||||
[hidden] { display:none !important; }
|
||||
.shell { grid-template-columns:184px minmax(0,1fr); }
|
||||
.sidebar { position:sticky; top:0; height:100dvh; overflow-y:auto; padding:12px 9px 10px; display:flex; flex-direction:column; border-left:5px solid transparent; border-image:linear-gradient(#ef4444,#dc3b68 55%,#4f8df7) 1; border-right:1px solid var(--line); }
|
||||
.shell.unpinned .sidebar { position:relative; }
|
||||
.brand { padding:0 0 12px; gap:8px; font-size:12px; letter-spacing:0; line-height:1.15; border-bottom:1px solid var(--line); margin-bottom:10px; }
|
||||
.brand-logo { width:32px; height:32px; }
|
||||
.brand .pin { margin-left:auto; padding:5px 7px; }
|
||||
.eyebrow { color:#ef4444; font-size:9px; font-weight:400; letter-spacing:.12em; }
|
||||
.nav { gap:6px; }
|
||||
.nav button { border:1px solid var(--line); color:var(--text); border-radius:12px; padding:9px 10px; }
|
||||
.nav button.active { color:#ef4444; background:#ef444412; border-color:#ef444440; box-shadow:none; }
|
||||
.sidebar-foot { position:static; margin-top:auto; padding:10px 0 0; border-top:1px solid var(--line); gap:8px; }
|
||||
.sidebar-foot .btn { justify-self:start; }
|
||||
.sidebar-foot small { font-size:9px; text-align:center; }
|
||||
.theme-control { display:grid; gap:6px; }
|
||||
.theme-caption { color:var(--muted); font-size:10px; }
|
||||
.sidebar-foot .theme-toggle { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; }
|
||||
.sidebar-foot .theme-option { padding:7px 2px; font-size:10px; }
|
||||
.theme-option.active { background:var(--blue-soft); color:var(--blue); border-color:var(--blue); }
|
||||
#theme-message:empty { display:none; }
|
||||
#theme-message { font-size:10px; margin:0; }
|
||||
.user-caption { display:grid; gap:6px; }
|
||||
.user-caption strong { color:var(--text); font-size:11px; overflow-wrap:anywhere; }
|
||||
.content { max-width:none; min-width:0; padding:12px 12px 28px; }
|
||||
.topline { margin-bottom:10px; min-height:27px; }
|
||||
h1 { font-size:13px; font-weight:600; letter-spacing:0; }
|
||||
h2 { font-size:14px; }
|
||||
.status { font-size:10px; }
|
||||
.grid { gap:10px; }
|
||||
.grid.equal { grid-template-columns:repeat(2,minmax(0,1fr)); align-items:start; }
|
||||
.grid.two { grid-template-columns:minmax(300px,1fr) minmax(0,1.4fr); }
|
||||
.card { border-radius:14px; padding:12px; min-width:0; background:var(--panel); color:var(--text); box-shadow:0 12px 30px #0000000d; }
|
||||
.card-head { margin-bottom:10px; }
|
||||
.card-head .note { margin-top:3px; }
|
||||
input,select,textarea { border-radius:10px; min-height:34px; padding:7px 10px; }
|
||||
input[type="checkbox"] { min-height:0; accent-color:#93c5fd; }
|
||||
input[type="color"] { padding:4px; width:36px; flex:0 0 36px; }
|
||||
.btn,.theme-option { border-radius:18px; padding:7px 11px; background:transparent; font-size:11px; }
|
||||
.btn.primary { border-color:transparent; background:linear-gradient(135deg,#ef4444,#b8275a 62%,#4f8df7); }
|
||||
.btn:disabled { cursor:not-allowed; opacity:.5; }
|
||||
.tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; }
|
||||
.tabs .btn { border-radius:12px; min-height:33px; }
|
||||
.tabs .active { color:#ef4444; border-color:#ef444440; background:#ef444412; }
|
||||
.protocol-tabs { padding-bottom:10px; border-bottom:1px solid var(--line); }
|
||||
.protocol-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); }
|
||||
.protocol-panel { min-width:0; }
|
||||
.bacnet-layout {
|
||||
display:grid;
|
||||
grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);
|
||||
grid-template-areas:"settings devices" "search devices";
|
||||
grid-template-rows:auto 1fr;
|
||||
align-items:start;
|
||||
gap:10px;
|
||||
}
|
||||
#bacnet-browser { display:contents; }
|
||||
.bacnet-settings { grid-area:settings; }
|
||||
.bacnet-search { grid-area:search; }
|
||||
.bacnet-settings .note,.bacnet-search .note { margin:4px 0; }
|
||||
.bacnet-devices {
|
||||
grid-area:devices;
|
||||
position:sticky;
|
||||
top:12px;
|
||||
display:flex;
|
||||
flex-direction:column;
|
||||
max-height:max(240px,calc(100dvh - 145px));
|
||||
}
|
||||
.bacnet-device-scroll {
|
||||
min-height:0;
|
||||
overflow:auto;
|
||||
overscroll-behavior:contain;
|
||||
scrollbar-color:var(--line-strong) transparent;
|
||||
}
|
||||
.bacnet-device-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); padding-top:8px; }
|
||||
.bacnet-device-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; }
|
||||
.bacnet-object-panel { min-height:0; display:flex; flex-direction:column; gap:8px; }
|
||||
.bacnet-object-panel .buttons { flex-wrap:wrap; }
|
||||
.bacnet-object-panel input[type="checkbox"] { width:auto; }
|
||||
.mapping-batch { margin-bottom:10px; }
|
||||
.mapping-batch .point-tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; }
|
||||
.mapping-batch .point-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); }
|
||||
.mapping-batch-grid { align-items:start; }
|
||||
.mapping-batch [data-bulk-modbus]:not([hidden]) { display:grid; gap:8px; }
|
||||
.bulk-point-list { max-height:36dvh; margin-top:8px; }
|
||||
.bulk-point-list thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); }
|
||||
.bulk-point-list td:first-child { width:5rem; }
|
||||
.bulk-point-list input { width:auto; }
|
||||
.bulk-point-list tr[data-bulk-point] { cursor:pointer; }
|
||||
.bulk-point-list tr:has(input:checked) { background:var(--blue-soft); }
|
||||
[data-bulk-assignments] ul { max-height:24dvh; overflow:auto; overflow-wrap:anywhere; }
|
||||
.connection-status-card p { margin:6px 0; overflow-wrap:anywhere; }
|
||||
.connection-facts { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:4px 12px; margin:6px 0; }
|
||||
.connection-facts dt { color:var(--muted); }
|
||||
.connection-facts dd { margin:0; overflow-wrap:anywhere; }
|
||||
.connection-issues { max-height:35dvh; overflow:auto; overflow-wrap:anywhere; }
|
||||
[data-mqtt-preview] { overflow-wrap:anywhere; }
|
||||
.mqtt-topic-browser { margin-bottom:10px; }
|
||||
.mqtt-browser-start { align-self:end; }
|
||||
.mqtt-browser-content { margin-top:12px; }
|
||||
.mqtt-browser-selection { margin:8px 0; flex-wrap:wrap; }
|
||||
.mqtt-topic-tree { max-height:50dvh; min-height:70px; overflow:auto; border:1px solid var(--line); border-radius:10px; margin-top:8px; padding:6px; }
|
||||
.mqtt-topic-tree ul { padding:0 0 0 16px; margin:0; list-style:none; }
|
||||
.mqtt-topic-tree > ul { padding-left:0; }
|
||||
.mqtt-tree-row { display:flex; align-items:center; gap:7px; min-width:0; margin-bottom:3px; }
|
||||
.mqtt-tree-row .btn { white-space:nowrap; border-radius:7px; text-align:left; padding:4px 7px; }
|
||||
.mqtt-tree-row input { width:auto; flex:none; }
|
||||
.mqtt-tree-row .mqtt-topic-value { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.mqtt-topic-item[aria-pressed="true"] { color:var(--blue); border-color:var(--blue); }
|
||||
.mqtt-topic-detail { border:1px solid var(--line); border-radius:10px; padding:10px; min-width:0; }
|
||||
.mqtt-topic-detail h3 { margin:0 0 8px; }
|
||||
.mqtt-topic-preview,.mqtt-topic-path { white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||
.list { display:grid; gap:4px; }
|
||||
.list-item { padding:7px 8px; border:1px solid var(--line); border-radius:12px; background:color-mix(in srgb,var(--panel-2) 50%,transparent); display:flex; align-items:center; justify-content:space-between; gap:10px; min-width:0; text-align:left; color:var(--text); }
|
||||
.list-item strong,.list-item .note { display:block; overflow-wrap:anywhere; }
|
||||
.list-item.active { border-color:var(--blue); }
|
||||
.scroll { max-height:60vh; overflow:auto; scrollbar-width:thin; scrollbar-color:var(--line-strong) transparent; }
|
||||
.alias-table { min-width:860px; }
|
||||
.alias-table th { text-transform:none; font-size:11px; letter-spacing:0; }
|
||||
.alias-table td { padding:3px 4px; border:0; vertical-align:middle; }
|
||||
.alias-table th:first-child,.alias-table td:first-child { color:#ef4444; width:85px; }
|
||||
.alias-table .color-field { display:flex; align-items:center; gap:6px; }
|
||||
.alias-table input { min-width:70px; }
|
||||
.alias-table input[type="color"] { min-width:36px; }
|
||||
.alias-table td:nth-child(2) { width:32%; }
|
||||
.alias-table td:nth-child(3) { width:18%; }
|
||||
.alias-table td:nth-child(4) { width:12%; }
|
||||
.alias-table td:nth-child(5) { width:12%; }
|
||||
.alias-table td:nth-child(6) { width:18%; }
|
||||
.full { grid-column:1/-1; }
|
||||
.form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
|
||||
.alarm-destination { border:1px solid var(--line); border-radius:10px; padding:8px; display:grid; gap:8px; }
|
||||
.chart { display:block; width:100%; height:225px; }
|
||||
.chart-legend { display:flex; flex-wrap:wrap; gap:10px; color:var(--muted); font-size:11px; }
|
||||
.chart-legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; }
|
||||
.widget-grid { margin-top:10px; }
|
||||
.table-scroll { overflow:auto; }
|
||||
.empty { text-align:center; padding:28px 10px; }
|
||||
.runner-columns { min-height:230px; }
|
||||
details > summary { cursor:pointer; color:var(--muted); padding:7px 0; }
|
||||
button:focus-visible,a:focus-visible { outline:2px solid var(--blue); outline-offset:2px; }
|
||||
@media(min-width:1800px) { .alias-table .scroll { max-height:65vh; } }
|
||||
@media(max-width:1100px) {
|
||||
.grid.two,.grid.equal { grid-template-columns:1fr; }
|
||||
.status { max-width:45%; text-align:right; }
|
||||
.bacnet-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"settings" "search" "devices"; grid-template-rows:auto; }
|
||||
.bacnet-devices { position:static; max-height:60dvh; }
|
||||
}
|
||||
@media(max-width:650px) { .shell { grid-template-columns:145px minmax(0,1fr); } .brand .pin { display:none; } .content { padding:10px 8px; } .form-grid,.row,.row.three { grid-template-columns:1fr; } .topline .status { display:none; } .sidebar { padding:10px 6px; } .brand { font-size:10px; } .card-head { flex-wrap:wrap; } }
|
||||
@@ -0,0 +1,208 @@
|
||||
const emptyGuid = '00000000-0000-0000-0000-000000000000';
|
||||
const trendColors = ['#c9dc1e', '#27e72e', '#12d0d3', '#2362d7', '#502ce2', '#cf177f', '#e61e14', '#ddad31'];
|
||||
const adminDefinitions = [['aliases','Aliase','edit_aliases'],['units','Einheiten','edit_aliases'],['alarms','Alarme','manage_alarms'],['users','Benutzer','manage_users'],['roles','Rollen','manage_roles'],['api','API','manage_integrations'],['runner','Runner','manage_runner'],['debug','Debug','view_debug']];
|
||||
function adminTabs() { return adminDefinitions.filter(tab => can(tab[2])); }
|
||||
function tabBar(tabs, selected, attribute) { return `<nav class="tabs" aria-label="Reiter">${tabs.map(([id, title]) => `<button class="btn ${id === selected ? 'active' : ''}" ${attribute}="${id}" aria-current="${id === selected ? 'page' : 'false'}">${title}</button>`).join('')}</nav>`; }
|
||||
function bodyOf(markup) { const template = document.createElement('template'); template.innerHTML = markup; template.content.querySelector('.topline')?.remove(); return template.innerHTML; }
|
||||
function presentation(point, index = 0) { return state.presentation.points.find(item => item.pointId === point.id) || { pointId: point.id, alias: point.displayName, unit: '', factor: 1, kind: /bool|binary/i.test(point.valueType) ? 'digital' : 'analog', color: trendColors[index % trendColors.length] }; }
|
||||
function pointTitle(point) { return presentation(point).alias; }
|
||||
function sourceKey(point) { return `${point.protocol} · ${point.scope}`; }
|
||||
function sourceOptions(selected) { return `<option value="">Alle Quellen</option>${[...new Set(state.points.map(sourceKey))].sort().map(key => `<option ${key === selected ? 'selected' : ''}>${escapeHtml(key)}</option>`).join('')}`; }
|
||||
function unitOptions(selected) { return `<option value="">—</option>${state.presentation.units.map(unit => `<option value="${escapeHtml(unit.symbol)}" ${selected === unit.symbol ? 'selected' : ''}>${escapeHtml(unit.symbol)} · ${escapeHtml(unit.name)}</option>`).join('')}`; }
|
||||
function uuid() { return typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)); }
|
||||
|
||||
function viewDataPoints() {
|
||||
const tabs = [...(can('manage_sources') ? [['points','Datenpunkte']] : []), ...(can('manage_gateway') ? [['bacnet','BACnet/IP'], ['opcua','OPC UA'], ['modbus','Modbus TCP / RTU'], ['knx','KNX IP / TP']] : []), ...(can('manage_integrations') ? [['mqtt','MQTT']] : []), ...(can('manage_gateway') ? [['serial','USB / COM']] : [])];
|
||||
if (canViewGatewayStatus()) tabs.push(['status', 'Status']);
|
||||
if (!tabs.some(tab => tab[0] === state.pointsTab)) state.pointsTab = tabs[0]?.[0];
|
||||
const navigation = `<nav class="tabs protocol-tabs" role="tablist" aria-label="Datenpunkte und Protokolle">${tabs.map(([id, title]) => `<button type="button" class="btn ${id === state.pointsTab ? 'active' : ''}" id="point-tab-${id}" role="tab" aria-controls="point-panel-${id}" aria-selected="${id === state.pointsTab}" tabindex="${id === state.pointsTab ? '0' : '-1'}" data-points-tab="${id}">${title}</button>`).join('')}</nav>`;
|
||||
return `${header('Datenpunkte')}${navigation}${can('manage_sources') ? pointPanel('points',bodyOf(viewPoints())) : ''}${can('manage_gateway') ? bodyOf(viewProtocols()) : ''}${can('manage_integrations') ? pointPanel('mqtt',bodyOf(viewMqtt())) : ''}${canViewGatewayStatus() ? pointPanel('status',viewGatewayStatus()) : ''}`;
|
||||
}
|
||||
function pointPanel(id, markup) {
|
||||
return `<section id="point-panel-${id}" class="protocol-panel" role="tabpanel" aria-labelledby="point-tab-${id}" data-points-panel="${id}" ${id === state.pointsTab ? '' : 'hidden'}>${markup}</section>`;
|
||||
}
|
||||
function bindPointTabs() {
|
||||
const tabs = [...document.querySelectorAll('[data-points-tab]')];
|
||||
const activate = button => {
|
||||
state.pointsTab = button.dataset.pointsTab;
|
||||
tabs.forEach(tab => {
|
||||
const active = tab === button;
|
||||
tab.classList.toggle('active',active);
|
||||
tab.setAttribute('aria-selected',String(active));
|
||||
tab.tabIndex = active ? 0 : -1;
|
||||
});
|
||||
document.querySelectorAll('[data-points-panel]').forEach(panel => { panel.hidden = panel.dataset.pointsPanel !== state.pointsTab; });
|
||||
if (state.pointsTab === 'status') refreshGatewayStatus(document.querySelector('#point-panel-status'));
|
||||
};
|
||||
tabs.forEach((button, index) => {
|
||||
button.addEventListener('click', () => activate(button));
|
||||
button.addEventListener('keydown', event => {
|
||||
const next = { ArrowRight: (index+1)%tabs.length, ArrowLeft: (index+tabs.length-1)%tabs.length, Home: 0, End: tabs.length-1 }[event.key];
|
||||
if (next === undefined) return;
|
||||
event.preventDefault();
|
||||
activate(tabs[next]);
|
||||
tabs[next].focus();
|
||||
});
|
||||
});
|
||||
}
|
||||
function viewAdmin() {
|
||||
const tabs = adminTabs();
|
||||
if (!tabs.some(tab => tab[0] === state.adminTab)) state.adminTab = tabs[0]?.[0];
|
||||
const views = { aliases: viewAliases, units: viewUnits, alarms: viewAlarms, users: () => viewSystem('users'), roles: () => viewSystem('roles'), api: viewNotificationKeys, runner: viewLtdRunner, debug: () => viewSystem('debug') };
|
||||
return `${header('Admin')}${tabBar(tabs,state.adminTab,'data-admin-tab')}${views[state.adminTab]?.() || ''}`;
|
||||
}
|
||||
function bindAdmin() {
|
||||
document.querySelectorAll('[data-admin-tab]').forEach(button => button.addEventListener('click', () => { state.adminTab = button.dataset.adminTab; renderView(); }));
|
||||
const bindings = { aliases: bindAliases, units: bindUnits, alarms: bindAlarms, api: bindNotificationKeys, runner: bindLtdRunner };
|
||||
if (bindings[state.adminTab]) bindings[state.adminTab](); else bindView('system');
|
||||
}
|
||||
|
||||
function viewAliases() {
|
||||
const points = state.points.filter(point => !state.aliasSource || sourceKey(point) === state.aliasSource);
|
||||
return `<article class="card"><div class="card-head"><div><h2>Aliase</h2><div class="note">Aliase, Einheiten und Farben direkt als CSV importieren oder exportieren. Faktoren gelten für die Anzeige, nicht für Protokollwerte.</div></div><div class="buttons"><button class="btn" id="alias-export">CSV Export</button><button class="btn" id="alias-import">CSV Import</button><input id="alias-file" type="file" accept=".csv,text/csv" hidden></div></div><label>Quelle<select id="alias-source">${sourceOptions(state.aliasSource)}</select></label><form id="aliases-form" class="form" style="margin-top:10px"><div class="scroll"><table class="alias-table"><thead><tr><th>Datenpunkt</th><th>Alias</th><th>Einheit</th><th>Faktor</th><th>Typ</th><th>Farbe</th></tr></thead><tbody>${points.map((point,index) => { const item = presentation(point,index); return `<tr data-alias-row="${point.id}"><td title="${escapeHtml(point.id)}">${escapeHtml(point.bacnetObjectInstance ?? `Wert ${state.points.indexOf(point)+1}`)}</td><td><input name="alias" aria-label="Alias" value="${escapeHtml(item.alias)}" required maxlength="160"></td><td><select name="unit" aria-label="Einheit">${unitOptions(item.unit)}</select></td><td><input name="factor" aria-label="Faktor" type="number" step="any" value="${item.factor}" required></td><td><select name="kind" aria-label="Typ"><option ${item.kind === 'analog' ? 'selected' : ''}>analog</option><option ${item.kind === 'digital' ? 'selected' : ''}>digital</option></select></td><td><div class="color-field"><input type="color" name="color" aria-label="Farbe" value="${item.color}"><input name="colorText" aria-label="Hex-Farbe" value="${item.color}" pattern="#[0-9a-fA-F]{6}" required></div></td></tr>`; }).join('')}</tbody></table>${points.length ? '' : '<div class="empty">Noch keine Datenpunkte in dieser Quelle.</div>'}</div><div class="buttons"><button class="btn primary" ${points.length ? '' : 'disabled'}>Aliase speichern</button></div><div id="aliases-message"></div></form></article>`;
|
||||
}
|
||||
function collectAliases() { return [...document.querySelectorAll('[data-alias-row]')].map(row => ({ pointId: row.dataset.aliasRow, alias: row.querySelector('[name=alias]').value, unit: row.querySelector('[name=unit]').value, factor: Number(row.querySelector('[name=factor]').value), kind: row.querySelector('[name=kind]').value, color: row.querySelector('[name=colorText]').value })); }
|
||||
function bindAliases() {
|
||||
document.querySelector('#alias-source').addEventListener('change', event => { state.aliasSource = event.target.value; renderView(); });
|
||||
document.querySelectorAll('[data-alias-row]').forEach(row => {
|
||||
row.querySelector('[name=color]').addEventListener('input', event => { row.querySelector('[name=colorText]').value = event.target.value; });
|
||||
row.querySelector('[name=colorText]').addEventListener('input', event => { if (/^#[\da-f]{6}$/i.test(event.target.value)) row.querySelector('[name=color]').value = event.target.value; });
|
||||
});
|
||||
document.querySelector('#aliases-form').addEventListener('submit', async event => { event.preventDefault(); try { await api('/api/presentation/points', { method:'PUT', body:JSON.stringify(collectAliases()) }); await loadData(); errorTarget('aliases-message','Aliase gespeichert.',true); } catch(error) { errorTarget('aliases-message',error.message); } });
|
||||
document.querySelector('#alias-export').addEventListener('click', () => { const lines = [['pointId','alias','unit','factor','kind','color'], ...collectAliases().map(item => [item.pointId,item.alias,item.unit,item.factor,item.kind,item.color])]; downloadText('\uFEFF'+lines.map(row => row.map(csvCell).join(';')).join('\r\n'),'gateway-aliase.csv','text/csv;charset=utf-8'); });
|
||||
document.querySelector('#alias-import').addEventListener('click', () => document.querySelector('#alias-file').click());
|
||||
document.querySelector('#alias-file').addEventListener('change', async event => {
|
||||
try {
|
||||
const file = event.target.files[0]; if (!file) return;
|
||||
if (file.size > 4*1024*1024) throw new Error('CSV ist zu groß (max. 4 MB).');
|
||||
const rows = parseAliasCsv(await file.text());
|
||||
if (!rows.length) throw new Error('Keine Alias-Zeilen gefunden.');
|
||||
if (!window.confirm(`${rows.length} Aliase aus der CSV übernehmen?`)) return;
|
||||
await api('/api/presentation/points',{method:'PUT',body:JSON.stringify(rows)}); await loadData(); renderView(); errorTarget('aliases-message',`${rows.length} Aliase importiert.`,true);
|
||||
} catch(error) { errorTarget('aliases-message',error.message); }
|
||||
});
|
||||
}
|
||||
function csvCell(value) { const raw=String(value); return '"'+raw.replace(/"/g,'""')+'"'; }
|
||||
function parseAliasCsv(text) {
|
||||
const lines=[]; let row=[],cell='',quoted=false; text=text.replace(/^\uFEFF/,'');
|
||||
for(let i=0;i<text.length;i++) { const c=text[i]; if(c==='"') { if(quoted && text[i+1]==='"') {cell+='"';i++;} else quoted=!quoted; } else if(c===';'&&!quoted) {row.push(cell);cell='';} else if((c==='\r'||c==='\n')&&!quoted) { if(c==='\r'&&text[i+1]==='\n')i++;row.push(cell);if(row.some(Boolean))lines.push(row);row=[];cell=''; } else cell+=c; }
|
||||
if(quoted)throw new Error('Nicht geschlossenes Anführungszeichen in der CSV.');
|
||||
row.push(cell);if(row.some(Boolean))lines.push(row);
|
||||
const headings=lines.shift(); if(headings?.join(';')!=='pointId;alias;unit;factor;kind;color')throw new Error('Spalten: pointId;alias;unit;factor;kind;color. Bitte CSV Export als Vorlage verwenden.');
|
||||
return lines.map((cells,index)=> { if(cells.length!==6)throw new Error(`CSV-Zeile ${index+2}: sechs Spalten erwartet.`); return {pointId:cells[0],alias:cells[1],unit:cells[2],factor:Number(cells[3].replace(',','.')),kind:cells[4],color:cells[5]}; });
|
||||
}
|
||||
function downloadText(text,name,type) { const url=URL.createObjectURL(new Blob([text],{type})); const link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); }
|
||||
|
||||
function viewUnits() { return `<article class="card"><div class="card-head"><div><h2>Einheiten</h2><div class="note">Einheiten zentral verwalten und bei Aliasen auswählen.</div></div><button class="btn" id="new-unit">Neue Einheit</button></div><form id="unit-form" class="form"><div class="row"><label>Symbol<input name="symbol" placeholder="z. B. bar" required maxlength="24"></label><label>Bezeichnung<input name="name" placeholder="z. B. Bar" required maxlength="100"></label></div><div class="buttons"><button class="btn" type="reset">Zurücksetzen</button><button class="btn primary">Einheit speichern</button></div><div id="unit-message"></div></form><div class="list">${state.presentation.units.map((unit,index)=>`<div class="list-item"><div><strong>${escapeHtml(unit.symbol)}</strong><span class="note">${escapeHtml(unit.name)}<br>${unit.isSystem?'Systemeinheit':'Eigene Einheit'}</span></div><button class="btn" data-edit-unit="${index}">Bearbeiten</button></div>`).join('')}</div></article>`; }
|
||||
function bindUnits() {
|
||||
const form=document.querySelector('#unit-form');
|
||||
document.querySelector('#new-unit').addEventListener('click',()=>{form.reset();form.elements.symbol.focus();});
|
||||
document.querySelectorAll('[data-edit-unit]').forEach(button=>button.addEventListener('click',()=>{const unit=state.presentation.units[Number(button.dataset.editUnit)];form.elements.symbol.value=unit.symbol;form.elements.name.value=unit.name;form.elements.name.focus();}));
|
||||
form.addEventListener('submit',async event=>{event.preventDefault();try{await api('/api/presentation/units',{method:'PUT',body:JSON.stringify({symbol:form.elements.symbol.value,name:form.elements.name.value})});await loadData();renderView();}catch(error){errorTarget('unit-message',error.message);}});
|
||||
}
|
||||
|
||||
function viewNotificationKeys() {
|
||||
const labels={Mail:'Mail',WhatsApp:'WhatsApp · nur Alarme',Ntfy:'ntfy · nur Alarme'};
|
||||
return `<section class="grid equal">${state.notifications.map(item=>`<article class="card"><div class="card-head"><h2>${labels[item.channel]}</h2><span class="tag ${item.hasApiKey?'':'gray'}">${item.hasApiKey?'Key gespeichert':'nicht freigeschaltet'}</span></div><form class="form" data-key-form="${item.channel}"><label>API-Key<input name="apiKey" type="password" autocomplete="new-password" placeholder="leer lassen = unverändert"></label><label class="switch"><input name="clearApiKey" type="checkbox"> Key löschen und Versand sperren</label><div class="note">${escapeHtml(item.endpoint)}</div><div class="buttons"><button class="btn primary">Speichern</button></div><div id="key-${item.channel}-message"></div></form></article>`).join('')}${can('manage_gateway')?`<article class="card"><div class="card-head"><h2>Komari</h2><span class="tag ${state.komari?.hasEnrollmentToken?'':'gray'}">${state.komari?.hasEnrollmentToken?'Key gespeichert':'kein Key'}</span></div><form id="komari-form" class="form"><label>Registrierungsschlüssel<input name="enrollmentToken" type="password" required minlength="8" maxlength="1024" autocomplete="new-password"></label><div class="note">Verschlüsselt in der Datenbank. Alternativ über die serverseitige Token-Datei importierbar.</div><div class="buttons"><button class="btn primary">Schlüssel ersetzen</button></div><div id="komari-message"></div></form></article>`:''}</section><p class="note">Gespeicherte Schlüssel werden nicht an den Browser zurückgegeben. Die API-Annahme einer Nachricht bestätigt noch keine Zustellung beim Empfänger.</p>`;
|
||||
}
|
||||
function bindNotificationKeys() {
|
||||
document.querySelectorAll('[data-key-form]').forEach(form=>form.addEventListener('submit',async event=>{event.preventDefault();const channel=form.dataset.keyForm;try{const clearApiKey=form.elements.clearApiKey.checked;if(clearApiKey&&!window.confirm('Key löschen? Dieser Kanal sendet anschließend keine Nachrichten mehr.'))return;await api(`/api/integrations/notifications/${channel}`,{method:'PUT',body:JSON.stringify({apiKey:form.elements.apiKey.value||null,clearApiKey})});form.elements.apiKey.value='';await loadData();renderView();errorTarget(`key-${channel}-message`,'Gespeichert.',true);}catch(error){errorTarget(`key-${channel}-message`,error.message);}}));
|
||||
document.querySelector('#komari-form')?.addEventListener('submit',async event=>{event.preventDefault();try{await api('/api/system/komari',{method:'PUT',body:JSON.stringify({enrollmentToken:event.currentTarget.elements.enrollmentToken.value})});await loadData();renderView();errorTarget('komari-message','Schlüssel verschlüsselt gespeichert.',true);}catch(error){errorTarget('komari-message',error.message);}});
|
||||
}
|
||||
|
||||
function viewAlarms() {
|
||||
const edit=state.alarms.find(rule=>rule.id===state.alarmEditId);
|
||||
const point=state.points.find(item=>item.id===(edit?.pointId||state.alarmPointId));
|
||||
const available=state.points.filter(item=>item.readable&&(!state.alarmSource||sourceKey(item)===state.alarmSource));
|
||||
const rules=state.alarms.filter(rule=>!state.alarmSource||sourceKey(state.points.find(p=>p.id===rule.pointId)||{})===state.alarmSource);
|
||||
return `<article class="card"><div class="card-head"><div><h2>Alarme</h2><div class="note">Datenpunkte unabhängig vom Trendlogging überwachen.</div></div><button class="btn" id="alarm-refresh">Aktualisieren</button></div><div class="grid equal"><div><h2>Quellen</h2><label>Aktive Quelle<select id="alarm-source">${sourceOptions(state.alarmSource)}</select></label></div><label>Suche<input id="alarm-search" placeholder="Alias, Datenpunkt oder Protokoll"></label><section><div class="card-head"><h2>Verfügbare Datenpunkte</h2><span class="tag gray">${available.length}</span></div><div class="list scroll">${available.map(item=>`<div class="list-item" data-alarm-search="${escapeHtml((pointTitle(item)+' '+item.displayName+' '+item.protocol).toLowerCase())}"><div><strong>${escapeHtml(pointTitle(item))}</strong><span class="note">${escapeHtml(item.protocol)} · ${escapeHtml(item.scope)}</span></div><button class="btn primary" data-add-alarm="${item.id}">Ins Alarming</button></div>`).join('')||'<div class="empty">Keine lesbaren Datenpunkte.</div>'}</div></section><section><div class="card-head"><h2>Wird alarmiert</h2><span class="tag gray">${rules.length}</span></div><div class="list scroll">${rules.map(rule=>`<div class="list-item"><div><strong>${escapeHtml(rule.name)}</strong><span class="note">${escapeHtml(state.points.find(p=>p.id===rule.pointId)?.displayName||rule.pointId)} · ${rule.enabled?'aktiv':'inaktiv'}<br>${rule.destinations.map(d=>escapeHtml(d.channel+' → '+d.recipient)).join(' · ')}</span></div><div class="buttons"><button class="btn" data-edit-alarm="${rule.id}">Bearbeiten</button><button class="btn danger" data-delete-alarm="${rule.id}">Löschen</button></div></div>`).join('')||'<div class="empty">Noch kein Datenpunkt im Alarming.</div>'}</div></section></div></article>${point?alarmEditor(point,edit):''}<article class="card" style="margin-top:10px"><div class="card-head"><h2>Versandstatus</h2></div><div class="table-scroll scroll"><table><thead><tr><th>Zeit</th><th>Meldung</th><th>Kanal</th><th>Status</th></tr></thead><tbody>${state.deliveries.map(item=>`<tr><td>${escapeHtml(new Date(item.createdAtUtc).toLocaleString('de-DE'))}</td><td>${escapeHtml(item.title)}</td><td>${escapeHtml(item.destination.channel)}</td><td>${escapeHtml(deliveryState(item.state))}${item.result?`<div class="note">${escapeHtml(item.result)}</div>`:''}</td></tr>`).join('')}</tbody></table>${state.deliveries.length?'':'<div class="empty">Noch keine Meldungen.</div>'}</div></article>`;
|
||||
}
|
||||
function deliveryState(value) { return ({Pending:'Wartend',Sending:'Wird gesendet',Accepted:'Von API angenommen',Failed:'Fehlgeschlagen',Unknown:'Unklar – kein automatischer Neuversand',Blocked:'Kanal gesperrt',Cancelled:'Abgebrochen'})[value]||value; }
|
||||
function alarmEditor(point,rule) {
|
||||
const destinations=rule?.destinations||[];
|
||||
return `<article class="card" style="margin-top:10px" id="alarm-editor"><div class="card-head"><h2>${rule?'Alarm bearbeiten':'Alarm anlegen'} · ${escapeHtml(pointTitle(point))}</h2><button class="btn" id="alarm-cancel">Schließen</button></div><form id="alarm-form" class="form"><div class="row"><label>Name<input name="name" value="${escapeHtml(rule?.name||pointTitle(point))}" required maxlength="120"></label><label>Bedingung<select name="condition">${[['Active','Aktiv / ungleich 0'],['Inactive','Inaktiv / gleich 0'],['Above','Über Grenzwert'],['Below','Unter Grenzwert']].map(([value,label])=>`<option value="${value}" ${rule?.condition===value?'selected':''}>${label}</option>`).join('')}</select></label></div><div class="row"><label>Grenzwert<input name="threshold" type="number" step="any" value="${rule?.threshold??0}" required></label><label>Hysterese<input name="hysteresis" type="number" min="0" step="any" value="${rule?.hysteresis??0}" required></label></div><label>Meldung<textarea name="message" maxlength="8000">${escapeHtml(rule?.message||'')}</textarea></label><div class="row"><label class="switch"><input name="enabled" type="checkbox" ${!rule||rule.enabled?'checked':''}> aktiv</label><label class="switch"><input name="notifyRecovery" type="checkbox" ${rule?.notifyRecovery?'checked':''}> Entwarnung senden</label></div><div class="grid equal">${['Mail','WhatsApp','Ntfy'].map(channel=>{ const dest=destinations.find(item=>item.channel===channel),ready=state.notifications.find(item=>item.channel===channel)?.hasApiKey;return `<fieldset class="alarm-destination" data-destination="${channel}"><legend>${channel}</legend><label class="switch"><input name="use" type="checkbox" ${dest?'checked':''} ${ready?'':'disabled'}> ${ready?'Versand aktivieren':'Kein API-Key – unter Admin → API freischalten'}</label><label>${channel==='Mail'?'E-Mail-Adresse':channel==='WhatsApp'?'Rufnummer (+49…)':'Topic'}<input name="recipient" value="${escapeHtml(dest?.recipient||'')}" ${channel==='Mail'?'type="email"':''}></label>${channel==='WhatsApp'?`<div class="row"><label>Genehmigte Vorlage<select name="template">${['infomessagegroup','infoapp','meldung','stoerung','se_portal_admin','contact_form','se_portal_manage','se_portal'].map(template=>`<option ${template===(dest?.template||'stoerung')?'selected':''}>${template}</option>`).join('')}</select></label><label>pn<input name="pn" value="${escapeHtml(dest?.personName||'SE-Inno')}" maxlength="60"></label></div><div class="note">Vorlagenparameter: Zeilenumbrüche und Tabs werden zu Leerzeichen. Unicode bleibt erhalten. Max. 1024 Zeichen je Meldungsparameter.</div>`:channel==='Ntfy'?`<div class="row"><label>Priorität<select name="priority">${[0,1,2,3,4,5].map(n=>`<option ${n===(dest?.priority??0)?'selected':''}>${n}</option>`).join('')}</select></label><label>Tags<input name="tags" value="${escapeHtml(dest?.tags||'alarm')}" maxlength="200"></label></div>`:''}</fieldset>`;}).join('')}</div><div class="note">Versand nur bei Zustandswechsel. Grenzwerte beziehen sich auf den unveränderten Datenpunktwert. Keine automatische Wiederholung bei unklarem Versandstatus.</div><div class="buttons"><button class="btn primary">Alarm speichern</button></div><div id="alarm-message"></div></form></article>`;
|
||||
}
|
||||
function bindAlarms() {
|
||||
document.querySelector('#alarm-source').addEventListener('change',event=>{state.alarmSource=event.target.value;renderView();});
|
||||
document.querySelector('#alarm-search').addEventListener('input',event=>{const search=event.target.value.toLowerCase();document.querySelectorAll('[data-alarm-search]').forEach(row=>{row.hidden=!row.dataset.alarmSearch.includes(search);});});
|
||||
document.querySelector('#alarm-refresh').addEventListener('click',async()=>{try{await loadData();renderView();}catch(error){window.alert(error.message);}});
|
||||
document.querySelectorAll('[data-add-alarm]').forEach(button=>button.addEventListener('click',()=>{state.alarmPointId=button.dataset.addAlarm;state.alarmEditId=null;renderView();document.querySelector('#alarm-editor').scrollIntoView({block:'start',behavior:'smooth'});}));
|
||||
document.querySelectorAll('[data-edit-alarm]').forEach(button=>button.addEventListener('click',()=>{state.alarmEditId=button.dataset.editAlarm;renderView();document.querySelector('#alarm-editor').scrollIntoView({block:'start',behavior:'smooth'});}));
|
||||
document.querySelectorAll('[data-delete-alarm]').forEach(button=>button.addEventListener('click',async()=>{if(!window.confirm('Alarmregel löschen und noch wartende Meldungen verwerfen?'))return;try{await api(`/api/alarms/${button.dataset.deleteAlarm}`,{method:'DELETE'});state.alarmEditId=null;state.alarmPointId=null;await loadData();renderView();}catch(error){window.alert(error.message);}}));
|
||||
document.querySelector('#alarm-cancel')?.addEventListener('click',()=>{state.alarmEditId=null;state.alarmPointId=null;renderView();});
|
||||
document.querySelector('#alarm-form')?.addEventListener('submit',async event=>{
|
||||
event.preventDefault();const form=new FormData(event.currentTarget),edit=state.alarms.find(rule=>rule.id===state.alarmEditId);
|
||||
const destinations=[...document.querySelectorAll('[data-destination]')].filter(field=>field.querySelector('[name=use]').checked&&!field.querySelector('[name=use]').disabled).map(field=>({channel:field.dataset.destination,recipient:field.querySelector('[name=recipient]').value,template:field.querySelector('[name=template]')?.value||'stoerung',personName:field.querySelector('[name=pn]')?.value||'SE-Inno',priority:Number(field.querySelector('[name=priority]')?.value||0),tags:field.querySelector('[name=tags]')?.value||'alarm'}));
|
||||
try{await api('/api/alarms',{method:'PUT',body:JSON.stringify({id:edit?.id||emptyGuid,name:form.get('name'),pointId:edit?.pointId||state.alarmPointId,condition:form.get('condition'),threshold:Number(form.get('threshold')),hysteresis:Number(form.get('hysteresis')),enabled:form.has('enabled'),notifyRecovery:form.has('notifyRecovery'),message:form.get('message'),destinations})});state.alarmPointId=null;state.alarmEditId=null;await loadData();renderView();}catch(error){errorTarget('alarm-message',error.message);}
|
||||
});
|
||||
}
|
||||
|
||||
function viewDashboard() {
|
||||
return `${header('Dashboard')}<section class="grid equal"><article class="card"><div class="card-head"><div><h2>Widget</h2><div class="note">Aus einer gespeicherten Trend-Auswahl.</div></div></div><form id="widget-form" class="form"><div class="row"><label>Titel<input name="title" required maxlength="120"></label><label>Typ<select name="type"><option value="Graph">Graph</option><option value="Values">Werte</option></select></label></div><div class="row"><label>Quelle<select name="selectionId" required><option value="">Auswahl wählen</option>${state.trendSelections.map(item=>`<option value="${item.id}">${escapeHtml(item.name)}</option>`).join('')}</select></label><label>Zeitraum<select name="rangeHours"><option value="24">24 h</option><option value="48">48 h</option><option value="168">7 Tage</option><option value="720">30 Tage</option></select></label></div><div class="buttons"><button class="btn primary" ${state.trendSelections.length&&can('view_trends')?'':'disabled'}>Widget übernehmen</button></div><div id="widget-message"></div></form></article><article class="card"><div class="card-head"><div><h2>Auswahlen</h2><div class="note">Gespeicherte Punktgruppen für Trend und Dashboard.</div></div></div><div class="list">${state.trendSelections.map(selection=>`<div class="list-item"><button class="btn" data-select-widget="${selection.id}">${escapeHtml(selection.name)} <span class="note">${selection.trendLogIds.length} Punkte</span></button>${selection.ownerId===state.user?.user?.id||state.user?.user?.role==='admin'?`<button class="btn danger" title="Auswahl löschen" data-delete-selection="${selection.id}">×</button>`:''}</div>`).join('')||'<div class="empty">Noch keine Auswahl. Im Reiter Trend eine Gruppe speichern.</div>'}</div></article></section><section class="grid equal widget-grid">${state.dashboard.map(widget=>`<article class="card"><div class="card-head"><h2>${escapeHtml(widget.title)}</h2><div class="buttons"><span class="note">${widget.rangeHours} h</span><button class="btn danger" data-remove-widget="${widget.id}" title="Widget entfernen">×</button></div></div><div data-widget="${widget.id}" class="chart-container"><div class="empty">Daten werden geladen …</div></div></article>`).join('')}</section>`;
|
||||
}
|
||||
function bindDashboard() {
|
||||
document.querySelector('#widget-form').addEventListener('submit',async event=>{event.preventDefault();const form=new FormData(event.currentTarget);try{const next=[...state.dashboard,{id:uuid(),title:form.get('title'),type:form.get('type'),selectionId:form.get('selectionId'),rangeHours:Number(form.get('rangeHours'))}];await api('/api/dashboard',{method:'PUT',body:JSON.stringify(next)});state.dashboard=next;renderView();}catch(error){errorTarget('widget-message',error.message);}});
|
||||
document.querySelectorAll('[data-select-widget]').forEach(button=>button.addEventListener('click',()=>{const form=document.querySelector('#widget-form');form.elements.selectionId.value=button.dataset.selectWidget;form.elements.title.value=state.trendSelections.find(item=>item.id===button.dataset.selectWidget)?.name||'';}));
|
||||
document.querySelectorAll('[data-delete-selection]').forEach(button=>button.addEventListener('click',deleteTrendSelection));
|
||||
document.querySelectorAll('[data-remove-widget]').forEach(button=>button.addEventListener('click',async()=>{try{const next=state.dashboard.filter(item=>item.id!==button.dataset.removeWidget);await api('/api/dashboard',{method:'PUT',body:JSON.stringify(next)});state.dashboard=next;renderView();}catch(error){errorTarget('widget-message',error.message);}}));
|
||||
state.dashboard.forEach(widget=>loadWidget(widget,document.querySelector(`[data-widget="${widget.id}"]`)));
|
||||
}
|
||||
async function loadWidget(widget,target) {
|
||||
try {
|
||||
if(!can('view_trends'))throw new Error('Keine Berechtigung für Trenddaten.');
|
||||
const selection=widget.singleTrendLogId?{trendLogIds:[widget.singleTrendLogId]}:state.trendSelections.find(item=>item.id===widget.selectionId);if(!selection)throw new Error('Auswahl nicht mehr verfügbar.');
|
||||
const start=Date.now()-widget.rangeHours*3600000;
|
||||
const series=await Promise.all(selection.trendLogIds.map(async(id,index)=>{const log=state.trendLogs.find(item=>item.id===id); const point=state.points.find(item=>item.id===log?.sourcePointId);const style=point?presentation(point,index):state.presentation.points.find(item=>item.pointId===log?.sourcePointId);const records=await api(`/api/trend-logs/${id}/records?limit=2000`);return {name:style?.alias||log?.name||id,color:style?.color||trendColors[index%trendColors.length],unit:style?.unit||'',digital:style?.kind==='digital',values:records.filter(row=>Date.parse(row.timestampUtc)>=start&&(typeof row.value==='number'||typeof row.value==='boolean')&&(!row.status||['good','ok'].includes(row.status.toLowerCase()))).map(row=>({t:Date.parse(row.timestampUtc),y:Number(row.value)*(style?.factor??1)})).sort((a,b)=>a.t-b.t)};}));
|
||||
if(!target?.isConnected)return;
|
||||
if(!series.some(item=>item.values.length)){target.innerHTML='<div class="empty">Keine numerischen Trendwerte in diesem Zeitraum.</div>';return;}
|
||||
if(widget.type==='Values') {target.innerHTML=`<div class="list">${series.map(item=>`<div class="list-item"><strong>${escapeHtml(item.name)}</strong><span>${item.values.length?escapeHtml(item.values.at(-1).y.toLocaleString('de-DE')):'—'} ${escapeHtml(item.unit)}</span></div>`).join('')}</div>`;return;}
|
||||
target.innerHTML=`<canvas class="chart" role="img" aria-label="Trendverlauf"></canvas><div class="chart-legend">${series.map(item=>`<span><i style="background:${item.color}"></i>${escapeHtml(item.name)} ${escapeHtml(item.unit)}</span>`).join('')}</div><div class="note">Bis zu 2.000 letzte Werte je Trend. Unterschiedliche Einheiten teilen sich hier eine Achse.</div>`;
|
||||
drawTrendChart(target.querySelector('canvas'),series,start,Date.now());
|
||||
} catch(error) { if(target?.isConnected){target.innerHTML='<div class="empty"></div>';target.firstElementChild.textContent=error.message;} }
|
||||
}
|
||||
function drawTrendChart(canvas,series,start,end) {
|
||||
const width=canvas.clientWidth||700,height=225,ratio=window.devicePixelRatio||1;canvas.width=width*ratio;canvas.height=height*ratio;const ctx=canvas.getContext('2d');ctx.scale(ratio,ratio);
|
||||
let min=Infinity,max=-Infinity;for(const item of series)for(const point of item.values){min=Math.min(min,point.y);max=Math.max(max,point.y);}if(min===max){min-=1;max+=1;}
|
||||
const x=t=>50+(t-start)/(end-start)*(width-66),y=value=>12+(max-value)/(max-min)*180;
|
||||
ctx.font='10px Segoe UI';ctx.fillStyle=getComputedStyle(canvas).getPropertyValue('--muted');ctx.strokeStyle='#71809633';
|
||||
for(let i=0;i<=4;i++){const value=min+(max-min)*i/4,pos=y(value);ctx.beginPath();ctx.moveTo(49,pos);ctx.lineTo(width-10,pos);ctx.stroke();ctx.fillText(value.toLocaleString('de-DE',{maximumFractionDigits:2}),1,pos+3);}
|
||||
ctx.fillText(new Date(start).toLocaleString('de-DE',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}),50,215);ctx.textAlign='right';ctx.fillText(new Date(end).toLocaleTimeString('de-DE'),width-10,215);
|
||||
for(const item of series){ctx.strokeStyle=item.color;ctx.fillStyle=item.color;ctx.lineWidth=Number(state.preferences?.trendLineWidth||1.8);ctx.beginPath();item.values.forEach((point,i)=>{if(!i)ctx.moveTo(x(point.t),y(point.y));else {if(item.digital)ctx.lineTo(x(point.t),y(item.values[i-1].y));ctx.lineTo(x(point.t),y(point.y));}});ctx.stroke();if(item.values.length===1){ctx.beginPath();ctx.arc(x(item.values[0].t),y(item.values[0].y),3,0,Math.PI*2);ctx.fill();}}
|
||||
}
|
||||
|
||||
function bindTrendViewer() {
|
||||
const target=document.createElement('article');target.className='card';target.style.marginBottom='10px';
|
||||
target.innerHTML=`<div class="card-head"><h2>Trend</h2><a class="btn" href="/public-trends.html" target="_blank" rel="noopener">Öffentliche Trends</a></div><div class="row"><label>Datenreihe<select id="trend-view-log">${state.trendLogs.map(log=>`<option value="${log.id}">${escapeHtml(log.name)}</option>`).join('')}</select></label><label>Zeitraum<select id="trend-view-hours"><option value="24">24 h</option><option value="168">7 Tage</option><option value="720">30 Tage</option></select></label></div><div id="trend-view-chart"></div>`;
|
||||
document.querySelector('#content .topline').after(target);
|
||||
const update=()=>{const id=document.querySelector('#trend-view-log').value;if(id)loadWidget({singleTrendLogId:id,rangeHours:Number(document.querySelector('#trend-view-hours').value),type:'Graph'},document.querySelector('#trend-view-chart'));else document.querySelector('#trend-view-chart').innerHTML='<div class="empty">Noch keine Trenddaten.</div>';};
|
||||
document.querySelector('#trend-view-log').addEventListener('change',update);document.querySelector('#trend-view-hours').addEventListener('change',update);update();
|
||||
}
|
||||
|
||||
function viewLtdRunner() {
|
||||
const job=state.runnerJobs.find(item=>item.id===state.runnerEditId);
|
||||
const mailReady=state.notifications.find(item=>item.channel==='Mail')?.hasApiKey;
|
||||
const fields=job||{name:'',selectionId:'',time:'06:00',rangeHours:24,delimiter:';',enabled:true,mailEnabled:false,mailTo:'',mailSubject:'Trenddaten',mailMessage:'Automatischer Export aus SE-Inno Universalgateway.'};
|
||||
return `<article class="card"><div class="card-head"><div><h2>CSV-Runner</h2><div class="note">Gespeicherte Auswahlen automatisch als CSV ins Dateisystem exportieren und optional per Mail verschicken.</div></div><button class="btn" id="new-runner">Neuer Job</button></div><form id="runner-form" class="form-grid"><label>Name<input name="name" value="${escapeHtml(fields.name)}" placeholder="Tagesexport Lüftung" maxlength="120" required></label><label>Auswahl<select name="selectionId" required><option value="">Auswahl wählen</option>${state.trendSelections.map(item=>`<option value="${item.id}" ${item.id===fields.selectionId?'selected':''}>${escapeHtml(item.name)}</option>`).join('')}</select></label><label>Uhrzeit (deutsch)<input name="time" type="time" value="${fields.time}" required><span class="note">Format HH:MM Uhr, Zeitzone Europe/Berlin.</span></label><label>Zeitraum<select name="rangeHours">${[24,48,168,720].map(hours=>`<option value="${hours}" ${hours===fields.rangeHours?'selected':''}>letzte ${hours<168?hours+' h':hours/24+' Tage'}</option>`).join('')}</select></label><label>CSV-Trennzeichen<select name="delimiter">${[[';','Semikolon ;'],[',','Komma ,'],['\t','Tabulator']].map(([value,label])=>`<option value="${value}" ${value===fields.delimiter?'selected':''}>${label}</option>`).join('')}</select></label><label class="switch"><input name="enabled" type="checkbox" ${fields.enabled?'checked':''}> aktiv</label><label class="switch"><input name="mailEnabled" type="checkbox" ${fields.mailEnabled?'checked':''} ${mailReady?'':'disabled'}> CSV per Mail verschicken ${mailReady?'':'(API-Key fehlt)'}</label><label>Mail an<input name="mailTo" value="${escapeHtml(fields.mailTo||'')}" placeholder="kunde@example.com; service@example.com"><span class="note">Mehrere Empfänger mit Semikolon oder Komma trennen.</span></label><label>Betreff<input name="mailSubject" value="${escapeHtml(fields.mailSubject)}"></label><label class="full">Nachricht<input name="mailMessage" value="${escapeHtml(fields.mailMessage)}"></label><div class="buttons full"><button class="btn primary">${job?'Runner speichern':'Runner-Job anlegen'}</button></div><div id="runner-message" class="full"></div></form><section class="grid equal runner-columns" style="margin-top:10px"><article class="card"><div class="card-head"><h2>Vorhandene Runner</h2><span>${state.runnerJobs.length}</span></div><div class="list">${state.runnerJobs.map(item=>`<div class="list-item"><div><strong>${escapeHtml(item.name)}</strong><span class="note">${escapeHtml(state.trendSelections.find(selection=>selection.id===item.selectionId)?.name||'Auswahl fehlt')} · ${item.time} Uhr · ${item.enabled?'aktiv':'inaktiv'}<br>${item.lastResult?escapeHtml(item.lastResult.success?'Letzter Lauf: '+new Date(item.lastResult.ranAtUtc).toLocaleString('de-DE'):item.lastResult.error||'Fehler'):'Noch nicht gelaufen'}</span></div><div class="buttons"><button class="btn" data-test-runner="${item.id}">Test</button><button class="btn" data-edit-runner="${item.id}">Bearbeiten</button><button class="btn" data-delete-runner="${item.id}">Löschen</button></div></div>`).join('')||'<div class="empty">Keine Runner angelegt.</div>'}</div></article><article class="card"><div class="card-head"><h2>Ausführung</h2></div><div id="runner-execution" class="empty">Geplante Jobs werden zur eingestellten Uhrzeit ausgeführt. Der letzte Lauf steht beim jeweiligen Job.</div></article></section></article>`;
|
||||
}
|
||||
function bindLtdRunner() {
|
||||
const status = document.querySelector('#runner-execution');
|
||||
status.parentElement.querySelector('h2').textContent = 'Warteschlange';
|
||||
const queue = document.createElement('div');
|
||||
queue.id = 'runner-queue';
|
||||
status.before(queue);
|
||||
status.textContent = '';
|
||||
const refreshQueue = async () => {
|
||||
try {
|
||||
const items = await api('/api/runner/queue');
|
||||
if (!queue.isConnected) return;
|
||||
queue.innerHTML = items.length ? `<div class="list">${items.map(item => `<div class="list-item"><div><strong>${escapeHtml(item.name)}</strong><span class="note">${item.state === 'Running' ? 'Wird ausgeführt' : 'Wartend'} · ${escapeHtml(new Date(item.enqueuedAtUtc).toLocaleTimeString('de-DE'))}</span></div></div>`).join('')}</div>` : '<div class="empty">Keine Aufträge warten auf die Ausführung.</div>';
|
||||
} catch (error) { if (queue.isConnected) queue.textContent = error.message; }
|
||||
};
|
||||
refreshQueue();
|
||||
const timer = setInterval(() => { if (!queue.isConnected) clearInterval(timer); else refreshQueue(); }, 2000);
|
||||
document.querySelector('#new-runner').addEventListener('click',()=>{state.runnerEditId=null;renderView();});
|
||||
document.querySelectorAll('[data-edit-runner]').forEach(button=>button.addEventListener('click',()=>{state.runnerEditId=button.dataset.editRunner;renderView();}));
|
||||
document.querySelectorAll('[data-delete-runner]').forEach(button=>button.addEventListener('click',deleteRunnerJob));
|
||||
document.querySelectorAll('[data-test-runner]').forEach(button=>button.addEventListener('click',async()=>{const job=state.runnerJobs.find(item=>item.id===button.dataset.testRunner);if(job.mailEnabled&&!window.confirm(`Test startet CSV-Export und Mailversand an ${job.mailTo}. Fortfahren?`))return;button.disabled=true;try{errorTarget('runner-execution','Job wird ausgeführt …',true);const result=await api(`/api/runner/jobs/${job.id}/test`,{method:'POST'});await loadData();renderView();errorTarget('runner-execution',result.success?'CSV erstellt'+(job.mailEnabled?' und von der Mail-API angenommen.':'.'):result.error,result.success);}catch(error){errorTarget('runner-execution',error.message);}finally{button.disabled=false;}}));
|
||||
document.querySelector('#runner-form').addEventListener('submit',async event=>{event.preventDefault();const form=new FormData(event.currentTarget);try{await api('/api/runner/jobs'+(state.runnerEditId?'/'+state.runnerEditId:''),{method:state.runnerEditId?'PATCH':'POST',body:JSON.stringify({name:form.get('name'),selectionId:form.get('selectionId'),time:form.get('time'),rangeHours:Number(form.get('rangeHours')),delimiter:form.get('delimiter'),enabled:form.has('enabled'),mailEnabled:form.has('mailEnabled'),mailTo:form.get('mailTo')||null,mailSubject:form.get('mailSubject'),mailMessage:form.get('mailMessage')})});state.runnerEditId=null;await loadData();renderView();}catch(error){errorTarget('runner-message',error.message);}});
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
const bulkProtocolTabs = [['All', 'Alle'], ['Bacnet', 'BACnet'], ['OpcUa', 'OPC UA'],
|
||||
['Modbus', 'Modbus'], ['Knx', 'KNX'], ['Mqtt', 'MQTT'], ['Internal', 'Intern']];
|
||||
|
||||
function viewMappingBatch() {
|
||||
return `<article class="card mapping-batch">
|
||||
<div class="card-head"><h2>Sammelmapping</h2></div>
|
||||
<div class="point-tabs" role="group" aria-label="Quellprotokoll">
|
||||
${bulkProtocolTabs.map(([key, label]) => `<button type="button" class="btn" data-bulk-protocol="${key}">${label}</button>`).join('')}
|
||||
</div>
|
||||
<div class="grid two mapping-batch-grid">
|
||||
<div>
|
||||
<div class="buttons">
|
||||
<button type="button" class="btn" data-bulk-select-all>Alle sichtbaren auswählen</button>
|
||||
<button type="button" class="btn" data-bulk-clear>Auswahl leeren</button>
|
||||
<span data-bulk-count role="status"></span>
|
||||
</div>
|
||||
<div class="table-scroll bulk-point-list">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Auswahl</th><th scope="col">Datenpunkt</th><th scope="col">Protokoll</th><th scope="col">Typ</th></tr></thead>
|
||||
<tbody data-bulk-points></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="note">Strg oder ⌘ wählt einzelne Zeilen zu oder ab. Umschalt wählt einen Bereich.</p>
|
||||
</div>
|
||||
<form id="bulk-mapping-form" class="form">
|
||||
<label>Ziel<select name="target">
|
||||
<option value="Bacnet">BACnet-Objekte auf dem Gateway</option>
|
||||
<option value="OpcUa">OPC-UA-Variablen auf dem Gateway</option>
|
||||
<option value="Modbus">Modbus-TCP-Server</option>
|
||||
${can('manage_integrations') ? '<option value="Mqtt">MQTT</option>' : ''}
|
||||
</select></label>
|
||||
<div data-bulk-mqtt class="form" hidden>
|
||||
<label class="switch"><input type="checkbox" name="seMonitoring" checked> SE-Monitoring verwenden</label>
|
||||
<div data-bulk-mqtt-site>${mqttMonitoringSiteFields()}</div>
|
||||
<div data-bulk-mqtt-free class="form" hidden>
|
||||
<label>Format<select name="mqttFreeFormat">${mqttTopicFormatOptions('SingleTopic')}</select></label>
|
||||
<label>MQTT-Topic-Präfix<input name="mqttTopicPrefix" placeholder="z. B. Heizung/ISP01" maxlength="850"></label>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bulk-modbus hidden>
|
||||
<label>Serverinstanz<select name="modbusServerId"></select></label>
|
||||
<label>Erste Modbus-Adresse (optional)<input name="firstRegister" type="number" min="0" max="65535"></label>
|
||||
<p class="note">Zahlen nutzen Input Register. Binäre Werte nutzen Discrete Inputs. Belegte Adressen werden übersprungen.</p>
|
||||
</div>
|
||||
<div><button type="submit" class="btn primary">Auswahl mappen</button></div>
|
||||
<div data-bulk-message role="status"></div>
|
||||
<div data-bulk-assignments></div>
|
||||
</form>
|
||||
</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function bindMappingBatch() {
|
||||
const card = document.querySelector('.mapping-batch');
|
||||
if (!card) return;
|
||||
const form = card.querySelector('form');
|
||||
const body = card.querySelector('[data-bulk-points]');
|
||||
const count = card.querySelector('[data-bulk-count]');
|
||||
const tabs = [...card.querySelectorAll('[data-bulk-protocol]')];
|
||||
const message = card.querySelector('[data-bulk-message]');
|
||||
const assignments = card.querySelector('[data-bulk-assignments]');
|
||||
const target = form.elements.target;
|
||||
const serverSelect = form.elements.modbusServerId;
|
||||
let serverRequest;
|
||||
let anchor;
|
||||
let visiblePoints = [];
|
||||
let running = false;
|
||||
const selected = new Set();
|
||||
let protocol = state.bulkMappingProtocol || 'All';
|
||||
|
||||
function updateSelection() {
|
||||
count.textContent = `${selected.size} ausgewählt`;
|
||||
form.querySelector('button[type=submit]').disabled = running || !selected.size;
|
||||
body.querySelectorAll('input[type=checkbox]').forEach(input => { input.checked = selected.has(input.value); });
|
||||
}
|
||||
|
||||
function renderPoints() {
|
||||
tabs.forEach(tab => {
|
||||
const active = tab.dataset.bulkProtocol === protocol;
|
||||
tab.classList.toggle('active', active);
|
||||
tab.setAttribute('aria-pressed', String(active));
|
||||
});
|
||||
visiblePoints = state.points.filter(point => point.readable && (protocol === 'All' || point.protocol === protocol));
|
||||
body.innerHTML = visiblePoints.map(point => `<tr data-bulk-point="${point.id}">
|
||||
<td><input type="checkbox" value="${point.id}" aria-label="${escapeHtml(point.displayName)} auswählen"></td>
|
||||
<td>${escapeHtml(point.displayName)}</td><td>${escapeHtml(point.protocol)}</td><td>${escapeHtml(point.valueType)}</td>
|
||||
</tr>`).join('') || '<tr><td colspan="4">Keine lesbaren Datenpunkte.</td></tr>';
|
||||
updateSelection();
|
||||
}
|
||||
|
||||
tabs.forEach(tab => tab.addEventListener('click', () => {
|
||||
protocol = state.bulkMappingProtocol = tab.dataset.bulkProtocol;
|
||||
anchor = undefined;
|
||||
renderPoints();
|
||||
}));
|
||||
body.addEventListener('click', event => {
|
||||
const row = event.target.closest('[data-bulk-point]');
|
||||
if (!row) return;
|
||||
const id = row.dataset.bulkPoint;
|
||||
const from = visiblePoints.findIndex(point => point.id === anchor);
|
||||
if (event.shiftKey && from >= 0) {
|
||||
const to = visiblePoints.findIndex(point => point.id === id);
|
||||
for (const point of visiblePoints.slice(Math.min(from, to), Math.max(from, to) + 1)) selected.add(point.id);
|
||||
} else {
|
||||
if (event.target.type !== 'checkbox' && !event.ctrlKey && !event.metaKey) {
|
||||
const onlySelected = selected.size === 1 && selected.has(id);
|
||||
selected.clear();
|
||||
if (!onlySelected) selected.add(id);
|
||||
} else if (selected.has(id)) selected.delete(id);
|
||||
else selected.add(id);
|
||||
anchor = id;
|
||||
}
|
||||
updateSelection();
|
||||
});
|
||||
card.querySelector('[data-bulk-select-all]').addEventListener('click', () => {
|
||||
visiblePoints.forEach(point => selected.add(point.id));
|
||||
updateSelection();
|
||||
});
|
||||
card.querySelector('[data-bulk-clear]').addEventListener('click', () => {
|
||||
selected.clear();
|
||||
anchor = undefined;
|
||||
updateSelection();
|
||||
});
|
||||
|
||||
async function updateTarget() {
|
||||
const modbus = target.value === 'Modbus';
|
||||
const mqtt = target.value === 'Mqtt';
|
||||
const prefix = form.elements.mqttTopicPrefix;
|
||||
card.querySelector('[data-bulk-modbus]').hidden = !modbus;
|
||||
card.querySelector('[data-bulk-mqtt]').hidden = !mqtt;
|
||||
const monitoring = mqtt && form.elements.seMonitoring.checked;
|
||||
card.querySelector('[data-bulk-mqtt-site]').hidden = !monitoring;
|
||||
card.querySelector('[data-bulk-mqtt-free]').hidden = !mqtt || monitoring;
|
||||
card.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; });
|
||||
prefix.required = mqtt && !monitoring;
|
||||
serverSelect.required = modbus;
|
||||
if (!modbus || serverRequest) return;
|
||||
serverSelect.innerHTML = '<option value="">Server werden geladen …</option>';
|
||||
try {
|
||||
serverRequest = api('/api/mappings/bulk/modbus-servers');
|
||||
const servers = await serverRequest;
|
||||
serverSelect.innerHTML = servers.map(server => `<option value="${server.id}">${escapeHtml(server.name)} · ${server.firstHoldingRegister}–${server.firstHoldingRegister + server.holdingRegisterCount - 1}</option>`).join('')
|
||||
|| '<option value="">Keine Modbus-TCP-Instanz konfiguriert</option>';
|
||||
} catch (error) {
|
||||
serverRequest = null;
|
||||
serverSelect.innerHTML = '<option value="">Serverliste nicht verfügbar</option>';
|
||||
message.textContent = error.message;
|
||||
}
|
||||
}
|
||||
target.addEventListener('change', updateTarget);
|
||||
form.elements.seMonitoring.addEventListener('change', updateTarget);
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (running || selected.size === 0) return;
|
||||
if (selected.size > 500) { message.textContent = 'Maximal 500 Datenpunkte pro Sammelmapping.'; return; }
|
||||
const fields = new FormData(form);
|
||||
const mqtt = target.value === 'Mqtt';
|
||||
const monitoring = mqtt && fields.has('seMonitoring');
|
||||
running = true;
|
||||
updateSelection();
|
||||
assignments.replaceChildren();
|
||||
message.textContent = 'Mappings werden angelegt …';
|
||||
try {
|
||||
const result = await api('/api/mappings/bulk', { method: 'POST', body: JSON.stringify({
|
||||
sourcePointIds: state.points.filter(point => selected.has(point.id)).map(point => point.id),
|
||||
target: target.value,
|
||||
modbusServerId: target.value === 'Modbus' ? fields.get('modbusServerId') || null : null,
|
||||
firstRegister: target.value === 'Modbus' && fields.get('firstRegister') !== '' ? Number(fields.get('firstRegister')) : null,
|
||||
mqttFormat: mqtt ? monitoring ? 'SeMonitoring' : fields.get('mqttFreeFormat') : null,
|
||||
mqttSite: monitoring ? mqttSiteFromForm(fields) : null,
|
||||
mqttTopicPrefix: mqtt && !monitoring ? fields.get('mqttTopicPrefix') : null
|
||||
}) });
|
||||
state.bulkMappingResult = result;
|
||||
await loadData();
|
||||
if (state.view === 'mappings') renderView();
|
||||
} catch (error) {
|
||||
message.textContent = error.message;
|
||||
} finally { running = false; updateSelection(); }
|
||||
});
|
||||
renderPoints();
|
||||
updateTarget();
|
||||
if (state.bulkMappingResult) {
|
||||
const { created, existing, assignments: entries } = state.bulkMappingResult;
|
||||
state.bulkMappingResult = null;
|
||||
message.textContent = `${created} angelegt, ${existing} bereits vorhanden.`;
|
||||
if (entries.length) assignments.innerHTML = `<details><summary>Zugewiesene Ziele anzeigen</summary><ul>${entries.map(entry => `<li>${escapeHtml(entry)}</li>`).join('')}</ul></details>`;
|
||||
}
|
||||
}
|
||||
|
||||
const configurationCsvFiles = {
|
||||
points: ['/api/points/csv', 'seiugw-datenpunkte.csv'],
|
||||
mappings: ['/api/mappings/csv', 'seiugw-mappings.csv'],
|
||||
mqtt: ['/api/mqtt/mappings/csv', 'seiugw-mqtt-mappings.csv']
|
||||
};
|
||||
|
||||
function configurationCsvButtons(kind) {
|
||||
return `<div class="buttons" data-configuration-csv="${kind}">
|
||||
<button type="button" class="btn" data-csv-export>CSV exportieren</button>
|
||||
<button type="button" class="btn" data-csv-import>CSV importieren</button>
|
||||
<input type="file" accept=".csv,text/csv" aria-label="CSV-Datei auswählen" hidden>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function bindConfigurationCsv(kind, statusId) {
|
||||
const buttons = document.querySelector(`[data-configuration-csv="${kind}"]`);
|
||||
if (!buttons) return;
|
||||
const fileInput = buttons.querySelector('input');
|
||||
const [route, filename] = configurationCsvFiles[kind];
|
||||
const status = () => document.getElementById(statusId);
|
||||
buttons.querySelector('[data-csv-export]').addEventListener('click', async () => {
|
||||
try {
|
||||
const result = await fetch(route, { headers: { Authorization: `Bearer ${state.token}` } });
|
||||
if (!result.ok) throw new Error(`CSV-Export fehlgeschlagen (${result.status}).`);
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(await result.blob());
|
||||
link.download = filename;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
} catch (error) { if (status()) status().textContent = error.message; }
|
||||
});
|
||||
buttons.querySelector('[data-csv-import]').addEventListener('click', () => fileInput.click());
|
||||
fileInput.addEventListener('change', async () => {
|
||||
const file = fileInput.files[0];
|
||||
fileInput.value = '';
|
||||
if (!file || !status()) return;
|
||||
const importButton = buttons.querySelector('[data-csv-import]');
|
||||
importButton.disabled = true;
|
||||
status().textContent = 'CSV wird eingelesen …';
|
||||
try {
|
||||
if (file.size > 4 * 1024 * 1024) throw new Error('Maximale CSV-Größe: 4 MB.');
|
||||
const result = await api(route, { method: 'POST', body: JSON.stringify({ csv: await file.text() }) });
|
||||
await loadData();
|
||||
if (!buttons.isConnected) return;
|
||||
renderView();
|
||||
if (status()) status().textContent = `${result.created} angelegt, ${result.updated} aktualisiert.`;
|
||||
} catch (error) { if (status()) status().textContent = error.message; }
|
||||
finally { importButton.disabled = false; }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
function mqttPointDefaults(id) {
|
||||
return state.mqttMappingDefaults?.points.find(point => point.pointId === id);
|
||||
}
|
||||
|
||||
function mqttMonitoringSiteFields(site = state.mqttMappingDefaults?.site) {
|
||||
return `<div class="row three">
|
||||
<label>Projektjahr<input name="projectYear" type="number" min="2000" max="2100" value="${site?.projectYear ?? ''}" data-mqtt-required></label>
|
||||
<label>Projektnummer<input name="projectNumber" maxlength="32" pattern="P[0-9]+" value="${escapeHtml(site?.projectNumber || '')}" data-mqtt-required></label>
|
||||
<label>ISP<input name="ispNumber" maxlength="32" pattern="ISP[0-9]+" value="${escapeHtml(site?.ispNumber || '')}" data-mqtt-required></label>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function mqttTopicFormatOptions(selected) {
|
||||
return `<option value="SingleTopic" ${selected === 'SingleTopic' ? 'selected' : ''}>Einzel-Topic (Zahl)</option>
|
||||
<option value="Json" ${selected === 'Json' ? 'selected' : ''}>JSON</option>`;
|
||||
}
|
||||
|
||||
function mqttMappingFormatLabel(format) {
|
||||
return { SeMonitoring: 'SE-Monitoring', SingleTopic: 'Einzel-Topic', Json: 'JSON' }[format] || format;
|
||||
}
|
||||
|
||||
function mqttSiteFromForm(form) {
|
||||
return {
|
||||
projectYear: Number(form.get('projectYear')),
|
||||
projectNumber: form.get('projectNumber').trim(),
|
||||
ispNumber: form.get('ispNumber').trim()
|
||||
};
|
||||
}
|
||||
|
||||
function mqttMappingForm(editing) {
|
||||
const points = mappingPointOptions(editing?.pointId, 'valueType');
|
||||
if (!points) return '<div class="notice">Zuerst einen Datenpunkt anlegen.</div>';
|
||||
const suggested = mqttPointDefaults(editing?.pointId ?? state.points[0]?.id);
|
||||
const monitoring = editing ? editing.format === 'SeMonitoring' : !!suggested?.category;
|
||||
const option = (value, label, selected) => `<option value="${value}" ${value === selected ? 'selected' : ''}>${label}</option>`;
|
||||
const categories = ['Analog', 'Notify', 'Alarms', 'Setpoints'];
|
||||
if (editing?.seCategory === 'Alarm') categories.push('Alarm');
|
||||
return `<form id="mqtt-mapping-form" class="form">
|
||||
<label>Datenpunkt<select name="pointId" required>${points}</select></label>
|
||||
<div class="row">
|
||||
<label>Richtung<select name="direction">
|
||||
${option('Publish', 'Nur senden', editing?.direction)}
|
||||
${option('Subscribe', 'Nur empfangen', editing?.direction)}
|
||||
${option('Bidirectional', 'Senden und empfangen', editing?.direction)}
|
||||
</select></label>
|
||||
<label>QoS<select name="qualityOfService">
|
||||
${option('AtMostOnce', '0 · höchstens einmal', editing?.qualityOfService)}
|
||||
${option('AtLeastOnce', '1 · mindestens einmal', editing?.qualityOfService ?? 'AtLeastOnce')}
|
||||
${option('ExactlyOnce', '2 · genau einmal', editing?.qualityOfService)}
|
||||
</select></label>
|
||||
</div>
|
||||
<label class="switch"><input type="checkbox" name="retain" ${editing?.retain ? 'checked' : ''}> Retained Message</label>
|
||||
<label class="switch"><input name="seMonitoring" type="checkbox" ${monitoring ? 'checked' : ''}> SE-Monitoring verwenden</label>
|
||||
<div data-mqtt-monitoring class="form" ${monitoring ? '' : 'hidden'}>
|
||||
${mqttMonitoringSiteFields(editing?.format === 'SeMonitoring' ? editing : undefined)}
|
||||
<div class="row">
|
||||
<label>Kategorie<select name="seCategory">
|
||||
${categories.map(category => option(category, category, editing?.seCategory ?? suggested?.category)).join('')}
|
||||
</select></label>
|
||||
<label>Punktname<input name="topicName" maxlength="200" value="${escapeHtml(editing?.topicName ?? suggested?.topicName ?? '')}" data-mqtt-required></label>
|
||||
</div>
|
||||
<code data-mqtt-preview class="note"></code>
|
||||
</div>
|
||||
<div data-mqtt-free class="form" ${monitoring ? 'hidden' : ''}>
|
||||
<div class="row">
|
||||
<label>Format<select name="freeFormat">${mqttTopicFormatOptions(editing?.format === 'Json' || !suggested?.category ? 'Json' : 'SingleTopic')}</select></label>
|
||||
<label>Topic<input name="jsonTopic" maxlength="1024" value="${escapeHtml(editing?.jsonTopic ?? '')}" placeholder="anlage/temperatur"></label>
|
||||
</div>
|
||||
<label data-mqtt-json-property>JSON-Eigenschaft (optional)<input name="jsonProperty" value="${escapeHtml(editing?.jsonProperty ?? '')}" placeholder="temperatur"></label>
|
||||
</div>
|
||||
<div class="buttons"><button type="submit" class="btn primary">MQTT-Mapping speichern</button>
|
||||
${editing ? '<button type="button" class="btn" id="cancel-mqtt-mapping-edit">Abbrechen</button>' : ''}</div>
|
||||
<div id="mqtt-mapping-message" role="status"></div>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
function bindMqttMappingOptions(form) {
|
||||
if (!form) return;
|
||||
const fields = form.elements;
|
||||
let preferMonitoring = !state.mqttMappingEditId || fields.seMonitoring.checked;
|
||||
let preferFreeFormat = state.mqttMappingEditId ? fields.freeFormat.value : 'SingleTopic';
|
||||
function update(reselect = false) {
|
||||
const selected = mqttPointDefaults(fields.pointId.value);
|
||||
const supportsNumbers = !!selected?.category;
|
||||
fields.seMonitoring.disabled = !supportsNumbers;
|
||||
fields.freeFormat.options[0].disabled = !supportsNumbers;
|
||||
if (reselect) {
|
||||
fields.seMonitoring.checked = supportsNumbers && preferMonitoring;
|
||||
fields.seCategory.value = selected?.category || 'Analog';
|
||||
fields.topicName.value = selected?.topicName || '';
|
||||
fields.freeFormat.value = supportsNumbers ? preferFreeFormat : 'Json';
|
||||
}
|
||||
if (!supportsNumbers) {
|
||||
fields.seMonitoring.checked = false;
|
||||
fields.freeFormat.value = 'Json';
|
||||
}
|
||||
const monitoring = fields.seMonitoring.checked;
|
||||
form.querySelector('[data-mqtt-monitoring]').hidden = !monitoring;
|
||||
form.querySelector('[data-mqtt-free]').hidden = monitoring;
|
||||
form.querySelector('[data-mqtt-json-property]').hidden = fields.freeFormat.value !== 'Json';
|
||||
fields.jsonTopic.required = !monitoring;
|
||||
form.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; });
|
||||
fields.direction.options[0].disabled = monitoring && fields.seCategory.value === 'Setpoints';
|
||||
fields.direction.options[1].disabled = fields.direction.options[0].disabled;
|
||||
if (fields.direction.options[0].disabled) fields.direction.value = 'Bidirectional';
|
||||
form.querySelector('[data-mqtt-preview]').textContent = `Projekte${fields.projectYear.value}/${fields.projectNumber.value}/${fields.ispNumber.value}/${fields.seCategory.value}/${fields.topicName.value}_Wert`;
|
||||
}
|
||||
fields.pointId.addEventListener('change', () => update(true));
|
||||
fields.seMonitoring.addEventListener('change', () => {
|
||||
preferMonitoring = fields.seMonitoring.checked;
|
||||
update();
|
||||
});
|
||||
fields.freeFormat.addEventListener('change', () => {
|
||||
preferFreeFormat = fields.freeFormat.value;
|
||||
update();
|
||||
});
|
||||
fields.seCategory.addEventListener('change', () => update());
|
||||
form.querySelector('[data-mqtt-monitoring]').addEventListener('input', () => update());
|
||||
update();
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
function viewMqttTopicBrowser() {
|
||||
return `<article class="card mqtt-topic-browser" id="mqtt-topic-browser">
|
||||
<div class="card-head"><h2>Topic-Browser</h2><span class="note" data-mqtt-browser-status></span></div>
|
||||
<form class="form" data-broker-filter>
|
||||
<div class="row">
|
||||
<label>Filter am Broker<input name="filter" maxlength="1024" placeholder="z. B. Projekte2019/#" value="${escapeHtml(state.mqttBrowser?.filter || '#')}"></label>
|
||||
<div class="buttons mqtt-browser-start"><button type="submit" class="btn primary">Topics beobachten</button></div>
|
||||
</div>
|
||||
</form>
|
||||
<div data-mqtt-browser-message role="status"></div>
|
||||
<div class="grid two mqtt-browser-content" hidden>
|
||||
<div>
|
||||
<label>Topic suchen<input type="search" data-topic-search placeholder="Teil des Topic-Pfads"></label>
|
||||
${can('manage_sources') ? `<div class="buttons mqtt-browser-selection">
|
||||
<button class="btn" type="button" data-topic-select-all>Alle Treffer auswählen</button>
|
||||
<button class="btn" type="button" data-topic-clear>Auswahl leeren</button>
|
||||
<button class="btn primary" type="button" data-topic-import>Auswahl übernehmen</button>
|
||||
<span class="note" data-topic-selected></span>
|
||||
</div>` : ''}
|
||||
<div class="mqtt-topic-tree" data-topic-tree aria-label="Topic-Baum" role="region" tabindex="0"></div>
|
||||
</div>
|
||||
<section class="mqtt-topic-detail" data-topic-detail aria-label="Topic-Details"></section>
|
||||
</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function mqttTopicNodes(topics) {
|
||||
const root = new Map();
|
||||
for (const topic of topics) {
|
||||
let children = root;
|
||||
const parts = topic.topic.split('/');
|
||||
const levels = parts.length > 48 ? [...parts.slice(0, 47), parts.slice(47).join('/')] : parts;
|
||||
for (let index = 0; index < levels.length; index++) {
|
||||
const label = levels[index];
|
||||
const path = levels.slice(0, index + 1).join('/');
|
||||
if (!children.has(label)) children.set(label, { label, path, children: new Map(), selectable: [] });
|
||||
const node = children.get(label);
|
||||
if (topic.valueType && !topic.pointId) node.selectable.push(topic.topic);
|
||||
if (index === levels.length - 1) node.topic = topic;
|
||||
children = node.children;
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
function bindMqttTopicBrowser() {
|
||||
const browser = document.querySelector('#mqtt-topic-browser');
|
||||
if (!browser) return;
|
||||
const model = state.mqttBrowser ??= {
|
||||
filter: '#', snapshot: null, query: '', picked: new Set(), expanded: new Map(), focused: null, message: ''
|
||||
};
|
||||
const nodes = browser.querySelector('[data-topic-tree]');
|
||||
const detail = browser.querySelector('[data-topic-detail]');
|
||||
const form = browser.querySelector('[data-broker-filter]');
|
||||
const search = browser.querySelector('[data-topic-search]');
|
||||
const message = browser.querySelector('[data-mqtt-browser-message]');
|
||||
const content = browser.querySelector('.mqtt-browser-content');
|
||||
const status = browser.querySelector('[data-mqtt-browser-status]');
|
||||
const importButton = browser.querySelector('[data-topic-import]');
|
||||
const canImport = !!importButton;
|
||||
let visibleTopics = [];
|
||||
let visibleBranches = new Map();
|
||||
let busy = false;
|
||||
let timer;
|
||||
let revision = 0;
|
||||
search.value = model.query;
|
||||
|
||||
const token = value => escapeHtml(encodeURIComponent(value));
|
||||
const importable = topic => topic.valueType && !topic.pointId;
|
||||
const displayType = type => ({ Boolean: 'Binär', Double: 'Zahl', String: 'Text', Json: 'JSON' }[type] || '—');
|
||||
|
||||
function renderLeaf(topic, name) {
|
||||
return `<div class="mqtt-tree-row mqtt-tree-leaf">
|
||||
${canImport && importable(topic) ? `<input type="checkbox" data-topic-pick="${token(topic.topic)}" aria-label="${escapeHtml(topic.topic)} auswählen">` : ''}
|
||||
<button type="button" class="btn mqtt-topic-item" data-topic-item="${token(topic.topic)}"
|
||||
aria-pressed="${topic.topic === model.focused}">${escapeHtml(name || '(leere Ebene)')}</button>
|
||||
<span class="note mqtt-topic-value" title="${escapeHtml(topic.preview)}">${escapeHtml(topic.preview)}</span>
|
||||
${topic.pointId ? '<span class="tag gray">übernommen</span>' : ''}</div>`;
|
||||
}
|
||||
|
||||
function renderBranch(branch) {
|
||||
const opened = model.expanded.get(branch.path) ?? !!model.query;
|
||||
visibleBranches.set(branch.path, branch.selectable);
|
||||
return `<li><div class="mqtt-tree-row mqtt-tree-branch">
|
||||
${canImport && branch.selectable.length ? `<input type="checkbox" data-topic-branch-pick="${token(branch.path)}" aria-label="Zweig ${escapeHtml(branch.path || '/')} auswählen">` : ''}
|
||||
<button type="button" class="btn" data-topic-branch="${token(branch.path)}" aria-expanded="${opened}">
|
||||
<span aria-hidden="true">${opened ? '▾' : '▸'}</span> ${escapeHtml(branch.label || '(leere Ebene)')}</button>
|
||||
</div>${opened ? `<ul>${branch.topic ? `<li>${renderLeaf(branch.topic, branch.label)}</li>` : ''}
|
||||
${renderNodes(branch.children)}</ul>` : ''}</li>`;
|
||||
}
|
||||
|
||||
function renderNodes(branches) {
|
||||
return [...branches.values()].map(branch => branch.children.size ? renderBranch(branch) :
|
||||
`<li>${renderLeaf(branch.topic, branch.label)}</li>`).join('');
|
||||
}
|
||||
|
||||
function renderDetail() {
|
||||
const topic = model.snapshot?.topics.find(item => item.topic === model.focused);
|
||||
detail.innerHTML = topic ? `<h3>Topic-Details</h3>
|
||||
<code class="mqtt-topic-path">${escapeHtml(topic.topic)}</code>
|
||||
<dl class="connection-facts">
|
||||
<dt>Werttyp</dt><dd>${displayType(topic.valueType)}</dd>
|
||||
<dt>Empfangen</dt><dd>${statusTime(topic.receivedAtUtc)}</dd>
|
||||
<dt>Retained</dt><dd>${topic.retained ? 'Ja' : '—'}</dd>
|
||||
</dl>
|
||||
<pre class="mqtt-topic-preview">${escapeHtml(topic.preview)}</pre>
|
||||
${topic.pointId ? '<p class="note">Als externer Datenpunkt angelegt.</p>' :
|
||||
canImport && importable(topic) ? '<button type="button" class="btn primary" data-topic-import-one>Datenpunkt übernehmen</button>' :
|
||||
!topic.valueType ? '<p class="note">Dieser Nachrichtenwert kann nicht als Datenpunkt übernommen werden.</p>' : ''}`
|
||||
: '<p class="note">Ein Topic auswählen, um Wert und Details zu sehen.</p>';
|
||||
}
|
||||
|
||||
function syncSelection() {
|
||||
if (!canImport) return;
|
||||
nodes.querySelectorAll('[data-topic-pick]').forEach(input => {
|
||||
input.checked = model.picked.has(decodeURIComponent(input.dataset.topicPick));
|
||||
});
|
||||
nodes.querySelectorAll('[data-topic-branch-pick]').forEach(input => {
|
||||
const topics = visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick));
|
||||
const count = topics.filter(topic => model.picked.has(topic)).length;
|
||||
input.checked = count === topics.length;
|
||||
input.indeterminate = count > 0 && count < topics.length;
|
||||
});
|
||||
browser.querySelector('[data-topic-selected]').textContent = `${model.picked.size} ausgewählt`;
|
||||
importButton.disabled = busy || !model.picked.size;
|
||||
browser.querySelector('[data-topic-select-all]').disabled = !visibleTopics.some(importable);
|
||||
browser.querySelector('[data-topic-clear]').disabled = !model.picked.size;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const snapshot = model.snapshot;
|
||||
const query = model.query.trim().toLowerCase();
|
||||
visibleTopics = (snapshot?.topics || []).filter(topic => topic.topic.toLowerCase().includes(query));
|
||||
content.hidden = !snapshot;
|
||||
message.textContent = model.message;
|
||||
status.textContent = snapshot ? `${snapshot.connected ? 'Verbunden' : 'Getrennt'} · ${visibleTopics.length} von ${snapshot.topics.length} Topics` : '';
|
||||
if (!snapshot) return;
|
||||
if (!model.message && snapshot.error) message.textContent = snapshot.error;
|
||||
if (snapshot.limitReached && !message.textContent) message.textContent = '3.000 Topics erreicht. Mit einem Broker-Filter lässt sich der Bereich eingrenzen.';
|
||||
const scroll = nodes.scrollTop;
|
||||
const focused = nodes.contains(document.activeElement) ? document.activeElement : null;
|
||||
const focusAttribute = ['data-topic-item', 'data-topic-branch', 'data-topic-pick', 'data-topic-branch-pick'].find(attribute => focused?.hasAttribute(attribute));
|
||||
visibleBranches = new Map();
|
||||
nodes.innerHTML = visibleTopics.length ? `<ul>${renderNodes(mqttTopicNodes(visibleTopics))}</ul>` :
|
||||
`<div class="empty">${query ? 'Keine passenden Topics.' : 'Warte auf Retained- oder neue Nachrichten.'}</div>`;
|
||||
if (focusAttribute) {
|
||||
[...nodes.querySelectorAll(`[${focusAttribute}]`)].find(element =>
|
||||
element.getAttribute(focusAttribute) === focused.getAttribute(focusAttribute))?.focus({ preventScroll: true });
|
||||
}
|
||||
nodes.scrollTop = scroll;
|
||||
if (!detail.contains(document.activeElement)) renderDetail();
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
function acceptSnapshot(snapshot) {
|
||||
model.snapshot = snapshot;
|
||||
const eligible = new Set(snapshot.topics.filter(importable).map(topic => topic.topic));
|
||||
for (const topic of model.picked) if (!eligible.has(topic)) model.picked.delete(topic);
|
||||
render();
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
clearTimeout(timer);
|
||||
if (!browser.isConnected || !model.snapshot) return;
|
||||
if (!busy && !browser.closest('[data-points-panel]')?.hidden) {
|
||||
const currentRevision = revision;
|
||||
try {
|
||||
const snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
|
||||
if (browser.isConnected && currentRevision === revision) acceptSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
if (currentRevision !== revision || !browser.isConnected) return;
|
||||
model.message = error.message;
|
||||
render();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (browser.isConnected) timer = setTimeout(refresh, 3000);
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
const button = form.querySelector('button');
|
||||
button.disabled = busy = true;
|
||||
const currentRevision = ++revision;
|
||||
clearTimeout(timer);
|
||||
model.message = 'Broker-Verbindung wird geöffnet …';
|
||||
render();
|
||||
try {
|
||||
const filter = form.elements.filter.value || '#';
|
||||
const snapshot = await api('/api/mqtt/browser', { method:'POST', body:JSON.stringify({ filter }) });
|
||||
if (!browser.isConnected || currentRevision !== revision) return;
|
||||
if (model.snapshot?.sessionId !== snapshot.sessionId) {
|
||||
model.focused = null;
|
||||
model.picked.clear();
|
||||
model.expanded.clear();
|
||||
}
|
||||
model.filter = snapshot.filter;
|
||||
model.message = '';
|
||||
acceptSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
model.snapshot = null;
|
||||
model.message = error.message;
|
||||
render();
|
||||
} finally {
|
||||
button.disabled = busy = false;
|
||||
syncSelection();
|
||||
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
|
||||
}
|
||||
});
|
||||
|
||||
search.addEventListener('input', () => { model.query = search.value; model.expanded.clear(); render(); });
|
||||
nodes.addEventListener('click', event => {
|
||||
const branch = event.target.closest('[data-topic-branch]');
|
||||
const item = event.target.closest('[data-topic-item]');
|
||||
if (branch) {
|
||||
model.expanded.set(decodeURIComponent(branch.dataset.topicBranch), branch.getAttribute('aria-expanded') !== 'true');
|
||||
render();
|
||||
} else if (item) {
|
||||
model.focused = decodeURIComponent(item.dataset.topicItem);
|
||||
nodes.querySelectorAll('[data-topic-item]').forEach(button => button.setAttribute('aria-pressed', String(button === item)));
|
||||
renderDetail();
|
||||
}
|
||||
});
|
||||
nodes.addEventListener('change', event => {
|
||||
const input = event.target;
|
||||
const selected = input.dataset.topicPick != null ? [decodeURIComponent(input.dataset.topicPick)] :
|
||||
input.dataset.topicBranchPick != null ? visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick)) : [];
|
||||
for (const topic of selected) input.checked ? model.picked.add(topic) : model.picked.delete(topic);
|
||||
syncSelection();
|
||||
});
|
||||
|
||||
async function importTopics(topics) {
|
||||
if (!topics.length || busy || !model.snapshot) return;
|
||||
busy = true;
|
||||
++revision;
|
||||
detail.querySelector('[data-topic-import-one]')?.setAttribute('disabled', '');
|
||||
syncSelection();
|
||||
try {
|
||||
const result = await api('/api/mqtt/browser/import', {
|
||||
method:'POST', body:JSON.stringify({ sessionId: model.snapshot.sessionId, topics })
|
||||
});
|
||||
model.message = `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unavailable} ohne importierbaren Wert`;
|
||||
await loadData();
|
||||
model.snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
|
||||
if (browser.isConnected) renderView();
|
||||
} catch (error) {
|
||||
model.message = error.message;
|
||||
render();
|
||||
} finally {
|
||||
busy = false;
|
||||
detail.querySelector('[data-topic-import-one]')?.removeAttribute('disabled');
|
||||
syncSelection();
|
||||
clearTimeout(timer);
|
||||
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
|
||||
}
|
||||
}
|
||||
if (canImport) {
|
||||
browser.querySelector('[data-topic-select-all]').addEventListener('click', () => {
|
||||
visibleTopics.filter(importable).forEach(topic => model.picked.add(topic.topic));
|
||||
syncSelection();
|
||||
});
|
||||
browser.querySelector('[data-topic-clear]').addEventListener('click', () => { model.picked.clear(); syncSelection(); });
|
||||
importButton.addEventListener('click', () => importTopics([...model.picked]));
|
||||
detail.addEventListener('click', event => {
|
||||
if (event.target.closest('[data-topic-import-one]')) importTopics([model.focused]);
|
||||
});
|
||||
}
|
||||
if (model.snapshot) {
|
||||
acceptSnapshot(model.snapshot);
|
||||
timer = setTimeout(refresh, 3000);
|
||||
} else render();
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
function bindHostNetwork(panel) {
|
||||
let selected;
|
||||
let pendingLayout;
|
||||
let timer;
|
||||
const base = '/api/system/network';
|
||||
const heading = '<h2>Netzwerk · IPv4</h2>';
|
||||
const schedule = delay => { clearTimeout(timer); timer = setTimeout(load, delay); };
|
||||
|
||||
async function load() {
|
||||
if (!panel.isConnected) return;
|
||||
try {
|
||||
const status = await api(base);
|
||||
if (panel.isConnected) render(status);
|
||||
} catch (error) {
|
||||
if (!panel.isConnected) return;
|
||||
if (panel.querySelector('#host-network-timer')) {
|
||||
panel.querySelector('#host-network-timer').textContent = 'Verbindung unterbrochen. Öffne das Gateway unter seiner neuen Adresse.';
|
||||
schedule(2500);
|
||||
} else {
|
||||
panel.innerHTML = `${heading}<p class="note">${escapeHtml(error.message)}</p><button type="button" class="btn">Erneut laden</button>`;
|
||||
panel.querySelector('button').addEventListener('click', load);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
clearTimeout(timer);
|
||||
if (status.pending) {
|
||||
renderPending(status);
|
||||
schedule(2000);
|
||||
return;
|
||||
}
|
||||
pendingLayout = null;
|
||||
if (status.busy) {
|
||||
panel.innerHTML = `${heading}<p class="note">Netzwerkdienst übernimmt die Einstellungen …</p>`;
|
||||
schedule(2000);
|
||||
return;
|
||||
}
|
||||
const cards = status.interfaces;
|
||||
const card = cards.find(item => item.name === selected) ?? cards[0];
|
||||
if (!card) {
|
||||
panel.innerHTML = `${heading}<p class="note">Keine verwaltbare Netzwerkkarte gefunden.</p>`;
|
||||
return;
|
||||
}
|
||||
selected = card.name;
|
||||
const routes = card.routes;
|
||||
const ipv4 = card.addresses[0];
|
||||
const saved = status.profiles[selected];
|
||||
const mode = saved?.mode || 'dhcp';
|
||||
panel.innerHTML = `${heading}
|
||||
${status.notice ? `<p class="note" role="status">${escapeHtml(status.notice)}</p>` : ''}
|
||||
<form class="form" style="margin-top:10px">
|
||||
<label>Netzwerkkarte<select name="interface">${cards.map(item =>
|
||||
`<option value="${escapeHtml(item.name)}" ${item.name === selected ? 'selected' : ''}>${escapeHtml(item.name)} · ${escapeHtml(item.macAddress)}</option>`
|
||||
).join('')}</select></label>
|
||||
<div class="note">Aktuell: ${escapeHtml(card.addresses.map(item => `${item.address}/${item.prefixLength}`).join(', ') || 'keine IPv4-Adresse')}
|
||||
${routes[0]?.gateway ? ` · Gateway ${escapeHtml(routes[0].gateway)}` : ''}</div>
|
||||
<div class="row">
|
||||
<label>Adressvergabe<select name="mode"><option value="dhcp">DHCP</option><option value="static" ${mode === 'static' ? 'selected' : ''}>Statisch</option></select></label>
|
||||
<label>Routenmetrik<input name="metric" type="number" min="1" max="65535" required value="${saved?.metric ?? routes[0]?.metric ?? (1000 + cards.indexOf(card))}"></label>
|
||||
</div>
|
||||
<fieldset class="form" data-static style="border:1px solid var(--line);border-radius:10px;min-width:0">
|
||||
<legend>Statische IPv4-Einstellungen</legend>
|
||||
<div class="row">
|
||||
<label>IPv4-Adresse<input name="address" inputmode="decimal" value="${escapeHtml(saved?.address || ipv4?.address || '')}" required></label>
|
||||
<label>Präfixlänge<input name="prefixLength" type="number" min="1" max="32" value="${saved?.prefixLength ?? ipv4?.prefixLength ?? 24}" required></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Standardgateway (optional)<input name="gateway" inputmode="decimal" value="${escapeHtml(saved ? saved.gateway || '' : routes[0]?.gateway || '')}"></label>
|
||||
<label>DNS-Server (optional, durch Leerzeichen getrennt)<input name="dns" value="${escapeHtml(saved?.dns?.join(' ') || '')}"></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="note">Nach dem Anwenden bleiben zwei Minuten zum Bestätigen. Eine niedrigere Routenmetrik hat Vorrang.</div>
|
||||
<div class="buttons"><button class="btn primary" type="submit">Netzwerkänderung anwenden</button></div>
|
||||
<div id="host-network-message" role="status"></div>
|
||||
</form>`;
|
||||
const form = panel.querySelector('form');
|
||||
const fields = form.querySelector('[data-static]');
|
||||
function syncFields() { fields.hidden = fields.disabled = form.elements.mode.value !== 'static'; }
|
||||
syncFields();
|
||||
form.elements.mode.addEventListener('change', syncFields);
|
||||
form.elements.interface.addEventListener('change', () => { selected = form.elements.interface.value; render(status); });
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const values = new FormData(form);
|
||||
const profile = {
|
||||
interface: values.get('interface'), mode: values.get('mode'), metric: Number(values.get('metric')),
|
||||
address: values.get('address')?.trim(), prefixLength: Number(values.get('prefixLength')) || null,
|
||||
gateway: values.get('gateway')?.trim(), dns: (values.get('dns') || '').split(/[\s,;]+/).filter(Boolean)
|
||||
};
|
||||
form.querySelector('button').disabled = true;
|
||||
try {
|
||||
render(await api(base + '/apply', { method: 'POST', body: JSON.stringify(profile) }));
|
||||
} catch (error) {
|
||||
errorTarget('host-network-message', error.message);
|
||||
form.querySelector('button').disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function renderPending(status) {
|
||||
const { id, profile, ready, secondsLeft } = status.pending;
|
||||
const card = status.interfaces.find(item => item.name === profile.interface);
|
||||
const address = profile.address || card?.addresses.find(item => item.dynamic)?.address;
|
||||
const layout = JSON.stringify([id, ready, address]);
|
||||
if (pendingLayout !== layout) {
|
||||
pendingLayout = layout;
|
||||
const link = address ? new URL(location.href) : null;
|
||||
if (link) { link.hostname = address; link.pathname = '/'; link.search = '?network-confirm=1'; link.hash = ''; }
|
||||
panel.innerHTML = `${heading}<p>Änderung für <strong>${escapeHtml(profile.interface)}</strong> · ${profile.mode === 'static' ? 'Statisch' : 'DHCP'}</p>
|
||||
<p id="host-network-timer" class="note"></p>
|
||||
${link && link.hostname !== location.hostname ? `<p><a class="btn" href="${escapeHtml(link.href)}">Gateway unter ${escapeHtml(address)} öffnen</a></p>` : ''}
|
||||
<div class="buttons">
|
||||
<button type="button" class="btn primary" data-network-action="confirm" ${ready ? '' : 'disabled'}>Netzwerkänderung bestätigen</button>
|
||||
<button type="button" class="btn" data-network-action="revert">Zurücksetzen</button>
|
||||
</div><div id="host-network-message" role="status"></div>`;
|
||||
panel.querySelectorAll('[data-network-action]').forEach(button => button.addEventListener('click', async () => {
|
||||
clearTimeout(timer);
|
||||
button.disabled = true;
|
||||
try {
|
||||
render(await api(base + '/' + button.dataset.networkAction, { method: 'POST', body: JSON.stringify({ id }) }));
|
||||
} catch (error) {
|
||||
errorTarget('host-network-message', error.message);
|
||||
button.disabled = false;
|
||||
schedule(2000);
|
||||
}
|
||||
}));
|
||||
}
|
||||
panel.querySelector('#host-network-timer').textContent = `${ready ? 'Neue Adresse aktiv.' : 'Warte auf die neue Adresse.'} Automatische Rückkehr in ${secondsLeft} s.`;
|
||||
}
|
||||
|
||||
load();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="de" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>SE-Inno Universalgateway · Trend Logs</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=20261009-tabs-1">
|
||||
<link rel="stylesheet" href="/ltd.css?v=20261009-tabs-1">
|
||||
</head>
|
||||
<body>
|
||||
<main style="max-width:1440px;margin:0 auto;padding:20px">
|
||||
<header class="topbar"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><span class="tag">öffentliche Trendansicht</span></header>
|
||||
<section class="card" style="margin-top:18px"><div class="card-head"><h1>Trend Logs</h1><label>Trend Log <select id="trend-log"><option>Laden …</option></select></label></div><div id="trend-status" class="empty">Öffentliche Trenddaten werden geladen …</div><div id="trend-table"></div></section>
|
||||
</main>
|
||||
<script src="/public-trends.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
const trendSelect = document.querySelector('#trend-log');
|
||||
const trendStatus = document.querySelector('#trend-status');
|
||||
const trendTable = document.querySelector('#trend-table');
|
||||
const escapeHtml = value => String(value ?? '').replace(/[&<>'"]/g, character => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]);
|
||||
|
||||
async function loadRecords(id) {
|
||||
if (!id) return;
|
||||
trendStatus.textContent = 'Werte werden geladen …';
|
||||
trendTable.innerHTML = '';
|
||||
const response = await fetch(`/api/public/trend-logs/${encodeURIComponent(id)}/records?limit=2000`);
|
||||
if (!response.ok) throw new Error('Dieses Trend Log ist nicht öffentlich freigegeben oder nicht mehr verfügbar.');
|
||||
const records = await response.json();
|
||||
trendStatus.textContent = records.length ? `${records.length} aufgezeichnete Werte` : 'Noch keine Werte aufgezeichnet.';
|
||||
trendTable.innerHTML = records.length ? `<table><thead><tr><th>Zeitpunkt</th><th>Wert</th><th>Quelle</th><th>Status</th></tr></thead><tbody>${records.map(record => `<tr><td>${escapeHtml(new Date(record.timestampUtc).toLocaleString('de-DE'))}</td><td>${escapeHtml(typeof record.value === 'string' ? record.value : JSON.stringify(record.value))}</td><td>${escapeHtml(record.sourceProtocol)}</td><td>${escapeHtml(record.status || '—')}</td></tr>`).join('')}</tbody></table>` : '';
|
||||
}
|
||||
|
||||
async function bootPublicTrends() {
|
||||
try {
|
||||
const response = await fetch('/api/public/trend-logs');
|
||||
if (!response.ok) throw new Error('Die öffentlichen Trend Logs konnten nicht geladen werden.');
|
||||
const logs = await response.json();
|
||||
if (!logs.length) { trendSelect.innerHTML = '<option>Keine öffentlichen Trend Logs</option>'; trendStatus.textContent = 'Der Administrator hat derzeit kein Trend Log veröffentlicht.'; return; }
|
||||
const requested = new URLSearchParams(location.search).get('log');
|
||||
const selected = logs.some(log => log.id === requested) ? requested : logs[0].id;
|
||||
trendSelect.innerHTML = logs.map(log => `<option value="${escapeHtml(log.id)}" ${log.id === selected ? 'selected' : ''}>${escapeHtml(log.name)}</option>`).join('');
|
||||
trendSelect.addEventListener('change', () => loadRecords(trendSelect.value).catch(error => { trendStatus.textContent = error.message; }));
|
||||
await loadRecords(selected);
|
||||
} catch (error) { trendStatus.textContent = error.message; }
|
||||
}
|
||||
|
||||
bootPublicTrends();
|
||||
@@ -1,33 +1,72 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #090c10;
|
||||
--panel: #10161d;
|
||||
--panel-2: #151c24;
|
||||
--line: #28333e;
|
||||
--muted: #8493a4;
|
||||
--text: #dfe8f0;
|
||||
--blue: #2f9deb;
|
||||
--blue-strong: #1579c0;
|
||||
--danger: #e26161;
|
||||
--warn: #dba951;
|
||||
color-scheme: light;
|
||||
--page: #f4f6fb;
|
||||
--page-overlay: linear-gradient(180deg, #f7f9fbe8, #f2f5f9f0);
|
||||
--page-image: url("/assets/se-ltd-light.png");
|
||||
--panel: #fffffff0;
|
||||
--panel-2: #f6f8fb;
|
||||
--sidebar: #f8fafcf2;
|
||||
--line: #d7e0e9;
|
||||
--line-strong: #bdcad6;
|
||||
--muted: #5e7082;
|
||||
--text: #172433;
|
||||
--blue: #1677bd;
|
||||
--blue-strong: #1267a7;
|
||||
--blue-soft: #e7f2fa;
|
||||
--row-hover: #eef5fa;
|
||||
--notice: #fff9e9;
|
||||
--notice-blue: #eaf4fc;
|
||||
--danger: #b54848;
|
||||
--danger-soft: #f8e9e9;
|
||||
--tag-line: #9bb7ca;
|
||||
--tag-text: #275d80;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--page: #090c10;
|
||||
--page-overlay: linear-gradient(180deg, #070c1480, #070c14b3);
|
||||
--page-image: url("/assets/se-ltd-dark.png");
|
||||
--panel: #0d1522f5;
|
||||
--panel-2: #111c2b;
|
||||
--sidebar: #090f19fa;
|
||||
--line: #28333e;
|
||||
--line-strong: #496071;
|
||||
--muted: #a4b3c5;
|
||||
--text: #edf2f7;
|
||||
--blue: #2f9deb;
|
||||
--blue-strong: #1579c0;
|
||||
--blue-soft: #0e1b27;
|
||||
--row-hover: #131b23;
|
||||
--notice: #191713;
|
||||
--notice-blue: #0e1b27;
|
||||
--danger: #e26161;
|
||||
--danger-soft: #2c1719;
|
||||
--tag-line: #334657;
|
||||
--tag-text: #b7d9f5;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 960px; min-height: 100vh; background: var(--page); color: var(--text); }
|
||||
body { margin: 0; min-width: 960px; min-height: 100vh; background: var(--page-overlay), var(--page-image) center / cover fixed, var(--page); color: var(--text); }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
|
||||
.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
|
||||
.sidebar { padding: 22px 14px; border-right: 1px solid var(--line); background: #0c1117; }
|
||||
.brand { display: flex; gap: 10px; align-items: center; padding: 0 10px 24px; letter-spacing: .08em; font-weight: 700; font-size: 12px; }
|
||||
.sidebar { padding: 22px 14px; border-right: 1px solid var(--line); background: var(--sidebar); }
|
||||
.brand { display: flex; gap: 10px; align-items: center; padding: 0 10px 24px; letter-spacing: .06em; font-weight: 700; font-size: 11px; }
|
||||
.brand-logo { width: 27px; height: 27px; object-fit: contain; }
|
||||
.mark { width: 24px; height: 24px; display: grid; place-items: center; background: var(--blue); color: #06111b; font-size: 11px; border-radius: 3px; }
|
||||
.nav { display: grid; gap: 3px; }
|
||||
.nav button { border: 0; color: var(--muted); background: transparent; text-align: left; border-radius: 4px; padding: 9px 10px; font-size: 12px; }
|
||||
.nav button:hover, .nav button.active { color: #eaf5ff; background: #172431; }
|
||||
.nav button:hover, .nav button.active { color: var(--text); background: var(--blue-soft); }
|
||||
.nav button.active { box-shadow: inset 2px 0 var(--blue); }
|
||||
.sidebar-foot { color: var(--muted); font-size: 11px; position: fixed; bottom: 20px; padding: 0 10px; }
|
||||
.sidebar-foot { color: var(--muted); font-size: 11px; position: fixed; bottom: 20px; padding: 0 10px; display: grid; gap: 12px; }
|
||||
.user-caption { line-height: 1.45; }
|
||||
.theme-toggle { display: flex; gap: 4px; }
|
||||
.theme-option { border: 1px solid var(--line); color: var(--muted); background: transparent; border-radius: 3px; padding: 5px 6px; font-size: 10px; }
|
||||
.theme-option:hover, .theme-option.active { border-color: var(--blue); color: var(--blue); background: var(--blue-soft); }
|
||||
|
||||
.content { padding: 24px 32px 42px; max-width: 1620px; width: 100%; }
|
||||
.topline { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
|
||||
@@ -45,30 +84,30 @@ h2 { margin: 0; font-size: 13px; font-weight: 600; }
|
||||
.metric-sub { color: var(--muted); margin-top: 4px; font-size: 11px; }
|
||||
.card-head { display: flex; justify-content: space-between; gap: 10px; align-items: center; margin-bottom: 14px; }
|
||||
.note { font-size: 11px; color: var(--muted); line-height: 1.55; }
|
||||
.notice { border-left: 2px solid var(--warn); padding: 9px 10px; background: #191713; color: #d9d4c8; font-size: 11px; line-height: 1.45; }
|
||||
.notice.blue { border-color: var(--blue); background: #0e1b27; }
|
||||
.notice { border-left: 2px solid #c39843; padding: 9px 10px; background: var(--notice); color: var(--text); font-size: 11px; line-height: 1.45; }
|
||||
.notice.blue { border-color: var(--blue); background: var(--notice-blue); }
|
||||
|
||||
.form { display: grid; gap: 11px; }
|
||||
.row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
|
||||
.row.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
label { display: grid; gap: 5px; color: var(--muted); font-size: 11px; }
|
||||
input, select, textarea { width: 100%; border: 1px solid var(--line); background: #0c1218; border-radius: 3px; color: var(--text); padding: 8px 9px; outline: none; font-size: 12px; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 2px #2f9deb20; }
|
||||
input, select, textarea { width: 100%; border: 1px solid var(--line); background: var(--panel-2); border-radius: 3px; color: var(--text); padding: 8px 9px; outline: none; font-size: 12px; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 2px color-mix(in srgb, var(--blue) 14%, transparent); }
|
||||
textarea { min-height: 74px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
|
||||
.switch { display: flex; align-items: center; gap: 7px; color: var(--text); font-size: 12px; }
|
||||
.switch input { width: auto; }
|
||||
.buttons { display: flex; align-items: center; gap: 8px; margin-top: 3px; }
|
||||
.btn { padding: 8px 11px; border: 1px solid var(--line); background: var(--panel-2); color: var(--text); border-radius: 3px; font-size: 11px; }
|
||||
.btn:hover { border-color: #496071; }
|
||||
.btn:hover { border-color: var(--line-strong); }
|
||||
.btn.primary { background: var(--blue-strong); border-color: var(--blue-strong); color: white; }
|
||||
.btn.danger { color: #ffb3b3; }
|
||||
.btn.danger { color: var(--danger); background: var(--danger-soft); }
|
||||
|
||||
table { width: 100%; border-collapse: collapse; font-size: 11px; }
|
||||
th { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .06em; font-weight: 500; text-align: left; padding: 0 9px 8px; }
|
||||
td { border-top: 1px solid #202b35; padding: 10px 9px; vertical-align: top; }
|
||||
tr:hover td { background: #131b23; }
|
||||
.tag { display: inline-block; border: 1px solid #334657; color: #b7d9f5; border-radius: 2px; padding: 2px 5px; font-size: 9px; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.tag.gray { border-color: #3a424b; color: #a5afb9; }
|
||||
td { border-top: 1px solid var(--line); padding: 10px 9px; vertical-align: top; }
|
||||
tr:hover td { background: var(--row-hover); }
|
||||
.tag { display: inline-block; border: 1px solid var(--tag-line); color: var(--tag-text); border-radius: 2px; padding: 2px 5px; font-size: 9px; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.tag.gray { border-color: var(--line-strong); color: var(--muted); }
|
||||
.tag.warn { border-color: #735c32; color: #e2bb72; }
|
||||
.empty { color: var(--muted); font-size: 12px; padding: 16px 0; }
|
||||
|
||||
@@ -76,7 +115,7 @@ tr:hover td { background: #131b23; }
|
||||
.auth-card { width: 360px; border: 1px solid var(--line); background: var(--panel); border-radius: 6px; padding: 24px; }
|
||||
.auth-card h1 { margin-bottom: 8px; }
|
||||
.auth-card p { margin: 0 0 21px; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||
.error { margin-top: 10px; color: #ffaaaa; font-size: 11px; line-height: 1.4; }
|
||||
.success { margin-top: 10px; color: #8ad5ff; font-size: 11px; line-height: 1.4; }
|
||||
.error { margin-top: 10px; color: var(--danger); font-size: 11px; line-height: 1.4; }
|
||||
.success { margin-top: 10px; color: var(--blue); font-size: 11px; line-height: 1.4; }
|
||||
.hidden { display: none; }
|
||||
@media (max-width: 1180px) { .grid.overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
Reference in new issue
Block a user