first commit
This commit is contained in:
commit
b31e9a7261
38 files changed
+3822
No files matched your search
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
data/
|
||||
artifacts/
|
||||
bin/
|
||||
obj/
|
||||
node_modules/
|
||||
.dotnet/
|
||||
.nuget-packages/
|
||||
result
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<AnalysisLevel>latest-recommended</AnalysisLevel>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,85 @@
|
||||
# SEIU Gateway
|
||||
|
||||
Ein Linux-Gateway für BACnet/IP, OPC UA, Modbus TCP, MQTT/MQTTS und später KNXnet/IP.
|
||||
|
||||
## Architekturentscheidungen
|
||||
|
||||
- BACnet wird als natives Gerät der B-BC-Klasse implementiert. Der Datenpfad verwendet den C-basierten [`bacnet-stack`](https://github.com/bacnet-stack/bacnet-stack), fest auf Commit `0bfe65645ff7238e15121a6727870f96413ac22e` zu pinnen. Der JavaScript-Stack ist nicht Teil des Feld-Datenpfads.
|
||||
- Vendor-ID ist fest `815`; die BACnet-Device-Instance ist konfigurierbar, Standard `23`.
|
||||
- BACnet/IP läuft direkt auf dem NixOS-Host. Das gilt ebenfalls für die Standard-Ports von BACnet/IP (`47808/udp`), KNXnet/IP (`3671/udp`), Modbus TCP (`502/tcp`) und OPC UA (`4840/tcp`). Es gibt keine NAT-Übersetzung oder Container-Netzschicht.
|
||||
- Die Konfiguration und Audit-Daten liegen in SQLite in `./data/seiugw.db`; Zertifikate liegen darunter in `pki/` und werden nicht im Image gespeichert.
|
||||
- MQTT ist ausschließlich ein Client zu einem bestehenden Broker – das Gateway stellt keinen Broker bereit. Broker-Credentials werden getrennt und verschlüsselt in der lokalen Datenhaltung abgelegt; der Schlüssel liegt ausschließlich im persistenten Datenvolume.
|
||||
- MQTT 3.1.1 wird für Kompatibilität mit Feld-Brokern verwendet, mit QoS 0/1/2, Retain, optionaler Benutzername/Passwort-Authentifizierung sowie optionalem TLS. Zertifikate werden standardmäßig validiert. Das bewusste Ignorieren von Zertifikatsfehlern ist nur bei aktivem TLS konfigurierbar und im UI deutlich markiert.
|
||||
- Jeder Mapping-Write erhält eine Herkunftskette und einen Eintrag im Schreibjournal. Eine Rückmeldung, die einer eigenen externen Schreiboperation entspricht, wird nicht erneut propagiert. Mehrere Schreiber auf dasselbe externe Objekt werden abgewiesen, außer bei explizit quittierten BACnet-Prioritäten.
|
||||
- Das Datenmodell und die Webverwaltung decken AI/AO/AV, BI/BO/BV, MSI/MSO/MSV, Schedule, Calendar, Event Enrollment, Notification Class sowie gateway-interne Trend Logs ab. Der native BACnet-Adapter materialisiert diese im nächsten Implementierungsschritt; Details stehen in [`docs/object-model.md`](docs/object-model.md).
|
||||
|
||||
## Deployment auf NixOS
|
||||
|
||||
Das Repository enthält eine gepinnte Nix-Flake, ein paketiertes ASP.NET-Programm und ein NixOS-Modul. Der Dienst läuft als eigener Systembenutzer `seiugw`, seine SQLite-Daten, Secrets und spätere PKI liegen dauerhaft in `/var/lib/seiugw`. MariaDB läuft lokal gebunden und erhält beim ersten Start das Legacy-Schema `wago` mit `isp01` bis `isp20` und je 200 `Wert…`-Feldern. Der Datenbankport wird nicht in der Firewall geöffnet.
|
||||
|
||||
Auf der VM einmalig:
|
||||
|
||||
```sh
|
||||
sudo git clone <DEIN-GIT-REPOSITORY> /etc/nixos/seiugw
|
||||
sudo cp /etc/nixos/seiugw/nix/host-snippet.nix /etc/nixos/seiugw-host.nix
|
||||
sudoedit /etc/nixos/seiugw-host.nix
|
||||
```
|
||||
|
||||
`/etc/nixos/seiugw-host.nix` in die `imports` von `/etc/nixos/configuration.nix` aufnehmen. Vor dem ersten Rebuild müssen dort mindestens das Feldnetz-Interface (beispielsweise `ens18`) und bei Bedarf Device-Instance bzw. Ports angepasst werden.
|
||||
|
||||
```nix
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
|
||||
imports = [
|
||||
./hardware-configuration.nix
|
||||
./seiugw-host.nix
|
||||
];
|
||||
```
|
||||
|
||||
Danach:
|
||||
|
||||
```sh
|
||||
sudo nixos-rebuild switch
|
||||
systemctl status seiugw
|
||||
```
|
||||
|
||||
Die Weboberfläche ist auf `http://<gateway-ip>:8088` verfügbar. Beim ersten Aufruf werden das Passwort für `admin`, die Projektnummer und die ISP-Nummer festgelegt. Für Updates reichen `git -C /etc/nixos/seiugw pull --ff-only` und anschließend `sudo nixos-rebuild switch`.
|
||||
|
||||
Die Flake sperrt Nixpkgs und sämtliche NuGet-Archive. Die Paketaktualisierung erfolgt bewusst, indem `flake.lock`, `nix/deps.json` und die Projekt-Abhängigkeiten zusammen geändert und getestet werden.
|
||||
|
||||
IP-Symcon wird nicht als Nix-Paket ausgegeben, weil der Hersteller offiziell ein Ubuntu-APT-Paket liefert und für die Installation eine gültige Subskription voraussetzt. Es wird auf derselben NixOS-VM als isolierter, nicht-nativer Vendor-Prozess angebunden; seine Daten liest das Gateway über die API. Das lizenzierte Paket beziehungsweise eine zulässige, versionsfeste Downloadquelle wird dafür noch benötigt.
|
||||
|
||||
## Einmalige Komari-Registrierung und Rechnername
|
||||
|
||||
Die Erstinbetriebnahme fragt verpflichtend nach Projektnummer und ISP. Aus `P190726` und `1` wird der Laufzeit-Hostname `SE-UGW-P190726-ISP01`. Er wird bei jedem Boot erneut aus der lokalen Gateway-Datenhaltung gesetzt; dadurch erscheint das Gerät in Komari eindeutig, ohne die NixOS-Konfiguration pro Projekt ändern zu müssen.
|
||||
|
||||
Der Komari-Agent wird nur einmal registriert: Erst wenn sowohl die Ersteinrichtung abgeschlossen ist als auch eine lokale Token-Datei existiert. Der Token gehört **nicht** nach Git, nicht in eine Flake und nicht in die Weboberfläche. Auf der NixOS-VM wird er einmalig mit restriktiven Rechten angelegt:
|
||||
|
||||
```sh
|
||||
sudo install -o root -g root -m 0600 /dev/null /var/lib/seiugw/komari-enrollment-token
|
||||
sudoedit /var/lib/seiugw/komari-enrollment-token
|
||||
```
|
||||
|
||||
Danach führt das deklarierte Einmal-Setup den angeforderten Upstream-Installer aus, legt den Agenten unter `/opt/komari` ab und startet die von NixOS verwaltete Unit `seiugw-komari-agent`. Der Agent erhält dabei die konfigurierte Endpoint-Adresse und die angeforderte Option zum Ignorieren unsicherer Zertifikatsfehler. Weil diese Option die Zertifikatsprüfung abschaltet, darf sie nur für den kontrollierten Komari-Endpunkt eingesetzt werden. Weder der Token noch sein Inhalt werden protokolliert oder in der Gateway-Datenbank gespeichert.
|
||||
|
||||
## MQTT-Mapping
|
||||
|
||||
Pro Datenpunkt gibt es ein Publishing-, Subscribe- oder bidirektionales Mapping. Eingehende MQTT-Werte werden dauerhaft als aktueller Punktwert gespeichert und können gateway-interne Trend Logs speisen. Werte, die selbst vom MQTT-Broker stammen, werden nicht blind auf denselben Broker zurückgespiegelt.
|
||||
|
||||
Neben frei konfigurierbaren JSON-Topics unterstützt das Gateway das SE-Monitoring-Schema:
|
||||
|
||||
```text
|
||||
Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/{Analog|Notify|Alarm|Setpoints}/{Punktname}_Wert
|
||||
```
|
||||
|
||||
`Analog` akzeptiert ausschließlich analoge Typen; `Notify` und `Alarm` ausschließlich digitale. `Setpoints` sind immer bidirektional. Schedule, Calendar und weitere strukturierte BACnet-Objekte sind absichtlich nur als JSON-Mapping zulässig. Das Segment lautet standardmäßig `Alarm`, entsprechend den bereitgestellten Explorer-Screenshots.
|
||||
|
||||
## Sicherheitsvorgaben
|
||||
|
||||
- Das Web-UI erzeugt keine Default-Zugangsdaten. Passwörter werden mit PBKDF2-SHA-512 und einem individuellen Salt gespeichert.
|
||||
- OPC-UA-Zertifikate und Trustlisten werden persistent gespeichert; unbekannte Zertifikate werden nicht automatisch vertraut.
|
||||
- Modbus-TCP-Serverinstanzen erhalten eine explizite Client-IP-Allowlist. Eine leere Allowlist bedeutet bewusst „alle erlauben“ und wird im UI sichtbar markiert.
|
||||
|
||||
## Nicht verwechseln
|
||||
|
||||
BACnet/IP verwendet UDP als Transport. Das Gateway implementiert dennoch ein reguläres BACnet-Gerät mit bestätigten Diensten und Unicast-Kommunikation; Broadcast ist nicht der alleinige Betriebsmodus. BBMD und Foreign Device werden im BACnet-Adapter konfiguriert. BACnet/SC ist als eigene Transportkonfiguration vorgesehen, wird aber erst nach der BACnet/IP-Interoperabilität aktiviert.
|
||||
Submodule
+1
Submodule SeLTD added at 2f5f86452f.
@@ -0,0 +1,54 @@
|
||||
# Datenpfad und Synchronisation
|
||||
|
||||
## Rollen
|
||||
|
||||
```text
|
||||
BACnet/IP ─┐
|
||||
OPC UA ───┼── Adapter ──> Mapping-Engine ──> Adapter ──┬── BACnet/IP
|
||||
Modbus ───┼── │ ├── OPC UA
|
||||
MQTT(S) ──┘ │ ├── Modbus
|
||||
└── SQLite / Audit / PKI └── MQTT(S)
|
||||
```
|
||||
|
||||
Der BACnet-Adapter wird als natives C-Modul aus `bacnet-stack` aufgebaut. Die Web- und Konfigurationsebene darf niemals selbst BACnet-UDP-Pakete erzeugen. Das verhindert, dass die UI versehentlich zum zweiten BACnet-Client wird.
|
||||
|
||||
## Deployment
|
||||
|
||||
Das Gateway wird direkt als gehärteter NixOS-`systemd`-Dienst ausgeführt, nicht in Docker. Damit besitzt BACnet/IP denselben Netzwerk-Namespace wie das Feldnetz-Interface und benötigt weder Host-Network-Ausnahmen noch veröffentlichte Container-Ports. Der NixOS-Dienst wartet auf `network-online.target`, wird bei Fehlern neu gestartet und läuft als nicht-anmeldbarer Benutzer `seiugw`. Seine einzige schreibbare Fläche ist das persistente Datenverzeichnis.
|
||||
|
||||
Die Langzeithistorie bleibt in einer lokalen MariaDB. Der NixOS-Service initialisiert bei einem leeren Datenverzeichnis die Datenbank `wago` mit den Legacy-Tabellen `isp01` bis `isp20`; jedes enthält `datum`, `userlevel` sowie `Wert1` bis `Wert200` als Textfelder. MariaDB bindet nur an `127.0.0.1` und verwendet für den Gateway-Prozess Unix-Socket-Authentifizierung. Testdaten werden nicht importiert.
|
||||
|
||||
IP-Symcon gehört nicht in den Gateway-Datenpfad. Der Gateway-Symcon-Adapter spricht die vom vorhandenen LTD-System verwendete, API-Key-geschützte Hook-Schnittstelle und übernimmt Werte in den zentralen Punkt- und Trendpfad. Weil der Hersteller derzeit nur einen Ubuntu-APT-Installationsweg dokumentiert, wird die Vendor-Laufzeit auf derselben NixOS-VM isoliert und nicht als reguläres Nix-Paket behandelt. Die konkrete Ausführung wird erst mit einem lizenzkonformen, versionsfesten Vendor-Artefakt aktiviert.
|
||||
|
||||
## Updateverarbeitung
|
||||
|
||||
1. Der jeweilige Adapter erhält eine Änderung. Bei BACnet erfolgt dies zuerst über `SubscribeCOV` beziehungsweise `SubscribeCOVProperty`; nur wenn ein Gegenüber COV nicht unterstützt oder die Subscription ausläuft, wird mit einem begrenzten Poll-Intervall nachgezogen.
|
||||
2. Die Mapping-Engine bewertet Schreibownership und Transformation und vergibt eine Herkunfts-ID.
|
||||
3. Vor einem externen Write hinterlegt sie Zieladresse, normierten Wert und Ablaufzeit im Schreibjournal.
|
||||
4. Meldet das Ziel denselben Wert zurück, verbraucht der Adapter den Journaleintrag. Diese Rückmeldung wird nicht als neue Quelländerung verteilt.
|
||||
5. Eine abweichende oder nicht journalisierte Rückmeldung gilt als externe Änderung und wird normal verteilt.
|
||||
|
||||
Damit wird ein Client-Write auf einen BACnet-AV mit Priorität 16 erkannt, auch wenn der effektive `Present_Value` wegen einer höheren aktiven Priorität abweicht. Die BACnet-Prioritätsarray-Information und der effektive Wert bleiben getrennt.
|
||||
|
||||
## MQTT(S)
|
||||
|
||||
Der MQTT-Adapter ist ein einzelner Client, nie ein lokaler Broker. Er verbindet sich nach einer Konfigurationsänderung neu, abonniert ausschließlich die exakt gespeicherten Subscribe-/Bidirectional-Topics und veröffentlicht auf Publish-/Bidirectional-Topics. Es werden keine Wildcards erzeugt.
|
||||
|
||||
Das Gateway verwendet MQTT 3.1.1 für die Kompatibilität zu älteren Feld-Brokern. Für jedes Mapping sind QoS 0, 1 oder 2 und das Retain-Flag separat konfigurierbar. Bei aktiviertem TLS wird die Zertifikatskette standardmäßig geprüft. Eine explizite Ausnahme kann den Zertifikats-Callback für bekannte, kontrollierte Installationen freigeben; das darf nicht als globale Standardeinstellung verwendet werden.
|
||||
|
||||
SE-Monitoring-Topics werden deterministisch als `Projekte{Jahr}/P{Projekt}/ISP{Nummer}/{Kategorie}/{Punkt}_Wert` aufgebaut. Als Kategorien gelten `Analog`, `Notify`, `Alarm` und `Setpoints`. Die Typprüfung erfolgt beim Speichern des Mappings, nicht erst zur Laufzeit. JSON-Mappings dürfen mehrere Eigenschaften auf einem Topic bündeln; bei gesetzter Eigenschaft wird beim Empfang genau diese Eigenschaft übernommen und beim Senden ein JSON-Objekt mit Zeitstempel und Eigenschaft erzeugt.
|
||||
|
||||
## Interne Trend-Historie
|
||||
|
||||
Trend Logs werden am Gateway als schreibgeschützte, protokollunabhängige Historie geführt. Der zentrale Adapter-Updatepfad ruft nach erfolgreicher Annahme `RecordPointObservation` auf. So wird genau dieselbe, bereits durch Herkunft und Mappingregeln geprüfte Änderung aus BACnet, OPC UA, Modbus oder KNX aufgezeichnet. Das Trend Log bleibt außerhalb der Rückschreib- und Mapping-Schleife.
|
||||
|
||||
## Mehrere BACnet-Prioritäten
|
||||
|
||||
Standardmäßig ist ein externer Zielpunkt nur einmal schreibbar. Die einzige konfigurierbare Ausnahme ist BACnet: Mehrere Quellen dürfen nur auf demselben Objekt schreiben, wenn jede Kante eine verschiedene Priorität 1–16 besitzt und jede Kante ausdrücklich quittiert wurde. Die Mapping-Engine erzeugt dafür vor dem Speichern eine sichtbare Warnung und schreibt einen Audit-Eintrag.
|
||||
|
||||
## BACnet/IP und Routing
|
||||
|
||||
- Lokale Discovery verwendet die BACnet-Dienste `Who-Is` und `I-Am`; normale bestätigte Dienste werden unicast verarbeitet.
|
||||
- BBMD-Betrieb verwendet eine persistente BDT. Als Foreign Device erneuert der Adapter die Registrierung vor Ablauf der TTL und überwacht die Antwort.
|
||||
- BACnet/SC bleibt als separater Adaptermodus vorbereitet. Er teilt keine Socket- oder Zertifikatskonfiguration mit BACnet/IP.
|
||||
- Ein Feldgerät, das nur mit `0.0.0.0` erscheint, wird nicht speziell „nachgebildet“. Es wird mit unicast Read/Write, COV-Subscription und gegebenenfalls BBMD/Foreign-Device-Routing getestet. Erst ein Mitschnitt entscheidet, ob es sich um ein proprietäres Verhalten handelt.
|
||||
@@ -0,0 +1,10 @@
|
||||
# BACnet-Stack-Bindung
|
||||
|
||||
Upstream: `https://github.com/bacnet-stack/bacnet-stack.git`
|
||||
Revision: `0bfe65645ff7238e15121a6727870f96413ac22e`
|
||||
|
||||
Für den nativen Adapter wird ausschließlich dieser Commit verwendet. Aktualisierungen werden als eigene, dokumentierte Änderung vorgenommen und müssen gegen die BACnet-Interoperabilitätssuite geprüft werden.
|
||||
|
||||
Der Stack stellt die benötigten Diensthandler für `Who-Is`, `ReadProperty`, `ReadPropertyMultiple`, `WriteProperty`, `WritePropertyMultiple`, `SubscribeCOV`, Zeit-Synchronisation und Device Communication Control bereit. Seine Umgebungsparameter decken BACnet/IP-Port, BDT und Foreign-Device-TTL ab. Der Adapter konfiguriert diese Werte aus SQLite und erzeugt keine zweite parallele UDP-Implementierung in .NET.
|
||||
|
||||
Der Herstellerhinweis zu Priva Blue ID wird als Interoperabilitätsrisiko geführt. Kein kompatibles Gateway darf aus einer angezeigten Remote-Adresse `0.0.0.0` eine Zieladresse ableiten oder dorthin schreiben.
|
||||
@@ -0,0 +1,27 @@
|
||||
# BACnet-Objektmodell der ersten Feldversion
|
||||
|
||||
Der native BACnet-Adapter wird folgende Standardobjekte veröffentlichen; Konfiguration, Validierung und Historie dafür sind bereits im Gateway-Kern umgesetzt:
|
||||
|
||||
| Aufgabe | Objekttypen |
|
||||
|---|---|
|
||||
| Numerische Werte | Analog Input, Analog Output, Analog Value |
|
||||
| Binäre Werte | Binary Input, Binary Output, Binary Value |
|
||||
| Mehrzustandswerte | Multi-state Input, Multi-state Output, Multi-state Value |
|
||||
| Kalender und Fahrpläne | Calendar, Schedule |
|
||||
| Alarmierung | Event Enrollment, Notification Class |
|
||||
| Gateway-Historie | Trend Log |
|
||||
|
||||
`Schedule` ist eine gerichtete Quelle: Sein `Present_Value` kann auf einen Zielpunkt mit konfigurierbarer BACnet-Priorität schreiben. Eine Rückrichtung in den Schedule wird abgewiesen. `Calendar`, `Event Enrollment` und `Notification Class` werden über ihre standardisierten Eigenschaften und Referenzen konfiguriert; sie sind keine generischen Wert-Mappings.
|
||||
|
||||
## Gateway-interne Trend Logs
|
||||
|
||||
Ein Trend Log bezieht sich auf einen lesbaren Gateway-Punkt. Jeder Adapter kann nach einer akzeptierten Änderung `RecordPointObservation` aufrufen. Die Historie speichert dabei:
|
||||
|
||||
- den Zeitstempel der beobachteten Änderung,
|
||||
- den unveränderten, normalisierten Wert als JSON,
|
||||
- Ursprungsprotokoll und optionalen Qualitätsstatus,
|
||||
- eine monoton wachsende Sequenznummer.
|
||||
|
||||
Ein konfiguriertes Intervall begrenzt die Aufzeichnungsrate. Die Retention entfernt ausschließlich die ältesten Records; aktuelle Werte und Mapping-Daten werden dabei nie verändert. Die Logs sind folglich aus BACnet, OPC UA, Modbus oder später KNX befüllbar, aber selbst keine zusätzliche Schreibquelle.
|
||||
|
||||
Bei der nativen BACnet-Anbindung werden diese Tabellen als `Trend Log`-Objekte mit passenden `Log_Buffer`, `Record_Count`, `Total_Record_Count` und `Stop_When_Full`-Eigenschaften materialisiert. Vorher erfolgt eine Interoperabilitätsprüfung gegen die konkrete Stack-Version.
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1781216227,
|
||||
"narHash": "sha256-9mUW6gNwoN2SWc/l0fW4svPNOulXLl8ijqKyeSOGgJE=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "a0374025a863d007d98e3297f6aa46cc3141c2f0",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-26.05",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
description = "SEIU Gateway – native NixOS deployment";
|
||||
|
||||
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
|
||||
|
||||
outputs = { self, nixpkgs }:
|
||||
let
|
||||
systems = [ "x86_64-linux" "aarch64-linux" ];
|
||||
forAllSystems = nixpkgs.lib.genAttrs systems;
|
||||
in
|
||||
{
|
||||
packages = forAllSystems (system:
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
in
|
||||
{
|
||||
default = pkgs.callPackage ./nix/package.nix { };
|
||||
seiugw = self.packages.${system}.default;
|
||||
});
|
||||
|
||||
devShells = forAllSystems (system:
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
in
|
||||
{
|
||||
default = pkgs.mkShell {
|
||||
packages = [ pkgs.dotnetCorePackages.sdk_8_0 ];
|
||||
};
|
||||
});
|
||||
|
||||
nixosModules.default = import ./nix/module.nix { inherit self; };
|
||||
nixosModules.seiugw = self.nixosModules.default;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "8.0.200",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
[
|
||||
{
|
||||
"pname": "Microsoft.Data.Sqlite",
|
||||
"version": "8.0.31",
|
||||
"hash": "sha256-8j8RPB1byBT5Whk7PnbCuHDQAmQqkEEH7BsfyILFGqg="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Data.Sqlite.Core",
|
||||
"version": "8.0.31",
|
||||
"hash": "sha256-roWfZVlyU6ykSNgscencfYtL9+gTwlIBbHJAv3fGYcE="
|
||||
},
|
||||
{
|
||||
"pname": "MQTTnet",
|
||||
"version": "5.2.0.1603",
|
||||
"hash": "sha256-w5T7ekYwVGg+Zs8uolvcWFyY+r9duni0qIigxgHgIdw="
|
||||
},
|
||||
{
|
||||
"pname": "SQLitePCLRaw.bundle_e_sqlite3",
|
||||
"version": "2.1.12",
|
||||
"hash": "sha256-qaBua1oxP27zZ1+RmX0BKt7/6KqeH/1p7Uak5oWwVOE="
|
||||
},
|
||||
{
|
||||
"pname": "SQLitePCLRaw.core",
|
||||
"version": "2.1.12",
|
||||
"hash": "sha256-rwaQQTj/ptyVpZkTPWTSVHFtb6zHVDprO5EHk9rp3KU="
|
||||
},
|
||||
{
|
||||
"pname": "SQLitePCLRaw.lib.e_sqlite3",
|
||||
"version": "2.1.12",
|
||||
"hash": "sha256-SiLAL/z0iXkpA88mPe+fzidzlxaIP5ZfC17v8WN0MKw="
|
||||
},
|
||||
{
|
||||
"pname": "SQLitePCLRaw.provider.e_sqlite3",
|
||||
"version": "2.1.12",
|
||||
"hash": "sha256-3ysycZkuXXGRhsRnHjz0+GWAl8FUy81BSUq1lMWZdZU="
|
||||
},
|
||||
{
|
||||
"pname": "System.Memory",
|
||||
"version": "4.5.3",
|
||||
"hash": "sha256-Cvl7RbRbRu9qKzeRBWjavUkseT2jhZBUWV1SPipUWFk="
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
{ ... }:
|
||||
|
||||
{
|
||||
imports = [
|
||||
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default
|
||||
];
|
||||
|
||||
services.seiugw = {
|
||||
enable = true;
|
||||
bacnet.interface = "ens18"; # Set this to the VM's BACnet/IP interface.
|
||||
bacnet.deviceInstance = 23;
|
||||
bacnet.ipPort = 47808;
|
||||
webPort = 8088;
|
||||
openFirewall = true;
|
||||
trends = {
|
||||
enable = true;
|
||||
databaseName = "wago";
|
||||
};
|
||||
komari = {
|
||||
enable = true;
|
||||
endpoint = "https://komari.cloud.se-inno.de";
|
||||
# Do not put the enrollment token into this Nix file or Git. See README.
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
-- Empty initial schema for the legacy SE-LTD data format.
|
||||
-- Existing systems expect isp01…isp20 with datum, userlevel and Wert1…Wert200.
|
||||
|
||||
DELIMITER //
|
||||
|
||||
CREATE PROCEDURE create_legacy_isp_tables()
|
||||
BEGIN
|
||||
DECLARE table_index INT DEFAULT 1;
|
||||
DECLARE value_index INT DEFAULT 1;
|
||||
DECLARE value_columns LONGTEXT DEFAULT '';
|
||||
DECLARE statement_sql LONGTEXT;
|
||||
|
||||
WHILE value_index <= 200 DO
|
||||
SET value_columns = CONCAT(value_columns, ', `Wert', value_index, '` TEXT NULL');
|
||||
SET value_index = value_index + 1;
|
||||
END WHILE;
|
||||
|
||||
WHILE table_index <= 20 DO
|
||||
SET statement_sql = CONCAT(
|
||||
'CREATE TABLE IF NOT EXISTS `isp',
|
||||
LPAD(table_index, 2, '0'),
|
||||
'` (',
|
||||
'`id` INT(11) NOT NULL AUTO_INCREMENT,',
|
||||
'`datum` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
|
||||
'`userlevel` INT(1) DEFAULT NULL',
|
||||
value_columns,
|
||||
', PRIMARY KEY (`id`)',
|
||||
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
|
||||
);
|
||||
|
||||
PREPARE statement FROM statement_sql;
|
||||
EXECUTE statement;
|
||||
DEALLOCATE PREPARE statement;
|
||||
SET table_index = table_index + 1;
|
||||
END WHILE;
|
||||
END//
|
||||
|
||||
CALL create_legacy_isp_tables()//
|
||||
DROP PROCEDURE create_legacy_isp_tables//
|
||||
|
||||
DELIMITER ;
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
{ self }:
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) escapeShellArg mkEnableOption mkIf mkOption optionals types;
|
||||
cfg = config.services.seiugw;
|
||||
hostProvisioningRequest = "${cfg.dataDir}/provisioning/host.json";
|
||||
komariInstalledMarker = "${cfg.dataDir}/provisioning/komari-installed";
|
||||
in
|
||||
{
|
||||
options.services.seiugw = {
|
||||
enable = mkEnableOption "SEIU Gateway";
|
||||
|
||||
package = mkOption {
|
||||
type = types.package;
|
||||
default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
|
||||
description = "SEIU Gateway package to run.";
|
||||
};
|
||||
|
||||
dataDir = mkOption {
|
||||
type = types.str;
|
||||
default = "/var/lib/seiugw";
|
||||
description = "Persistent SQLite database, gateway key and later PKI storage.";
|
||||
};
|
||||
|
||||
listenAddress = mkOption {
|
||||
type = types.str;
|
||||
default = "0.0.0.0";
|
||||
description = "Address for the local web administration service.";
|
||||
};
|
||||
|
||||
webPort = mkOption {
|
||||
type = types.port;
|
||||
default = 8088;
|
||||
description = "TCP port for the local web administration service.";
|
||||
};
|
||||
|
||||
openFirewall = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Open the configured web and BACnet/IP ports in the NixOS firewall.";
|
||||
};
|
||||
|
||||
bacnet = {
|
||||
interface = mkOption {
|
||||
type = types.str;
|
||||
example = "ens18";
|
||||
description = "Linux interface connected to the BACnet/IP field network.";
|
||||
};
|
||||
|
||||
deviceInstance = mkOption {
|
||||
type = types.ints.between 0 4194303;
|
||||
default = 23;
|
||||
description = "Configurable BACnet device instance. Vendor ID remains fixed at 815.";
|
||||
};
|
||||
|
||||
ipPort = mkOption {
|
||||
type = types.port;
|
||||
default = 47808;
|
||||
description = "BACnet/IP UDP port.";
|
||||
};
|
||||
};
|
||||
|
||||
opcUa.port = mkOption {
|
||||
type = types.port;
|
||||
default = 4840;
|
||||
description = "Reserved OPC UA TCP port passed to the gateway.";
|
||||
};
|
||||
|
||||
trends = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Run the local MariaDB store for long-term and legacy trend data.";
|
||||
};
|
||||
|
||||
databaseName = mkOption {
|
||||
type = types.str;
|
||||
default = "wago";
|
||||
description = "MariaDB database retaining the legacy SE-LTD table format.";
|
||||
};
|
||||
};
|
||||
|
||||
komari = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Register the gateway with a Komari server once the one-time commissioning request and secret token exist.";
|
||||
};
|
||||
|
||||
endpoint = mkOption {
|
||||
type = types.str;
|
||||
default = "https://komari.cloud.se-inno.de";
|
||||
description = "Komari endpoint passed to the agent.";
|
||||
};
|
||||
|
||||
enrollmentTokenFile = mkOption {
|
||||
type = types.str;
|
||||
default = "${cfg.dataDir}/komari-enrollment-token";
|
||||
description = "Root-readable file with the Komari one-time enrollment token. It must not be stored in Nix or Git.";
|
||||
};
|
||||
|
||||
installDir = mkOption {
|
||||
type = types.str;
|
||||
default = "/opt/komari";
|
||||
description = "Mutable location used by the upstream Komari installer for its agent binary.";
|
||||
};
|
||||
|
||||
installerUrl = mkOption {
|
||||
type = types.str;
|
||||
default = "https://raw.githubusercontent.com/komari-monitor/komari-agent/refs/heads/main/install.sh";
|
||||
description = "Upstream Komari installer URL. It is deliberately only fetched during one-time commissioning.";
|
||||
};
|
||||
|
||||
ignoreUnsafeCertificateErrors = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Pass --ignore-unsafe-cert to the Komari agent as requested for the controlled Komari endpoint.";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
config = mkIf cfg.enable {
|
||||
users.groups.seiugw = { };
|
||||
users.users.seiugw = {
|
||||
isSystemUser = true;
|
||||
group = "seiugw";
|
||||
home = cfg.dataDir;
|
||||
createHome = true;
|
||||
};
|
||||
|
||||
systemd.tmpfiles.rules = [
|
||||
"d ${cfg.dataDir} 0750 seiugw seiugw -"
|
||||
"d ${cfg.dataDir}/provisioning 0750 seiugw seiugw -"
|
||||
] ++ optionals cfg.komari.enable [
|
||||
"d ${cfg.komari.installDir} 0750 root root -"
|
||||
];
|
||||
|
||||
networking.firewall = mkIf cfg.openFirewall {
|
||||
allowedTCPPorts = [ cfg.webPort ];
|
||||
allowedUDPPorts = [ cfg.bacnet.ipPort ];
|
||||
};
|
||||
|
||||
# Keep MariaDB local. The gateway process receives socket-authenticated access;
|
||||
# no database password or network-exposed database account is created.
|
||||
services.mysql = mkIf cfg.trends.enable {
|
||||
enable = true;
|
||||
package = pkgs.mariadb;
|
||||
settings.mysqld.bind-address = "127.0.0.1";
|
||||
ensureDatabases = [ cfg.trends.databaseName ];
|
||||
ensureUsers = [
|
||||
{
|
||||
name = "seiugw";
|
||||
ensurePermissions = {
|
||||
"${cfg.trends.databaseName}.*" = "ALL PRIVILEGES";
|
||||
};
|
||||
}
|
||||
];
|
||||
initialDatabases = [
|
||||
{
|
||||
name = cfg.trends.databaseName;
|
||||
schema = ./legacy-schema.sql;
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
systemd.services.seiugw = {
|
||||
description = "SEIU industrial protocol gateway";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" ] ++ optionals cfg.trends.enable [ "mysql.service" ];
|
||||
requires = optionals cfg.trends.enable [ "mysql.service" ];
|
||||
|
||||
environment = {
|
||||
ASPNETCORE_URLS = "http://${cfg.listenAddress}:${toString cfg.webPort}";
|
||||
Gateway__DataDirectory = cfg.dataDir;
|
||||
Gateway__Bacnet__Interface = cfg.bacnet.interface;
|
||||
Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance;
|
||||
Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort;
|
||||
Gateway__OpcUa__Port = toString cfg.opcUa.port;
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
ExecStart = "${cfg.package}/bin/Gateway.Api";
|
||||
User = "seiugw";
|
||||
Group = "seiugw";
|
||||
WorkingDirectory = cfg.dataDir;
|
||||
UMask = "0077";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectHome = true;
|
||||
ProtectSystem = "strict";
|
||||
ReadWritePaths = [ cfg.dataDir ];
|
||||
};
|
||||
};
|
||||
|
||||
# The web process writes only project number and ISP as JSON after its first
|
||||
# successful commissioning. This root helper validates both values again
|
||||
# before applying the runtime hostname. The data is retained so the name is
|
||||
# re-applied after every later boot without changing NixOS configuration.
|
||||
systemd.services.seiugw-apply-hostname = {
|
||||
description = "Apply SEIU Gateway commissioning hostname";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig.Type = "oneshot";
|
||||
path = [ pkgs.coreutils pkgs.gnugrep pkgs.hostname pkgs.jq ];
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
request=${escapeShellArg hostProvisioningRequest}
|
||||
[ -s "$request" ] || exit 0
|
||||
|
||||
project="$(${pkgs.jq}/bin/jq -er '.projectNumber' "$request")" || exit 0
|
||||
isp="$(${pkgs.jq}/bin/jq -er '.ispNumber' "$request")" || exit 0
|
||||
if ! ${pkgs.gnugrep}/bin/grep -Eq '^P[A-Z0-9_-]{1,32}$' <<<"$project"; then
|
||||
exit 0
|
||||
fi
|
||||
case "$isp" in
|
||||
*[!0-9]*|"") exit 0 ;;
|
||||
esac
|
||||
if [ "$isp" -lt 1 ] || [ "$isp" -gt 99 ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
host_name="SE-UGW-$project-ISP$(printf '%02d' "$isp")"
|
||||
[ "''${#host_name}" -le 63 ] || exit 0
|
||||
${pkgs.hostname}/bin/hostname "$host_name"
|
||||
'';
|
||||
};
|
||||
|
||||
systemd.paths.seiugw-apply-hostname = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathExists = hostProvisioningRequest;
|
||||
PathChanged = hostProvisioningRequest;
|
||||
Unit = "seiugw-apply-hostname.service";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.seiugw-komari-bootstrap = mkIf cfg.komari.enable {
|
||||
description = "One-time Komari agent installer for SEIU Gateway";
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
|
||||
requires = [ "seiugw-apply-hostname.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "30s";
|
||||
};
|
||||
path = [ pkgs.bash pkgs.coreutils pkgs.curl ];
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
marker=${escapeShellArg komariInstalledMarker}
|
||||
token_file=${escapeShellArg cfg.komari.enrollmentTokenFile}
|
||||
install_dir=${escapeShellArg cfg.komari.installDir}
|
||||
agent="$install_dir/agent"
|
||||
[ -e "$marker" ] && exit 0
|
||||
[ -s ${escapeShellArg hostProvisioningRequest} ] || exit 0
|
||||
[ -r "$token_file" ] || exit 0
|
||||
|
||||
token="$(${pkgs.coreutils}/bin/cat "$token_file")"
|
||||
[ -n "$token" ] || exit 0
|
||||
if [ ! -x "$agent" ]; then
|
||||
${pkgs.curl}/bin/curl --fail --location --silent --show-error --proto '=https' ${escapeShellArg cfg.komari.installerUrl} \
|
||||
| ${pkgs.bash}/bin/bash -s -- --install-dir "$install_dir" --install-no-mirror -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
|
||||
fi
|
||||
[ -x "$agent" ]
|
||||
${pkgs.systemd}/bin/systemctl try-restart seiugw-komari-agent.service || ${pkgs.systemd}/bin/systemctl start seiugw-komari-agent.service
|
||||
${pkgs.coreutils}/bin/touch "$marker"
|
||||
${pkgs.coreutils}/bin/chmod 0600 "$marker"
|
||||
'';
|
||||
};
|
||||
|
||||
systemd.paths.seiugw-komari-request = mkIf cfg.komari.enable {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathExists = hostProvisioningRequest;
|
||||
PathChanged = hostProvisioningRequest;
|
||||
Unit = "seiugw-komari-bootstrap.service";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathExists = cfg.komari.enrollmentTokenFile;
|
||||
PathChanged = cfg.komari.enrollmentTokenFile;
|
||||
Unit = "seiugw-komari-bootstrap.service";
|
||||
};
|
||||
};
|
||||
|
||||
# The upstream installer deliberately does not create a NixOS unit. NixOS
|
||||
# owns this unit instead, while the binary remains in the upstream mutable
|
||||
# install directory. The enrollment token is read at service start and is
|
||||
# never placed in the Nix store.
|
||||
systemd.services.seiugw-komari-agent = mkIf cfg.komari.enable {
|
||||
description = "Komari monitoring agent";
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
unitConfig.ConditionPathExists = "${cfg.komari.installDir}/agent";
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
WorkingDirectory = cfg.komari.installDir;
|
||||
Restart = "always";
|
||||
RestartSec = "10s";
|
||||
};
|
||||
path = [ pkgs.bash pkgs.coreutils ];
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg cfg.komari.enrollmentTokenFile})"
|
||||
[ -n "$token" ]
|
||||
exec ${escapeShellArg "${cfg.komari.installDir}/agent"} -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
|
||||
'';
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{ lib, buildDotnetModule, dotnetCorePackages }:
|
||||
|
||||
buildDotnetModule {
|
||||
pname = "seiugw";
|
||||
version = "0.1.0";
|
||||
|
||||
src = lib.cleanSource ../.;
|
||||
projectFile = "src/Gateway.Api/Gateway.Api.csproj";
|
||||
nugetDeps = ./deps.json;
|
||||
|
||||
dotnet-sdk = dotnetCorePackages.sdk_8_0;
|
||||
dotnet-runtime = dotnetCorePackages.aspnetcore_8_0;
|
||||
executables = [ "Gateway.Api" ];
|
||||
|
||||
meta = {
|
||||
description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT";
|
||||
platforms = lib.platforms.linux;
|
||||
};
|
||||
}
|
||||
@@ -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)); } }
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/Gateway.Api/Gateway.Api.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,209 @@
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Contracts;
|
||||
using Gateway.Api.Domain;
|
||||
using Gateway.Api.Options;
|
||||
using Gateway.Api.Services;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
var validator = new MappingValidator();
|
||||
var sourceOne = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
|
||||
var sourceTwo = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
|
||||
var bacnetTarget = CreatePoint(PointProtocol.Bacnet, PointScope.External, "device:77/analog-value:3");
|
||||
|
||||
var firstMapping = CreateMapping(sourceOne.Id, bacnetTarget.Id, MappingDirection.OneWay, null, false);
|
||||
var validSingleWriter = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [firstMapping]);
|
||||
Assert(validSingleWriter.IsValid, "A single external writer must be valid.");
|
||||
|
||||
var conflictingSecondWriter = CreateMapping(sourceTwo.Id, bacnetTarget.Id, MappingDirection.OneWay, null, false);
|
||||
var conflict = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [firstMapping, conflictingSecondWriter]);
|
||||
Assert(!conflict.IsValid, "Two unqualified writers must be rejected.");
|
||||
|
||||
var priorityOne = firstMapping with { BacnetPriority = 16, AcknowledgeMultipleExternalWriters = true };
|
||||
var priorityTwo = conflictingSecondWriter with { BacnetPriority = 14, AcknowledgeMultipleExternalWriters = true };
|
||||
var explicitPriorityCase = validator.Validate([sourceOne, sourceTwo, bacnetTarget], [priorityOne, priorityTwo]);
|
||||
Assert(explicitPriorityCase.IsValid && explicitPriorityCase.Warnings.Count == 1, "Explicitly acknowledged BACnet priorities must be permitted with a warning.");
|
||||
|
||||
var reverseMapping = CreateMapping(bacnetTarget.Id, sourceOne.Id, MappingDirection.OneWay, null, false);
|
||||
var loop = validator.Validate([sourceOne, bacnetTarget], [firstMapping, reverseMapping]);
|
||||
Assert(!loop.IsValid, "Two opposing one-way mappings must be rejected.");
|
||||
|
||||
var journal = new WriteJournal();
|
||||
journal.Register("bacnet:77/av:3", "21.5", TimeSpan.FromSeconds(10));
|
||||
Assert(journal.ConsumeReflection("bacnet:77/av:3", "21.5"), "The first adapter reflection must be consumed.");
|
||||
Assert(!journal.ConsumeReflection("bacnet:77/av:3", "21.5"), "A reflection cannot be consumed twice.");
|
||||
|
||||
var dataDirectory = Path.Combine(Path.GetTempPath(), "seiugw-smoke-" + Guid.NewGuid().ToString("N"));
|
||||
var options = Options.Create(new GatewayOptions
|
||||
{
|
||||
DataDirectory = dataDirectory,
|
||||
Bacnet = new BacnetBootstrapOptions { Interface = "eth0", DeviceInstance = 23, IpPort = 47808 },
|
||||
OpcUa = new OpcUaBootstrapOptions { Port = 4840 }
|
||||
});
|
||||
var database = new GatewayDatabase(options);
|
||||
var store = new GatewayStore(database, new PasswordService(), validator, new SecretProtector(options), options);
|
||||
store.Initialize();
|
||||
Assert(!store.HasAdmin(), "A new database must not contain an admin password.");
|
||||
store.CreateInitialAdmin(new SetInitialAdminRequest("correct horse battery staple", "P190726", 1));
|
||||
Assert(store.HasAdmin() && store.VerifyAdminPassword("correct horse battery staple"), "The configured admin must authenticate.");
|
||||
Assert(store.GetGatewayConfiguration().VendorId == 815 && store.GetGatewayConfiguration().DeviceInstance == 23, "BACnet bootstrap defaults must be persisted.");
|
||||
Assert(store.GetGatewayConfiguration().Installation?.HostName == "SE-UGW-P190726-ISP01", "First commissioning must create the requested Komari-visible hostname.");
|
||||
Assert(File.Exists(Path.Combine(dataDirectory, "provisioning", "host.json")), "The NixOS hostname helper must receive an identity-only provisioning request.");
|
||||
|
||||
var sourcePoint = store.CreatePoint(new CreatePointRequest(
|
||||
"Internal temperature",
|
||||
PointProtocol.Internal,
|
||||
PointScope.Internal,
|
||||
"Real",
|
||||
true,
|
||||
false,
|
||||
null,
|
||||
JsonElementFor("{}")));
|
||||
store.UpdateMqttConfiguration(new UpdateMqttConfigurationRequest(
|
||||
new MqttConfiguration(true, "mqtt.example.local", 8883, true, true, "seiugw-test", "gateway"),
|
||||
"broker-secret",
|
||||
false));
|
||||
var mqttConfiguration = store.GetMqttConfiguration();
|
||||
Assert(mqttConfiguration.Configuration.UseTls && mqttConfiguration.Configuration.IgnoreCertificateErrors && mqttConfiguration.HasPassword, "MQTTS configuration and encrypted password marker must be persisted.");
|
||||
Assert(store.GetMqttConnectionConfiguration().Password == "broker-secret", "The MQTT client must receive the locally protected broker password.");
|
||||
|
||||
var analogMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
||||
sourcePoint.Id,
|
||||
MqttMappingFormat.SeMonitoring,
|
||||
MqttDirection.Publish,
|
||||
MqttQualityOfService.AtLeastOnce,
|
||||
true,
|
||||
2019,
|
||||
"P1909015",
|
||||
"ISP1",
|
||||
SeMonitoringCategory.Analog,
|
||||
"iVlTempFuehler4Speicher",
|
||||
null,
|
||||
null));
|
||||
Assert(
|
||||
GatewayStore.GetMqttTopic(analogMqttMapping) == "Projekte2019/P1909015/ISP1/Analog/iVlTempFuehler4Speicher_Wert",
|
||||
"SE Monitoring topics must match the requested hierarchy.");
|
||||
|
||||
var invalidNotifyMappingRejected = false;
|
||||
try
|
||||
{
|
||||
store.CreateMqttMapping(new CreateMqttMappingRequest(
|
||||
sourcePoint.Id,
|
||||
MqttMappingFormat.SeMonitoring,
|
||||
MqttDirection.Publish,
|
||||
MqttQualityOfService.AtLeastOnce,
|
||||
false,
|
||||
2019,
|
||||
"P1909015",
|
||||
"ISP1",
|
||||
SeMonitoringCategory.Notify,
|
||||
"temperatureAsNotify",
|
||||
null,
|
||||
null));
|
||||
}
|
||||
catch (DomainValidationException)
|
||||
{
|
||||
invalidNotifyMappingRejected = true;
|
||||
}
|
||||
Assert(invalidNotifyMappingRejected, "Analog values must not be mapped to Notify.");
|
||||
|
||||
var setpoint = store.CreatePoint(new CreatePointRequest(
|
||||
"Supply setpoint",
|
||||
PointProtocol.Internal,
|
||||
PointScope.Internal,
|
||||
"Real",
|
||||
true,
|
||||
true,
|
||||
null,
|
||||
JsonElementFor("{}")));
|
||||
var setpointMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
||||
setpoint.Id,
|
||||
MqttMappingFormat.SeMonitoring,
|
||||
MqttDirection.Bidirectional,
|
||||
MqttQualityOfService.AtLeastOnce,
|
||||
false,
|
||||
2019,
|
||||
"P1909015",
|
||||
"ISP1",
|
||||
SeMonitoringCategory.Setpoints,
|
||||
"supplyTemperature",
|
||||
null,
|
||||
null));
|
||||
Assert(GatewayStore.GetMqttTopic(setpointMqttMapping).Contains("/Setpoints/", StringComparison.Ordinal), "Setpoints must use their dedicated bidirectional category.");
|
||||
store.SetPointValue(setpoint.Id, JsonElementFor("21.5"), PointProtocol.Mqtt, DateTimeOffset.UtcNow);
|
||||
Assert(store.ListPointValues().Single(value => value.PointId == setpoint.Id).Value.GetDouble() == 21.5, "Incoming MQTT values must persist as point values.");
|
||||
|
||||
var schedule = store.CreatePoint(new CreatePointRequest(
|
||||
"Week schedule",
|
||||
PointProtocol.Bacnet,
|
||||
PointScope.Gateway,
|
||||
"Schedule",
|
||||
true,
|
||||
false,
|
||||
null,
|
||||
JsonElementFor("{}"),
|
||||
BacnetObjectKind.Schedule));
|
||||
var scheduleJsonMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
|
||||
schedule.Id,
|
||||
MqttMappingFormat.Json,
|
||||
MqttDirection.Publish,
|
||||
MqttQualityOfService.AtLeastOnce,
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
"plant/schedule",
|
||||
"weekProgram"));
|
||||
Assert(GatewayStore.GetMqttTopic(scheduleJsonMapping) == "plant/schedule", "Structured BACnet values must be mappable through JSON MQTT.");
|
||||
var trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true));
|
||||
var historyStart = new DateTimeOffset(2026, 10, 7, 8, 0, 0, TimeSpan.Zero);
|
||||
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("21.5"), PointProtocol.Internal, null, historyStart));
|
||||
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.0"), PointProtocol.Internal, null, historyStart.AddMinutes(1)));
|
||||
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.5"), PointProtocol.Internal, null, historyStart.AddMinutes(2)));
|
||||
var retainedRecords = store.ListTrendRecords(trendLog.Id, 10);
|
||||
Assert(retainedRecords.Count == 2 && retainedRecords[0].SequenceNumber == 3, "Trend retention must remove only the oldest records.");
|
||||
|
||||
var sampledSourcePoint = store.CreatePoint(new CreatePointRequest(
|
||||
"Internal humidity",
|
||||
PointProtocol.Internal,
|
||||
PointScope.Internal,
|
||||
"Real",
|
||||
true,
|
||||
false,
|
||||
null,
|
||||
JsonElementFor("{}")));
|
||||
var sampledLog = store.CreateTrendLog(new CreateTrendLogRequest(sampledSourcePoint.Id, "Humidity sampled", 102, 60, 10, true));
|
||||
var sampleTime = new DateTimeOffset(2026, 10, 7, 9, 0, 0, TimeSpan.Zero);
|
||||
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.0"), PointProtocol.Internal, null, sampleTime).Count == 1, "The first source observation must be recorded.");
|
||||
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.1"), PointProtocol.Internal, null, sampleTime.AddSeconds(30)).Count == 0, "Observations inside the configured interval must not be recorded twice.");
|
||||
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.2"), PointProtocol.Internal, null, sampleTime.AddSeconds(60)).Count == 1, "Observations at the configured interval must be recorded.");
|
||||
Assert(store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "The sampled trend log must contain two records.");
|
||||
|
||||
Console.WriteLine("Gateway smoke tests passed.");
|
||||
|
||||
static GatewayPoint CreatePoint(PointProtocol protocol, PointScope scope, string? externalIdentity)
|
||||
{
|
||||
using var document = JsonDocument.Parse("{}");
|
||||
return new GatewayPoint(Guid.NewGuid(), Guid.NewGuid().ToString(), protocol, scope, "Real", true, true, externalIdentity, document.RootElement.Clone(), DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
static PointMapping CreateMapping(Guid source, Guid target, MappingDirection direction, int? priority, bool acknowledged)
|
||||
{
|
||||
using var document = JsonDocument.Parse("{}");
|
||||
return new PointMapping(Guid.NewGuid(), source, target, direction, true, priority, acknowledged, document.RootElement.Clone(), DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
static JsonElement JsonElementFor(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
|
||||
static void Assert(bool condition, string message)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user