first commit
This commit is contained in:
commit
b31e9a7261
38 files changed
+3822
No files matched your search
@@ -0,0 +1,9 @@
|
||||
namespace Gateway.Api.Contracts;
|
||||
|
||||
public sealed record SetInitialAdminRequest(string Password, string ProjectNumber, int IspNumber);
|
||||
|
||||
public sealed record LoginRequest(string Username, string Password);
|
||||
|
||||
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAtUtc);
|
||||
|
||||
public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public sealed record AuditEntry(
|
||||
long Id,
|
||||
DateTimeOffset OccurredAtUtc,
|
||||
string Category,
|
||||
string Message);
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public sealed record GatewayConfiguration(
|
||||
int VendorId,
|
||||
int DeviceInstance,
|
||||
string DeviceName,
|
||||
BacnetConfiguration Bacnet,
|
||||
OpcUaConfiguration OpcUa,
|
||||
IReadOnlyList<ModbusServerConfiguration> ModbusServers,
|
||||
KnxConfiguration Knx,
|
||||
MqttConfiguration? Mqtt = null,
|
||||
InstallationIdentity? Installation = null)
|
||||
{
|
||||
public static GatewayConfiguration CreateDefault(int deviceInstance, int bacnetPort, int opcUaPort, string interfaceName) => new(
|
||||
VendorId: 815,
|
||||
DeviceInstance: deviceInstance,
|
||||
DeviceName: $"SEIU-Gateway-{deviceInstance}",
|
||||
Bacnet: new BacnetConfiguration(interfaceName, bacnetPort, BbmdMode.Disabled, null, null, false),
|
||||
OpcUa: new OpcUaConfiguration(opcUaPort, true, true, false),
|
||||
ModbusServers: [],
|
||||
Knx: new KnxConfiguration(false, false),
|
||||
Mqtt: MqttConfiguration.CreateDefault(),
|
||||
Installation: null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Immutable identity assigned during the one-time commissioning workflow.
|
||||
/// The NixOS host helper consumes a deliberately small JSON request derived from
|
||||
/// this record; credentials are never part of the request.
|
||||
/// </summary>
|
||||
public sealed record InstallationIdentity(string ProjectNumber, int IspNumber)
|
||||
{
|
||||
public string HostName => $"SE-UGW-{ProjectNumber}-ISP{IspNumber:D2}";
|
||||
}
|
||||
|
||||
public sealed record BacnetConfiguration(
|
||||
string Interface,
|
||||
int IpPort,
|
||||
BbmdMode BbmdMode,
|
||||
string? BbmdAddress,
|
||||
int? ForeignDeviceTtlSeconds,
|
||||
bool SecureConnectEnabled);
|
||||
|
||||
public enum BbmdMode
|
||||
{
|
||||
Disabled,
|
||||
Bbmd,
|
||||
ForeignDevice
|
||||
}
|
||||
|
||||
public sealed record OpcUaConfiguration(
|
||||
int Port,
|
||||
bool ClientEnabled,
|
||||
bool ServerEnabled,
|
||||
bool AllowAnonymous);
|
||||
|
||||
public sealed record ModbusServerConfiguration(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string BindAddress,
|
||||
int Port,
|
||||
int UnitId,
|
||||
int FirstHoldingRegister,
|
||||
int HoldingRegisterCount,
|
||||
IReadOnlyList<string> AllowedClientIps);
|
||||
|
||||
public sealed record KnxConfiguration(bool Enabled, bool Secure);
|
||||
|
||||
public sealed record MqttConfiguration(
|
||||
bool Enabled,
|
||||
string Host,
|
||||
int Port,
|
||||
bool UseTls,
|
||||
bool IgnoreCertificateErrors,
|
||||
string ClientId,
|
||||
string? Username)
|
||||
{
|
||||
public static MqttConfiguration CreateDefault() => new(
|
||||
Enabled: false,
|
||||
Host: "",
|
||||
Port: 1883,
|
||||
UseTls: false,
|
||||
IgnoreCertificateErrors: false,
|
||||
ClientId: "seiugw",
|
||||
Username: null);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public enum MqttMappingFormat
|
||||
{
|
||||
SeMonitoring,
|
||||
Json
|
||||
}
|
||||
|
||||
public enum MqttDirection
|
||||
{
|
||||
Publish,
|
||||
Subscribe,
|
||||
Bidirectional
|
||||
}
|
||||
|
||||
public enum SeMonitoringCategory
|
||||
{
|
||||
Analog,
|
||||
Notify,
|
||||
Alarm,
|
||||
Setpoints
|
||||
}
|
||||
|
||||
public enum MqttQualityOfService
|
||||
{
|
||||
AtMostOnce,
|
||||
AtLeastOnce,
|
||||
ExactlyOnce
|
||||
}
|
||||
|
||||
public sealed record MqttMapping(
|
||||
Guid Id,
|
||||
Guid PointId,
|
||||
MqttMappingFormat Format,
|
||||
MqttDirection Direction,
|
||||
MqttQualityOfService QualityOfService,
|
||||
bool Retain,
|
||||
int? ProjectYear,
|
||||
string? ProjectNumber,
|
||||
string? IspNumber,
|
||||
SeMonitoringCategory? SeCategory,
|
||||
string? TopicName,
|
||||
string? JsonTopic,
|
||||
string? JsonProperty,
|
||||
DateTimeOffset CreatedAtUtc);
|
||||
|
||||
public sealed record CreateMqttMappingRequest(
|
||||
Guid PointId,
|
||||
MqttMappingFormat Format,
|
||||
MqttDirection Direction,
|
||||
MqttQualityOfService QualityOfService,
|
||||
bool Retain,
|
||||
int? ProjectYear,
|
||||
string? ProjectNumber,
|
||||
string? IspNumber,
|
||||
SeMonitoringCategory? SeCategory,
|
||||
string? TopicName,
|
||||
string? JsonTopic,
|
||||
string? JsonProperty);
|
||||
|
||||
public sealed record UpdateMqttConfigurationRequest(
|
||||
MqttConfiguration Configuration,
|
||||
string? Password,
|
||||
bool ClearPassword);
|
||||
|
||||
public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool HasPassword);
|
||||
|
||||
public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc);
|
||||
|
||||
public sealed record MqttClientStatus(
|
||||
bool Enabled,
|
||||
bool Connected,
|
||||
string? Endpoint,
|
||||
string? LastError,
|
||||
DateTimeOffset? ConnectedAtUtc,
|
||||
DateTimeOffset? LastReceivedAtUtc,
|
||||
DateTimeOffset? LastPublishedAtUtc);
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
public enum PointProtocol
|
||||
{
|
||||
Bacnet,
|
||||
OpcUa,
|
||||
Modbus,
|
||||
Knx,
|
||||
Mqtt,
|
||||
Internal
|
||||
}
|
||||
|
||||
public enum PointScope
|
||||
{
|
||||
External,
|
||||
Gateway,
|
||||
Internal
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BACnet object types that the gateway can materialize. Event/Alarm behavior is
|
||||
/// represented by Event Enrollment plus Notification Class, not by a proprietary alarm object.
|
||||
/// </summary>
|
||||
public enum BacnetObjectKind
|
||||
{
|
||||
AnalogInput,
|
||||
AnalogOutput,
|
||||
AnalogValue,
|
||||
BinaryInput,
|
||||
BinaryOutput,
|
||||
BinaryValue,
|
||||
MultiStateInput,
|
||||
MultiStateOutput,
|
||||
MultiStateValue,
|
||||
Schedule,
|
||||
Calendar,
|
||||
EventEnrollment,
|
||||
NotificationClass,
|
||||
TrendLog
|
||||
}
|
||||
|
||||
public sealed record GatewayPoint(
|
||||
Guid Id,
|
||||
string DisplayName,
|
||||
PointProtocol Protocol,
|
||||
PointScope Scope,
|
||||
string ValueType,
|
||||
bool Readable,
|
||||
bool Writable,
|
||||
string? ExternalIdentity,
|
||||
JsonElement Address,
|
||||
DateTimeOffset CreatedAtUtc,
|
||||
BacnetObjectKind? BacnetObjectKind = null,
|
||||
uint? BacnetObjectInstance = null);
|
||||
|
||||
public sealed record CreatePointRequest(
|
||||
string DisplayName,
|
||||
PointProtocol Protocol,
|
||||
PointScope Scope,
|
||||
string ValueType,
|
||||
bool Readable,
|
||||
bool Writable,
|
||||
string? ExternalIdentity,
|
||||
JsonElement Address,
|
||||
BacnetObjectKind? BacnetObjectKind = null,
|
||||
uint? BacnetObjectInstance = null);
|
||||
|
||||
public sealed record PointValue(
|
||||
Guid PointId,
|
||||
JsonElement Value,
|
||||
PointProtocol SourceProtocol,
|
||||
DateTimeOffset UpdatedAtUtc,
|
||||
string? Status);
|
||||
|
||||
public enum MappingDirection
|
||||
{
|
||||
OneWay,
|
||||
Bidirectional
|
||||
}
|
||||
|
||||
public sealed record PointMapping(
|
||||
Guid Id,
|
||||
Guid SourcePointId,
|
||||
Guid TargetPointId,
|
||||
MappingDirection Direction,
|
||||
bool Enabled,
|
||||
int? BacnetPriority,
|
||||
bool AcknowledgeMultipleExternalWriters,
|
||||
JsonElement Transform,
|
||||
DateTimeOffset CreatedAtUtc);
|
||||
|
||||
public sealed record CreateMappingRequest(
|
||||
Guid SourcePointId,
|
||||
Guid TargetPointId,
|
||||
MappingDirection Direction,
|
||||
bool Enabled,
|
||||
int? BacnetPriority,
|
||||
bool AcknowledgeMultipleExternalWriters,
|
||||
JsonElement Transform);
|
||||
|
||||
public sealed record CreateMappingResponse(PointMapping Mapping, IReadOnlyList<string> Warnings);
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Gateway.Api.Domain;
|
||||
|
||||
/// <summary>A gateway-owned trend log can sample any mapped source point without writing to it.</summary>
|
||||
public sealed record GatewayTrendLog(
|
||||
Guid Id,
|
||||
Guid SourcePointId,
|
||||
string Name,
|
||||
uint BacnetObjectInstance,
|
||||
int IntervalSeconds,
|
||||
int MaxRecords,
|
||||
bool Enabled,
|
||||
DateTimeOffset CreatedAtUtc);
|
||||
|
||||
public sealed record CreateTrendLogRequest(
|
||||
Guid SourcePointId,
|
||||
string Name,
|
||||
uint BacnetObjectInstance,
|
||||
int IntervalSeconds,
|
||||
int MaxRecords,
|
||||
bool Enabled);
|
||||
|
||||
public sealed record TrendRecord(
|
||||
Guid TrendLogId,
|
||||
long SequenceNumber,
|
||||
DateTimeOffset TimestampUtc,
|
||||
JsonElement Value,
|
||||
PointProtocol SourceProtocol,
|
||||
string? Status);
|
||||
|
||||
public sealed record AppendTrendRecordRequest(
|
||||
JsonElement Value,
|
||||
PointProtocol SourceProtocol,
|
||||
string? Status,
|
||||
DateTimeOffset? TimestampUtc);
|
||||
@@ -0,0 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.31" />
|
||||
<PackageReference Include="MQTTnet" Version="5.2.0.1603" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Gateway.Api.Options;
|
||||
|
||||
public sealed class GatewayOptions
|
||||
{
|
||||
public string DataDirectory { get; init; } = "data";
|
||||
|
||||
public BacnetBootstrapOptions Bacnet { get; init; } = new();
|
||||
|
||||
public OpcUaBootstrapOptions OpcUa { get; init; } = new();
|
||||
}
|
||||
|
||||
public sealed class BacnetBootstrapOptions
|
||||
{
|
||||
public string Interface { get; init; } = "eth0";
|
||||
|
||||
public int DeviceInstance { get; init; } = 23;
|
||||
|
||||
public int IpPort { get; init; } = 47808;
|
||||
}
|
||||
|
||||
public sealed class OpcUaBootstrapOptions
|
||||
{
|
||||
public int Port { get; init; } = 4840;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Gateway.Api.Contracts;
|
||||
using Gateway.Api.Domain;
|
||||
using Gateway.Api.Options;
|
||||
using Gateway.Api.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.Configure<GatewayOptions>(builder.Configuration.GetSection("Gateway"));
|
||||
builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
builder.Services.AddSingleton<GatewayDatabase>();
|
||||
builder.Services.AddSingleton<PasswordService>();
|
||||
builder.Services.AddSingleton<SessionService>();
|
||||
builder.Services.AddSingleton<MappingValidator>();
|
||||
builder.Services.AddSingleton<WriteJournal>();
|
||||
builder.Services.AddSingleton<SecretProtector>();
|
||||
builder.Services.AddSingleton<GatewayStore>();
|
||||
builder.Services.AddSingleton<MqttClientService>();
|
||||
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MqttClientService>());
|
||||
|
||||
var app = builder.Build();
|
||||
app.Services.GetRequiredService<GatewayStore>().Initialize();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (DomainValidationException exception)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsJsonAsync(new { error = exception.Message });
|
||||
}
|
||||
});
|
||||
|
||||
app.UseDefaultFiles();
|
||||
app.UseStaticFiles();
|
||||
|
||||
app.MapGet("/api/health", (GatewayStore store) => Results.Ok(new
|
||||
{
|
||||
status = "ok",
|
||||
adminConfigured = store.HasAdmin(),
|
||||
protocolDataPlane = "not-started"
|
||||
}));
|
||||
|
||||
app.MapGet("/api/setup", (GatewayStore store) => Results.Ok(new { adminConfigured = store.HasAdmin() }));
|
||||
|
||||
app.MapPost("/api/setup", (SetInitialAdminRequest request, GatewayStore store) =>
|
||||
{
|
||||
store.CreateInitialAdmin(request);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapPost("/api/auth/login", (LoginRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (request.Username != "admin" || !store.VerifyAdminPassword(request.Password))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var token = sessions.Create();
|
||||
return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12)));
|
||||
});
|
||||
|
||||
app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) =>
|
||||
{
|
||||
sessions.Remove(request.Headers.Authorization);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapPost("/api/auth/password", (ChangePasswordRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(httpRequest.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
store.ChangeAdminPassword(request.CurrentPassword, request.NewPassword);
|
||||
sessions.Remove(httpRequest.Headers.Authorization);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/gateway/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? 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))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
store.UpdateGatewayConfiguration(configuration);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/points", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.ListPoints())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var createdPoint = store.CreatePoint(point);
|
||||
return Results.Created($"/api/points/{createdPoint.Id}", createdPoint);
|
||||
});
|
||||
|
||||
app.MapGet("/api/mqtt/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.GetMqttConfiguration())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPut("/api/mqtt/configuration", (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
store.UpdateMqttConfiguration(mqtt);
|
||||
mqttClient.RequestReconfigure();
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
app.MapGet("/api/mqtt/status", (HttpRequest request, SessionService sessions, MqttClientService mqttClient) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(mqttClient.GetStatus())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.ListMqttMappings().Select(mapping => new { Mapping = mapping, Topic = GatewayStore.GetMqttTopic(mapping) }))
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var createdMapping = store.CreateMqttMapping(mapping);
|
||||
mqttClient.RequestReconfigure();
|
||||
return Results.Created($"/api/mqtt/mappings/{createdMapping.Id}", new { Mapping = createdMapping, Topic = GatewayStore.GetMqttTopic(createdMapping) });
|
||||
});
|
||||
|
||||
app.MapGet("/api/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.ListMappings())
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var response = store.CreateMapping(mapping);
|
||||
return Results.Created($"/api/mappings/{response.Mapping.Id}", response);
|
||||
});
|
||||
|
||||
app.MapGet("/api/trend-logs", (HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? 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))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var createdTrendLog = store.CreateTrendLog(trendLog);
|
||||
return Results.Created($"/api/trend-logs/{createdTrendLog.Id}", createdTrendLog);
|
||||
});
|
||||
|
||||
app.MapGet("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500))
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, AppendTrendRecordRequest trendRecord, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
{
|
||||
if (!sessions.IsValid(request.Headers.Authorization))
|
||||
{
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
var createdRecord = store.AppendTrendRecord(trendLogId, trendRecord);
|
||||
return createdRecord is null ? Results.NoContent() : Results.Created($"/api/trend-logs/{trendLogId}/records/{createdRecord.SequenceNumber}", createdRecord);
|
||||
});
|
||||
|
||||
app.MapGet("/api/audit", (int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
|
||||
sessions.IsValid(request.Headers.Authorization)
|
||||
? Results.Ok(store.ListAudit(limit ?? 100))
|
||||
: Results.Unauthorized());
|
||||
|
||||
app.MapFallbackToFile("index.html");
|
||||
app.Run();
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class DomainValidationException(string message) : Exception(message)
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using Gateway.Api.Options;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class GatewayDatabase
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
|
||||
public string DataDirectory { get; }
|
||||
|
||||
public GatewayDatabase(IOptions<GatewayOptions> options)
|
||||
{
|
||||
DataDirectory = Path.GetFullPath(options.Value.DataDirectory);
|
||||
Directory.CreateDirectory(DataDirectory);
|
||||
_connectionString = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = Path.Combine(DataDirectory, "seiugw.db"),
|
||||
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||
Cache = SqliteCacheMode.Shared
|
||||
}.ToString();
|
||||
}
|
||||
|
||||
public SqliteConnection OpenConnection()
|
||||
{
|
||||
var connection = new SqliteConnection(_connectionString);
|
||||
connection.Open();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;";
|
||||
command.ExecuteNonQuery();
|
||||
return connection;
|
||||
}
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
using var connection = OpenConnection();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
PRAGMA journal_mode = WAL;
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT NOT NULL PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS admin_account (
|
||||
id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1),
|
||||
username TEXT NOT NULL UNIQUE CHECK(username = 'admin'),
|
||||
password_hash BLOB NOT NULL,
|
||||
password_salt BLOB NOT NULL,
|
||||
password_iterations INTEGER NOT NULL,
|
||||
changed_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS points (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
protocol TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
value_type TEXT NOT NULL,
|
||||
readable INTEGER NOT NULL,
|
||||
writable INTEGER NOT NULL,
|
||||
external_identity TEXT NULL,
|
||||
address_json TEXT NOT NULL,
|
||||
created_at_utc TEXT NOT NULL,
|
||||
bacnet_object_kind TEXT NULL,
|
||||
bacnet_object_instance INTEGER NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_points_external_identity
|
||||
ON points(protocol, external_identity)
|
||||
WHERE external_identity IS NOT NULL;
|
||||
CREATE TABLE IF NOT EXISTS mappings (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
source_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT,
|
||||
target_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT,
|
||||
direction TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
bacnet_priority INTEGER NULL,
|
||||
acknowledge_multiple_external_writers INTEGER NOT NULL,
|
||||
transform_json TEXT NOT NULL,
|
||||
created_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS mqtt_mappings (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT,
|
||||
format TEXT NOT NULL,
|
||||
direction TEXT NOT NULL,
|
||||
quality_of_service TEXT NOT NULL,
|
||||
retain INTEGER NOT NULL,
|
||||
project_year INTEGER NULL,
|
||||
project_number TEXT NULL,
|
||||
isp_number TEXT NULL,
|
||||
se_category TEXT NULL,
|
||||
topic_name TEXT NULL,
|
||||
json_topic TEXT NULL,
|
||||
json_property TEXT NULL,
|
||||
created_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_mqtt_mapping_point_topic
|
||||
ON mqtt_mappings(point_id, format, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property);
|
||||
CREATE TABLE IF NOT EXISTS point_values (
|
||||
point_id TEXT NOT NULL PRIMARY KEY REFERENCES points(id) ON DELETE CASCADE,
|
||||
value_json TEXT NOT NULL,
|
||||
source_protocol TEXT NOT NULL,
|
||||
updated_at_utc TEXT NOT NULL,
|
||||
status TEXT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
occurred_at_utc TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
message TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS trend_logs (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
source_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT,
|
||||
name TEXT NOT NULL,
|
||||
bacnet_object_instance INTEGER NOT NULL UNIQUE,
|
||||
interval_seconds INTEGER NOT NULL,
|
||||
max_records INTEGER NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
created_at_utc TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS trend_records (
|
||||
trend_log_id TEXT NOT NULL REFERENCES trend_logs(id) ON DELETE CASCADE,
|
||||
sequence_number INTEGER NOT NULL,
|
||||
timestamp_utc TEXT NOT NULL,
|
||||
value_json TEXT NOT NULL,
|
||||
source_protocol TEXT NOT NULL,
|
||||
status TEXT NULL,
|
||||
PRIMARY KEY(trend_log_id, sequence_number)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_trend_records_query
|
||||
ON trend_records(trend_log_id, sequence_number DESC);
|
||||
""";
|
||||
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 = """
|
||||
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;
|
||||
""";
|
||||
bacnetObjectIndex.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
private static void EnsureColumn(SqliteConnection connection, string tableName, string columnName, string definition)
|
||||
{
|
||||
using var pragma = connection.CreateCommand();
|
||||
pragma.CommandText = $"PRAGMA table_info({tableName});";
|
||||
using var reader = pragma.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
if (string.Equals(reader.GetString(1), columnName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
using var alter = connection.CreateCommand();
|
||||
alter.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {columnName} {definition};";
|
||||
alter.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,187 @@
|
||||
using Gateway.Api.Domain;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Applies the write-ownership rules before a mapping is allowed into the active graph.</summary>
|
||||
public sealed class MappingValidator
|
||||
{
|
||||
public MappingValidationResult Validate(IReadOnlyList<GatewayPoint> points, IReadOnlyList<PointMapping> mappings)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
var pointsById = points.ToDictionary(point => point.Id);
|
||||
var activeMappings = mappings.Where(mapping => mapping.Enabled).ToArray();
|
||||
|
||||
foreach (var mapping in activeMappings)
|
||||
{
|
||||
if (!pointsById.ContainsKey(mapping.SourcePointId) || !pointsById.ContainsKey(mapping.TargetPointId))
|
||||
{
|
||||
errors.Add($"Mapping {mapping.Id} verweist auf einen nicht vorhandenen Punkt.");
|
||||
}
|
||||
if (mapping.SourcePointId == mapping.TargetPointId)
|
||||
{
|
||||
errors.Add($"Mapping {mapping.Id} hat identische Quelle und Ziel.");
|
||||
}
|
||||
if (pointsById.TryGetValue(mapping.SourcePointId, out var source) &&
|
||||
pointsById.TryGetValue(mapping.TargetPointId, out var target))
|
||||
{
|
||||
ValidateSpecialObjectMapping(mapping, source, target, errors);
|
||||
}
|
||||
}
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return new MappingValidationResult(false, errors, warnings);
|
||||
}
|
||||
|
||||
foreach (var duplicate in activeMappings.GroupBy(mapping => new
|
||||
{
|
||||
mapping.SourcePointId,
|
||||
mapping.TargetPointId,
|
||||
mapping.Direction
|
||||
}).Where(group => group.Count() > 1))
|
||||
{
|
||||
errors.Add($"Die Mapping-Kante {duplicate.Key.SourcePointId} → {duplicate.Key.TargetPointId} ist mehrfach vorhanden.");
|
||||
}
|
||||
|
||||
var oneWayPairs = activeMappings.Where(mapping => mapping.Direction == MappingDirection.OneWay)
|
||||
.Select(mapping => (mapping.SourcePointId, mapping.TargetPointId))
|
||||
.ToHashSet();
|
||||
foreach (var (source, target) in oneWayPairs)
|
||||
{
|
||||
if (oneWayPairs.Contains((target, source)))
|
||||
{
|
||||
errors.Add("Zwei gegenläufige Einweg-Mappings sind nicht zulässig. Verwende ein ausdrückliches bidirektionales Mapping, damit das Schreibjournal Rückmeldungen korrekt erkennt.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var edges = ExpandEdges(activeMappings);
|
||||
DetectUncontrolledCycles(edges, errors);
|
||||
ValidateExternalWriteOwnership(pointsById, edges, errors, warnings);
|
||||
|
||||
return new MappingValidationResult(errors.Count == 0, errors.Distinct().ToArray(), warnings.Distinct().ToArray());
|
||||
}
|
||||
|
||||
private static List<MappingEdge> ExpandEdges(IEnumerable<PointMapping> mappings)
|
||||
{
|
||||
var edges = new List<MappingEdge>();
|
||||
foreach (var mapping in mappings)
|
||||
{
|
||||
edges.Add(new MappingEdge(mapping.Id, mapping.SourcePointId, mapping.TargetPointId, mapping.Direction == MappingDirection.Bidirectional, mapping));
|
||||
if (mapping.Direction == MappingDirection.Bidirectional)
|
||||
{
|
||||
edges.Add(new MappingEdge(mapping.Id, mapping.TargetPointId, mapping.SourcePointId, true, mapping));
|
||||
}
|
||||
}
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
private static void ValidateSpecialObjectMapping(
|
||||
PointMapping mapping,
|
||||
GatewayPoint source,
|
||||
GatewayPoint target,
|
||||
List<string> errors)
|
||||
{
|
||||
if (source.BacnetObjectKind is BacnetObjectKind.Calendar or BacnetObjectKind.EventEnrollment or BacnetObjectKind.NotificationClass ||
|
||||
target.BacnetObjectKind is BacnetObjectKind.Calendar or BacnetObjectKind.EventEnrollment or BacnetObjectKind.NotificationClass)
|
||||
{
|
||||
errors.Add("Calendar, Event Enrollment und Notification Class werden über ihre BACnet-Objekteigenschaften konfiguriert und dürfen nicht als generische Mapping-Kante verwendet werden.");
|
||||
}
|
||||
if (target.BacnetObjectKind == BacnetObjectKind.Schedule || mapping.Direction == MappingDirection.Bidirectional && source.BacnetObjectKind == BacnetObjectKind.Schedule)
|
||||
{
|
||||
errors.Add("Ein Schedule darf nur als gerichtete Quelle wirken. Das Ziel wird über die Mapping-Kante geschrieben.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DetectUncontrolledCycles(IReadOnlyList<MappingEdge> edges, List<string> errors)
|
||||
{
|
||||
var adjacency = edges.GroupBy(edge => edge.SourcePointId).ToDictionary(group => group.Key, group => group.ToArray());
|
||||
var states = new Dictionary<Guid, VisitState>();
|
||||
|
||||
foreach (var pointId in adjacency.Keys)
|
||||
{
|
||||
if (!states.ContainsKey(pointId))
|
||||
{
|
||||
Visit(pointId, null);
|
||||
}
|
||||
}
|
||||
|
||||
void Visit(Guid pointId, Guid? arrivingMappingId)
|
||||
{
|
||||
states[pointId] = VisitState.Visiting;
|
||||
if (adjacency.TryGetValue(pointId, out var outgoing))
|
||||
{
|
||||
foreach (var edge in outgoing)
|
||||
{
|
||||
// Returning over the one declared bidirectional link is expected and journalled.
|
||||
if (edge.IsBidirectional && edge.MappingId == arrivingMappingId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
states.TryGetValue(edge.TargetPointId, out var targetState);
|
||||
if (targetState == VisitState.Visiting)
|
||||
{
|
||||
errors.Add("Das Mapping enthält einen unkontrollierten Zyklus. Verwende eine interne Variable als Eigentümer oder entferne eine Kante.");
|
||||
continue;
|
||||
}
|
||||
if (targetState == VisitState.NotVisited)
|
||||
{
|
||||
Visit(edge.TargetPointId, edge.MappingId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
states[pointId] = VisitState.Visited;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateExternalWriteOwnership(
|
||||
IReadOnlyDictionary<Guid, GatewayPoint> points,
|
||||
IReadOnlyList<MappingEdge> edges,
|
||||
List<string> errors,
|
||||
List<string> warnings)
|
||||
{
|
||||
var externalDestinations = edges.Where(edge => points[edge.TargetPointId].Scope == PointScope.External)
|
||||
.GroupBy(edge => new ExternalDestination(
|
||||
points[edge.TargetPointId].Protocol,
|
||||
points[edge.TargetPointId].ExternalIdentity ?? points[edge.TargetPointId].Id.ToString()));
|
||||
|
||||
foreach (var destination in externalDestinations)
|
||||
{
|
||||
var distinctSources = destination.Select(edge => edge.SourcePointId).Distinct().ToArray();
|
||||
if (distinctSources.Length <= 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var edgesForDestination = destination.ToArray();
|
||||
var isExplicitBacnetPriorityCase = destination.Key.Protocol == PointProtocol.Bacnet &&
|
||||
edgesForDestination.All(edge => edge.Mapping.BacnetPriority is >= 1 and <= 16) &&
|
||||
edgesForDestination.Select(edge => edge.Mapping.BacnetPriority).Distinct().Count() == edgesForDestination.Length &&
|
||||
edgesForDestination.All(edge => edge.Mapping.AcknowledgeMultipleExternalWriters);
|
||||
if (!isExplicitBacnetPriorityCase)
|
||||
{
|
||||
errors.Add($"Mehrere Quellen würden auf das externe Objekt '{destination.Key.Identity}' schreiben. Das ist ohne explizit quittierte, verschiedene BACnet-Prioritäten nicht zulässig.");
|
||||
continue;
|
||||
}
|
||||
|
||||
var priorities = string.Join(", ", edgesForDestination.Select(edge => edge.Mapping.BacnetPriority).Order());
|
||||
warnings.Add($"Mehrfachschreiben auf BACnet-Objekt '{destination.Key.Identity}' ist mit den ausdrücklich bestätigten Prioritäten {priorities} aktiviert.");
|
||||
}
|
||||
}
|
||||
|
||||
private enum VisitState
|
||||
{
|
||||
NotVisited,
|
||||
Visiting,
|
||||
Visited
|
||||
}
|
||||
|
||||
private sealed record MappingEdge(Guid MappingId, Guid SourcePointId, Guid TargetPointId, bool IsBidirectional, PointMapping Mapping);
|
||||
|
||||
private sealed record ExternalDestination(PointProtocol Protocol, string Identity);
|
||||
}
|
||||
|
||||
public sealed record MappingValidationResult(bool IsValid, IReadOnlyList<string> Errors, IReadOnlyList<string> Warnings);
|
||||
@@ -0,0 +1,360 @@
|
||||
using System.Buffers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using MQTTnet;
|
||||
using MQTTnet.Formatter;
|
||||
using MQTTnet.Protocol;
|
||||
|
||||
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.
|
||||
/// </summary>
|
||||
public sealed class MqttClientService : BackgroundService
|
||||
{
|
||||
private readonly GatewayStore _store;
|
||||
private readonly MqttClientFactory _factory = new();
|
||||
private readonly SemaphoreSlim _publishGate = new(1, 1);
|
||||
private readonly object _clientLock = new();
|
||||
private IMqttClient? _client;
|
||||
private MqttClientStatus _status = new(false, false, null, null, null, null, null);
|
||||
private int _reconfigureRequested = 1;
|
||||
private CancellationToken _stoppingToken;
|
||||
|
||||
public MqttClientService(GatewayStore store)
|
||||
{
|
||||
_store = store;
|
||||
_store.PointValueUpdated += OnPointValueUpdated;
|
||||
}
|
||||
|
||||
public MqttClientStatus GetStatus() => Volatile.Read(ref _status);
|
||||
|
||||
/// <summary>Applies changed broker or subscription configuration without a process restart.</summary>
|
||||
public void RequestReconfigure() => Interlocked.Exchange(ref _reconfigureRequested, 1);
|
||||
|
||||
public async Task<int> PublishPointValueAsync(PointValue pointValue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var client = GetConnectedClient();
|
||||
if (client is null)
|
||||
{
|
||||
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
|
||||
{
|
||||
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 });
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Publish: {exception.Message}" });
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_publishGate.Release();
|
||||
}
|
||||
|
||||
return published;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_stoppingToken = stoppingToken;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (configuration, password) = _store.GetMqttConnectionConfiguration();
|
||||
if (!configuration.Enabled)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
SetStatus(new MqttClientStatus(false, false, null, null, null, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
|
||||
}
|
||||
else if (Interlocked.Exchange(ref _reconfigureRequested, 0) == 1 || GetConnectedClient() is null)
|
||||
{
|
||||
await DisconnectCurrentAsync(stoppingToken);
|
||||
await ConnectAsync(configuration, password, stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false, LastError = exception.Message });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await DisconnectCurrentAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_store.PointValueUpdated -= OnPointValueUpdated;
|
||||
_publishGate.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = _factory.CreateClientOptionsBuilder()
|
||||
.WithClientId(configuration.ClientId)
|
||||
.WithTcpServer(configuration.Host, configuration.Port)
|
||||
// MQTT 3.1.1 gives the widest compatibility with existing field brokers.
|
||||
.WithProtocolVersion(MqttProtocolVersion.V311);
|
||||
if (!string.IsNullOrWhiteSpace(configuration.Username))
|
||||
{
|
||||
builder.WithCredentials(configuration.Username, password ?? string.Empty);
|
||||
}
|
||||
|
||||
if (configuration.UseTls)
|
||||
{
|
||||
builder.WithTlsOptions(tls =>
|
||||
{
|
||||
tls.UseTls();
|
||||
if (configuration.IgnoreCertificateErrors)
|
||||
{
|
||||
// This is opt-in and deliberately visible in the UI; normal operation validates certificates.
|
||||
tls.WithCertificateValidationHandler(_ => true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private async Task 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(group => new
|
||||
{
|
||||
Topic = group.Key,
|
||||
QualityOfService = group.Max(mapping => mapping.QualityOfService)
|
||||
})
|
||||
.ToArray();
|
||||
if (subscriptions.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var builder = _factory.CreateSubscribeOptionsBuilder();
|
||||
foreach (var subscription in subscriptions)
|
||||
{
|
||||
builder.WithTopicFilter(filter => filter
|
||||
.WithTopic(subscription.Topic)
|
||||
.WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService)));
|
||||
}
|
||||
|
||||
await client.SubscribeAsync(builder.Build(), cancellationToken);
|
||||
}
|
||||
|
||||
private async Task HandleReceivedMessageAsync(MqttApplicationMessageReceivedEventArgs arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
var topic = arguments.ApplicationMessage.Topic;
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
UpdateStatus(status => status with { LastReceivedAtUtc = DateTimeOffset.UtcNow, LastError = null });
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
UpdateStatus(status => status with { LastError = $"Empfang: {exception.Message}" });
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs arguments)
|
||||
{
|
||||
lock (_clientLock)
|
||||
{
|
||||
_client = null;
|
||||
}
|
||||
|
||||
if (arguments.Exception is not null)
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false, LastError = arguments.Exception.Message });
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateStatus(status => status with { Connected = false });
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task DisconnectCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
IMqttClient? client;
|
||||
lock (_clientLock)
|
||||
{
|
||||
client = _client;
|
||||
_client = null;
|
||||
}
|
||||
|
||||
if (client is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.IsConnected)
|
||||
{
|
||||
await client.DisconnectAsync(_factory.CreateClientDisconnectOptionsBuilder().Build(), cancellationToken);
|
||||
}
|
||||
|
||||
if (client is IDisposable disposable)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private IMqttClient? GetConnectedClient()
|
||||
{
|
||||
lock (_clientLock)
|
||||
{
|
||||
return _client is { IsConnected: true } client ? client : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPointValueUpdated(object? sender, PointValue pointValue)
|
||||
{
|
||||
// MQTT-originated values must not be reflected to the same broker again.
|
||||
if (pointValue.SourceProtocol == PointProtocol.Mqtt || !GetStatus().Connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PublishPointValueSafelyAsync(pointValue);
|
||||
}
|
||||
|
||||
private async Task PublishPointValueSafelyAsync(PointValue pointValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PublishPointValueAsync(pointValue, _stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (_stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The status field has the error; a later adapter update or reconnect can retry.
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument ParsePayload(string rawPayload)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(rawPayload);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return JsonDocument.Parse(JsonSerializer.Serialize(rawPayload));
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.Json && !string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
{
|
||||
if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty(mapping.JsonProperty, out var property))
|
||||
{
|
||||
throw new DomainValidationException($"Das JSON-Topic enthält keine Eigenschaft '{mapping.JsonProperty}'.");
|
||||
}
|
||||
|
||||
return property.Clone();
|
||||
}
|
||||
|
||||
return payload.Clone();
|
||||
}
|
||||
|
||||
private static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
|
||||
{
|
||||
if (mapping.Format == MqttMappingFormat.SeMonitoring)
|
||||
{
|
||||
return pointValue.Value.GetRawText();
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(mapping.JsonProperty))
|
||||
{
|
||||
return pointValue.Value.GetRawText();
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(pointValue.Value.GetRawText());
|
||||
return JsonSerializer.Serialize(new Dictionary<string, object?>
|
||||
{
|
||||
["timestamp"] = pointValue.UpdatedAtUtc.ToString("O"),
|
||||
[mapping.JsonProperty] = document.RootElement.Clone()
|
||||
});
|
||||
}
|
||||
|
||||
private static MqttQualityOfServiceLevel ToMqttQualityOfService(MqttQualityOfService qualityOfService) => qualityOfService switch
|
||||
{
|
||||
MqttQualityOfService.AtMostOnce => MqttQualityOfServiceLevel.AtMostOnce,
|
||||
MqttQualityOfService.AtLeastOnce => MqttQualityOfServiceLevel.AtLeastOnce,
|
||||
MqttQualityOfService.ExactlyOnce => MqttQualityOfServiceLevel.ExactlyOnce,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(qualityOfService))
|
||||
};
|
||||
|
||||
private void SetStatus(MqttClientStatus status) => Volatile.Write(ref _status, status);
|
||||
|
||||
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update) => SetStatus(update(GetStatus()));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class PasswordService
|
||||
{
|
||||
private const int SaltLength = 16;
|
||||
private const int HashLength = 32;
|
||||
private const int Iterations = 310_000;
|
||||
|
||||
public PasswordHash Create(string password)
|
||||
{
|
||||
ValidatePassword(password);
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltLength);
|
||||
var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, Iterations, HashAlgorithmName.SHA512, HashLength);
|
||||
return new PasswordHash(hash, salt, Iterations);
|
||||
}
|
||||
|
||||
public bool Verify(string password, byte[] expectedHash, byte[] salt, int iterations)
|
||||
{
|
||||
var candidate = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, expectedHash.Length);
|
||||
return CryptographicOperations.FixedTimeEquals(candidate, expectedHash);
|
||||
}
|
||||
|
||||
public static void ValidatePassword(string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(password) || password.Length < 12)
|
||||
{
|
||||
throw new DomainValidationException("Das Passwort muss mindestens 12 Zeichen haben.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record PasswordHash(byte[] Hash, byte[] Salt, int Iterations);
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Gateway.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Keeps broker credentials encrypted in SQLite; the local appliance key stays in its persistent data volume.</summary>
|
||||
public sealed class SecretProtector
|
||||
{
|
||||
private const int KeyLength = 32;
|
||||
private const int NonceLength = 12;
|
||||
private const int TagLength = 16;
|
||||
private readonly byte[] _key;
|
||||
|
||||
public SecretProtector(IOptions<GatewayOptions> options)
|
||||
{
|
||||
var dataDirectory = Path.GetFullPath(options.Value.DataDirectory);
|
||||
Directory.CreateDirectory(dataDirectory);
|
||||
var keyPath = Path.Combine(dataDirectory, "secrets.key");
|
||||
if (File.Exists(keyPath))
|
||||
{
|
||||
_key = File.ReadAllBytes(keyPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
_key = RandomNumberGenerator.GetBytes(KeyLength);
|
||||
File.WriteAllBytes(keyPath, _key);
|
||||
}
|
||||
|
||||
if (_key.Length != KeyLength)
|
||||
{
|
||||
throw new InvalidOperationException("The gateway secret key is invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
public string Protect(string secret)
|
||||
{
|
||||
var plaintext = Encoding.UTF8.GetBytes(secret);
|
||||
var nonce = RandomNumberGenerator.GetBytes(NonceLength);
|
||||
var ciphertext = new byte[plaintext.Length];
|
||||
var tag = new byte[TagLength];
|
||||
using var cipher = new AesGcm(_key, TagLength);
|
||||
cipher.Encrypt(nonce, plaintext, ciphertext, tag);
|
||||
return Convert.ToBase64String([.. nonce, .. tag, .. ciphertext]);
|
||||
}
|
||||
|
||||
public string Unprotect(string protectedSecret)
|
||||
{
|
||||
var data = Convert.FromBase64String(protectedSecret);
|
||||
if (data.Length < NonceLength + TagLength)
|
||||
{
|
||||
throw new InvalidOperationException("The protected gateway secret is invalid.");
|
||||
}
|
||||
|
||||
var nonce = data[..NonceLength];
|
||||
var tag = data[NonceLength..(NonceLength + TagLength)];
|
||||
var ciphertext = data[(NonceLength + TagLength)..];
|
||||
var plaintext = new byte[ciphertext.Length];
|
||||
using var cipher = new AesGcm(_key, TagLength);
|
||||
cipher.Decrypt(nonce, ciphertext, tag, plaintext);
|
||||
return Encoding.UTF8.GetString(plaintext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class SessionService
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
|
||||
|
||||
public string Create()
|
||||
{
|
||||
PruneExpired();
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
_sessions[token] = DateTimeOffset.UtcNow.AddHours(12);
|
||||
return token;
|
||||
}
|
||||
|
||||
public bool IsValid(string? authorizationHeader)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader) || !authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = authorizationHeader[7..];
|
||||
return _sessions.TryGetValue(token, out var expiresAt) && expiresAt > DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void Remove(string? authorizationHeader)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
{
|
||||
_sessions.TryRemove(authorizationHeader[7..], out _);
|
||||
}
|
||||
}
|
||||
|
||||
private void PruneExpired()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var (token, expiresAt) in _sessions)
|
||||
{
|
||||
if (expiresAt <= now)
|
||||
{
|
||||
_sessions.TryRemove(token, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
/// <summary>Tracks gateway-originated writes so adapter feedback is not re-published as a new source update.</summary>
|
||||
public sealed class WriteJournal
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, JournalEntry> _entries = new(StringComparer.Ordinal);
|
||||
|
||||
public string Register(string endpointIdentity, string normalizedValue, TimeSpan validFor)
|
||||
{
|
||||
var originId = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
|
||||
_entries[CreateKey(endpointIdentity, normalizedValue)] = new JournalEntry(originId, DateTimeOffset.UtcNow.Add(validFor));
|
||||
RemoveExpired();
|
||||
return originId;
|
||||
}
|
||||
|
||||
public bool ConsumeReflection(string endpointIdentity, string normalizedValue)
|
||||
{
|
||||
var key = CreateKey(endpointIdentity, normalizedValue);
|
||||
return _entries.TryRemove(key, out var entry) && entry.ExpiresAtUtc > DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private static string CreateKey(string endpointIdentity, string normalizedValue) => $"{endpointIdentity}\u001f{normalizedValue}";
|
||||
|
||||
private void RemoveExpired()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var (key, entry) in _entries)
|
||||
{
|
||||
if (entry.ExpiresAtUtc <= now)
|
||||
{
|
||||
_entries.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record JournalEntry(string OriginId, DateTimeOffset ExpiresAtUtc);
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
const app = document.querySelector('#app');
|
||||
const state = { token: sessionStorage.getItem('seiugw-token'), view: 'overview', points: [], mappings: [], trendLogs: [], configuration: null, mqtt: null, mqttMappings: [], mqttStatus: null };
|
||||
|
||||
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.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
throw new Error(body.error || `Anfrage fehlgeschlagen (${response.status})`);
|
||||
}
|
||||
return response.status === 204 ? null : response.json();
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(/[&<>'"]/g, char => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[char]));
|
||||
}
|
||||
|
||||
function errorTarget(id, message, success = false) {
|
||||
const target = document.querySelector(`#${id}`);
|
||||
if (!target) return;
|
||||
target.className = success ? 'success' : 'error';
|
||||
target.textContent = message;
|
||||
}
|
||||
|
||||
async function boot() {
|
||||
const setup = await api('/api/setup');
|
||||
if (!setup.adminConfigured) return renderSetup();
|
||||
if (!state.token) return renderLogin();
|
||||
await loadData();
|
||||
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>`;
|
||||
const updateHostName = () => {
|
||||
const project = document.querySelector('#setup-project').value.trim().toUpperCase() || 'P';
|
||||
const isp = String(document.querySelector('#setup-isp').value || '1').padStart(2, '0');
|
||||
document.querySelector('#setup-hostname').textContent = `SE-UGW-${project}-ISP${isp}`;
|
||||
};
|
||||
document.querySelector('#setup-project').addEventListener('input', updateHostName);
|
||||
document.querySelector('#setup-isp').addEventListener('input', updateHostName);
|
||||
document.querySelector('#setup-form').addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const password = document.querySelector('#setup-password').value;
|
||||
if (password !== document.querySelector('#setup-confirm').value) return errorTarget('setup-message', 'Die Passwörter stimmen nicht überein.');
|
||||
try { await api('/api/setup', { method: 'POST', body: JSON.stringify({ password, projectNumber: document.querySelector('#setup-project').value.trim().toUpperCase(), ispNumber: Number(document.querySelector('#setup-isp').value) }) }); await boot(); }
|
||||
catch (error) { errorTarget('setup-message', error.message); }
|
||||
});
|
||||
}
|
||||
|
||||
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>`;
|
||||
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();
|
||||
} 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')
|
||||
]);
|
||||
}
|
||||
|
||||
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>`;
|
||||
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => { state.view = button.dataset.view; renderView(); }));
|
||||
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 };
|
||||
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>`;
|
||||
}
|
||||
|
||||
function viewOverview() {
|
||||
const c = state.configuration;
|
||||
const mqttStatus = state.mqttStatus?.connected ? 'MQTT verbunden' : state.mqtt?.configuration?.enabled ? 'MQTT nicht verbunden' : 'MQTT deaktiviert';
|
||||
const installation = c.installation ? `${escapeHtml(c.installation.projectNumber)} · ISP${String(c.installation.ispNumber).padStart(2, '0')}` : 'noch nicht zugewiesen';
|
||||
const hostName = c.installation ? `SE-UGW-${escapeHtml(c.installation.projectNumber)}-ISP${String(c.installation.ispNumber).padStart(2, '0')}` : '—';
|
||||
return `${header('Übersicht', mqttStatus)}<section class="grid overview">
|
||||
<article class="card"><div class="metric-label">BACnet Device</div><div class="metric-value">${c.deviceInstance}</div><div class="metric-sub">Vendor ID ${c.vendorId} · UDP ${c.bacnet.ipPort}</div></article>
|
||||
<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>`;
|
||||
}
|
||||
|
||||
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>`;
|
||||
}
|
||||
|
||||
function viewMappings() {
|
||||
const pointOptions = state.points.map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${point.protocol}</option>`).join('');
|
||||
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>`;
|
||||
}
|
||||
|
||||
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 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>`;
|
||||
}).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>`;
|
||||
}
|
||||
|
||||
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>`;
|
||||
}
|
||||
|
||||
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>`;
|
||||
}
|
||||
|
||||
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 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(); }
|
||||
}
|
||||
|
||||
async function submitPoint(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
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 loadData(); renderView();
|
||||
} catch (error) { errorTarget('point-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitMapping(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
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 }) });
|
||||
await loadData(); renderView();
|
||||
if (response.warnings?.length) window.alert(response.warnings.join('\n'));
|
||||
} catch (error) { errorTarget('mapping-message', error.message); }
|
||||
}
|
||||
|
||||
async function submitMqttConfiguration(event) {
|
||||
event.preventDefault(); const form = new FormData(event.currentTarget);
|
||||
const ignoreCertificateErrors = form.get('ignoreCertificateErrors') === 'on';
|
||||
if (ignoreCertificateErrors && !window.confirm('TLS-Zertifikatsfehler wirklich ignorieren? Das ist nur für kontrollierte Broker zulässig.')) return;
|
||||
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' }) });
|
||||
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);
|
||||
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 }) });
|
||||
await loadData(); renderView();
|
||||
} catch (error) { errorTarget('mqtt-mapping-message', error.message); }
|
||||
}
|
||||
|
||||
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 loadData(); renderView();
|
||||
} catch (error) { errorTarget('trend-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);
|
||||
} catch (error) { errorTarget('bacnet-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(); }
|
||||
catch (error) { errorTarget('password-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>`; });
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<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">
|
||||
</head>
|
||||
<body>
|
||||
<main id="app" aria-live="polite"></main>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,82 @@
|
||||
: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;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 960px; min-height: 100vh; background: 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; }
|
||||
.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.active { box-shadow: inset 2px 0 var(--blue); }
|
||||
.sidebar-foot { color: var(--muted); font-size: 11px; position: fixed; bottom: 20px; padding: 0 10px; }
|
||||
|
||||
.content { padding: 24px 32px 42px; max-width: 1620px; width: 100%; }
|
||||
.topline { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
|
||||
h1 { margin: 0; font-size: 19px; font-weight: 600; letter-spacing: -.02em; }
|
||||
h2 { margin: 0; font-size: 13px; font-weight: 600; }
|
||||
.status { font-size: 11px; color: var(--muted); display: inline-flex; align-items: center; gap: 7px; }
|
||||
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--blue); box-shadow: 0 0 10px #2f9deb99; }
|
||||
|
||||
.grid { display: grid; gap: 14px; }
|
||||
.grid.overview { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.grid.two { grid-template-columns: minmax(340px, 1fr) minmax(420px, 1.7fr); align-items: start; }
|
||||
.card { border: 1px solid var(--line); border-radius: 5px; background: var(--panel); padding: 16px; }
|
||||
.metric-label { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.metric-value { margin-top: 9px; font-size: 23px; 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; }
|
||||
|
||||
.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; }
|
||||
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.primary { background: var(--blue-strong); border-color: var(--blue-strong); color: white; }
|
||||
.btn.danger { color: #ffb3b3; }
|
||||
|
||||
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; }
|
||||
.tag.warn { border-color: #735c32; color: #e2bb72; }
|
||||
.empty { color: var(--muted); font-size: 12px; padding: 16px 0; }
|
||||
|
||||
.auth { min-height: 100vh; display: grid; place-items: center; padding: 24px; }
|
||||
.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; }
|
||||
.hidden { display: none; }
|
||||
@media (max-width: 1180px) { .grid.overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
Reference in new issue
Block a user