Synchronize deployed gateway features and documentation

This commit is contained in:
jhartworks committed 2026-11-24 13:38:27 +01:00
1 parent 98c48d9d78
commit 198b1d7b78
20 files changed
+1235 -45

No files matched your search

+9 -3
View File
@@ -46,7 +46,8 @@ public sealed record MqttMapping(
string? TopicName,
string? JsonTopic,
string? JsonProperty,
DateTimeOffset CreatedAtUtc);
DateTimeOffset CreatedAtUtc,
string? TopicTemplate = null);
public sealed record CreateMqttMappingRequest(
Guid PointId,
@@ -60,7 +61,8 @@ public sealed record CreateMqttMappingRequest(
SeMonitoringCategory? SeCategory,
string? TopicName,
string? JsonTopic,
string? JsonProperty);
string? JsonProperty,
string? TopicTemplate = null);
public sealed record UpdateMqttConfigurationRequest(
MqttConfiguration Configuration,
@@ -71,7 +73,11 @@ public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool
public sealed record MqttMonitoringSite(int? ProjectYear, string? ProjectNumber, string? IspNumber);
public sealed record MqttPointDefaults(Guid PointId, SeMonitoringCategory? Category, string TopicName);
public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList<MqttPointDefaults> Points);
public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList<MqttPointDefaults> Points, MqttTopicTemplateView TopicTemplate);
public sealed record MqttTopicPlaceholder(string Token, string Description);
public sealed record MqttTopicTemplateView(string Template, string DefaultTemplate, IReadOnlyList<MqttTopicPlaceholder> Placeholders,
IReadOnlyDictionary<string, string> PreviewValues);
public sealed record UpdateMqttTopicTemplateRequest(string Template);
public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc);
+6
View File
@@ -8,4 +8,10 @@
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.378.182" />
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Content Include="../../*.md" TargetPath="Documentation/%(Filename)%(Extension)"
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../docs/**/*.md" TargetPath="Documentation/docs/%(RecursiveDir)%(Filename)%(Extension)"
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+12
View File
@@ -25,6 +25,7 @@ builder.Services.AddSingleton<MappingValidator>();
builder.Services.AddSingleton<WriteJournal>();
builder.Services.AddSingleton<SecretProtector>();
builder.Services.AddSingleton<GatewayStore>();
builder.Services.AddSingleton<GatewayDocumentation>();
builder.Services.AddSingleton<HardwareDiscoveryService>();
builder.Services.AddSingleton<HostNetworkService>();
builder.Services.AddSingleton<BacnetBrowserService>();
@@ -81,6 +82,14 @@ app.Use(async (context, next) =>
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapGet("/api/docs", (HttpRequest request, SessionService sessions, GatewayDocumentation docs) =>
sessions.IsValid(request.Headers.Authorization) ? Results.Ok(docs.Entries) : Results.Unauthorized());
app.MapGet("/api/docs/content", (string path, HttpRequest request, SessionService sessions, GatewayDocumentation docs) =>
{
if (!sessions.IsValid(request.Headers.Authorization)) return Results.Unauthorized();
return docs.Find(path) is { } file ? Results.Ok(file) : Results.NotFound();
});
app.MapGet("/api/presentation", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
? Results.Ok(new { units = store.ListDisplayUnits(), points = store.ListPointPresentations() }) : Results.Unauthorized());
@@ -474,6 +483,9 @@ app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, Sessi
app.MapGet("/api/mqtt/mapping-defaults", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.GetMqttMappingDefaults()) : Results.StatusCode(403));
app.MapPut("/api/mqtt/topic-template", (UpdateMqttTopicTemplateRequest template, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.UpdateMqttTopicTemplate(template.Template)) : Results.StatusCode(403));
app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
{
+3 -1
View File
@@ -156,7 +156,8 @@ public sealed class GatewayDatabase
topic_name TEXT NULL,
json_topic TEXT NULL,
json_property TEXT NULL,
created_at_utc TEXT NOT NULL
created_at_utc TEXT NOT NULL,
topic_template TEXT 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);
@@ -230,6 +231,7 @@ public sealed class GatewayDatabase
EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0");
EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0");
EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL");
EnsureColumn(connection, "mqtt_mappings", "topic_template", "TEXT NULL");
using var indexMigration = connection.BeginTransaction();
using var pointIndexes = connection.CreateCommand();
pointIndexes.Transaction = indexMigration;
@@ -0,0 +1,37 @@
namespace Gateway.Api.Services;
public sealed record DocumentationEntry(string Path, string Title);
public sealed record DocumentationFile(string Path, string Markdown);
public sealed class GatewayDocumentation
{
private readonly Dictionary<string, DocumentationFile> _files;
public IReadOnlyList<DocumentationEntry> Entries { get; }
public GatewayDocumentation()
{
var directory = Path.Combine(AppContext.BaseDirectory, "Documentation");
var paths = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md", SearchOption.AllDirectories) : [];
_files = paths.Select(path => new DocumentationFile(Path.GetRelativePath(directory, path).Replace('\\', '/'),
File.ReadAllText(path)))
.ToDictionary(file => file.Path, StringComparer.Ordinal);
Entries = _files.Values
.OrderBy(file => file.Path != "README.md")
.ThenBy(file => file.Path, StringComparer.Ordinal)
.Select(file => new DocumentationEntry(file.Path, ReadTitle(file))).ToArray();
}
public DocumentationFile? Find(string path) => _files.GetValueOrDefault(path);
private static string ReadTitle(DocumentationFile file)
{
using var reader = new StringReader(file.Markdown);
while (reader.ReadLine() is { } line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
if (line.StartsWith("# ", StringComparison.Ordinal)) return line[2..].Trim();
break;
}
return Path.GetFileNameWithoutExtension(file.Path);
}
}
@@ -37,6 +37,7 @@ public sealed partial class GatewayStore
var prefix = request.MqttTopicPrefix?.Trim().TrimEnd('/');
var mqttFormat = request.MqttFormat ?? (prefix is null ? MqttMappingFormat.SeMonitoring : MqttMappingFormat.Json);
var site = request.MqttSite ?? DefaultMonitoringSite(configuration.Installation);
var topicTemplate = ReadMqttTopicTemplate(connection, transaction);
var alarms = request.Target == BulkMappingTarget.Mqtt && mqttFormat == MqttMappingFormat.SeMonitoring
? ReadMqttAlarmPoints(connection, transaction) : [];
if (request.Target == BulkMappingTarget.Mqtt && mqttFormat != MqttMappingFormat.SeMonitoring &&
@@ -74,7 +75,7 @@ public sealed partial class GatewayStore
if (monitoring && pointDefaults.Category is null)
throw new DomainValidationException($"'{source.DisplayName}' benötigt das MQTT-Format JSON.");
var topicName = pointDefaults.TopicName;
var topic = monitoring ? BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName) :
var topic = monitoring ? BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName) :
$"{prefix}/{(slug.Length == 0 ? "punkt" : slug)}-{source.Id:N}";
var occupied = mqtt.Where(mapping => GetMqttTopic(mapping) == topic).ToArray();
if (occupied.Any(mapping => mapping.PointId == source.Id && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
@@ -85,7 +86,7 @@ public sealed partial class GatewayStore
if (monitoring && occupied.Length > 0)
{
topicName = $"{topicName}-{source.Id:N}";
topic = BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName);
topic = BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName);
if (mqtt.Any(mapping => mapping.PointId == source.Id && GetMqttTopic(mapping) == topic &&
mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
{
@@ -98,7 +99,8 @@ public sealed partial class GatewayStore
var mqttMapping = SaveMqttMapping(connection, transaction, null, new CreateMqttMappingRequest(source.Id, mqttFormat,
MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false,
monitoring ? site.ProjectYear : null, monitoring ? site.ProjectNumber : null, monitoring ? site.IspNumber : null,
monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null))!;
monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null,
monitoring ? topicTemplate : null))!;
mqtt.Add(mqttMapping);
mqttCreated.Add(mqttMapping.Id);
saved.Add($"{source.DisplayName} → {topic}");
@@ -18,7 +18,7 @@ public sealed partial class GatewayStore
private static readonly string[] MappingColumns =
["Id", "SourcePointId", "TargetPointId", "Direction", "Enabled", "BacnetPriority", "AcknowledgeMultipleExternalWriters", "Transform"];
private static readonly string[] MqttMappingColumns =
["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty"];
["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty", "TopicTemplate"];
public string ExportConfigurationCsv(ConfigurationCsvKind kind)
{
@@ -32,7 +32,8 @@ public sealed partial class GatewayStore
mapping.AcknowledgeMultipleExternalWriters, mapping.Transform.GetRawText() }),
_ => ListMqttMappings().Select(mapping => new object?[] { mapping.Id, mapping.PointId, mapping.Format,
mapping.Direction, mapping.QualityOfService, mapping.Retain, mapping.ProjectYear, mapping.ProjectNumber,
mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty })
mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty,
mapping.Format == MqttMappingFormat.SeMonitoring ? mapping.TopicTemplate ?? DefaultMqttTopicTemplate : null })
};
var output = new StringBuilder("\uFEFF");
output.AppendJoin(';', CsvColumns(kind)).Append("\r\n");
@@ -65,7 +66,10 @@ public sealed partial class GatewayStore
var columns = CsvColumns(kind);
try
{
if (!(parser.ReadFields() ?? []).Select(value => value.Trim()).SequenceEqual(columns, StringComparer.OrdinalIgnoreCase))
var importedColumns = (parser.ReadFields() ?? []).Select(value => value.Trim()).ToArray();
if (kind == ConfigurationCsvKind.MqttMappings && importedColumns.Length == columns.Length - 1)
columns = columns[..^1];
if (!importedColumns.SequenceEqual(columns, StringComparer.OrdinalIgnoreCase))
throw new DomainValidationException("Die CSV-Spalten stimmen mit der exportierten Vorlage nicht überein.");
}
catch (MalformedLineException) { throw new DomainValidationException("Ungültiger CSV-Kopf."); }
@@ -136,7 +140,8 @@ public sealed partial class GatewayStore
CsvEnum<MqttDirection>(fields[3], "Direction"), CsvEnum<MqttQualityOfService>(fields[4], "QualityOfService"),
CsvBool(fields[5], "Retain"), CsvInteger(fields[6], "ProjectYear"), CsvOptional(fields[7]), CsvOptional(fields[8]),
CsvOptional(fields[9]) is { } category ? CsvEnum<SeMonitoringCategory>(category, "SeCategory") : null,
CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12]));
CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12]),
fields.Length > 13 ? CsvOptional(fields[13]) : DefaultMqttTopicTemplate);
SaveMqttMapping(connection, transaction, update ? id : null, mqtt, update ? null : id);
break;
}
@@ -11,7 +11,8 @@ public sealed partial class GatewayStore
using var connection = _database.OpenConnection();
var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection).Installation);
var alarms = ReadMqttAlarmPoints(connection);
return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray());
return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray(),
TopicTemplateView(ReadMqttTopicTemplate(connection), site));
}
internal GatewayPoint? GetMqttPoint(Guid id)
@@ -49,6 +50,4 @@ public sealed partial class GatewayStore
return new(point.Id, category, name.Length == 0 ? "Punkt" : name);
}
private static string BuildMonitoringTopic(MqttMonitoringSite site, SeMonitoringCategory category, string name) =>
$"Projekte{site.ProjectYear}/{site.ProjectNumber}/{site.IspNumber}/{GetCategorySegment(category)}/{name}_Wert";
}
@@ -0,0 +1,97 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
private const string MqttTopicTemplateKey = "mqtt_topic_template";
private const string DefaultMqttTopicTemplate = "Projekte{Jahr}/{Projekt}/{ISP}/{Kategorie}/{Datenpunkt}_Wert";
private static readonly Regex MqttTemplateTokenPattern = new(@"\{([^{}]*)\}", RegexOptions.CultureInvariant);
private static readonly MqttTopicPlaceholder[] MqttTopicPlaceholders =
[
new("{Jahr}", "Projektjahr"),
new("{Projekt}", "Projektnummer mit P"),
new("{ISP}", "ISP mit Präfix"),
new("{Kategorie}", "Analog, Notify, Alarms oder Setpoints"),
new("{Datenpunkt}", "Punktname aus dem Mapping"),
new("{Rechnername}", "Aus Projekt und ISP")
];
public MqttTopicTemplateView UpdateMqttTopicTemplate(string template)
{
var normalized = template?.Trim() ?? "";
ValidateMqttTopicTemplate(normalized);
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection, transaction).Installation);
SetSetting(connection, MqttTopicTemplateKey, normalized, transaction);
WriteAudit(connection, "mqtt", "Default MQTT topic template updated.", transaction);
transaction.Commit();
return TopicTemplateView(normalized, site);
}
private static string ReadMqttTopicTemplate(SqliteConnection connection, SqliteTransaction? transaction = null) =>
GetSetting(connection, MqttTopicTemplateKey, transaction) ?? DefaultMqttTopicTemplate;
private static MqttTopicTemplateView TopicTemplateView(string template, MqttMonitoringSite site) =>
new(template, DefaultMqttTopicTemplate, MqttTopicPlaceholders, TopicTemplateValues(
new(site.ProjectYear ?? DateTimeOffset.UtcNow.Year, site.ProjectNumber ?? "P190726", site.IspNumber ?? "ISP1"),
SeMonitoringCategory.Analog, "Vorlauftemperatur"));
private static Dictionary<string, string> TopicTemplateValues(MqttMonitoringSite site, SeMonitoringCategory category, string name)
{
var isp = site.IspNumber ?? "";
var project = site.ProjectNumber ?? "";
return new(StringComparer.Ordinal)
{
["{Jahr}"] = site.ProjectYear?.ToString(CultureInfo.InvariantCulture) ?? "",
["{Projekt}"] = project,
["{ISP}"] = isp,
["{Kategorie}"] = GetCategorySegment(category),
["{Datenpunkt}"] = name,
["{Rechnername}"] = isp.StartsWith("ISP", StringComparison.Ordinal) && project.Length > 0
? $"SE-UGW-{project}-ISP{isp[3..].PadLeft(2, '0')}" : ""
};
}
private static void ValidateMqttTopicTemplate(string template)
{
if (template.Length is 0 or > 1024 || template.Any(char.IsControl))
throw new DomainValidationException("Der MQTT-Standardpfad muss 1 bis 1024 Zeichen enthalten, ohne Steuerzeichen.");
if (!template.Contains("{Datenpunkt}", StringComparison.Ordinal))
throw new DomainValidationException("Der MQTT-Standardpfad benötigt den Platzhalter {Datenpunkt}.");
var sample = BuildMonitoringTopic(template, new(2019, "P190726", "ISP1"), SeMonitoringCategory.Analog, "Vorlauftemperatur");
if (!MqttExternalTopics.IsTopic(sample))
throw new DomainValidationException("Der erzeugte MQTT-Pfad ist zu lang oder enthält Wildcards (+ oder #).");
}
private static void ValidateMqttTopicInputs(string template, CreateMqttMappingRequest mapping)
{
ValidateMqttTopicTemplate(template);
var needsHost = template.Contains("{Rechnername}", StringComparison.Ordinal);
if (template.Contains("{Jahr}", StringComparison.Ordinal) && mapping.ProjectYear is not (>= 2000 and <= 2100))
throw new DomainValidationException("Für {Jahr} ein Projektjahr zwischen 2000 und 2100 eingeben.");
if (needsHost || template.Contains("{Projekt}", StringComparison.Ordinal))
{
var project = mapping.ProjectNumber;
var valid = template == DefaultMqttTopicTemplate ? IsProjectNumber(project)
: project is not null && Regex.IsMatch(project, "^P[A-Z0-9_-]{1,32}$", RegexOptions.CultureInvariant);
if (!valid) throw new DomainValidationException("Für den MQTT-Pfad eine gültige Projektnummer mit Präfix P eingeben.");
}
if ((needsHost || template.Contains("{ISP}", StringComparison.Ordinal)) && !IsIspNumber(mapping.IspNumber))
throw new DomainValidationException("Für den MQTT-Pfad eine gültige ISP-Nummer mit Präfix ISP eingeben.");
}
private static string BuildMonitoringTopic(string template, MqttMonitoringSite site, SeMonitoringCategory category, string name)
{
var values = TopicTemplateValues(site, category, name);
var topic = MqttTemplateTokenPattern.Replace(template, match => values.TryGetValue(match.Value, out var value) ? value :
throw new DomainValidationException($"Unbekannter MQTT-Platzhalter '{match.Value}'."));
if (topic.IndexOfAny(['{', '}']) >= 0)
throw new DomainValidationException("Ein MQTT-Platzhalter enthält eine unvollständige Klammer.");
return topic;
}
}
+24 -12
View File
@@ -717,7 +717,7 @@ public sealed partial class GatewayStore
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
SELECT id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc
SELECT id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc, topic_template
FROM mqtt_mappings
ORDER BY created_at_utc;
""";
@@ -753,7 +753,12 @@ public sealed partial class GatewayStore
var point = FindActivePoint(connection, transaction, request.PointId)
?? throw new DomainValidationException("Der MQTT-Quellpunkt existiert nicht.");
ValidateMqttMappingRequest(request, point);
var template = request.Format == MqttMappingFormat.SeMonitoring
? NormalizeNullable(request.TopicTemplate) ?? (existing?.Format == MqttMappingFormat.SeMonitoring
? existing.TopicTemplate ?? DefaultMqttTopicTemplate
: ReadMqttTopicTemplate(connection, transaction))
: null;
ValidateMqttMappingRequest(request, point, template);
var mapping = new MqttMapping(
existing?.Id ?? newId ?? Guid.NewGuid(),
request.PointId,
@@ -768,11 +773,15 @@ public sealed partial class GatewayStore
NormalizeNullable(request.TopicName),
NormalizeNullable(request.JsonTopic),
NormalizeNullable(request.JsonProperty),
existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow);
existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow,
template == DefaultMqttTopicTemplate ? null : template);
var topic = GetMqttTopic(mapping);
if (mapping.Format == MqttMappingFormat.SeMonitoring && !MqttExternalTopics.IsTopic(topic))
throw new DomainValidationException("Der aus der Vorlage erzeugte MQTT-Pfad ist ungültig oder zu lang.");
if (mappings.Any(other => other.Id != mapping.Id && GetMqttTopic(other) == topic &&
(mapping.Format == MqttMappingFormat.SingleTopic || other.Format == MqttMappingFormat.SingleTopic ||
mapping.TopicTemplate != null || other.TopicTemplate != null ||
other.PointId == mapping.PointId && other.Format == mapping.Format &&
(mapping.Format != MqttMappingFormat.Json || other.JsonProperty == mapping.JsonProperty))))
throw new DomainValidationException("Dieses MQTT-Topic ist bereits für eine kollidierende Zuordnung belegt.");
@@ -782,13 +791,13 @@ public sealed partial class GatewayStore
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = existing is null ? """
INSERT INTO mqtt_mappings(id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc)
VALUES($id, $pointId, $format, $direction, $qualityOfService, $retain, $projectYear, $projectNumber, $ispNumber, $category, $topicName, $jsonTopic, $jsonProperty, $createdAt);
INSERT INTO mqtt_mappings(id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc, topic_template)
VALUES($id, $pointId, $format, $direction, $qualityOfService, $retain, $projectYear, $projectNumber, $ispNumber, $category, $topicName, $jsonTopic, $jsonProperty, $createdAt, $template);
""" : """
UPDATE mqtt_mappings SET point_id=$pointId, format=$format, direction=$direction,
quality_of_service=$qualityOfService, retain=$retain, project_year=$projectYear,
project_number=$projectNumber, isp_number=$ispNumber, se_category=$category,
topic_name=$topicName, json_topic=$jsonTopic, json_property=$jsonProperty WHERE id=$id;
topic_name=$topicName, json_topic=$jsonTopic, json_property=$jsonProperty, topic_template=$template WHERE id=$id;
""";
command.Parameters.AddWithValue("$id", mapping.Id.ToString());
command.Parameters.AddWithValue("$pointId", mapping.PointId.ToString());
@@ -803,6 +812,7 @@ public sealed partial class GatewayStore
command.Parameters.AddWithValue("$topicName", (object?)mapping.TopicName ?? DBNull.Value);
command.Parameters.AddWithValue("$jsonTopic", (object?)mapping.JsonTopic ?? DBNull.Value);
command.Parameters.AddWithValue("$jsonProperty", (object?)mapping.JsonProperty ?? DBNull.Value);
command.Parameters.AddWithValue("$template", (object?)mapping.TopicTemplate ?? DBNull.Value);
if (existing is null) command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O"));
command.ExecuteNonQuery();
WriteAudit(connection, "mqtt", $"MQTT mapping '{topic}' {(existing is null ? "created" : "updated")} for point '{point.DisplayName}'.", transaction);
@@ -816,7 +826,8 @@ public sealed partial class GatewayStore
public static string GetMqttTopic(MqttMapping mapping) => mapping.Format switch
{
MqttMappingFormat.SeMonitoring => BuildMonitoringTopic(new MqttMonitoringSite(mapping.ProjectYear, mapping.ProjectNumber, mapping.IspNumber), mapping.SeCategory!.Value, mapping.TopicName!),
MqttMappingFormat.SeMonitoring => BuildMonitoringTopic(mapping.TopicTemplate ?? DefaultMqttTopicTemplate,
new MqttMonitoringSite(mapping.ProjectYear, mapping.ProjectNumber, mapping.IspNumber), mapping.SeCategory!.Value, mapping.TopicName!),
MqttMappingFormat.Json or MqttMappingFormat.SingleTopic => mapping.JsonTopic ?? throw new InvalidOperationException("The MQTT topic is missing."),
_ => throw new InvalidOperationException("Unknown MQTT mapping format.")
};
@@ -1560,9 +1571,10 @@ public sealed partial class GatewayStore
reader.IsDBNull(10) ? null : reader.GetString(10),
reader.IsDBNull(11) ? null : reader.GetString(11),
reader.IsDBNull(12) ? null : reader.GetString(12),
ParseTimestamp(reader.GetString(13)));
ParseTimestamp(reader.GetString(13)),
reader.IsDBNull(14) ? null : reader.GetString(14));
private static void ValidateMqttMappingRequest(CreateMqttMappingRequest request, GatewayPoint point)
private static void ValidateMqttMappingRequest(CreateMqttMappingRequest request, GatewayPoint point, string? topicTemplate)
{
if (!Enum.IsDefined(request.Format) || !Enum.IsDefined(request.Direction) || !Enum.IsDefined(request.QualityOfService) ||
request.SeCategory is { } category && !Enum.IsDefined(category))
@@ -1588,11 +1600,11 @@ public sealed partial class GatewayStore
return;
}
if (request.ProjectYear is not (>= 2000 and <= 2100) || !IsProjectNumber(request.ProjectNumber) || !IsIspNumber(request.IspNumber) ||
request.SeCategory is null || !IsValidTopicName(request.TopicName))
if (request.SeCategory is null || !IsValidTopicName(request.TopicName))
{
throw new DomainValidationException("SE-Monitoring benötigt Jahr, Projektnummer P…, ISP-Nummer ISP…, Kategorie und einen gültigen Punktnamen.");
throw new DomainValidationException("SE-Monitoring benötigt eine Kategorie und einen gültigen Punktnamen.");
}
ValidateMqttTopicInputs(topicTemplate!, request);
if (classification == MqttPointClassification.Structured)
{
+9 -5
View File
@@ -134,6 +134,8 @@ function renderShell() {
const nav = `${can('view_dashboard') ? '<button data-view="overview">Dashboard</button>' : ''}${can('view_trends') ? '<button data-view="trends">Trend</button>' : ''}${can('manage_sources') || can('manage_gateway') || can('manage_integrations') ? '<button data-view="points">Datenpunkte</button>' : ''}${can('manage_sources') ? '<button data-view="mappings">Mappings</button>' : ''}${adminTabs().length ? '<button data-view="admin">Admin</button>' : ''}<button data-view="system">Einstellungen</button>`;
const theme = state.preferences?.theme || 'system';
app.innerHTML = `<section class="shell"><aside class="sidebar"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"><div><span class="eyebrow">SE-INNO</span><br>Universal&shy;gateway</div><button class="btn pin" id="sidebar-pin" title="Seitenleiste anheften" aria-pressed="${state.preferences?.sidebarPinned !== false}">⌖</button></div><nav class="nav">${nav}</nav><div class="sidebar-foot">${themeControls(theme)}<div id="theme-message" role="status"></div><div class="user-caption"><strong>${escapeHtml(state.user?.user?.displayName || '')} · @${escapeHtml(state.user?.user?.username || '')}</strong><span>${escapeHtml(state.user?.user?.role || '')}</span></div><button class="btn" id="sidebar-logout">Abmelden</button><small>by J.H. | SE Inno GmbH</small></div></aside><section id="content" class="content"></section></section>`;
document.querySelector('.sidebar-foot').insertAdjacentHTML('afterbegin',
'<nav class="nav" aria-label="Dokumentation"><button type="button" data-view="docs">Doku</button></nav>');
document.querySelector('#sidebar-logout').addEventListener('click', logout);
document.querySelector('.shell').classList.toggle('unpinned', state.preferences?.sidebarPinned === false);
document.querySelector('#sidebar-pin').addEventListener('click', async () => { try { state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ sidebarPinned: state.preferences?.sidebarPinned === false }) }); renderShell(); } catch (error) { window.alert(error.message); } });
@@ -145,7 +147,7 @@ function renderShell() {
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: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem };
const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem, docs: viewDocumentation };
content.innerHTML = views[state.view]();
bindView(state.view);
}
@@ -211,9 +213,9 @@ function viewPoints() {
<div id="point-message" role="status"></div>
</form>
</article>
<article class="card"><div class="card-head"><h2>Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2>${configurationCsvButtons('points')}</div>
<article class="card point-inventory"><div class="card-head"><h2 id="point-inventory-title">Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2>${configurationCsvButtons('points')}</div>
<div id="point-list-message" role="status"></div>
${rows ? `<div class="table-scroll"><table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th>
${rows ? `<div class="table-scroll point-inventory-scroll" tabindex="0" role="region" aria-labelledby="point-inventory-title"><table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th>
<th>BACnet-Objekt</th><th>Zugriff</th><th>Identität</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>`
: '<div class="empty">Noch keine Datenpunkte.</div>'}
</article>
@@ -280,7 +282,7 @@ function viewMqtt() {
const mapping = entry.mapping;
return `<tr><td>${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}</td><td>${escapeHtml(mqttMappingFormatLabel(mapping.format))}</td><td>${escapeHtml(mapping.direction)}</td><td><code>${escapeHtml(entry.topic)}</code></td><td>${escapeHtml(mapping.qualityOfService)}</td><td>${mapping.retain ? 'ja' : 'nein'}</td><td>${mappingActions(mapping.id, 'mqtt-mapping')}</td></tr>`;
}).join('');
return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarms</td><td>Digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}</h2></div>${mqttMappingForm(editing)}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2>${configurationCsvButtons('mqtt')}</div><div id="mqtt-mapping-list-message" role="status"></div>${state.mqttMappings.length ? `<div class="table-scroll"><table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>${escapeHtml(mqttTopicTemplate() || '—')}</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarms</td><td>Digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}</h2></div>${mqttMappingForm(editing)}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2>${configurationCsvButtons('mqtt')}</div><div id="mqtt-mapping-list-message" role="status"></div>${state.mqttMappings.length ? `<div class="table-scroll"><table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
}
function viewTrends() {
@@ -344,10 +346,11 @@ function viewSystem(section = 'settings') {
if (section === 'users') return userPanel;
if (section === 'roles') return rolePanel;
if (section === 'debug') return auditPanel;
return `${header('Einstellungen')}<section class="grid equal"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" autocomplete="current-password" required></label><label>Neues Passwort<input type="password" name="next" autocomplete="new-password" minlength="12" required></label><label>Neues Passwort wiederholen<input type="password" name="confirmation" autocomplete="new-password" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Darstellung</h2></div><div class="theme-toggle settings-theme" aria-label="Farbschema"><button class="theme-option ${theme === 'system' ? 'active' : ''}" data-theme="system" type="button">System</button><button class="theme-option ${theme === 'light' ? 'active' : ''}" data-theme="light" type="button">Hell</button><button class="theme-option ${theme === 'dark' ? 'active' : ''}" data-theme="dark" type="button">Dunkel</button></div><div id="system-message"></div></article>${can('manage_gateway') ? viewInstallationSettings() : ''}</section>${can('manage_gateway') ? '<section class="card" id="host-network" style="margin-top:10px"><h2>Netzwerk · IPv4</h2><p class="note">Netzwerkstatus wird geladen …</p></section>' : ''}`;
return `${header('Einstellungen')}<section class="grid equal"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" autocomplete="current-password" required></label><label>Neues Passwort<input type="password" name="next" autocomplete="new-password" minlength="12" required></label><label>Neues Passwort wiederholen<input type="password" name="confirmation" autocomplete="new-password" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Darstellung</h2></div><div class="theme-toggle settings-theme" aria-label="Farbschema"><button class="theme-option ${theme === 'system' ? 'active' : ''}" data-theme="system" type="button">System</button><button class="theme-option ${theme === 'light' ? 'active' : ''}" data-theme="light" type="button">Hell</button><button class="theme-option ${theme === 'dark' ? 'active' : ''}" data-theme="dark" type="button">Dunkel</button></div><div id="system-message"></div></article>${can('manage_gateway') ? viewInstallationSettings() : ''}${can('manage_integrations') ? viewMqttTopicTemplateSettings() : ''}</section>${can('manage_gateway') ? '<section class="card" id="host-network" style="margin-top:10px"><h2>Netzwerk · IPv4</h2><p class="note">Netzwerkstatus wird geladen …</p></section>' : ''}`;
}
function bindView(view) {
if (view === 'docs') return bindDocumentation();
if (view === 'overview') return bindDashboard();
if (view === 'admin') return bindAdmin();
if (view === 'points') {
@@ -403,6 +406,7 @@ function bindView(view) {
if (view === 'system') {
document.querySelector('#password-form')?.addEventListener('submit', submitPassword);
bindInstallationSettings();
bindMqttTopicTemplateSettings();
const networkPanel = document.querySelector('#host-network');
if (networkPanel) bindHostNetwork(networkPanel);
document.querySelector('#content').querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme)));
+140
View File
@@ -0,0 +1,140 @@
function viewDocumentation() {
return `${header('Dokumentation')}<section id="documentation">
<nav class="tabs protocol-tabs" role="tablist" aria-label="Dokumente" hidden></nav>
<article class="card documentation-card" id="documentation-panel">
<p class="note" role="status">Dokumentation wird geladen …</p>
</article>
</section>`;
}
function bindDocumentation() {
const root = document.querySelector('#documentation');
const tabs = root.querySelector('[role=tablist]');
const panel = root.querySelector('#documentation-panel');
let documents = [];
let revision = 0;
function setMessage(message) {
const text = document.createElement('p');
text.className = 'note';
text.role = 'status';
text.textContent = message;
panel.replaceChildren(text);
}
function scrollToHeading(fragment) {
if (!fragment) return;
[...panel.querySelectorAll('[id]')].find(heading => heading.id === fragment)?.scrollIntoView({ block:'start' });
}
async function openDocument(index, fragment) {
const selected = documents[index];
if (!selected) return;
const current = ++revision;
state.documentationPath = selected.path;
[...tabs.children].forEach((tab, position) => {
const active = position === index;
tab.classList.toggle('active', active);
tab.setAttribute('aria-selected', String(active));
tab.tabIndex = active ? 0 : -1;
});
panel.setAttribute('aria-labelledby', `documentation-tab-${index}`);
setMessage('Dokument wird geladen …');
try {
const file = await api(`/api/docs/content?path=${encodeURIComponent(selected.path)}`);
if (!root.isConnected || current !== revision) return;
panel.replaceChildren(renderDocumentationMarkdown(file, documents));
scrollToHeading(fragment);
} catch (error) {
if (root.isConnected && current === revision) setMessage(error.message);
}
}
tabs.addEventListener('click', event => {
const tab = event.target.closest('[data-document-tab]');
if (tab) openDocument(Number(tab.dataset.documentTab));
});
tabs.addEventListener('keydown', event => {
const tab = event.target.closest('[data-document-tab]');
if (!tab) return;
const index = Number(tab.dataset.documentTab);
const next = { ArrowLeft:(index + documents.length - 1) % documents.length, ArrowRight:(index + 1) % documents.length,
Home:0, End:documents.length - 1 }[event.key];
if (next === undefined) return;
event.preventDefault();
tabs.children[next].focus();
openDocument(next);
});
panel.addEventListener('click', event => {
const link = event.target.closest('[data-document-link]');
if (!link) return;
const target = link.dataset.documentLink;
event.preventDefault();
if (target === state.documentationPath) scrollToHeading(link.dataset.documentFragment);
else openDocument(documents.findIndex(document => document.path === target), link.dataset.documentFragment);
});
api('/api/docs').then(catalog => {
if (!root.isConnected) return;
documents = catalog;
if (!documents.length) {
setMessage('Keine Dokumente vorhanden.');
return;
}
tabs.innerHTML = documents.map(({ title }, index) => `<button type="button" class="btn" id="documentation-tab-${index}"
role="tab" aria-controls="documentation-panel" data-document-tab="${index}">${escapeHtml(title)}</button>`).join('');
tabs.hidden = false;
panel.role = 'tabpanel';
panel.tabIndex = 0;
openDocument(Math.max(0, documents.findIndex(document => document.path === state.documentationPath)));
}).catch(error => { if (root.isConnected) setMessage(error.message); });
}
function renderDocumentationMarkdown(file, documents) {
const content = document.createElement('div');
content.className = 'documentation-markdown';
content.innerHTML = window.markdownit({ html:false }).render(file.markdown);
const slugs = new Set();
for (const heading of content.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
const base = heading.textContent.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').trim().replace(/\s+/g, '-') || 'abschnitt';
let slug = base;
for (let suffix = 1; slugs.has(slug); suffix++) slug = `${base}-${suffix}`;
slugs.add(slug);
heading.id = slug;
}
for (const table of content.querySelectorAll('table')) {
const container = document.createElement('div');
container.className = 'table-scroll';
table.replaceWith(container);
container.append(table);
}
const paths = new Set(documents.map(document => document.path));
const localOrigin = 'https://documentation.invalid';
const base = new URL(file.path.split('/').map(encodeURIComponent).join('/'), localOrigin);
for (const link of content.querySelectorAll('a[href]')) {
let url;
try { url = new URL(link.getAttribute('href'), base); }
catch {
link.removeAttribute('href');
continue;
}
if (url.origin === localOrigin) {
try {
const path = decodeURIComponent(url.pathname.slice(1));
if (paths.has(path)) {
link.dataset.documentLink = path;
link.dataset.documentFragment = decodeURIComponent(url.hash.slice(1));
link.href = url.hash || '#';
continue;
}
} catch (error) {
if (!(error instanceof URIError)) throw error;
}
link.removeAttribute('href');
} else if (url.protocol === 'https:' || url.protocol === 'http:') {
link.target = '_blank';
link.rel = 'noopener noreferrer';
} else if (url.protocol !== 'mailto:') link.removeAttribute('href');
}
return content;
}
+6 -4
View File
@@ -11,17 +11,19 @@
} catch { /* Dark is the default when browser storage is unavailable. */ }
</script>
<link rel="stylesheet" href="/styles.css?v=20261009-tabs-1">
<link rel="stylesheet" href="/ltd.css?v=20261119-mqtt-browser-1">
<link rel="stylesheet" href="/ltd.css?v=20261124-point-scroll-1">
</head>
<body>
<main id="app" aria-live="polite"></main>
<script src="/ltd.js?v=20261119-status-1" defer></script>
<script src="/network-settings.js?v=20261119-network-1" defer></script>
<script src="/bacnet-browser.js?v=20261119-batch-2" defer></script>
<script src="/mqtt-mapping-form.js?v=20261119-status-1" defer></script>
<script src="/mqtt-mapping-form.js?v=20261119-mqtt-template-1" defer></script>
<script src="/gateway-status.js?v=20261119-status-1" defer></script>
<script src="/mapping-batch.js?v=20261119-status-1" defer></script>
<script src="/mapping-batch.js?v=20261119-mqtt-template-1" defer></script>
<script src="/mqtt-topic-browser.js?v=20261119-mqtt-browser-1" defer></script>
<script src="/app.js?v=20261119-mqtt-browser-1" defer></script>
<script src="/vendor/markdown-it-15.0.3.min.js" defer></script>
<script src="/documentation.js?v=20261119-docs-1" defer></script>
<script src="/app.js?v=20261124-point-scroll-1" defer></script>
</body>
</html>
+32
View File
@@ -16,6 +16,23 @@ body { min-width:360px; font-size:12px; }
.sidebar-foot { position:static; margin-top:auto; padding:10px 0 0; border-top:1px solid var(--line); gap:8px; }
.sidebar-foot .btn { justify-self:start; }
.sidebar-foot small { font-size:9px; text-align:center; }
.documentation-card { padding:16px 20px; }
.documentation-markdown { max-width:112ch; font-size:13px; line-height:1.6; overflow-wrap:anywhere; }
.documentation-markdown :is(h1,h2,h3,h4,h5,h6) { margin:1.15em 0 .45em; scroll-margin-top:12px; }
.documentation-markdown h1 { font-size:23px; margin-top:0; }
.documentation-markdown h2 { font-size:17px; }
.documentation-markdown h3 { font-size:15px; }
.documentation-markdown p { margin:0 0 10px; }
.documentation-markdown :is(ul,ol) { margin:0 0 12px; padding-left:24px; }
.documentation-markdown li + li { margin-top:3px; }
.documentation-markdown a { color:var(--blue); text-decoration:underline; }
.documentation-markdown hr { border:0; border-top:1px solid var(--line); margin:18px 0; }
.documentation-markdown blockquote { border-left:3px solid var(--blue); margin:10px 0; padding:5px 12px; }
.documentation-markdown pre { overflow:auto; border:1px solid var(--line); border-radius:8px; background:var(--panel-2); padding:10px; }
.documentation-markdown :not(pre) > code { background:var(--panel-2); padding:1px 4px; border-radius:4px; }
.documentation-markdown table { margin:3px 0 10px; }
.documentation-markdown :is(td,th) { text-align:left; vertical-align:top; }
.documentation-markdown img { max-width:100%; }
.theme-control { display:grid; gap:6px; }
.theme-caption { color:var(--muted); font-size:10px; }
.sidebar-foot .theme-toggle { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; }
@@ -97,6 +114,8 @@ input[type="color"] { padding:4px; width:36px; flex:0 0 36px; }
.connection-facts dd { margin:0; overflow-wrap:anywhere; }
.connection-issues { max-height:35dvh; overflow:auto; overflow-wrap:anywhere; }
[data-mqtt-preview] { overflow-wrap:anywhere; }
.mqtt-topic-placeholders { display:flex; flex-wrap:wrap; gap:5px; }
.mqtt-topic-placeholders .btn { display:flex; flex-wrap:wrap; gap:5px; border-radius:8px; }
.mqtt-topic-browser { margin-bottom:10px; }
.mqtt-browser-start { align-self:end; }
.mqtt-browser-content { margin-top:12px; }
@@ -137,6 +156,18 @@ input[type="color"] { padding:4px; width:36px; flex:0 0 36px; }
.chart-legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; }
.widget-grid { margin-top:10px; }
.table-scroll { overflow:auto; }
.point-inventory {
display:flex;
flex-direction:column;
max-height:max(16rem,calc(100dvh - 12rem));
}
.point-inventory-scroll {
min-height:0;
overscroll-behavior:contain;
scrollbar-color:var(--line-strong) transparent;
}
.point-inventory-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); }
.point-inventory-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; }
.empty { text-align:center; padding:28px 10px; }
.runner-columns { min-height:230px; }
details > summary { cursor:pointer; color:var(--muted); padding:7px 0; }
@@ -144,6 +175,7 @@ button:focus-visible,a:focus-visible { outline:2px solid var(--blue); outline-of
@media(min-width:1800px) { .alias-table .scroll { max-height:65vh; } }
@media(max-width:1100px) {
.grid.two,.grid.equal { grid-template-columns:1fr; }
.point-inventory { max-height:max(16rem,60dvh); }
.status { max-width:45%; text-align:right; }
.bacnet-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"settings" "search" "devices"; grid-template-rows:auto; }
.bacnet-devices { position:static; max-height:60dvh; }
+5 -2
View File
@@ -31,7 +31,10 @@ function viewMappingBatch() {
</select></label>
<div data-bulk-mqtt class="form" hidden>
<label class="switch"><input type="checkbox" name="seMonitoring" checked> SE-Monitoring verwenden</label>
<div data-bulk-mqtt-site>${mqttMonitoringSiteFields()}</div>
<div data-bulk-mqtt-site class="form">
${mqttMonitoringSiteFields()}
<code class="note" data-mqtt-preview>${escapeHtml(mqttTopicTemplate() || '')}</code>
</div>
<div data-bulk-mqtt-free class="form" hidden>
<label>Format<select name="mqttFreeFormat">${mqttTopicFormatOptions('SingleTopic')}</select></label>
<label>MQTT-Topic-Präfix<input name="mqttTopicPrefix" placeholder="z. B. Heizung/ISP01" maxlength="850"></label>
@@ -131,7 +134,7 @@ function bindMappingBatch() {
const monitoring = mqtt && form.elements.seMonitoring.checked;
card.querySelector('[data-bulk-mqtt-site]').hidden = !monitoring;
card.querySelector('[data-bulk-mqtt-free]').hidden = !mqtt || monitoring;
card.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; });
syncMqttMonitoringSiteFields(form, monitoring, mqttTopicTemplate() || '');
prefix.required = mqtt && !monitoring;
serverSelect.required = modbus;
if (!modbus || serverRequest) return;
+98 -8
View File
@@ -2,14 +2,33 @@ function mqttPointDefaults(id) {
return state.mqttMappingDefaults?.points.find(point => point.pointId === id);
}
function mqttTopicTemplate(editing) {
const settings = state.mqttMappingDefaults?.topicTemplate;
return editing?.format === 'SeMonitoring' ? editing.topicTemplate ?? settings?.defaultTemplate : settings?.template;
}
function expandMqttTopicTemplate(template, values) {
return template.replace(/\{[^{}]*\}/g, token => values[token] ?? token);
}
function mqttMonitoringSiteFields(site = state.mqttMappingDefaults?.site) {
return `<div class="row three">
<label>Projektjahr<input name="projectYear" type="number" min="2000" max="2100" value="${site?.projectYear ?? ''}" data-mqtt-required></label>
<label>Projektnummer<input name="projectNumber" maxlength="32" pattern="P[0-9]+" value="${escapeHtml(site?.projectNumber || '')}" data-mqtt-required></label>
<label>ISP<input name="ispNumber" maxlength="32" pattern="ISP[0-9]+" value="${escapeHtml(site?.ispNumber || '')}" data-mqtt-required></label>
<label>Projektjahr<input name="projectYear" type="number" min="2000" max="2100" value="${site?.projectYear ?? ''}" data-mqtt-site="{Jahr}"></label>
<label>Projektnummer<input name="projectNumber" maxlength="33" value="${escapeHtml(site?.projectNumber || '')}" data-mqtt-site="{Projekt}"></label>
<label>ISP<input name="ispNumber" maxlength="32" pattern="ISP[0-9]+" value="${escapeHtml(site?.ispNumber || '')}" data-mqtt-site="{ISP}"></label>
</div>`;
}
function syncMqttMonitoringSiteFields(form, monitoring, template) {
const needsHost = template.includes('{Rechnername}');
form.querySelectorAll('[data-mqtt-site]').forEach(input => {
const needed = template.includes(input.dataset.mqttSite) || needsHost && input.name !== 'projectYear';
input.required = monitoring && needed;
input.disabled = !monitoring || !needed;
input.closest('label').hidden = !needed;
});
}
function mqttTopicFormatOptions(selected) {
return `<option value="SingleTopic" ${selected === 'SingleTopic' ? 'selected' : ''}>Einzel-Topic (Zahl)</option>
<option value="Json" ${selected === 'Json' ? 'selected' : ''}>JSON</option>`;
@@ -21,9 +40,9 @@ function mqttMappingFormatLabel(format) {
function mqttSiteFromForm(form) {
return {
projectYear: Number(form.get('projectYear')),
projectNumber: form.get('projectNumber').trim(),
ispNumber: form.get('ispNumber').trim()
projectYear: form.get('projectYear') ? Number(form.get('projectYear')) : null,
projectNumber: form.get('projectNumber')?.trim() || null,
ispNumber: form.get('ispNumber')?.trim() || null
};
}
@@ -35,7 +54,7 @@ function mqttMappingForm(editing) {
const option = (value, label, selected) => `<option value="${value}" ${value === selected ? 'selected' : ''}>${label}</option>`;
const categories = ['Analog', 'Notify', 'Alarms', 'Setpoints'];
if (editing?.seCategory === 'Alarm') categories.push('Alarm');
return `<form id="mqtt-mapping-form" class="form">
return `<form id="mqtt-mapping-form" class="form" data-topic-template="${escapeHtml(mqttTopicTemplate(editing) || '')}">
<label>Datenpunkt<select name="pointId" required>${points}</select></label>
<div class="row">
<label>Richtung<select name="direction">
@@ -77,6 +96,7 @@ function mqttMappingForm(editing) {
function bindMqttMappingOptions(form) {
if (!form) return;
const fields = form.elements;
const template = form.dataset.topicTemplate;
let preferMonitoring = !state.mqttMappingEditId || fields.seMonitoring.checked;
let preferFreeFormat = state.mqttMappingEditId ? fields.freeFormat.value : 'SingleTopic';
function update(reselect = false) {
@@ -99,11 +119,21 @@ function bindMqttMappingOptions(form) {
form.querySelector('[data-mqtt-free]').hidden = monitoring;
form.querySelector('[data-mqtt-json-property]').hidden = fields.freeFormat.value !== 'Json';
fields.jsonTopic.required = !monitoring;
syncMqttMonitoringSiteFields(form, monitoring, template);
form.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; });
fields.direction.options[0].disabled = monitoring && fields.seCategory.value === 'Setpoints';
fields.direction.options[1].disabled = fields.direction.options[0].disabled;
if (fields.direction.options[0].disabled) fields.direction.value = 'Bidirectional';
form.querySelector('[data-mqtt-preview]').textContent = `Projekte${fields.projectYear.value}/${fields.projectNumber.value}/${fields.ispNumber.value}/${fields.seCategory.value}/${fields.topicName.value}_Wert`;
const project = fields.projectNumber.value.trim();
const isp = fields.ispNumber.value.trim();
form.querySelector('[data-mqtt-preview]').textContent = expandMqttTopicTemplate(template, {
'{Jahr}': fields.projectYear.value,
'{Projekt}': project,
'{ISP}': isp,
'{Kategorie}': fields.seCategory.value,
'{Datenpunkt}': fields.topicName.value.trim(),
'{Rechnername}': project && /^ISP\d+$/.test(isp) ? `SE-UGW-${project}-ISP${isp.slice(3).padStart(2, '0')}` : ''
});
}
fields.pointId.addEventListener('change', () => update(true));
fields.seMonitoring.addEventListener('change', () => {
@@ -118,3 +148,63 @@ function bindMqttMappingOptions(form) {
form.querySelector('[data-mqtt-monitoring]').addEventListener('input', () => update());
update();
}
function viewMqttTopicTemplateSettings() {
const settings = state.mqttMappingDefaults?.topicTemplate;
if (!settings) return '';
return `<article class="card"><div class="card-head"><h2>MQTT-Standardpfad</h2></div>
<form class="form" id="mqtt-topic-template-form">
<label>Topic-Vorlage<input name="template" type="text" value="${escapeHtml(settings.template)}" maxlength="1024" autocomplete="off" spellcheck="false" required></label>
<div class="mqtt-topic-placeholders" role="group" aria-label="Platzhalter">
${settings.placeholders.map(({token, description}) => `<button type="button" class="btn" data-template-insert="${escapeHtml(token)}">
<code>${escapeHtml(token)}</code><span class="note">${escapeHtml(description)}</span></button>`).join('')}
</div>
<div class="note">Vorschau mit Beispielpunkt</div>
<code data-mqtt-preview></code>
<div class="buttons">
<button type="submit" class="btn primary">Standardpfad speichern</button>
<button type="button" class="btn" data-template-default>Standardvorlage einsetzen</button>
</div>
<div id="mqtt-template-message" role="status"></div>
</form>
</article>`;
}
function bindMqttTopicTemplateSettings() {
const form = document.querySelector('#mqtt-topic-template-form');
if (!form) return;
let settings = state.mqttMappingDefaults.topicTemplate;
const input = form.elements.template;
const preview = form.querySelector('[data-mqtt-preview]');
const save = form.querySelector('[type=submit]');
const updatePreview = () => {
preview.textContent = expandMqttTopicTemplate(input.value, settings.previewValues) || '—';
};
form.querySelectorAll('[data-template-insert]').forEach(button => button.addEventListener('click', () => {
const start = input.selectionStart;
const end = input.selectionEnd;
input.focus({ preventScroll: true });
input.setRangeText(button.dataset.templateInsert, start, end, 'end');
updatePreview();
}));
form.querySelector('[data-template-default]').addEventListener('click', () => {
input.value = settings.defaultTemplate;
input.focus({ preventScroll: true });
updatePreview();
});
input.addEventListener('input', updatePreview);
form.addEventListener('submit', async event => {
event.preventDefault();
save.disabled = true;
const value = input.value;
try {
settings = await api('/api/mqtt/topic-template', { method:'PUT', body:JSON.stringify({ template:value }) });
state.mqttMappingDefaults.topicTemplate = settings;
if (input.value === value) input.value = settings.template;
updatePreview();
errorTarget('mqtt-template-message', 'MQTT-Standardpfad gespeichert.', true);
} catch (error) { errorTarget('mqtt-template-message', error.message); }
finally { save.disabled = false; }
});
updatePreview();
}
@@ -0,0 +1,14 @@
(function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.markdownit=t())})(this,function(){var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n={};function r(e){let t=n[e];if(t)return t;t=n[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);t.push(n)}for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[r]=`%`+(`0`+r.toString(16).toUpperCase()).slice(-2)}return t}function i(e,t){typeof t!=`string`&&(t=i.defaultChars);let n=r(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t=``;for(let r=0,i=e.length;r<i;r+=3){let a=parseInt(e.slice(r+1,r+3),16);if(a<128)t+=n[a];else{if((a&224)==192&&r+3<i){let n=parseInt(e.slice(r+4,r+6),16);if((n&192)==128){let e=a<<6&1984|n&63;t+=e<128?`��`:String.fromCharCode(e),r+=3;continue}}if((a&240)==224&&r+6<i){let n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16);if((n&192)==128&&(i&192)==128){let e=a<<12&61440|n<<6&4032|i&63;t+=e<2048||e>=55296&&e<=57343?`���`:String.fromCharCode(e),r+=6;continue}}if((a&248)==240&&r+9<i){let n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),o=parseInt(e.slice(r+10,r+12),16);if((n&192)==128&&(i&192)==128&&(o&192)==128){let e=a<<18&1835008|n<<12&258048|i<<6&4032|o&63;e<65536||e>1114111?t+=`����`:(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(e&1023))),r+=9;continue}}t+=`�`}}return t})}i.defaultChars=`;/?:@&=+$,#`,i.componentChars=``;var a={};function o(e){let t=a[e];if(t)return t;t=a[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);/^[0-9a-z]$/i.test(n)?t.push(n):t.push(`%`+(`0`+e.toString(16).toUpperCase()).slice(-2))}for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=e[n];return t}function s(e,t,n){typeof t!=`string`&&(n=t,t=s.defaultChars),n===void 0&&(n=!0);let r=o(t),i=``;for(let t=0,a=e.length;t<a;t++){let o=e.charCodeAt(t);if(n&&o===37&&t+2<a&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))i+=e.slice(t,t+3),t+=2;else if(o<128)i+=r[o];else if(o>=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1<a){let n=e.charCodeAt(t+1);if(n>=56320&&n<=57343){i+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}i+=`%EF%BF%BD`}else i+=encodeURIComponent(e[t])}return i}s.defaultChars=`;/?:@&=+$,-_.!~*'()#`,s.componentChars=`-_.!~*'()`;function c(e){let t=``;return t+=e.protocol||``,t+=e.slashes?`//`:``,t+=e.auth?e.auth+`@`:``,e.hostname&&e.hostname.indexOf(`:`)!==-1?t+=`[`+e.hostname+`]`:t+=e.hostname||``,t+=e.port?`:`+e.port:``,t+=e.pathname||``,t+=e.search||``,t+=e.hash||``,t}function l(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}var u=/^([a-z0-9.+-]+:)/i,d=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,p=[`%`,`/`,`?`,`;`,`#`,`'`,`{`,`}`,`|`,`\\`,`^`,"`",`<`,`>`,`"`,"`",` `,`\r`,`
`,` `],m=[`/`,`?`,`#`],h=255,g=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function b(e,t){if(e&&e instanceof l)return e;let n=new l;return n.parse(e,t),n}l.prototype.parse=function(e,t){let n,r,i,a=e;if(a=a.trim(),!t&&e.split(`#`).length===1){let e=f.exec(a);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=u.exec(a);if(o&&(o=o[0],n=o.toLowerCase(),this.protocol=o,a=a.substr(o.length)),(t||o||a.match(/^\/\/[^@\/]+@[^@\/]+/))&&(i=a.substr(0,2)===`//`,i&&!(o&&v[o])&&(a=a.substr(2),this.slashes=!0)),!v[o]&&(i||o&&!y[o])){let e=-1;for(let t=0;t<m.length;t++)r=a.indexOf(m[t]),r!==-1&&(e===-1||r<e)&&(e=r);let t,n;n=e===-1?a.lastIndexOf(`@`):a.lastIndexOf(`@`,e),n!==-1&&(t=a.slice(0,n),a=a.slice(n+1),this.auth=t),e=-1;for(let t=0;t<p.length;t++)r=a.indexOf(p[t]),r!==-1&&(e===-1||r<e)&&(e=r);e===-1&&(e=a.length),a[e-1]===`:`&&e--;let i=a.slice(0,e);a=a.slice(e),this.parseHost(i),this.hostname=this.hostname||``;let o=this.hostname[0]===`[`&&this.hostname[this.hostname.length-1]===`]`;if(!o){let e=this.hostname.split(/\./);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n&&!n.match(g)){let r=``;for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+=`x`:r+=n[e];if(!r.match(g)){let r=e.slice(0,t),i=e.slice(t+1),o=n.match(_);o&&(r.push(o[1]),i.unshift(o[2])),i.length&&(a=i.join(`.`)+a),this.hostname=r.join(`.`);break}}}}this.hostname.length>h&&(this.hostname=``),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}let s=a.indexOf(`#`);s!==-1&&(this.hash=a.substr(s),a=a.slice(0,s));let c=a.indexOf(`?`);return c!==-1&&(this.search=a.substr(c),a=a.slice(0,c)),a&&(this.pathname=a),y[n]&&this.hostname&&!this.pathname&&(this.pathname=``),this},l.prototype.parseHost=function(e){let t=d.exec(e);t&&(t=t[0],t!==`:`&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var x=t({decode:()=>i,encode:()=>s,format:()=>c,parse:()=>b}),S=t({Any:()=>C,Cc:()=>ee,Cf:()=>te,P:()=>ne,S:()=>re,Z:()=>ie}),C=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,ee=/[\0-\x1F\x7F-\x9F]/,te=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,ne=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B4E\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDD6E\uDEAD\uDED0\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9\uDFD4\uDFD5\uDFD7\uDFD8]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09\uDFE1]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDD6D-\uDD6F\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD839\uDDFF|\uD83A[\uDD5E\uDD5F]/,re=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\ Line truncated
`;if(o){let e=a.attrIndex(`class`),t=a.attrs?a.attrs.slice():[];e<0?t.push([`class`,`${n.langPrefix}${s}`]):(t[e]=[t[e][0],t[e][1]],t[e][1]+=` ${n.langPrefix}${s}`);let r={attrs:t};return`<pre><code${i.renderAttrs(r)}>${l}</code></pre>\n`}return`<pre><code${i.renderAttrs(a)}>${l}</code></pre>\n`},V.image=function(e,t,n,r,i){let a=e[t];return a.attrs[a.attrIndex(`alt`)][1]=i.renderInlineAsText(a.children,n,r),i.renderToken(e,t,n)},V.hardbreak=function(e,t,n){return n.xhtmlOut?`<br />
`:`<br>
`},V.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?`<br />
`:`<br>
`:`
`},V.text=function(e,t){return M(e[t].content)},V.html_block=function(e,t){return e[t].content},V.html_inline=function(e,t){return e[t].content};var Ze=class{constructor(){D(this,`rules`,Object.assign({},V))}renderAttrs(e){let t,n,r;if(!e.attrs)return``;for(r=``,t=0,n=e.attrs.length;t<n;t++)r+=` ${M(e.attrs[t][0])}="${M(String(e.attrs[t][1]))}"`;return r}renderToken(e,t,n){let r=e[t],i=``;if(r.hidden)return``;let a=t-1;for(;a>=0&&e[a].hidden&&e[a].nesting===0;)a--;r.block&&r.nesting!==-1&&a>=0&&e[a].hidden&&e[a].nesting===-1&&(i+=`
`),i+=(r.nesting===-1?`</`:`<`)+r.tag,i+=this.renderAttrs(r),r.nesting===0&&n.xhtmlOut&&(i+=` /`);let o=!1;if(r.block&&(o=!0,r.nesting===1)){let n=t+1;for(;n<e.length&&e[n].hidden&&e[n].nesting===0;)n++;if(n<e.length){let t=e[n];(t.type===`inline`||t.hidden||t.nesting===-1&&t.tag===r.tag)&&(o=!1)}}return i+=o?`>
`:`>`,i}renderInline(e,t,n){let r=``,i=this.rules;for(let a=0,o=e.length;a<o;a++){let o=e[a].type;i[o]===void 0?r+=this.renderToken(e,a,t):r+=i[o](e,a,t,n,this)}return r}renderInlineAsText(e,t,n){let r=``;for(let i=0,a=e.length;i<a;i++)switch(e[i].type){case`text`:case`code_inline`:r+=e[i].content;break;case`image`:r+=this.renderInlineAsText(e[i].children,t,n);break;case`html_inline`:case`html_block`:r+=e[i].content;break;case`softbreak`:case`hardbreak`:r+=`
`}return r}render(e,t,n){let r=``,i=this.rules;for(let a=0,o=e.length;a<o;a++){let o=e[a].type;o===`inline`?r+=this.renderInline(e[a].children,t,n):i[o]===void 0?r+=this.renderToken(e,a,t):r+=i[o](e,a,t,n,this)}return r}},Qe=class{constructor(e,t,n){D(this,`tokens`,[]),D(this,`inlineMode`,!1),D(this,`Token`,z),this.src=e,this.env=n,this.md=t}},$e=/\r\n?/g,et=/\0/g;function tt(e){let t;t=e.src.replace($e,`
`),t=t.replace(et,`�`),e.src=t}function nt(e){let t;e.inlineMode?(t=new e.Token(`inline`,``,0),t.content=e.src,t.map=[0,1],t.children=[],e.tokens.push(t)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}function rt(e){let t=e.tokens,n=0;for(let e=0;e<t.length;e++)t[e].type!==`reference_definition`&&(e!==n&&(t[n]=t[e]),n++);t.length!==n&&(t.length=n)}function it(e){let t=e.tokens;for(let n=0,r=t.length;n<r;n++){let r=t[n];r.type===`inline`&&e.md.inline.parse(r.content,e.md,e.env,r.children)}}function at(e){return/^<a[>\s]/i.test(e)}function ot(e){return/^<\/a\s*>/i.test(e)}function st(e){let t=e.tokens;if(e.md.options.linkify)for(let n=0,r=t.length;n<r;n++){if(t[n].type!==`inline`||!e.md.linkify.test(t[n].content))continue;let r=t[n].children,i=[],a=0;for(let t=r.length-1;t>=0;t--){let n=r[t];if(n.type===`link_close`)for(t--;r[t].level!==n.level&&r[t].type!==`link_open`;)t--;else if(n.type===`html_inline`&&(at(n.content)&&a>0&&a--,ot(n.content)&&a++),!(a>0)&&n.type===`text`&&e.md.linkify.test(n.content)){let a=n.content,o=e.md.linkify.match(a),s=[],c=n.level,l=0;o.length>0&&o[0].index===0&&t>0&&r[t-1].type===`text_special`&&(o=o.slice(1));for(let t=0;t<o.length;t++){let n=o[t].url,r=e.md.normalizeLink(n);if(!e.md.validateLink(r))continue;let i=o[t].text;i=o[t].schema?o[t].schema===`mailto:`&&!/^mailto:/i.test(i)?e.md.normalizeLinkText(`mailto:${i}`).replace(/^mailto:/,``):e.md.normalizeLinkText(i):e.md.normalizeLinkText(`http://${i}`).replace(/^http:\/\//,``);let u=o[t].index;if(u>l){let t=new e.Token(`text`,``,0);t.content=a.slice(l,u),t.level=c,s.push(t)}let d=new e.Token(`link_open`,`a`,1);d.attrs=[[`href`,r]],d.level=c++,d.markup=`linkify`,d.info=`auto`,s.push(d);let f=new e.Token(`text`,``,0);f.content=i,f.level=c,s.push(f);let p=new e.Token(`link_close`,`a`,-1);p.level=--c,p.markup=`linkify`,p.info=`auto`,s.push(p),l=o[t].lastIndex}if(l<a.length){let t=new e.Token(`text`,``,0);t.content=a.slice(l),t.level=c,s.push(t)}i.push({index:t,nodes:s})}}if(i.length>0){let e=r.length;for(let t of i)e+=t.nodes.length-1;let a=Array(e),o=0,s=0;i.reverse();for(let e=0;e<r.length;e++){let t=i[o];if((t==null?void 0:t.index)===e){for(let e of t.nodes)a[s++]=e;o++}else a[s++]=r[e]}t[n].children=a}}}var ct=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,lt=/\((c|tm|r)\)/i,ut=/\((c|tm|r)\)/gi,dt={c:`©`,r:`®`,tm:`™`};function ft(e,t){return dt[t.toLowerCase()]}function pt(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];r.type===`text`&&!t&&(r.content=r.content.replace(ut,ft)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function mt(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];r.type===`text`&&!t&&ct.test(r.content)&&(r.content=r.content.replace(/\+-/g,`±`).replace(/\.{2,}/g,`…`).replace(/([?!])…/g,`$1..`).replace(/([?!]){4,}/g,`$1$1$1`).replace(/,{2,}/g,`,`).replace(/(^|[^-])---(?=[^-]|$)/gm,`$1—`).replace(/(^|\s)--(?=\s|$)/gm,`$1–`).replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,`$1–`)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function ht(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)e.tokens[t].type===`inline`&&(lt.test(e.tokens[t].content)&&pt(e.tokens[t].children),ct.test(e.tokens[t].content)&&mt(e.tokens[t].children))}var gt=/['"]/,_t=/['"]/g,vt=`’`,yt=1e3;function bt(e,t,n){for(;e.length>n;){let n=e.pop();n.isSingleQuote?t.single=n.prevSameQuoteIdx:t.double=n.prevSameQuoteIdx}}function H(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function xt(e,t){let n=``,r=0;t.sort((e,t)=>e.pos-t.pos);for(let i=0;i<t.length;i++){let a=t[i];n+=e.slice(r,a.pos)+a.ch,r=a.pos+1}return n+e.slice(r)}function St(e,t){let n,r=[],i={single:-1,double:-1},a={};for(let o=0;o<e.length;o++){let s=e[o],c=e[o].level;for(n=r.length-1;n>=0&&!(r[n].level<=c);n--);if(bt(r,i,n+1),s.type!==`text`)continue;let l=s.content,u=0,d=l.length;OUTER:for(;u<d;){_t.lastIndex=u;let s=_t.exec(l);if(!s)break;let f=!0,p=!0;u=s.index+1;let m=s[0]===`'`,h=32;if(s.index-1>=0)h=l.charCodeAt(s.index-1);else for(n=o-1;n>=0&&e[n].type!==`softbreak`&&e[n].type!==`hardbreak`;n--)if(e[n].content){h=e[n].content.charCodeAt(e[n].content.length-1);break}let g=32;if(u<d)g=l.charCodeAt(u);else for(n=o+1;n<e.length&&e[n].type!==`softbreak`&&e[n].type!==`hardbreak`;n++)if(e[n].content){g=e[n].content.charCodeAt(0);break}let _=I(h)||F(h),v=I(g)||F(g),y=P(h),b=P(g);if(b?f=!1:v&&(y||_||(f=!1)),y?p=!1:_&&(b||v||(p=!1)),g===34&&s[0]===`"`&&h>=48&&h<=57&&(p=f=!1),f&&p&&(f=_,p=v),!f&&!p)m&&H(a,o,s.index,vt);else{if(p&&(n=m?i.single:i.double,n>=0&&r[n].level===c)){let e=r[n],c,l;m?(c=t.md.options.quotes[2],l=t.md.options.quotes[3]):(c=t.md.options.quotes[0],l=t.md.options.quotes[1]),H(a,o,s.index,l),H(a,e.tokenIdx,e.contentPos,c),bt(r,i,n);continue OUTER}if(f){if(r.length>=yt)return;r.push({tokenIdx:o,contentPos:s.index,isSingleQuote:m,level:c,prevSameQuoteIdx:m?i.single:i.double}),m?i.single=r.length-1:i.double=r.length-1}else p&&m&&H(a,o,s.index,vt)}}}Object.keys(a).forEa Line truncated
`,a.map=[t,e.line],!0}function Pt(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4||i+3>a)return!1;let o=e.src.charCodeAt(i);if(o!==126&&o!==96)return!1;let s=i;i=e.skipChars(i,o);let c=i-s;if(c<3)return!1;let l=e.src.slice(s,i),u=e.src.slice(i,a);if(o===96&&u.indexOf(String.fromCharCode(o))>=0)return!1;if(r)return!0;let d=t,f=!1;for(;d++,!(d>=n||(i=s=e.bMarks[d]+e.tShift[d],a=e.eMarks[d],i<a&&e.sCount[d]<e.blkIndent));)if(e.src.charCodeAt(i)===o&&!(e.sCount[d]-e.blkIndent>=4)&&(i=e.skipChars(i,o),!(i-s<c)&&(i=e.skipSpaces(i),!(i<a)))){f=!0;break}c=e.sCount[t],e.line=d+ +!!f;let p=e.push(`fence`,`code`,0);return p.info=u,p.content=e.getLines(t+1,d,c,!0),p.markup=l,p.map=[t,e.line],!0}function Ft(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t],o=e.lineMax;if(e.sCount[t]-e.blkIndent>=4||e.src.charCodeAt(i)!==62)return!1;if(r)return!0;let s=[],c=[],l=[],u=[],d=e.md.block.ruler.getRules(`blockquote`),f=e.parentType;e.parentType=`blockquote`;let p=!1,m;for(m=t;m<n;m++){let t=e.sCount[m]<e.blkIndent;if(i=e.bMarks[m]+e.tShift[m],a=e.eMarks[m],i>=a)break;if(e.src.charCodeAt(i++)===62&&!t){let t=e.sCount[m]+1,n,r;e.src.charCodeAt(i)===32?(i++,t++,r=!1,n=!0):e.src.charCodeAt(i)===9?(n=!0,(e.bsCount[m]+t)%4==3?(i++,t++,r=!1):r=!0):n=!1;let o=t;for(s.push(e.bMarks[m]),e.bMarks[m]=i;i<a;){let t=e.src.charCodeAt(i);if(N(t))t===9?o+=4-(o+e.bsCount[m]+ +!!r)%4:o++;else break;i++}p=i>=a,c.push(e.bsCount[m]),e.bsCount[m]=e.sCount[m]+1+ +!!n,l.push(e.sCount[m]),e.sCount[m]=o-t,u.push(e.tShift[m]),e.tShift[m]=i-e.bMarks[m];continue}if(p)break;let r=!1;for(let t=0,i=d.length;t<i;t++)if(d[t](e,m,n,!0)){r=!0;break}if(r){e.lineMax=m,e.blkIndent!==0&&(s.push(e.bMarks[m]),c.push(e.bsCount[m]),u.push(e.tShift[m]),l.push(e.sCount[m]),e.sCount[m]-=e.blkIndent);break}s.push(e.bMarks[m]),c.push(e.bsCount[m]),u.push(e.tShift[m]),l.push(e.sCount[m]),e.sCount[m]=-1}let h=e.blkIndent;e.blkIndent=0;let g=e.push(`blockquote_open`,`blockquote`,1);g.markup=`>`;let _=[t,0];g.map=_,e.md.block.tokenize(e,t,m);let v=e.push(`blockquote_close`,`blockquote`,-1);v.markup=`>`,e.lineMax=o,e.parentType=f,_[1]=e.line;for(let n=0;n<u.length;n++)e.bMarks[n+t]=s[n],e.tShift[n+t]=u[n],e.sCount[n+t]=l[n],e.bsCount[n+t]=c[n];return e.blkIndent=h,!0}function It(e,t,n,r){let i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let a=e.bMarks[t]+e.tShift[t],o=e.src.charCodeAt(a++);if(o!==42&&o!==45&&o!==95)return!1;let s=1;for(;a<i;){let t=e.src.charCodeAt(a++);if(t!==o&&!N(t))return!1;t===o&&s++}if(s<3)return!1;if(r)return!0;e.line=t+1;let c=e.push(`hr`,`hr`,0);return c.map=[t,e.line],c.markup=Array(s+1).join(String.fromCharCode(o)),!0}function Lt(e,t){let n=e.eMarks[t],r=e.bMarks[t]+e.tShift[t],i=e.src.charCodeAt(r++);return i!==42&&i!==45&&i!==43||r<n&&!N(e.src.charCodeAt(r))?-1:r}function Rt(e,t){let n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t],i=n;if(i+1>=r)return-1;let a=e.src.charCodeAt(i++);if(a<48||a>57)return-1;for(;;){if(i>=r)return-1;if(a=e.src.charCodeAt(i++),a>=48&&a<=57){if(i-n>=10)return-1}else{if(a===41||a===46)break;return-1}}return i<r&&(a=e.src.charCodeAt(i),!N(a))?-1:i}function zt(e,t){let n=e.level+2;for(let r=t+2,i=e.tokens.length-2;r<i;r++)e.tokens[r].level===n&&e.tokens[r].type===`paragraph_open`&&(e.tokens[r+2].hidden=!0,e.tokens[r].hidden=!0,r+=2)}function Bt(e,t,n,r){let i,a,o,s,c=t,l=!0;if(e.sCount[c]-e.blkIndent>=4||e.listIndent>=0&&e.sCount[c]-e.listIndent>=4&&e.sCount[c]<e.blkIndent)return!1;let u=!1;r&&e.parentType===`paragraph`&&e.sCount[c]>=e.blkIndent&&(u=!0);let d,f,p;if((p=Rt(e,c))>=0){if(d=!0,o=e.bMarks[c]+e.tShift[c],f=Number(e.src.slice(o,p-1)),u&&f!==1)return!1}else if((p=Lt(e,c))>=0)d=!1;else return!1;if(u&&e.skipSpaces(p)>=e.eMarks[c])return!1;if(r)return!0;let m=e.src.charCodeAt(p-1),h=e.tokens.length;d?(s=e.push(`ordered_list_open`,`ol`,1),f!==1&&(s.attrs=[[`start`,f]])):s=e.push(`bullet_list_open`,`ul`,1);let g=[c,0];s.map=g,s.markup=String.fromCharCode(m);let _=!1,v=e.md.block.ruler.getRules(`list`),y=e.parentType;for(e.parentType=`list`;c<n;){a=p,i=e.eMarks[c];let t=e.sCount[c]+p-(e.bMarks[c]+e.tShift[c]),r=t;for(;a<i;){let t=e.src.charCodeAt(a);if(t===9)r+=4-(r+e.bsCount[c])%4;else if(t===32)r++;else break;a++}let u=a,f;f=u>=i?1:r-t,f>4&&(f=1);let h=t+f;s=e.push(`list_item_open`,`li`,1),s.markup=String.fromCharCode(m);let g=[c,0];s.map=g,d&&(s.info=e.src.slice(o,p-1));let y=e.tight,b=e.tShift[c],x=e.sCount[c],S=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=h,e.tight=!0,e.tShift[c]=u-e.bMarks[c],e.sCount[c]=r,u>=i&&e.isEmpty(c+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,c,n),(!e.tight||_)&&(l=!1),_=e.line-c>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=S,e.tShift[c]=b,e.sCount[c]=x,e.tight=y,s=e.push(`list_item_close`,`li`,-1),s.markup=String.fromCharCode(m),c=e.line,g[1]=c,c>=n||e.sCount[c]<e.blkIndent||e.sCount[c]-e.blkIndent>=4)break;let C=!1;for(let t=0,r=v.length;t<r;t++)if(v[t](e,c,n,!0)){C=!0;break}if(C)break;if(d){if(p=Rt(e,c),p<0)break;o=e.bMar Line truncated
//# sourceMappingURL=markdown-it.umd.min.js.map
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.