Compare commits

...
9 Commits
Author SHA1 Message Date
jhartworks c52cbebd60 Advertise reachable OPC UA endpoints 2026-11-24 23:36:32 +01:00
jhartworks 353a1fb741 Remove the 500-point bulk mapping cap 2026-11-24 14:53:14 +01:00
jhartworks 36b2057991 Show running Gateway commit and available updates 2026-11-24 14:05:38 +01:00
jhartworks 32b240469c Document Gateway updates and recovery 2026-11-24 13:52:11 +01:00
jhartworks 73ccb1bb75 Allow SQLite to create its rollback snapshot journal 2026-11-24 13:50:46 +01:00
jhartworks 4e35a3a557 Add authenticated Gateway system updates with rollback 2026-11-24 13:46:40 +01:00
jhartworks 198b1d7b78 Synchronize deployed gateway features and documentation 2026-11-24 13:38:27 +01:00
jhartworks 98c48d9d78 Add comprehensive smoke and feature tests for Gateway API
- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality.
- Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management.
- Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications.
- Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing.
- Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
2026-11-19 16:06:54 +01:00
jhartworks d9165a60ff Fix published web UI content root 2026-10-08 12:33:17 +02:00
93 changed files with 12933 additions and 324 deletions

No files matched your search

+46 -4
View File
@@ -4,14 +4,14 @@ Ein Linux-Gateway für BACnet/IP, OPC UA, Modbus TCP, MQTT/MQTTS und später KNX
## 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.
- BACnet wird als natives Gerät mit dem Zielprofil B-BC entwickelt; eine bestätigte B-BC-Konformität besteht noch nicht. Der Datenpfad verwendet den C-basierten [`bacnet-stack`](https://github.com/bacnet-stack/bacnet-stack), fest auf Commit `0bfe65645ff7238e15121a6727870f96413ac22e` gepinnt. 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).
- Der native BACnet-Adapter materialisiert AI/AO/AV, BI/BO/BV, MSI/MSO/MSV, Schedule und Calendar. Event Enrollment, Notification Class sowie interne Trend Logs existieren bisher nur im Datenmodell bzw. in der Webverwaltung; der Abschnitt „Native BACnet-Objekte“ dokumentiert die verbleibenden Grenzen.
## Deployment auf NixOS
@@ -45,6 +45,8 @@ 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`.
**Einstellungen → Gateway-Update** ist für Administratoren verfügbar, wenn `services.seiugw.updates` in der NixOS-Hostkonfiguration aktiviert ist und `remote` auf das vertrauenswürdige HTTPS-Repository verweist. Die Seite zeigt den Commit der laufenden Version und prüft beim Öffnen den konfigurierten Branch. Nach erneuter Passworteingabe baut das Gateway den neueren Git-Stand und prüft Web und BACnet vor der dauerhaften Aktivierung. Bei einem Fehler stellt es den vorherigen Checkout und bei Bedarf die vorherige NixOS-Generation und den SQLite-Stand wieder her. Nach einem Dienstneustart kann eine erneute Anmeldung erforderlich sein.
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.
@@ -53,14 +55,54 @@ IP-Symcon wird nicht als Nix-Paket ausgegeben, weil der Hersteller offiziell ein
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:
Der Komari-Schlüssel kann unter **Admin → API → Komari** ersetzt werden. Er wird mit AES-256-GCM in der Gateway-Datenbank verschlüsselt; der gerätespezifische Schlüssel liegt in `/var/lib/seiugw/secrets.key` (0600). Klartextschlüssel und Entschlüsselungsschlüssel gehören nicht nach Git oder in den weltweit lesbaren Nix-Store. Eine verschlüsselte Datenbank ist nur zusammen mit dem passenden Geräteschlüssel wiederherstellbar.
Alternativ wird eine root-lesbare Importdatei unterstützt:
```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.
`seiugw-komari-token.service` importiert die Datei verschlüsselt und entfernt danach die Klartext-Importdatei. Für den Agenten wird der Token nur unter `/run/seiugw-komari/token` mit restriktiven Rechten bereitgestellt. Änderungen per Web oder Importdatei aktualisieren diesen Laufzeit-Token und starten den Agenten neu. Bei einer Erstinstallation folgt der einmalige Upstream-Installer, sobald die Ersteinrichtung abgeschlossen ist. Der Agent liegt unter `/opt/komari`; NixOS verwaltet seinen Dienst. Die angeforderte Option `--ignore-unsafe-cert` gilt ausschließlich für den konfigurierten Komari-Endpunkt.
## LTD-Oberfläche und Benachrichtigungen
Die gemeinsame Oberfläche verwendet die originalen LTD-Hintergründe und das kompakte Seitenleisten-/Reiterlayout. Quellen, Protokollkonfiguration und MQTT sind unter **Datenpunkte** zusammengefasst. **Admin** enthält Aliase, Einheiten, Alarme, Benutzer, Rollen, API, Runner und Debug; Reiter werden nach Rollenberechtigung angezeigt.
- Aliase, Einheiten, Anzeigefaktoren, Farben und Dashboard-Widgets werden in SQLite gespeichert. Alias-CSV verwendet die Spalten `pointId;alias;unit;factor;kind;color`; Export dient als Importvorlage. Anzeigefaktoren verändern keine Buswerte. Widgets und private Trend-Auswahlen gehören ihrem Benutzer.
- Trendgraphen zeigen bis zu 2000 letzte Werte je Datenreihe; normale Trendaufzeichnung und CSV-Export behalten ihre eigene Retention. Gatewayeigene BACnet-/OPC-UA-Datenpunkte speisen dieselbe interne Historie über eingehende Punktwerte. Bei BACnet wird nur der nativ ermittelte effektive Present_Value aufgezeichnet, nicht ein noch nicht priorisierter Schreibauftrag.
- Mail, WhatsApp und ntfy besitzen feste SE-Inno-Endpunkte und verschlüsselte, per Web austauschbare API-Keys. Ohne Key bleibt der Kanal gesperrt. Versand erfolgt als UTF-8-Multipart-Formular mit den angegebenen API-Feldnamen, TLS-Prüfung, 10-Sekunden-Zeitlimit und ohne Redirects. WhatsApp/ntfy dienen ausschließlich dem Alarmversand; Mail zusätzlich dem CSV-Runner.
- Alarme arbeiten auf gültigen, zeitlich neuen Punktwerten und senden bei Zustandswechsel, mit optionaler Entwarnung und analoger Hysterese. Der Versandauftrag ist dauerhaft gespeichert. Nach Timeout oder Neustart während eines Versands bleibt die Zustellung **unklar**; keine automatische Wiederholung mit möglichem Doppelversand. „Von API angenommen“ ist keine Bestätigung der Endzustellung.
- WhatsApp verwendet ausschließlich die vom Nutzer genannten Vorlagennamen. Zeilenumbrüche, Tabs und wiederholte Leerzeichen in Parametern werden vereinheitlicht; Umlaute und Emoji bleiben erhalten. Überlange Parameter werden abgewiesen, nicht abgeschnitten. Die konkrete Meta-Vorlage muss im Betreiberkonto genehmigt sein; deren feste Texte und Variablenzuordnung werden von der SE-Inno-API verwaltet und sind hier nicht bekannt.
Tests: `dotnet run --project tests/Gateway.SmokeTests`. Die Benachrichtigungstests verwenden einen simulierten HTTP-Empfänger und senden keine echten Nachrichten. Ein NixOS-Rebuild erhält die vorhandene MariaDB und ihr Legacy-Schema unverändert.
## OPC-UA-Server und Browser
Unter **Datenpunkte** angelegte Punkte mit Protokoll **OpcUa** und Bereich **Gateway** erscheinen unter **Objects → SE-Inno Universalgateway**. Namespace-URI: `urn:se-inno:universalgateway:points`; stabile NodeId: `nsu=urn:se-inno:universalgateway:points;g=<Punkt-UUID>`. Namespace-Indizes müssen Clients über die URI auflösen. Neue Punkte erscheinen innerhalb von zwei Sekunden ohne Serverneustart.
Unterstützt werden skalare Boolean, Real/Float (32 Bit), Double, SByte, Byte, Int16, UInt16, Integer/Int32, Unsigned/UInt32, Int64, UInt64 und String. Fehlende Werte melden `BadWaitingForInitialData`, ungültige Typen `BadTypeMismatch`; fremde Fehlerqualitäten werden konservativ auf `BadNoCommunication` abgebildet. Werte und Quellzeit stammen aus dem gemeinsamen Punktspeicher. UA-Schreibzugriffe durchlaufen Mapping, Alarmierung und Trendaufzeichnung genau einmal; abonnierte Änderungen werden nicht zurückgeschrieben. UA erhält spätestens im 100-ms-Takt den neuesten Punktwert; die Trendaufzeichnung bleibt davon unabhängig. Historische UA-Dienste und strukturierte UA-Datentypen sind noch nicht implementiert.
Der Server bietet Basic256Sha256 mit Sign oder SignAndEncrypt. Clients verbinden sich über `opc.tcp://<Gateway-IP>:4840` oder den erreichbaren Hostnamen. Die verwendete Adresse muss im Serverzertifikat stehen. Anmeldung über die Web-Benutzer: `manage_sources` erlaubt Schreiben auf beschreibbare Punkte, `view_dashboard` nur Lesen. Optionaler anonymer Zugriff ist ausschließlich lesend. Geänderte oder deaktivierte Benutzer und geänderte Rollenrechte beenden bestehende Sitzungen inklusive Abos. Benutzerzertifikat-Anmeldung ist noch nicht implementiert und wird nicht als funktionsfähige Auswahl angeboten.
Anwendungszertifikate bleiben gerätelokal: Client `pki/opcua/own`, Server `pki/opcua/server-own`, gemeinsame Vertrauensliste `pki/opcua/trusted`, abgewiesene Zertifikate `pki/opcua/rejected`, jeweils unter `/var/lib/seiugw`. Client und Gegenstelle müssen sich gegenseitig vertrauen. Nach Prüfung des Fingerabdrucks das öffentliche Gegenstellenzertifikat aus `rejected/certs` nach `trusted/certs` übernehmen und den Gateway-Dienst neu starten; private Schlüssel niemals kopieren. Vorhandene Client-Zertifikate werden nicht gelöscht. Zertifikatsverwaltung per Web steht noch aus.
Der Web-Browser unterstützt Benutzer/Passwort und anonymen Zugriff, hierarchisches Öffnen, Fortsetzungsseiten und blockweises Lesen. Verbindungen werden gespeichert; Passwörter liegen ausschließlich verschlüsselt in SQLite. Ein leeres Passwortfeld beim Bearbeiten behält das vorhandene Passwort bei. Änderungen an Verbindungsdaten vor dem Browsen speichern. Lesbare skalare Variablen können einzeln oder vollständig je Ebene importiert werden; Namespace-URIs halten ihre Identität auch bei geänderten Namespace-Indizes stabil. Arrays und komplexe ExtensionObjects werden nicht als Skalare importiert.
Pro aktivierter Verbindung läuft eine dauerhafte Session mit Subscription, automatischem Wiederaufbau und Neulesen nach einem Abbruch. Mapping-Schreibvorgänge werden einmal gesendet; unklare Ergebnisse und Offline-Schreibaufträge werden nicht später automatisch wiederholt. Schlechte Qualität löst keine externen Stellbefehle aus. „Unbekanntes Serverzertifikat akzeptieren“ hebt nur die Vertrauenslistenprüfung der gewählten Verbindung auf, nicht Ablauf-, Namens- oder andere Zertifikatsfehler. Status unter Datenpunkte → Quellen / Protokolle; technische Details auch unter `/api/opcua/clients`.
## Native BACnet-Objekte
`nix/bacnet.nix` baut den fest gepinnten C-Stack mit nativer SQLite-Brücke. Gatewaypunkte AI/AO/AV, BI/BO/BV, MSI/MSO/MSV sowie Schedule und Calendar erscheinen ohne Dienstneustart in Object_List. Keine Demo-Punkte. Vendor-ID 815; Geräteinstanz, Gerätename, Interface und Port stammen aus der Gateway-Konfiguration. Netzwerkänderungen führen zu einem kontrollierten Neustart. Abweichende Ports zusätzlich in der NixOS-Firewall freigeben.
AV/BV/MSV sind commandable. Schreibbefehle verwenden die Mapping-Priorität, standardmäßig 16; Priorität 6 bleibt reserviert. NULL gibt einen Prioritätsslot frei. Prioritätswerte und erfolgreich über BACnet geschriebene Objekteigenschaften bleiben in SQLite erhalten. Inputs werden intern aktualisiert; externe Present_Value-Schreibzugriffe richten sich nach Out_Of_Service. Werte ohne gültige Anfangsbeobachtung erscheinen nicht als gute Nullwerte. Im Adress-JSON sind numerische BACnet-`units` und bei Multistate `numberOfStates` (1–1000, Standard 16) möglich.
Native Rückmeldungen fließen über dieselben Mappings und Trendfunktionen wie OPC UA. Befehle verfallen nach zehn Sekunden; ein bei einem Absturz bereits beanspruchter Befehl wird nicht erneut ausgeführt. Laufzeitstatus und letzte fehlgeschlagene Befehle: `/api/bacnet/status` (Anmeldung erforderlich).
Noch nicht als fertig zu betrachten: externe BACnet-Dauersubscriptions einschließlich Priva-Interoperabilität, EventEnrollment/NotificationClass im nativen Objektmodell, Veröffentlichung der internen Historie als BACnet-TrendLog/ReadRange, grafische Schedule-/Calendar-Eigenschaftseditoren und vollständige strukturierte JSON-Übertragung. Derzeit liefern Schedule/Calendar an die Punktwertbrücke ihren Present_Value, nicht ihre komplette Konfiguration. BBMD/Foreign Device sind verdrahtet, aber noch nicht netzübergreifend getestet; BDT-Verwaltung per Web und BACnet/SC fehlen. Eine B-BC-/AMEV-Konformität oder Zertifizierung wird nicht behauptet.
Prüfung: `dotnet run --project tests/Gateway.SmokeTests`; auf Linux zusätzlich `python3 tests/native_bacnet_test.py <Nix-BACnet-Paketpfad>`. Der Drahttest verwendet ausschließlich Loopback, Ports 47828–47830 und eine eigene temporäre Datenbank; keine Feldgeräte werden beschrieben.
## MQTT-Mapping
+675
View File
@@ -0,0 +1,675 @@
# SE Local Trenddata
SE Local Trenddata ist eine webbasierte Trend-, Dashboard- und Quellenverwaltung fuer lokale Anlagen- und WAGO-Daten. Das Projekt besteht aus einem React-Frontend, einer Node.js/Express-API, MariaDB, Redis und einem Collector-Service fuer Protokollquellen wie Modbus TCP, OPC UA, BACnet IP und KNX IP.
Das Ziel ist, bestehende breite Trendtabellen wie `isp01`, `isp02` usw. weiter nutzen zu koennen und zusaetzlich neue Quellen sauber ueber eine Weboberflaeche anzulegen, zu scannen, zu loggen und im Dashboard oder in der Trendansicht auszuwerten.
---
## Inhaltsverzeichnis
- [Projektaufbau](#projektaufbau)
- [Architektur](#architektur)
- [Services und Ports](#services-und-ports)
- [Schnellstart mit Docker Compose](#schnellstart-mit-docker-compose)
- [Lokale Entwicklung](#lokale-entwicklung)
- [Konfiguration](#konfiguration)
- [Login, Benutzer und Rollen](#login-benutzer-und-rollen)
- [Frontend-Funktionen](#frontend-funktionen)
- [API-Funktionen](#api-funktionen)
- [Collector-Funktionen](#collector-funktionen)
- [Datenbank und Speicher](#datenbank-und-speicher)
- [WAGO- oder SD-Karten-Betrieb](#wago--oder-sd-karten-betrieb)
- [Backup und Restore](#backup-und-restore)
- [Deployment-Hinweise](#deployment-hinweise)
- [Troubleshooting](#troubleshooting)
- [Sicherheits-Checkliste](#sicherheits-checkliste)
---
## Projektaufbau
```text
SeLTD/
├── .env.example
├── docker-compose.yml
├── docker-compose.wago.yml
├── docker/
│ └── redis/
│ └── redis.conf
├── api/
│ ├── Dockerfile
│ ├── package.json
│ └── src/
│ ├── index.js
│ ├── auth.js
│ ├── config.js
│ ├── db.js
│ ├── redis.js
│ └── lib/
│ ├── isp.js
│ └── store.js
├── collector/
│ ├── Dockerfile
│ ├── package.json
│ └── src/
│ └── index.js
└── web/
├── Dockerfile
├── package.json
├── vite.config.js
├── public/
│ └── logo.png
└── src/
├── App.jsx
├── api.js
├── main.jsx
├── styles.css
└── components/
├── Gauge.jsx
└── TrendChart.jsx
```
### Hauptbereiche
| Bereich | Aufgabe |
| --- | --- |
| `web/` | React/Vite-Frontend fuer Login, Dashboard, Trends, Admin-Bereich, Quellen, Rollen und Benutzer |
| `api/` | Express-API fuer Auth, Rollen, Aliase, Trendabfragen, Dashboard, SQL-Import und Benutzerverwaltung |
| `collector/` | HTTP-Service fuer Protokollquellen, Datenpunkte, Scans, Imports und zyklisches Logging |
| `mariadb` | Persistente Trenddaten und Benutzer-Tabelle |
| `redis` | Metadaten, Aliase, Rollen, Einheiten, Dashboards, Auswahlen und User-Praeferenzen |
| `dockhand` | Docker-Verwaltung ueber Weboberflaeche |
| `cadvisor` | Container-Metriken fuer Monitoring |
---
## Architektur
```text
Browser
│
│ http://localhost:5173
▼
React/Vite Frontend (web)
│
├── API-Aufrufe: http://localhost:18080/api/...
│ ▼
│ Express API (api, intern Port 8080)
│ ├── MariaDB: Benutzer, Trendtabellen, SQL-Daten
│ └── Redis: Rollen, Einheiten, Aliase, Dashboard, Auswahlen
│
└── Collector-Aufrufe: http://localhost:18110/...
▼
Collector-Service
├── sources.json unter /app/data
├── Modbus TCP / OPC UA / BACnet / KNX
└── schreibt aktive Datenpunkte in MariaDB-Trendtabellen
```
Wichtig: Die API laeuft im Container intern auf Port `8080`, wird aber nach aussen auf `18080` gemappt. Das Frontend muss deshalb im Browser auf `http://localhost:18080/api` zugreifen.
---
## Services und Ports
| Service | Container | Interner Port | Host-Port | Zweck |
| --- | --- | ---: | ---: | --- |
| Web | `seltd-web` | 5173 | 5173 | React/Vite-Oberflaeche |
| API | `seltd-api` | 8080 | 18080 | REST-API |
| Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling |
| MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten |
| Redis | `seltd-redis` | 6379 | 6379 | Metadaten und App-State |
| Dockhand | `dockhand` | 3000 | 3000 | Docker-Webverwaltung |
| cAdvisor | `cadvisor_ltd` | 8080 | 9090 | Container-Metriken |
---
## Schnellstart mit Docker Compose
Du solltest WSL installiert haben.
Falls du das nicht hast:
```powershell
wsl --install Ubuntu
```
Dann kannst du Docker Desktop installieren:
https://docs.docker.com/desktop/setup/install/windows-install/
Die Installation einfach durchklicken und wenn du gefragt wirst ob du Hyper-V oder WSL verwenden möchtest, wähle WSL.
### 1. Repository vorbereiten
Wenn du git auf deinem rechner installiert hast, dann öffne eine Powershell in dem Ordner, in dem du das LTD-System haben willst.
(rechtsklick im Windowsexplorer ins leere --> "In Terminal öffnen")
```powershell
git clone https://git.portal.se-cloud.de/Hannes/SE-LTD
cd ./SeLTD
```
Powershell nicht schließen, brauchst du gleich noch.
### 2. Stack bauen und starten
Falls du Powershell geschlossen hast:
(rechtsklick im Windowsexplorer ins leere --> "In Terminal öffnen")
```powershell
docker compose build --no-cache web api collector
docker compose up -d --force-recreate
```
Die lokalen Images werden jetzt gebaut und die Onlineimages werden heruntrergeladen.
Wenn das fertig ist müssen alle 7 Container gestartet sein.
Im Nachgang kannst du dies in der Powershell mit...
```powershell
docker ps -a
```
...überprüfen
### 3. Aufrufen
Nun stehen dir mehrere Tools zur Verfügung:
| Frontend | `http://localhost:5173` |
--> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends.
| API Healthcheck | `http://localhost:18080/api/health` |
--> hier kannst du schauen ob die API läuft
| Collector Healthcheck | `http://localhost:18110/health` |
--> hier kannst du schauen ob der Collector läuft, was nur wichtig ist, wenn du Datenpunkte per OPC,KNX, Modbus oder Bacnet angebunden hast.
| Dockhand | `http://localhost:3000` |
--> Dockhand ist Container verwaltungstool, dass es dir ermöglicht, auch grafisch den Zustand deiner Container und deines Stacks zu sehen.
Der Vorteil hier, im Gegensatz zur normalen Docker Desktopoberfläche: Du kannst es auf jedem beliebigen anderen Rechner, der auf dein Netzwerk zugriff hat, öffnen.
| cAdvisor | `http://localhost:9090` |
--> Cadvisor stellt alle Containerdaten für Monitoring und Analyticprogramme bereit.
So kann bei einer größeren Anlage, das Dockersystem mitr Prometheus oder ähnlichem überwacht werden.
Cadvisor stellt di Daten per html bereit, kannst du dir gern anschauen, ist aber ziemlich unübersichtlich.
### 4. Standard-Login
```text
Username: admin
Passwort: [individuell festlegen]
```
---
## Konfiguration
Die wichtigsten Variablen liegen in `.env`.
| Variable | Beispiel | Beschreibung |
| --- | --- | --- |
| `JWT_SECRET` | `[individuell festlegen]` | Signatur fuer Login-Tokens. In Produktion unbedingt aendern. |
| `ADMIN_USERNAME` | `admin` | Initialer Admin-Username |
| `ADMIN_EMAIL` | `admin@example.com` | Initiale Admin-E-Mail |
| `ADMIN_PASSWORD` | `[individuell festlegen]` | Initiales Admin-Passwort |
| `ADMIN_NAME` | `System Admin` | Anzeigename des Admins |
| `MARIADB_ROOT_PASSWORD` | `[individuell festlegen]` | MariaDB-Root-Passwort |
| `DB_PASSWORD_FALLBACK` | `[individuell festlegen]` | Fallback fuer alte Entwicklungsvolumes |
| `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe |
| `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt |
| `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung |
## Login, Benutzer und Rollen
Die API legt beim Start automatisch einen Admin-Benutzer an oder aktualisiert den vorhandenen Admin.
### Systemrollen
| Rolle | Rechte |
| --- | --- |
| `viewer` | Dashboard anzeigen, Trendansicht anzeigen |
| `technician` | Dashboard, Trends, Aliase, Quellen, Debug |
| `admin` | Alle Rechte inkl. Benutzer- und Rollenverwaltung |
### Rechtekatalog
| Recht | Bedeutung |
| --- | --- |
| `view_dashboard` | Dashboard anzeigen und speichern |
| `view_trends` | Trends anzeigen, Auswahlen nutzen |
| `edit_aliases` | Aliase und Einheiten bearbeiten |
| `manage_sources` | Quellen und Datenpunkte verwalten |
| `manage_users` | Benutzer anlegen und bearbeiten |
| `manage_roles` | Rollen und Rechte verwalten |
| `view_debug` | Collector-Debug sehen |
Benutzer, Rollen und Passwoerter werden ueber den Admin-Bereich verwaltet.
---
## Frontend-Funktionen
### Login
- Username-basierter Login
- JWT-Token wird im Browser gespeichert
- Passwortwechsel ueber Einstellungen
- Rollenbasierte Navigation
### Dashboard
- Widgets aus aktueller Auswahl oder gespeicherter Auswahl
- Widget-Typen:
- Graph
- Zahl
- Zeigermanometer
- Dashboard wird pro Benutzer gespeichert
### Trendansicht
- Datenpunkte aus mehreren Trendtabellen kombinierbar
- Auswahl speicherbar und optional fuer andere Benutzer freigebbar
- Zeitraeume als Presets von 5 Minuten bis 30 Tage
- Eigener Start-/Endzeitraum moeglich
- Aktuelle Werte werden separat angezeigt
- Fokusmodus fuer den Graphen
### Trend-Export
Der Trendgraph kann exportiert werden als:
- CSV
- XLSX
- PNG
- JPG
- SVG
- PDF
### Admin: Aliase
- Anzeigename und Beschreibung pro Trendtabelle
- Alias, Einheit, Faktor, Typ, Min/Max und Farbe pro Wert
- CSV-Import und CSV-Export
- Encoding-/Grad-Celsius-Bereinigung
### Admin: Einheiten
- Systemeinheiten wie `°C`, `%`, `K`, `V`, `A`, `Pa`
- Eigene Einheiten wie `bar`, `m³/h`, `Hz` usw.
- Einheitenauswahl bei Aliasen und Datenpunkten
### Admin: Quellen
- Protokollquellen anlegen und bearbeiten
- Unterstuetzte Protokolle in der UI:
- Modbus TCP
- OPC UA
- BACnet IP
- KNX IP
- Poll-Intervall und Schreibmodus konfigurierbar
- Scan-Ergebnisse und importierte Punkte koennen ins Logging uebernommen werden
- Manuelle Datenpunkte koennen erstellt und bearbeitet werden
---
## API-Funktionen
Die API laeuft unter:
```text
http://localhost:18080/api
```
### Authentifizierung
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `POST` | `/api/auth/login` | Login mit Username/Passwort |
| `GET` | `/api/auth/me` | Aktuellen Benutzer lesen |
| `POST` | `/api/auth/change-password` | Passwort aendern |
### Trends und ISPs
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `GET` | `/api/isps` | Verfuegbare Trendtabellen lesen |
| `GET` | `/api/isps/:isp/aliases` | Alias-Metadaten lesen |
| `PUT` | `/api/isps/:isp/aliases` | Alias-Metadaten speichern |
| `POST` | `/api/trend-tables` | Neue Trendtabelle anlegen |
| `POST` | `/api/trends/query` | Trenddaten abfragen |
| `POST` | `/api/points/latest` | Letzte Werte lesen |
### Einheiten
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `GET` | `/api/units` | Einheiten lesen |
| `POST` | `/api/units` | Einheit anlegen |
| `PATCH` | `/api/units/:symbol` | Einheit bearbeiten |
### Benutzer und Rollen
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `GET` | `/api/users` | Benutzerliste |
| `POST` | `/api/users` | Benutzer anlegen |
| `PATCH` | `/api/users/:id` | Benutzer bearbeiten |
| `GET` | `/api/roles` | Rollenliste inkl. Rechtekatalog |
| `POST` | `/api/roles` | Rolle anlegen |
| `PATCH` | `/api/roles/:name` | Rolle bearbeiten |
### Auswahlen und Dashboard
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `GET` | `/api/selections` | Gespeicherte Auswahlen lesen |
| `POST` | `/api/selections` | Auswahl speichern |
| `PUT` | `/api/selections/:selectionId` | Auswahl aktualisieren |
| `DELETE` | `/api/selections/:selectionId` | Auswahl loeschen |
| `GET` | `/api/dashboard` | Dashboard laden |
| `PUT` | `/api/dashboard` | Dashboard speichern |
| `POST` | `/api/dashboard/data` | Widget-Daten laden |
| `GET` | `/api/preferences` | Benutzerpraeferenzen laden |
| `PUT` | `/api/preferences` | Benutzerpraeferenzen speichern |
---
## Collector-Funktionen
Der Collector laeuft unter:
```text
http://localhost:18110
```
Er verwaltet Quellen und Datenpunkte in einer JSON-Datei (`/app/data/sources.json`) und schreibt aktive Punkte zyklisch in MariaDB.
### Collector-Endpunkte
| Methode | Pfad | Beschreibung |
| --- | --- | --- |
| `GET` | `/health` | Healthcheck |
| `GET` | `/capabilities` | Unterstuetzte Protokolle/Funktionen |
| `GET` | `/sources` | Quellen lesen |
| `POST` | `/sources` | Quelle anlegen |
| `PUT` | `/sources/:id` | Quelle bearbeiten |
| `DELETE` | `/sources/:id` | Quelle loeschen |
| `GET` | `/datapoints` | Datenpunkte lesen |
| `POST` | `/datapoints/manual` | Datenpunkt manuell anlegen |
| `PATCH` | `/datapoints/:id` | Datenpunkt bearbeiten, aktivieren, deaktivieren |
| `POST` | `/datapoints/:id/read` | Live-Wert lesen |
| `POST` | `/imports/modbus-csv` | Modbus-CSV importieren |
| `POST` | `/imports/knx-xml` | KNX-XML importieren |
| `POST` | `/scan/opcua` | OPC-UA-Scan starten |
| `POST` | `/scan/bacnet` | BACnet-Scan starten |
| `GET` | `/debug` | Debugdaten lesen |
### Schreibmodus
| Modus | Bedeutung |
| --- | --- |
| `interval` | Jeder Poll wird geschrieben |
| `cov` | Nur bei Wertaenderung wird geschrieben |
### Aktive vs. inaktive Datenpunkte
- Inaktive Datenpunkte sind gefunden/importiert, werden aber nicht geloggt.
- Aktive Datenpunkte werden vom Collector gepollt und in die zugehoerige Trendtabelle geschrieben.
- In der Weboberflaeche entspricht das der Trennung zwischen „Gefunden / importiert“ und „Wird geloggt“.
---
## Datenbank und Speicher
### MariaDB
MariaDB speichert:
- `app_users`
- bestehende `isp...` Tabellen
- neue `trend_...` Tabellen
- Registry-Tabellen fuer Quellen und Datenpunkte, falls vom Collector/API genutzt
Die API kann bestehende breite Tabellen mit `Wert1`, `Wert2`, ... lesen. Neue lokale Trendtabellen koennen bis zu 2000 Werte unterstuetzen.
### Redis
Redis speichert:
- Rollen
- Einheiten
- Aliase und Tabellen-Metadaten
- Auswahlen
- Dashboard-Konfiguration
- Benutzerpraeferenzen
Redis sollte deshalb ebenfalls gebackupt werden, nicht nur MariaDB.
---
### MariaDB Backup
```powershell
docker exec seltd-mariadb mariadb-dump -uroot -p --all-databases > seltd-mariadb-backup.sql
```
Restore:
```powershell
type .\seltd-mariadb-backup.sql | docker exec -i seltd-mariadb mariadb -uroot -p
```
### Redis Backup
Redis nutzt ein Docker-Volume. Fuer ein einfaches Dateibackup:
```powershell
docker run --rm -v seltd_redis_data:/data -v ${PWD}:/backup alpine tar czf /backup/seltd-redis-backup.tar.gz -C /data .
```
### Collector Backup
```powershell
docker run --rm -v seltd_collector_data:/data -v ${PWD}:/backup alpine tar czf /backup/seltd-collector-backup.tar.gz -C /data .
```
---
### Browsercache
Bei alten JavaScript-Fehlern nach einem Fix:
```text
Strg + F5
```
### Nginx Proxy Manager
Wenn das Frontend hinter Nginx laeuft, muessen die API- und Collector-URLs sauber erreichbar sein. Entweder:
- Frontend, API und Collector unter eigenen Subdomains veroeffentlichen, oder
- Nginx so konfigurieren, dass `/api` zur API und `/collector` zum Collector weitergeleitet wird.
In diesem Fall kann `VITE_API_URL` statt `VITE_API_PORT` gesetzt werden:
```env
VITE_API_URL=https://trend-api.example.local/api
VITE_COLLECTOR_URL=https://trend-collector.example.local
```
---
## Troubleshooting
### Fehler: `NetworkError when attempting to fetch resource`
Ursachen:
- API-Container laeuft nicht
- falscher Port im Frontend
- CORS nicht korrekt
- Browser ruft alte Version auf
Pruefen:
```powershell
docker ps
curl http://localhost:18080/api/health
```
Wenn Frontend lokal auf `localhost:5173` laeuft:
```env
CORS_ORIGIN=*
```
Danach API neu starten:
```powershell
docker compose restart api
```
### Fehler: Browser zeigt alte React-Fehler nach Fix
Sehr wahrscheinlich wurde das Docker-Image nicht neu gebaut.
```powershell
docker compose down
docker compose build --no-cache web api collector
docker compose up -d
```
Danach im Browser `Strg + F5`.
### MariaDB Login oder DB-Verbindung fehlgeschlagen
Logs ansehen:
```powershell
docker logs seltd-api --tail 100
docker logs seltd-mariadb --tail 100
```
Pruefen, ob MariaDB healthy ist:
```powershell
docker ps
```
### Redis-Probleme
```powershell
docker exec seltd-redis redis-cli ping
```
Erwartet:
```text
PONG
```
---
## Nuetzliche Befehle
### Alle Container anzeigen
```powershell
docker compose ps
```
### Logs live verfolgen
```powershell
docker compose logs -f
```
Nur API:
```powershell
docker logs seltd-api -f
```
Nur Frontend:
```powershell
docker logs seltd-web -f
```
Nur Collector:
```powershell
docker logs seltd-collector -f
```
### Komplett neu starten
```powershell
docker compose restart
```
### Komplett neu bauen
```powershell
docker compose down
docker compose build --no-cache
docker compose up -d
```
### Volumes loeschen
Achtung: Dadurch gehen Daten verloren.
```powershell
docker compose down -v
```
---
## Sicherheits-Checkliste
Vor produktiver Nutzung:
- [ ] `JWT_SECRET` auf langen zufaelligen Wert setzen
- [ ] Admin-Passwort aendern
- [ ] MariaDB-Root-Passwort aendern
- [ ] MariaDB-Port `3306` nicht ungeschuetzt ins Internet veroeffentlichen
- [ ] Redis-Port `6379` nicht ungeschuetzt ins Internet veroeffentlichen
- [ ] Dockhand absichern oder nur intern bereitstellen
- [ ] Backups fuer MariaDB, Redis und Collector-Daten einrichten
- [ ] Reverse Proxy mit HTTPS verwenden
---
## Bekannte Hinweise
- Leere Trendtabellen erscheinen nicht in der Trendauswahl, aber im Admin-Bereich.
- Bestehende breite `isp...` Tabellen bleiben kompatibel.
- Neue lokale Tabellen koennen als `trend_...` Tabellen angelegt werden.
- Der Collector speichert seine Quellen/Datenpunkte aktuell dateibasiert in `sources.json`.
- Fuer vollstaendige Protokollintegration muessen je nach Feldbus noch Details wie Adressierung, Datentyp, Byteorder und Authentifizierung sauber projektspezifisch gepflegt werden.
---
---
## Konfiguration und Sicherheit
Vor dem ersten Start `.env.example` nach `.env` kopieren und mindestens `JWT_SECRET`, `ADMIN_PASSWORD` und `REDIS_PASSWORD` durch eigene lange Zufallswerte ersetzen. Die lokale `.env` wird nicht versioniert.
Redis ist ausschließlich innerhalb des Docker-Netzwerks erreichbar und verlangt ein Passwort. Für Diagnosezwecke:
```powershell
docker compose exec redis redis-cli -a $env:REDIS_PASSWORD ping
```
Alle Dienste können vor einem Deployment statisch geprüft werden:
```powershell
npm --prefix api run check
npm --prefix collector run check
npm --prefix symcon-collector run check
npm --prefix bacnet-collector run check
npm --prefix runner run check
npm --prefix web run check
```
+2 -1
View File
@@ -14,8 +14,9 @@
pkgs = import nixpkgs { inherit system; };
in
{
default = pkgs.callPackage ./nix/package.nix { };
default = pkgs.callPackage ./nix/package.nix { sourceRevision = self.rev or ""; };
seiugw = self.packages.${system}.default;
bacnet = pkgs.callPackage ./nix/bacnet.nix { };
});
devShells = forAllSystems (system:
+474
View File
@@ -0,0 +1,474 @@
/* SE-Inno native object bridge. APDU encoding, COV and priority arbitration
* remain entirely in the pinned upstream BACnet stack. No UDP emulation. */
#include "gateway_bridge.h"
#include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "bacnet/bacapp.h"
#include "bacnet/iam.h"
#include "bacnet/basic/service/h_apdu.h"
#include "bacnet/basic/service/s_whois.h"
#include "bacnet/datalink/bip.h"
#include "bacnet/datalink/bvlc.h"
#include "bacnet/basic/object/device.h"
#include "bacnet/basic/object/ai.h"
#include "bacnet/basic/object/ao.h"
#include "bacnet/basic/object/av.h"
#include "bacnet/basic/object/bi.h"
#include "bacnet/basic/object/bo.h"
#include "bacnet/basic/object/bv.h"
#include "bacnet/basic/object/ms-input.h"
#include "bacnet/basic/object/mso.h"
#include "bacnet/basic/object/msv.h"
#include "bacnet/basic/object/calendar.h"
#include "bacnet/basic/object/schedule.h"
#include "bacnet/basic/object/netport.h"
#include "bacnet/basic/bbmd/h_bbmd.h"
typedef struct {
const char *name;
BACNET_OBJECT_TYPE type;
bool (*name_set)(uint32_t, const char *);
bool (*reliability_set)(uint32_t, BACNET_RELIABILITY);
} Kind;
static const Kind kinds[] = {
{"AnalogInput", OBJECT_ANALOG_INPUT, Analog_Input_Name_Set, Analog_Input_Reliability_Set},
{"AnalogOutput", OBJECT_ANALOG_OUTPUT, Analog_Output_Name_Set, Analog_Output_Reliability_Set},
{"AnalogValue", OBJECT_ANALOG_VALUE, Analog_Value_Name_Set, Analog_Value_Reliability_Set},
{"BinaryInput", OBJECT_BINARY_INPUT, Binary_Input_Name_Set, Binary_Input_Reliability_Set},
{"BinaryOutput", OBJECT_BINARY_OUTPUT, Binary_Output_Name_Set, Binary_Output_Reliability_Set},
{"BinaryValue", OBJECT_BINARY_VALUE, Binary_Value_Name_Set, Binary_Value_Reliability_Set},
{"MultiStateInput", OBJECT_MULTI_STATE_INPUT, Multistate_Input_Name_Set, Multistate_Input_Reliability_Set},
{"MultiStateOutput", OBJECT_MULTI_STATE_OUTPUT, Multistate_Output_Name_Set, Multistate_Output_Reliability_Set},
{"MultiStateValue", OBJECT_MULTI_STATE_VALUE, Multistate_Value_Name_Set, Multistate_Value_Reliability_Set},
{"Calendar", OBJECT_CALENDAR, Calendar_Name_Set, NULL},
{"Schedule", OBJECT_SCHEDULE, Schedule_Name_Set, NULL}
};
typedef struct Point {
char id[37];
char *name;
char *address_json;
char *value_type;
const Kind *kind;
uint32_t instance;
bool writable, ready, present;
char last[128];
struct Point *next;
} Point;
static sqlite3 *db;
static Point *points;
static object_functions_t table[16];
static write_property_function writers[MAX_BACNET_OBJECT_TYPE];
static char *network_configuration;
static uint32_t network_ipv4, network_netmask;
static char discovery_id[33];
static char discovery_target[16];
static uint16_t discovery_port;
static long long discovery_until;
static long long last_scan;
static long long now_ms(void)
{
struct timespec t; clock_gettime(CLOCK_REALTIME, &t);
return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
static void fatal(void) { fprintf(stderr, "Gateway database failure: %s\n", sqlite3_errmsg(db)); exit(75); }
static sqlite3_stmt *prepare(const char *sql)
{
sqlite3_stmt *s = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &s, NULL) != SQLITE_OK) fatal();
return s;
}
static void execute(sqlite3_stmt *s)
{
if (sqlite3_step(s) != SQLITE_DONE) fatal();
sqlite3_finalize(s);
}
static void sql(const char *text) { if (sqlite3_exec(db, text, NULL, NULL, NULL) != SQLITE_OK) fatal(); }
static const char *str(sqlite3_stmt *s, int i) { const char *v = (const char *)sqlite3_column_text(s, i); return v ? v : ""; }
static Point *find(BACNET_OBJECT_TYPE type, uint32_t instance)
{
for (Point *p = points; p; p = p->next) if (p->kind->type == type && p->instance == instance) return p;
return NULL;
}
static bool input(Point *p) { return p->kind->type == OBJECT_ANALOG_INPUT || p->kind->type == OBJECT_BINARY_INPUT || p->kind->type == OBJECT_MULTI_STATE_INPUT; }
static bool point_current(Point *p)
{
sqlite3_stmt *s = prepare(
"SELECT 1 FROM points WHERE id=? AND bacnet_object_kind=? AND bacnet_object_instance=? AND "
"address_json=? AND value_type=? AND writable=? AND deleted_at_utc IS NULL "
"AND protocol='Bacnet' AND scope='Gateway'");
sqlite3_bind_text(s, 1, p->id, -1, SQLITE_STATIC);
sqlite3_bind_text(s, 2, p->kind->name, -1, SQLITE_STATIC);
sqlite3_bind_int64(s, 3, p->instance);
sqlite3_bind_text(s, 4, p->address_json, -1, SQLITE_STATIC);
sqlite3_bind_text(s, 5, p->value_type, -1, SQLITE_STATIC);
sqlite3_bind_int(s, 6, p->writable);
bool current = sqlite3_step(s) == SQLITE_ROW;
sqlite3_finalize(s);
return current;
}
static void ready(Point *p)
{
p->ready = true;
if (p->kind->reliability_set) p->kind->reliability_set(p->instance, RELIABILITY_NO_FAULT_DETECTED);
}
static void persist(Point *p, BACNET_WRITE_PROPERTY_DATA *w)
{
sqlite3_stmt *s = prepare("INSERT OR REPLACE INTO bacnet_properties(point_id,property,array_index,priority,payload) VALUES(?,?,?,?,?)");
sqlite3_bind_text(s, 1, p->id, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 2, w->object_property);
sqlite3_bind_int64(s, 3, w->array_index);
sqlite3_bind_int(s, 4, w->priority);
sqlite3_bind_blob(s, 5, w->application_data, w->application_data_len, SQLITE_TRANSIENT);
execute(s);
}
static bool network_write(BACNET_WRITE_PROPERTY_DATA *w)
{
Point *p = find(w->object_type, w->object_instance);
if (!p || w->object_property == PROP_OBJECT_IDENTIFIER || w->object_property == PROP_OBJECT_NAME ||
(!p->writable && !input(p) && w->object_property == PROP_PRESENT_VALUE)) {
w->error_class = ERROR_CLASS_PROPERTY; w->error_code = ERROR_CODE_WRITE_ACCESS_DENIED; return false;
}
sql("BEGIN IMMEDIATE");
if (!point_current(p)) {
sql("ROLLBACK");
w->error_class = ERROR_CLASS_OBJECT;
w->error_code = ERROR_CODE_UNKNOWN_OBJECT;
return false;
}
bool ok = writers[w->object_type] && writers[w->object_type](w);
if (ok) {
persist(p, w);
if (w->object_property == PROP_PRESENT_VALUE) ready(p);
sql("COMMIT");
} else sql("ROLLBACK");
return ok;
}
static bool apply_input(Point *p, BACNET_WRITE_PROPERTY_DATA *w)
{
BACNET_APPLICATION_DATA_VALUE value = {0};
if (bacapp_decode_application_data(w->application_data, w->application_data_len, &value) <= 0) return false;
switch (p->kind->type) {
case OBJECT_ANALOG_INPUT:
if (Analog_Input_Out_Of_Service(p->instance)) return false;
Analog_Input_Present_Value_Set(p->instance, value.type.Real); return true;
case OBJECT_BINARY_INPUT:
return !Binary_Input_Out_Of_Service(p->instance) && Binary_Input_Present_Value_Set(p->instance, value.type.Enumerated);
case OBJECT_MULTI_STATE_INPUT:
return !Multistate_Input_Out_Of_Service(p->instance) && Multistate_Input_Present_Value_Set(p->instance, value.type.Unsigned_Int);
default: return false;
}
}
static void restore(Point *p)
{
sqlite3_stmt *s = prepare("SELECT property,array_index,priority,payload FROM bacnet_properties WHERE point_id=? ORDER BY id");
sqlite3_bind_text(s, 1, p->id, -1, SQLITE_TRANSIENT);
while (sqlite3_step(s) == SQLITE_ROW) {
BACNET_WRITE_PROPERTY_DATA w = {0};
w.object_type = p->kind->type; w.object_instance = p->instance;
w.object_property = sqlite3_column_int(s, 0); w.array_index = sqlite3_column_int64(s, 1); w.priority = sqlite3_column_int(s, 2);
w.application_data_len = sqlite3_column_bytes(s, 3);
if (w.application_data_len > MAX_APDU) continue;
memcpy(w.application_data, sqlite3_column_blob(s, 3), w.application_data_len);
bool ok = input(p) && w.object_property == PROP_PRESENT_VALUE && w.priority == 0 ? apply_input(p, &w) : writers[w.object_type](&w);
if (ok && w.object_property == PROP_PRESENT_VALUE) ready(p);
if (!ok) fprintf(stderr, "Cannot restore BACnet object %s property %u\n", p->id, w.object_property);
}
sqlite3_finalize(s);
}
static void load_points(void)
{
// Remove stale objects before adding replacements, even if they reuse an instance.
sql("BEGIN");
sqlite3_stmt *s = prepare(
"SELECT id,display_name,bacnet_object_kind,bacnet_object_instance,writable,"
"COALESCE(json_extract(address_json,'$.units'),95),COALESCE(json_extract(address_json,'$.numberOfStates'),16),"
"address_json,value_type FROM points WHERE protocol='Bacnet' AND scope='Gateway' AND deleted_at_utc IS NULL");
for (Point *p = points; p; p = p->next) p->present = false;
while (sqlite3_step(s) == SQLITE_ROW) {
for (Point *p = points; p; p = p->next) {
if (strcmp(p->id, str(s, 0)) || strcmp(p->kind->name, str(s, 2)) ||
p->instance != (uint32_t)sqlite3_column_int(s, 3) ||
strcmp(p->address_json, str(s, 7)) || strcmp(p->value_type, str(s, 8))) continue;
p->present = true;
p->writable = sqlite3_column_int(s, 4);
if (strcmp(p->name, str(s, 1))) {
char *name = strdup(str(s, 1));
if (!name) exit(75);
if (!p->kind->name_set(p->instance, name)) { free(name); exit(75); }
free(p->name);
p->name = name;
Device_Inc_Database_Revision();
}
break;
}
}
if (sqlite3_reset(s) != SQLITE_OK) fatal();
Point **link = &points;
while (*link) {
Point *p = *link;
if (p->present) { link = &p->next; continue; }
BACNET_DELETE_OBJECT_DATA object = { .object_type = p->kind->type, .object_instance = p->instance };
if (!Device_Delete_Object(&object)) {
fprintf(stderr, "Unable to remove stale BACnet object; rebuilding from the active catalog\n");
exit(75);
}
*link = p->next;
free(p->name); free(p->address_json); free(p->value_type); free(p);
}
while (sqlite3_step(s) == SQLITE_ROW) {
const Kind *kind = NULL;
for (unsigned i = 0; i < sizeof(kinds)/sizeof(kinds[0]); i++) if (!strcmp(str(s, 2), kinds[i].name)) kind = &kinds[i];
if (!kind || find(kind->type, sqlite3_column_int(s, 3))) continue;
object_functions_t *f = Device_Object_Functions_Find(kind->type);
uint32_t instance = sqlite3_column_int(s, 3);
if (!f || !f->Object_Create || f->Object_Create(instance) != instance) continue;
Point *p = calloc(1, sizeof(*p)); if (!p) exit(75);
snprintf(p->id, sizeof(p->id), "%s", str(s, 0)); p->name = strdup(str(s, 1));
p->address_json = strdup(str(s, 7)); p->value_type = strdup(str(s, 8));
if (!p->name || !p->address_json || !p->value_type) exit(75);
p->kind = kind; p->instance = instance; p->writable = sqlite3_column_int(s, 4); p->next = points; points = p;
kind->name_set(instance, p->name);
if (kind->reliability_set) kind->reliability_set(instance, RELIABILITY_UNRELIABLE_OTHER); else p->ready = true;
unsigned units = sqlite3_column_int(s, 5), states = sqlite3_column_int(s, 6);
char *state_names = NULL;
if (kind->type == OBJECT_MULTI_STATE_INPUT || kind->type == OBJECT_MULTI_STATE_OUTPUT || kind->type == OBJECT_MULTI_STATE_VALUE) {
if (states < 1 || states > 1000) states = 16;
state_names = calloc(states * 24 + 1, 1); if (!state_names) exit(75);
char *next = state_names;
for (unsigned i = 1; i <= states; i++) next += sprintf(next, "State %u", i) + 1;
}
switch (kind->type) {
case OBJECT_ANALOG_INPUT: Analog_Input_Units_Set(instance, units); break;
case OBJECT_ANALOG_OUTPUT: Analog_Output_Units_Set(instance, units); break;
case OBJECT_ANALOG_VALUE: Analog_Value_Units_Set(instance, units); break;
case OBJECT_MULTI_STATE_INPUT: Multistate_Input_State_Text_List_Set(instance, state_names); break;
case OBJECT_MULTI_STATE_OUTPUT: Multistate_Output_State_Text_List_Set(instance, state_names); break;
case OBJECT_MULTI_STATE_VALUE: Multistate_Value_State_Text_List_Set(instance, state_names); break;
default: break;
}
free(state_names);
restore(p);
Device_Inc_Database_Revision();
}
sqlite3_finalize(s);
sql("COMMIT");
}
void Gateway_Init(void)
{
const char *path = getenv("SEIUGW_DATABASE");
if (sqlite3_open_v2(path ? path : "seiugw.db", &db, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) fatal();
sqlite3_busy_timeout(db, 5000);
Device_Object_Functions_Init(NULL);
unsigned n = 0;
table[n++] = *Device_Object_Functions_Find(OBJECT_DEVICE);
table[n++] = *Device_Object_Functions_Find(OBJECT_NETWORK_PORT);
for (unsigned i = 0; i < sizeof(kinds)/sizeof(kinds[0]); i++) {
object_functions_t *f = Device_Object_Functions_Find(kinds[i].type);
if (!f) { fprintf(stderr, "Missing object implementation %s\n", kinds[i].name); exit(75); }
table[n] = *f; writers[f->Object_Type] = f->Object_Write_Property;
table[n++].Object_Write_Property = network_write;
}
table[n].Object_Type = MAX_BACNET_OBJECT_TYPE;
Device_Init(table);
Device_Set_Vendor_Identifier(815);
load_points();
// Claimed commands were interrupted: never replay an unknown write outcome.
sql("UPDATE bacnet_commands SET state='failed',result='Interrupted; not replayed' WHERE state='claimed'");
}
static void read_interface_ipv4(uint32_t *address, uint32_t *netmask)
{
*address = *netmask = 0;
const char *name = getenv("BACNET_IFACE");
if (!name || strlen(name) >= IFNAMSIZ) return;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return;
struct ifreq request = {0};
strcpy(request.ifr_name, name);
if (ioctl(fd, SIOCGIFADDR, &request) == 0)
*address = ((struct sockaddr_in *)&request.ifr_addr)->sin_addr.s_addr;
if (ioctl(fd, SIOCGIFNETMASK, &request) == 0)
*netmask = ((struct sockaddr_in *)&request.ifr_netmask)->sin_addr.s_addr;
close(fd);
}
void Gateway_Configure(void)
{
sqlite3_stmt *s = prepare("SELECT json_extract(value,'$.deviceInstance'),json_extract(value,'$.deviceName'),json_extract(value,'$.bacnet.interface'),json_extract(value,'$.bacnet.ipPort'),json_extract(value,'$.bacnet.bbmdMode'),json_extract(value,'$.bacnet.bbmdAddress'),json_extract(value,'$.bacnet.foreignDeviceTtlSeconds'),json_extract(value,'$.bacnet') FROM settings WHERE key='gateway.configuration'");
if (sqlite3_step(s) != SQLITE_ROW) fatal();
Device_Set_Object_Instance_Number(sqlite3_column_int(s, 0)); Device_Object_Name_ANSI_Init(str(s, 1));
setenv("BACNET_IFACE", str(s, 2), 1); setenv("BACNET_IP_PORT", str(s, 3), 1); setenv("BACNET_IP_BROADCAST_PORT", str(s, 3), 1);
setenv("SEIUGW_BBMD_MODE", str(s, 4), 1);
if (!strcmp(str(s, 4), "ForeignDevice")) {
setenv("BACNET_BBMD_ADDRESS", str(s, 5), 1); setenv("BACNET_BBMD_TIMETOLIVE", str(s, 6), 1);
}
network_configuration = strdup(str(s, 7));
sqlite3_finalize(s);
read_interface_ipv4(&network_ipv4, &network_netmask);
}
static void receive_i_am(uint8_t *request, uint16_t length, BACNET_ADDRESS *source)
{
if (!discovery_id[0] || now_ms() >= discovery_until || source->mac_len != 6)
return;
uint32_t device;
unsigned max_apdu;
int segmentation;
uint16_t vendor;
if (bacnet_iam_request_decode(request, length, &device, &max_apdu, &segmentation, &vendor) <= 0 ||
max_apdu > 65535)
return;
char address[16];
const uint8_t *mac = source->mac;
unsigned port = (mac[4] << 8) | mac[5];
if (memcmp(mac, &network_ipv4, 4) == 0 && port == bip_get_port()) return;
snprintf(address, sizeof(address), "%u.%u.%u.%u", mac[0], mac[1], mac[2], mac[3]);
if (discovery_target[0] && (strcmp(address, discovery_target) || port != discovery_port))
return;
sqlite3_stmt *s = prepare(
"INSERT OR IGNORE INTO bacnet_discovered_devices(scan_id,device_instance,address,port,vendor,max_apdu,network,mac) VALUES(?,?,?,?,?,?,?,?)");
sqlite3_bind_text(s, 1, discovery_id, -1, SQLITE_STATIC);
sqlite3_bind_int(s, 2, device);
sqlite3_bind_text(s, 3, address, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 4, port);
sqlite3_bind_int(s, 5, vendor);
sqlite3_bind_int(s, 6, max_apdu);
sqlite3_bind_int(s, 7, source->net);
if (source->net && source->len && source->len <= MAX_MAC_LEN) {
char remote_mac[MAX_MAC_LEN * 2 + 1];
for (unsigned i = 0; i < source->len; i++)
snprintf(remote_mac + 2 * i, 3, "%02X", source->adr[i]);
sqlite3_bind_text(s, 8, remote_mac, -1, SQLITE_TRANSIENT);
} else {
sqlite3_bind_null(s, 8);
}
execute(s);
}
static void discover(long long now)
{
sqlite3_stmt *s = prepare("SELECT scan_id,target,port,expires_ms FROM bacnet_discovery WHERE id=1 AND sent=0 AND expires_ms>?");
sqlite3_bind_int64(s, 1, now);
if (sqlite3_step(s) != SQLITE_ROW) {
sqlite3_finalize(s);
return;
}
snprintf(discovery_id, sizeof(discovery_id), "%s", str(s, 0));
snprintf(discovery_target, sizeof(discovery_target), "%s", str(s, 1));
discovery_port = (uint16_t)sqlite3_column_int(s, 2);
discovery_until = sqlite3_column_int64(s, 3);
sqlite3_finalize(s);
if (discovery_target[0]) {
BACNET_IP_ADDRESS ip = {0};
BACNET_ADDRESS address = {0};
char port[6];
snprintf(port, sizeof(port), "%u", discovery_port);
if (!bvlc_address_port_from_ascii(&ip, discovery_target, port) ||
!bvlc_ip_address_to_bacnet_local(&address, &ip))
return;
Send_WhoIs_Remote(&address, -1, -1);
} else {
Send_WhoIs_Global(-1, -1);
}
s = prepare("UPDATE bacnet_discovery SET sent=1 WHERE scan_id=?");
sqlite3_bind_text(s, 1, discovery_id, -1, SQLITE_STATIC);
execute(s);
}
void Gateway_Network_Ready(void)
{
const char *mode = getenv("SEIUGW_BBMD_MODE");
bool bbmd = mode && !strcmp(mode, "Bbmd");
uint32_t instance = Network_Port_Index_To_Instance(0);
bvlc_bbmd_accept_fd_registrations_set(bbmd);
Network_Port_BBMD_Accept_FD_Registrations_Set(instance, bbmd);
Network_Port_BIP_Mode_Set(instance, bbmd ? BACNET_IP_MODE_BBMD : mode && !strcmp(mode, "ForeignDevice") ? BACNET_IP_MODE_FOREIGN : BACNET_IP_MODE_NORMAL);
apdu_set_unconfirmed_handler(SERVICE_UNCONFIRMED_I_AM, receive_i_am);
}
static void commands(void)
{
for (unsigned i = 0; i < 100; i++) {
sqlite3_stmt *s = prepare("SELECT id,point_id,value_json,priority,created_ms FROM bacnet_commands WHERE state='pending' ORDER BY id LIMIT 1");
if (sqlite3_step(s) != SQLITE_ROW) { sqlite3_finalize(s); break; }
long long id = sqlite3_column_int64(s, 0), created = sqlite3_column_int64(s, 4);
Point *p = points; while (p && strcmp(p->id, str(s, 1))) p = p->next;
char *value = strdup(str(s, 2)); unsigned priority = sqlite3_column_int(s, 3); sqlite3_finalize(s);
s = prepare("UPDATE bacnet_commands SET state='claimed' WHERE id=?"); sqlite3_bind_int64(s, 1, id); execute(s);
bool ok = false;
if (p && now_ms() - created < 10000 && priority >= 1 && priority <= 16 && priority != 6) {
BACNET_WRITE_PROPERTY_DATA w = {0};
w.object_type = p->kind->type; w.object_instance = p->instance;
w.object_property = PROP_PRESENT_VALUE; w.array_index = BACNET_ARRAY_ALL; w.priority = input(p) ? 0 : priority;
if (!strcmp(value, "null")) w.application_data_len = encode_application_null(w.application_data);
else if (p->kind->type <= OBJECT_ANALOG_VALUE) w.application_data_len = encode_application_real(w.application_data, strtof(value, NULL));
else if (p->kind->type >= OBJECT_BINARY_INPUT && p->kind->type <= OBJECT_BINARY_VALUE) w.application_data_len = encode_application_enumerated(w.application_data, !strcmp(value, "true") ? BINARY_ACTIVE : BINARY_INACTIVE);
else w.application_data_len = encode_application_unsigned(w.application_data, strtoul(value, NULL, 10));
sql("BEGIN IMMEDIATE");
if (point_current(p))
ok = input(p) ? apply_input(p, &w) : writers[w.object_type](&w);
if (ok) { persist(p, &w); ready(p); sql("COMMIT"); } else sql("ROLLBACK");
}
free(value);
s = prepare("UPDATE bacnet_commands SET state=?,result=? WHERE id=?");
sqlite3_bind_text(s, 1, ok ? "done" : "failed", -1, SQLITE_STATIC);
sqlite3_bind_text(s, 2, ok ? "Good" : "Rejected, expired or object unavailable", -1, SQLITE_STATIC);
sqlite3_bind_int64(s, 3, id); execute(s);
}
}
static void observe(Point *p)
{
uint8_t buffer[MAX_APDU]; BACNET_READ_PROPERTY_DATA r = {0}; BACNET_APPLICATION_DATA_VALUE value = {0};
r.object_type = p->kind->type; r.object_instance = p->instance; r.object_property = PROP_PRESENT_VALUE;
r.array_index = BACNET_ARRAY_ALL; r.application_data = buffer; r.application_data_len = sizeof(buffer);
int length = Device_Read_Property(&r);
if (length <= 0 || bacapp_decode_application_data(buffer, length, &value) <= 0) return;
char json[80] = "null";
if (p->ready) switch (value.tag) {
case BACNET_APPLICATION_TAG_REAL: if (isfinite(value.type.Real)) snprintf(json, sizeof(json), "%.9g", (double)value.type.Real); break;
case BACNET_APPLICATION_TAG_UNSIGNED_INT: snprintf(json, sizeof(json), "%u", (unsigned)value.type.Unsigned_Int); break;
case BACNET_APPLICATION_TAG_ENUMERATED: snprintf(json, sizeof(json), "%s", value.type.Enumerated ? "true" : "false"); break;
case BACNET_APPLICATION_TAG_BOOLEAN: snprintf(json, sizeof(json), "%s", value.type.Boolean ? "true" : "false"); break;
default: break;
}
const char *status = p->ready && strcmp(json, "null") ? "Good" : "BadWaitingForInitialData";
r.object_property = PROP_RELIABILITY;
length = Device_Read_Property(&r);
if (p->ready && length > 0 && bacapp_decode_application_data(buffer, length, &value) > 0 && value.type.Enumerated != RELIABILITY_NO_FAULT_DETECTED) status = "BadSensorFailure";
r.object_property = PROP_STATUS_FLAGS;
length = Device_Read_Property(&r);
if (length > 0 && bacapp_decode_application_data(buffer, length, &value) > 0 && value.tag == BACNET_APPLICATION_TAG_BIT_STRING && bitstring_bit(&value.type.Bit_String, STATUS_FLAG_OUT_OF_SERVICE)) status = "UncertainOutOfService";
char snapshot[128]; snprintf(snapshot, sizeof(snapshot), "%s:%s", status, json);
if (!strcmp(snapshot, p->last)) return;
sqlite3_stmt *s = prepare("INSERT INTO bacnet_observations(point_id,value_json,status,observed_ms) VALUES(?,?,?,?)");
sqlite3_bind_text(s, 1, p->id, -1, SQLITE_TRANSIENT); sqlite3_bind_text(s, 2, json, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 3, status, -1, SQLITE_STATIC); sqlite3_bind_int64(s, 4, now_ms()); execute(s);
snprintf(p->last, sizeof(p->last), "%s", snapshot);
}
void Gateway_Tick(void)
{
long long now = now_ms();
if (now - last_scan >= 1000) {
uint32_t address, netmask;
read_interface_ipv4(&address, &netmask);
if (address != network_ipv4 || netmask != network_netmask) {
fprintf(stderr, "BACnet interface IPv4 address or netmask changed; restarting\n");
exit(75);
}
last_scan = now; load_points();
sqlite3_stmt *s = prepare("SELECT json_extract(value,'$.bacnet'),json_extract(value,'$.deviceInstance'),json_extract(value,'$.deviceName') FROM settings WHERE key='gateway.configuration'");
if (sqlite3_step(s) == SQLITE_ROW && (strcmp(network_configuration, str(s, 0)) || Device_Object_Instance_Number() != sqlite3_column_int(s, 1))) {
sqlite3_finalize(s); fprintf(stderr, "BACnet network configuration changed; restarting\n"); exit(75);
}
if (sqlite3_column_count(s) >= 3) Device_Object_Name_ANSI_Init(str(s, 2));
sqlite3_finalize(s);
discover(now);
s = prepare("INSERT OR REPLACE INTO bacnet_runtime VALUES(1,?,'Running')"); sqlite3_bind_int64(s, 1, now); execute(s);
s = prepare("DELETE FROM bacnet_commands WHERE state IN ('done','failed') AND created_ms<?"); sqlite3_bind_int64(s, 1, now - 86400000); execute(s);
}
commands();
for (Point *p = points; p; p = p->next) observe(p);
}
+7
View File
@@ -0,0 +1,7 @@
#ifndef SEIUGW_BRIDGE_H
#define SEIUGW_BRIDGE_H
void Gateway_Init(void);
void Gateway_Configure(void);
void Gateway_Network_Ready(void);
void Gateway_Tick(void);
#endif
+50
View File
@@ -0,0 +1,50 @@
{ stdenv, fetchzip, cmake, perl, sqlite }:
stdenv.mkDerivation {
pname = "seiugw-bacnet";
version = "1.7.0-0bfe656";
src = fetchzip {
extension = "tar.gz";
url = "https://codeload.github.com/bacnet-stack/bacnet-stack/tar.gz/0bfe65645ff7238e15121a6727870f96413ac22e";
sha256 = "1yjdj0brziizrxqxf14z25yl6hgqjn07jci2d080llj391vyzxhi";
};
nativeBuildInputs = [ cmake perl ];
buildInputs = [ sqlite ];
postPatch = ''
cp ${../native/bacnet/gateway_bridge.c} apps/server/gateway_bridge.c
cp ${../native/bacnet/gateway_bridge.h} apps/server/gateway_bridge.h
substituteInPlace apps/server/main.c \
--replace-fail '#include <stdio.h>' '#include <stdio.h>
#include "gateway_bridge.h"' \
--replace-fail 'Device_Init(NULL);' 'Gateway_Init();' \
--replace-fail 'dlenv_init();' 'Gateway_Configure(); dlenv_init(); Gateway_Network_Ready();' \
--replace-fail 'Device_Timer(elapsed_milliseconds);' 'Device_Timer(elapsed_milliseconds); Gateway_Tick();'
perl -0pi -e 's@ /\* create some dynamically created objects as examples \*/.*?(?= /\* set up our confirmed)@@s or die "example block missing"' apps/server/main.c
# Object lifecycle belongs to the gateway DB, not the example Create/Delete service.
perl -0pi -e 's@ apdu_set_confirmed_handler\(\s*SERVICE_CONFIRMED_(CREATE|DELETE)_OBJECT, handler_(create|delete)_object\);@@g' apps/server/main.c
substituteInPlace src/bacnet/basic/bbmd/h_bbmd.c \
--replace-fail '#include <stdio.h>' '#include <stdlib.h>
#include <stdio.h>' \
--replace-fail 'return bvlc_bbmd_enabled_handler(addr, src, npdu, npdu_len);' 'if (getenv("SEIUGW_BBMD_MODE") && strcmp(getenv("SEIUGW_BBMD_MODE"), "Bbmd")) return bvlc_bbmd_disabled_handler(addr, src, npdu, npdu_len);
return bvlc_bbmd_enabled_handler(addr, src, npdu, npdu_len);'
substituteInPlace CMakeLists.txt \
--replace-fail 'add_executable(server apps/server/main.c)' 'add_executable(server apps/server/main.c apps/server/gateway_bridge.c)
target_link_libraries(server PRIVATE sqlite3)'
'';
cmakeFlags = [
"-DBACDL_BIP6=OFF" "-DBAC_ROUTING=OFF"
"-DCMAKE_C_FLAGS=-DBACNET_OBJECT_ANALOG_VALUE_COMMANDABLE=1 -DBACNET_OBJECT_BINARY_VALUE_COMMANDABLE=1 -DBACNET_OBJECT_MULTISTATE_VALUE_COMMANDABLE=1 -DBACNET_ADDRESS_CACHE_FILE=1"
];
buildPhase = ''
runHook preBuild
cmake --build . --target server readprop writeprop scov whois --parallel $NIX_BUILD_CORES
runHook postBuild
'';
installPhase = ''
mkdir -p $out/bin
install -m755 server $out/bin/bacserv
install -m755 readprop $out/bin/bacrp
install -m755 writeprop $out/bin/bacwp
install -m755 scov $out/bin/bacscov
install -m755 whois $out/bin/bacwi
'';
}
+31
View File
@@ -0,0 +1,31 @@
# Minimal persistent NixOS base system used before the gateway module is added.
{ pkgs, ... }:
{
imports = [ ./hardware-configuration.nix ];
boot.loader.systemd-boot.enable = true;
boot.loader.efi.canTouchEfiVariables = true;
networking.hostName = "seiugw-bootstrap";
networking.useDHCP = true;
networking.firewall.allowedTCPPorts = [ 22 ];
time.timeZone = "Europe/Berlin";
i18n.defaultLocale = "de_DE.UTF-8";
console.keyMap = "de";
services.openssh = {
enable = true;
settings = {
PermitRootLogin = "yes";
PasswordAuthentication = true;
KbdInteractiveAuthentication = false;
};
};
environment.systemPackages = with pkgs; [ git curl vim ];
nix.settings.experimental-features = [ "nix-command" "flakes" ];
system.stateVersion = "26.05";
}
+23
View File
@@ -0,0 +1,23 @@
# Hardware profile for the initial Hyper-V deployment. Filesystems use labels so
# the installation remains independent of the virtual disk's UUIDs.
{ lib, ... }:
{
boot.initrd.availableKernelModules = [ "sd_mod" "sr_mod" ];
fileSystems."/" = {
device = "/dev/disk/by-label/nixos";
fsType = "ext4";
};
fileSystems."/boot" = {
device = "/dev/disk/by-label/EFI";
fsType = "vfat";
options = [ "fmask=0022" "dmask=0022" ];
};
swapDevices = [ { device = "/dev/disk/by-label/swap"; } ];
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
virtualisation.hypervGuest.enable = true;
}
+145
View File
@@ -14,6 +14,16 @@
"version": "5.2.0.1603",
"hash": "sha256-w5T7ekYwVGg+Zs8uolvcWFyY+r9duni0qIigxgHgIdw="
},
{
"pname": "NModbus",
"version": "3.0.83",
"hash": "sha256-V9+Bnt+b4yqRJNPXrDrhOKUqtEllcGPVicqKrthrpgk="
},
{
"pname": "NModbus.Serial",
"version": "3.0.83",
"hash": "sha256-Z6Yk8IozblLq3obdx/GXTqT/hSMTaTf8UkleJpcNYwQ="
},
{
"pname": "SQLitePCLRaw.bundle_e_sqlite3",
"version": "2.1.12",
@@ -38,5 +48,140 @@
"pname": "System.Memory",
"version": "4.5.3",
"hash": "sha256-Cvl7RbRbRu9qKzeRBWjavUkseT2jhZBUWV1SPipUWFk="
},
{
"pname": "System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-G8j9c0erBzZfJAVlW08XoE58gPhiNWJE78sFaBV2e4Q="
},
{
"pname": "runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-BqExVU/zHj7o++mzOpY9y+i9yZZVbcGmO/D4mRzigY8="
},
{
"pname": "BitFaster.Caching",
"version": "2.6.0",
"hash": "sha256-cF3SDKbopdWPiZ7Wrx5Uh7PXxohUoVPAVCkmjeBwPPw="
},
{
"pname": "Microsoft.Extensions.DependencyInjection",
"version": "10.0.8",
"hash": "sha256-eKex/vpm5A4o2WV6sJyjqKPydWhekJFO6wrH0V7RyBY="
},
{
"pname": "Microsoft.Extensions.DependencyInjection.Abstractions",
"version": "10.0.8",
"hash": "sha256-HV30fu+lF/GYkeVP+Yq/EU1FzgdMqwqlepCpvxUgugE="
},
{
"pname": "Microsoft.Extensions.Logging",
"version": "10.0.8",
"hash": "sha256-wcnZWJDQGe6iTd7SIvcbyZLO+Lyc3zCKWlYYP8ovA44="
},
{
"pname": "Microsoft.Extensions.Logging.Abstractions",
"version": "10.0.8",
"hash": "sha256-VruWNhGycjxU2+BxiE++Aw2Tzv50lARcslDp66ImCDE="
},
{
"pname": "Microsoft.Extensions.Options",
"version": "10.0.8",
"hash": "sha256-KHcgAMsOPgjK0ly34mAt3/1hPA4XDSltXUNrEjSNnh8="
},
{
"pname": "Microsoft.Extensions.Primitives",
"version": "10.0.8",
"hash": "sha256-LJFzI1nODfakvP3owQn8xwVKliRxIYs6nl19xAbxKOc="
},
{
"pname": "Newtonsoft.Json",
"version": "13.0.4",
"hash": "sha256-8JCB1FdAW681qXP6DFDWvycu1oPyVoxaYgpJ2pUvZSk="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Client",
"version": "1.5.378.182",
"hash": "sha256-/UD3bbZC4fDNUvR5pP12NxsnFrzASdxho2I2kDqNZqw="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Configuration",
"version": "1.5.378.182",
"hash": "sha256-T71KTHoti4q4hphw/SGFVl8FipOE/MSVXDnTWIz+ee4="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Core",
"version": "1.5.378.182",
"hash": "sha256-Uxk7j7t65dez3rbOiTYQj5FljT7DxLqUs7pwtF4n1pw="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Security.Certificates",
"version": "1.5.378.182",
"hash": "sha256-8SCA9p/Wp1x3hP3wQbAi2jcj+fCcBjlZ6tsLNRLUNSc="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Server",
"version": "1.5.378.182",
"hash": "sha256-wiaT8XHzRaWoH487f4ulJoMZB4rdBoAyOxjlCLrs5ZQ="
},
{
"pname": "OPCFoundation.NetStandard.Opc.Ua.Types",
"version": "1.5.378.182",
"hash": "sha256-3f14kZ6NffAXLT+tcpSfHW0KeIeHp0wGZdBhgsW2IEA="
},
{
"pname": "runtime.linux-arm.runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-m5+od7ZhlzImwSE9E7Qq1nH3A3muXwCnsvrVUoJ7+WE="
},
{
"pname": "runtime.linux-arm64.runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-IgbG3HT3A0VItWl5asE7Hk0zaQjQneKQS9f65cQAjLI="
},
{
"pname": "runtime.linux-x64.runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-44oujSHhc0Nl2WCvLYkScrAyqNAlbGfOnlzPwCofwlA="
},
{
"pname": "runtime.osx-arm64.runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-oFMF60yyTy3fXwLlXJkNUtzdRz4EyxevAUIcfcVESCE="
},
{
"pname": "runtime.osx-x64.runtime.native.System.IO.Ports",
"version": "8.0.0",
"hash": "sha256-b2J9DcunMtChpuyNC0XN39Z01Wr738HI/syJW1n9bfE="
},
{
"pname": "System.Collections.Immutable",
"version": "10.0.8",
"hash": "sha256-HTsGt7wf5O54IXUvy3UeIrzJn+ICRlRbwU60d5YH33I="
},
{
"pname": "System.Diagnostics.DiagnosticSource",
"version": "10.0.8",
"hash": "sha256-WUukX2DEBYxDiJVcGosDMfq16sarrbDGtzq7p5WC7EE="
},
{
"pname": "System.Formats.Asn1",
"version": "10.0.8",
"hash": "sha256-WPATl+pz3/qYhOtp6GQNlWlZpkwUgBpEYPc9taU1VYg="
},
{
"pname": "System.IO.Pipelines",
"version": "10.0.8",
"hash": "sha256-/7LqBohsw/Z6/2tDUKoLjQyR8mEbvk4vU2t83EcB2ag="
},
{
"pname": "System.Text.Encodings.Web",
"version": "10.0.8",
"hash": "sha256-HGgwNazFJc8PPhjA3p4P3Zgc/Zg8KOk+0uruWPHuo3M="
},
{
"pname": "System.Text.Json",
"version": "10.0.8",
"hash": "sha256-RTXz0xPQalhyyRLXiu6reSl+dsUXE58GzjYmPP9+hYU="
}
]
+28
View File
@@ -0,0 +1,28 @@
{ ... }:
{
imports = [
(builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default
];
services.seiugw = {
enable = true;
bacnet.interface = "eth0";
bacnet.deviceInstance = 23;
bacnet.ipPort = 47808;
webPort = 8088;
updates = {
enable = true;
remote = "https://git.portal.se-cloud.de/Hannes/SE-UGW";
};
openFirewall = true;
trends = {
enable = true;
databaseName = "wago";
};
komari = {
enable = true;
endpoint = "https://komari.cloud.se-inno.de";
};
};
}
+269
View File
@@ -0,0 +1,269 @@
"""Apply and confirm per-interface IPv4 profiles using the existing dhcpcd unit."""
import fnmatch
import ipaddress
import json
import os
from pathlib import Path
import re
import socket
import subprocess
import sys
import time
import uuid
BASE = Path(sys.argv[2])
IP = sys.argv[3]
SYSTEMCTL = sys.argv[4]
STATE = Path("/var/lib/seiugw-network")
RUN = Path("/run/seiugw-network")
CONFIRMED = STATE / "profiles.json"
EFFECTIVE = RUN / "dhcpcd.conf"
TRIAL = RUN / "trial"
TRIAL_SECONDS = 120
def atomic_write(path, content, mode=0o600):
temporary = path.with_suffix(".tmp")
with temporary.open("w", encoding="utf-8") as output:
os.fchmod(output.fileno(), mode)
output.write(content)
output.flush()
os.fsync(output.fileno())
temporary.replace(path)
directory = os.open(path.parent, os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
def configuration(profiles):
lines = [BASE.read_text(), "# IPv4 profiles managed by SE-Inno Universalgateway"]
for name, profile in sorted(profiles.items()):
lines.extend(["", f"interface {name}", f"metric {profile['metric']}"])
if profile["mode"] == "static":
lines.append(f"static ip_address={profile['address']}/{profile['prefixLength']}")
if profile["gateway"]:
lines.append(f"static routers={profile['gateway']}")
if profile["dns"]:
lines.append("static domain_name_servers=" + " ".join(profile["dns"]))
return "\n".join(lines) + "\n"
def install(profiles):
atomic_write(EFFECTIVE, configuration(profiles), 0o644)
def configured_profiles():
return json.loads(CONFIRMED.read_text()) if CONFIRMED.exists() else {}
def ip_json(*args):
return json.loads(subprocess.check_output([IP, "-j", "-4", *args], timeout=3))
def inventory():
settings = {}
for line in BASE.read_text().splitlines():
words = line.partition("#")[0].split()
if words and words[0] in ("allowinterfaces", "denyinterfaces"):
settings.setdefault(words[0], []).extend(words[1:])
allowed = settings.get("allowinterfaces", [])
denied = settings.get("denyinterfaces", [])
routes = ip_json("route", "show", "default")
cards = {}
for link in ip_json("address", "show"):
name = link["ifname"]
device = Path("/sys/class/net") / name
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith("-"):
continue
if not (device / "device").exists() or (device / "type").read_text().strip() != "1":
continue
if any(fnmatch.fnmatchcase(name, pattern) for pattern in denied):
continue
if allowed and not any(fnmatch.fnmatchcase(name, pattern) for pattern in allowed):
continue
ipv4 = [{"address": info["local"], "prefixLength": info["prefixlen"],
"dynamic": info.get("dynamic", False)}
for info in link["addr_info"] if info["family"] == "inet" and info.get("scope") == "global"]
cards[name] = {"name": name, "macAddress": (device / "address").read_text().strip(),
"addresses": ipv4, "routes": [route for route in routes if route.get("dev") == name]}
return cards
def unicast(value):
if not isinstance(value, str):
raise ValueError("Eine gültige IPv4-Adresse ist erforderlich.")
address = ipaddress.IPv4Address(value)
if address.is_unspecified or address.is_multicast or address.is_loopback or address.is_reserved:
raise ValueError("Eine nutzbare IPv4-Adresse ist erforderlich.")
return address
def validate(profile, cards, profiles):
name = profile.get("interface")
if not isinstance(name, str) or name not in cards:
raise ValueError("Diese Netzwerkkarte kann nicht verwaltet werden.")
mode = profile.get("mode")
metric = profile.get("metric")
if mode not in ("dhcp", "static") or type(metric) is not int or not 1 <= metric <= 65535:
raise ValueError("Bitte Modus und Routenmetrik (1–65535) prüfen.")
result = {"interface": name, "mode": mode, "metric": metric, "address": None,
"prefixLength": None, "gateway": None, "dns": []}
if mode == "dhcp":
return result
address = unicast(profile.get("address"))
prefix = profile.get("prefixLength")
if type(prefix) is not int or not 1 <= prefix <= 32:
raise ValueError("Die Präfixlänge muss zwischen 1 und 32 liegen.")
subnet = ipaddress.IPv4Network((address, prefix), strict=False)
if prefix <= 30 and address in (subnet.network_address, subnet.broadcast_address):
raise ValueError("Die Adresse darf keine Netz- oder Broadcast-Adresse sein.")
gateway = unicast(profile["gateway"]) if profile.get("gateway") else None
if gateway is not None and (gateway not in subnet or gateway == address or
(prefix <= 30 and gateway in (subnet.network_address, subnet.broadcast_address))):
raise ValueError("Das Standardgateway muss eine andere nutzbare Adresse im selben Subnetz sein.")
dns = profile.get("dns") or []
if not isinstance(dns, list) or len(dns) > 4:
raise ValueError("Bis zu vier IPv4-DNS-Server sind zulässig.")
if any(other != name and (any(item["address"] == str(address) for item in card["addresses"]) or
profiles.get(other, {}).get("address") == str(address)) for other, card in cards.items()):
raise ValueError("Die Adresse ist bereits einer anderen Netzwerkkarte zugeordnet.")
result.update(address=str(address), prefixLength=prefix, gateway=str(gateway) if gateway else None,
dns=list(dict.fromkeys(str(unicast(item)) for item in dns)))
return result
def restart_dhcp():
return subprocess.Popen([SYSTEMCTL, "restart", "dhcpcd.service"])
class NetworkControl:
def __init__(self):
self.profiles = configured_profiles()
self.change = None
self.job = None
self.notice = None
if TRIAL.exists():
self.revert("Nicht bestätigte Netzwerkeinstellungen wurden zurückgesetzt.")
def revert(self, notice):
install(self.profiles)
# Queue another restart even if a previous systemctl client is still waiting.
self.job = restart_dhcp()
self.change = None
self.notice = notice
def tick(self):
now = time.monotonic()
if self.job is not None and self.job.poll() is not None:
success = self.job.returncode == 0
self.job = None
if self.change and not success:
self.revert("Der Netzwerkdienst konnte die Änderung nicht laden. Vorheriges Profil wiederhergestellt.")
elif not self.change:
if success:
TRIAL.unlink(missing_ok=True)
else:
self.notice = "Rücksetzen gespeichert. Der DHCP-Dienst meldet einen Startfehler."
if self.change is None:
return
if now >= self.change["deadline"]:
self.revert("Zeit abgelaufen. Vorheriges Profil wiederhergestellt.")
elif not self.change["started"] and now >= self.change["start"]:
self.change["started"] = True
try:
install(self.profiles | {self.change["profile"]["interface"]: self.change["profile"]})
self.job = restart_dhcp()
except OSError:
self.revert("Netzwerkeinstellungen konnten nicht angewendet werden.")
def status(self, cards):
pending = None
if self.change:
change = self.change
profile = change["profile"]
card = cards.get(profile["interface"], {})
addresses = card.get("addresses", [])
ready = change["started"] and self.job is None and any(
candidate["dynamic"] if profile["mode"] == "dhcp" else
candidate["address"] == profile["address"] and candidate["prefixLength"] == profile["prefixLength"]
for candidate in addresses)
pending = {"id": change["id"], "profile": profile, "ready": ready,
"secondsLeft": max(0, round(change["deadline"] - time.monotonic()))}
return {"interfaces": list(cards.values()), "profiles": self.profiles, "pending": pending,
"busy": self.job is not None, "notice": self.notice}
def handle(self, request):
if not isinstance(request, dict):
raise ValueError("Ungültige Netzwerk-Anfrage.")
action = request.get("action")
cards = inventory()
if action == "apply":
if self.change or self.job:
raise ValueError("Es läuft bereits eine Netzwerkänderung.")
profile = request.get("profile")
if not isinstance(profile, dict):
raise ValueError("Das Netzwerkprofil fehlt.")
profile = validate(profile, cards, self.profiles)
now = time.monotonic()
atomic_write(TRIAL, "pending\n")
self.change = {"id": uuid.uuid4().hex, "profile": profile, "start": now + 2,
"deadline": now + TRIAL_SECONDS, "started": False}
self.notice = None
elif action in ("confirm", "revert"):
if not self.change or self.change["id"] != request.get("id"):
raise ValueError("Diese Netzwerkänderung ist nicht mehr offen.")
if action == "revert":
self.revert("Vorheriges Profil wiederhergestellt.")
else:
if not self.status(cards)["pending"]["ready"]:
raise ValueError("Die neue Adresse ist noch nicht aktiv.")
profile = self.change["profile"]
profiles = self.profiles | {profile["interface"]: profile}
atomic_write(CONFIRMED, json.dumps(profiles))
self.profiles, self.change = profiles, None
TRIAL.unlink(missing_ok=True)
self.notice = "Netzwerkeinstellungen gespeichert."
elif action != "status":
raise ValueError("Ungültige Netzwerkaktion.")
return self.status(cards)
def serve():
control = NetworkControl()
listener = socket.socket(fileno=3) # systemd ListenStream
listener.settimeout(0.5)
while True:
control.tick()
try:
client, _ = listener.accept()
except TimeoutError:
continue
with client:
client.settimeout(2)
try:
request = client.makefile("rb").read(8193)
if len(request) > 8192:
raise ValueError("Netzwerk-Anfrage zu groß.")
result = control.handle(json.loads(request))
except ValueError as error:
result = {"error": str(error)}
except (OSError, subprocess.SubprocessError) as error:
print(error, file=sys.stderr, flush=True)
result = {"error": "Der Netzwerkdienst konnte die Anfrage nicht verarbeiten."}
try:
client.sendall(json.dumps(result).encode())
except OSError:
pass
if __name__ == "__main__":
if sys.argv[1] == "prepare":
# A tentative change exists only in /run; a reboot loads the confirmed profiles.
install(configured_profiles())
else:
serve()
+1 -1
View File
@@ -2,7 +2,7 @@
{
imports = [
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default
(builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default
];
services.seiugw = {
+35
View File
@@ -0,0 +1,35 @@
# Persistent Hyper-V host configuration after the SEIU Gateway source has been
# placed in /etc/nixos/seiugw.
{ pkgs, ... }:
{
imports = [
./hardware-configuration.nix
./seiugw-host.nix
];
boot.loader.systemd-boot.enable = true;
boot.loader.efi.canTouchEfiVariables = true;
networking.hostName = "seiugw-bootstrap";
networking.useDHCP = true;
networking.firewall.allowedTCPPorts = [ 22 ];
time.timeZone = "Europe/Berlin";
i18n.defaultLocale = "de_DE.UTF-8";
console.keyMap = "de";
services.openssh = {
enable = true;
settings = {
PermitRootLogin = "yes";
PasswordAuthentication = true;
KbdInteractiveAuthentication = false;
};
};
environment.systemPackages = with pkgs; [ git curl vim ];
nix.settings.experimental-features = [ "nix-command" "flakes" ];
system.stateVersion = "26.05";
}
+246 -19
View File
@@ -6,6 +6,37 @@ let
cfg = config.services.seiugw;
hostProvisioningRequest = "${cfg.dataDir}/provisioning/host.json";
komariInstalledMarker = "${cfg.dataDir}/provisioning/komari-installed";
komariRuntimeToken = "/run/seiugw-komari/token";
bacnetStackServer = pkgs.callPackage ./bacnet.nix { };
manageHostNetwork = config.networking.useDHCP && config.networking.dhcpcd.enable
&& !config.networking.useNetworkd && !config.networking.networkmanager.enable;
dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart);
networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}";
updateSocket = "/run/seiugw-update/request.sock";
updateAvailability = pkgs.writeShellScript "seiugw-update-availability" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git ]}
export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote}
export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch}
${builtins.readFile ./system-update-availability.sh}
'';
updateWorker = pkgs.writeShellScript "seiugw-system-update" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin
export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"}
export SEIUGW_UPDATE_REPO=${escapeShellArg cfg.updates.checkout}
export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote}
export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch}
export SEIUGW_UPDATE_DATA=${escapeShellArg cfg.dataDir}
export SEIUGW_UPDATE_HEALTH=${escapeShellArg "http://127.0.0.1:${toString cfg.webPort}"}
${builtins.readFile ./system-update.sh}
'';
updateTrigger = pkgs.writeShellScript "seiugw-request-update" ''
if ${pkgs.systemd}/bin/systemd-run --quiet --collect --unit=seiugw-update-worker \
--property=Type=exec ${updateWorker} >&2; then
printf 'accepted\n'
else
printf 'unavailable\n'
fi
'';
in
{
options.services.seiugw = {
@@ -41,6 +72,25 @@ in
description = "Open the configured web and BACnet/IP ports in the NixOS firewall.";
};
updates = {
enable = mkEnableOption "local-root system updates requested by the Gateway administrator";
checkout = mkOption {
type = types.str;
default = "/etc/nixos/seiugw";
description = "Root-owned checkout already used by the NixOS host configuration.";
};
remote = mkOption {
type = types.str;
default = "";
description = "Trusted HTTPS Git URL used by the update worker.";
};
branch = mkOption {
type = types.str;
default = "main";
description = "Branch allowed for fast-forward gateway updates.";
};
};
bacnet = {
interface = mkOption {
type = types.str;
@@ -67,6 +117,12 @@ in
description = "Reserved OPC UA TCP port passed to the gateway.";
};
modbusTcpPorts = mkOption {
type = types.listOf types.port;
default = [ 502 ];
description = "Modbus-TCP ports opened by the NixOS firewall. Add every non-standard port used by a server instance.";
};
trends = {
enable = mkOption {
type = types.bool;
@@ -97,7 +153,7 @@ in
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.";
description = "Root-only import file for a replacement Komari token. Imported into encrypted gateway storage, then removed. Never put plaintext tokens into Nix or Git.";
};
installDir = mkOption {
@@ -121,10 +177,19 @@ in
};
config = mkIf cfg.enable {
assertions = optionals cfg.updates.enable [
{
assertion = builtins.match "https://[^/@]+/[^?#]+" cfg.updates.remote != null;
message = "Gateway system updates require an HTTPS Git remote without embedded credentials.";
}
];
users.groups.seiugw = { };
users.groups.dialout = { };
users.users.seiugw = {
isSystemUser = true;
group = "seiugw";
extraGroups = [ "dialout" ];
home = cfg.dataDir;
createHome = true;
};
@@ -132,15 +197,87 @@ in
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 seiugw seiugw -"
"d ${cfg.dataDir}/provisioning 0750 seiugw seiugw -"
] ++ optionals manageHostNetwork [
"d /run/seiugw-network 0750 root seiugw -"
"d /var/lib/seiugw-network 0700 root root -"
] ++ optionals cfg.komari.enable [
"d ${cfg.komari.installDir} 0750 root root -"
] ++ optionals cfg.updates.enable [
"d /var/lib/seiugw-updater 0755 root root -"
];
systemd.sockets.seiugw-update = mkIf cfg.updates.enable {
description = "Local Gateway system update requests";
wantedBy = [ "sockets.target" ];
socketConfig = {
ListenStream = updateSocket;
SocketUser = "root";
SocketGroup = "seiugw";
SocketMode = "0660";
Accept = true;
RemoveOnStop = true;
};
};
systemd.services."seiugw-update@" = mkIf cfg.updates.enable {
description = "Start the independent Gateway update worker";
serviceConfig = {
ExecStart = updateTrigger;
StandardInput = "socket";
StandardOutput = "socket";
StandardError = "journal";
};
};
networking.firewall = mkIf cfg.openFirewall {
allowedTCPPorts = [ cfg.webPort ];
allowedTCPPorts = [ cfg.webPort cfg.opcUa.port ] ++ cfg.modbusTcpPorts;
allowedUDPPorts = [ cfg.bacnet.ipPort ];
};
# dhcpcd sees the composed file only in its own mount namespace.
# The NixOS base config and options remain the source for unmanaged cards.
systemd.services.dhcpcd = mkIf manageHostNetwork {
requires = [ "seiugw-network-prepare.service" ];
after = [ "seiugw-network-prepare.service" ];
serviceConfig.BindReadOnlyPaths = [ "/run/seiugw-network/dhcpcd.conf:${dhcpcdBase}" ];
};
systemd.services.seiugw-network-prepare = mkIf manageHostNetwork {
description = "Load confirmed SE-Inno IPv4 profiles";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${networkHelper} prepare ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl";
};
};
systemd.sockets.seiugw-network = mkIf manageHostNetwork {
wantedBy = [ "sockets.target" ];
socketConfig = {
ListenStream = "/run/seiugw-network/control.sock";
SocketMode = "0660";
SocketGroup = "seiugw";
RemoveOnStop = true;
};
};
systemd.services.seiugw-network = mkIf manageHostNetwork {
description = "SE-Inno host IPv4 control and rollback";
after = [ "seiugw-network-prepare.service" ];
requires = [ "seiugw-network-prepare.service" ];
serviceConfig = {
ExecStart = "${networkHelper} serve ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl";
Restart = "on-failure";
RestartSec = "1s";
UMask = "0077";
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
NoNewPrivileges = true;
ReadWritePaths = [ "/run/seiugw-network" "/var/lib/seiugw-network" ];
};
};
# 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 {
@@ -174,10 +311,17 @@ in
environment = {
ASPNETCORE_URLS = "http://${cfg.listenAddress}:${toString cfg.webPort}";
Gateway__DataDirectory = cfg.dataDir;
Gateway__ProtocolDataPlane = "native-bacnet-ip";
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;
Gateway__RunningCommit = cfg.package.sourceRevision or "";
} // lib.optionalAttrs cfg.updates.enable {
Gateway__UpdateSocketPath = updateSocket;
Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json";
Gateway__UpdateAvailabilityCommand = updateAvailability;
Gateway__UpdateBranch = cfg.updates.branch;
};
serviceConfig = {
@@ -188,6 +332,56 @@ in
UMask = "0077";
Restart = "on-failure";
RestartSec = "5s";
AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
ReadWritePaths = [ cfg.dataDir ];
};
};
# Native BACnet/IP device. This is a separate, supervised C process from
# the upstream BACnet stack; it owns UDP/47808 rather than relying on a
# web process or Docker networking. Objects and durable priority slots
# are materialised from SQLite by the native bridge.
systemd.services.seiugw-bacnet = {
description = "SEIU native BACnet/IP device";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" "seiugw.service" ];
after = [ "network-online.target" "seiugw.service" ];
# The web unit is Type=simple: ordering alone does not mean its schema
# migration has finished. Wait for the bridge tables on a first upgrade.
preStart = ''
for attempt in {1..30}; do
if [ -f ${escapeShellArg "${cfg.dataDir}/seiugw.db"} ] && \
[ "$(${pkgs.sqlite}/bin/sqlite3 ${escapeShellArg "${cfg.dataDir}/seiugw.db"} "SELECT (SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('bacnet_commands','bacnet_properties','bacnet_observations','bacnet_runtime','bacnet_discovery','bacnet_discovered_devices'))+(SELECT COUNT(*) FROM pragma_table_info('bacnet_discovered_devices') WHERE name IN ('network','mac'))+(SELECT COUNT(*) FROM pragma_table_info('points') WHERE name='deleted_at_utc');" 2>/dev/null)" = 9 ]; then
exit 0
fi
sleep 1
done
echo "Gateway database schema is not ready" >&2
exit 1
'';
environment = {
BACNET_DATALINK = "bip";
SEIUGW_DATABASE = "${cfg.dataDir}/seiugw.db";
BACNET_IFACE = cfg.bacnet.interface;
BACNET_IP_PORT = toString cfg.bacnet.ipPort;
BACNET_IP_BROADCAST_PORT = toString cfg.bacnet.ipPort;
};
serviceConfig = {
ExecStart = "${bacnetStackServer}/bin/bacserv ${toString cfg.bacnet.deviceInstance} SEIU-Gateway";
User = "seiugw";
Group = "seiugw";
WorkingDirectory = cfg.dataDir;
UMask = "0077";
Restart = "on-failure";
RestartSec = "5s";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
@@ -202,9 +396,12 @@ in
# re-applied after every later boot without changing NixOS configuration.
systemd.services.seiugw-apply-hostname = {
description = "Apply SEIU Gateway commissioning hostname";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig.Type = "oneshot";
serviceConfig = {
Type = "oneshot";
};
path = [ pkgs.coreutils pkgs.gnugrep pkgs.hostname pkgs.jq ];
script = ''
set -euo pipefail
@@ -225,6 +422,7 @@ in
host_name="SE-UGW-$project-ISP$(printf '%02d' "$isp")"
[ "''${#host_name}" -le 63 ] || exit 0
[ "$(${pkgs.hostname}/bin/hostname)" != "$host_name" ] || exit 0
${pkgs.hostname}/bin/hostname "$host_name"
'';
};
@@ -232,19 +430,57 @@ in
systemd.paths.seiugw-apply-hostname = {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathExists = hostProvisioningRequest;
PathChanged = hostProvisioningRequest;
Unit = "seiugw-apply-hostname.service";
};
};
systemd.services.seiugw-komari-token = mkIf cfg.komari.enable {
description = "Import and materialize encrypted Komari credential";
wantedBy = [ "multi-user.target" ];
after = [ "seiugw.service" ];
requires = [ "seiugw.service" ];
environment.Gateway__DataDirectory = cfg.dataDir;
serviceConfig = { Type = "oneshot"; UMask = "0077"; Restart = "on-failure"; RestartSec = "10s"; };
script = ''
set -euo pipefail
${pkgs.coreutils}/bin/install -d -m 0700 -o seiugw -g seiugw /run/seiugw-komari
# Stage root's input for the unprivileged database owner. Never print it.
if [ -s ${escapeShellArg cfg.komari.enrollmentTokenFile} ]; then
${pkgs.coreutils}/bin/install -m 0600 -o seiugw -g seiugw ${escapeShellArg cfg.komari.enrollmentTokenFile} /run/seiugw-komari/import
${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --import-komari-token /run/seiugw-komari/import
${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/import ${escapeShellArg cfg.komari.enrollmentTokenFile}
fi
if ${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --materialize-komari-token /run/seiugw-komari/next; then
if ! ${pkgs.diffutils}/bin/cmp -s /run/seiugw-komari/next ${komariRuntimeToken}; then
${pkgs.coreutils}/bin/mv /run/seiugw-komari/next ${komariRuntimeToken}
${pkgs.systemd}/bin/systemctl --no-block try-restart seiugw-komari-agent.service
${pkgs.systemd}/bin/systemctl --no-block restart seiugw-komari-bootstrap.service
else
${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/next
fi
fi
'';
};
systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathChanged = [ "${cfg.dataDir}/provisioning/komari-token.request" cfg.komari.enrollmentTokenFile ];
Unit = "seiugw-komari-token.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" ];
after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
requires = [ "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
# Both prerequisites are already watched by the commissioning path.
# A completed installer must remain active; otherwise PathExists can
# repeatedly start this successful no-op and hit systemd's start limit.
RemainAfterExit = true;
Restart = "on-failure";
RestartSec = "30s";
};
@@ -252,7 +488,7 @@ in
script = ''
set -euo pipefail
marker=${escapeShellArg komariInstalledMarker}
token_file=${escapeShellArg cfg.komari.enrollmentTokenFile}
token_file=${escapeShellArg komariRuntimeToken}
install_dir=${escapeShellArg cfg.komari.installDir}
agent="$install_dir/agent"
[ -e "$marker" ] && exit 0
@@ -281,23 +517,14 @@ in
};
};
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" ];
after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
wants = [ "network-online.target" "seiugw-komari-token.service" ];
wantedBy = [ "multi-user.target" ];
unitConfig.ConditionPathExists = "${cfg.komari.installDir}/agent";
serviceConfig = {
@@ -309,7 +536,7 @@ in
path = [ pkgs.bash pkgs.coreutils ];
script = ''
set -euo pipefail
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg cfg.komari.enrollmentTokenFile})"
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg komariRuntimeToken})"
[ -n "$token" ]
exec ${escapeShellArg "${cfg.komari.installDir}/agent"} -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
'';
+3 -1
View File
@@ -1,4 +1,4 @@
{ lib, buildDotnetModule, dotnetCorePackages }:
{ lib, buildDotnetModule, dotnetCorePackages, sourceRevision ? "" }:
buildDotnetModule {
pname = "seiugw";
@@ -12,6 +12,8 @@ buildDotnetModule {
dotnet-runtime = dotnetCorePackages.aspnetcore_8_0;
executables = [ "Gateway.Api" ];
passthru = { inherit sourceRevision; };
meta = {
description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT";
platforms = lib.platforms.linux;
+30
View File
@@ -0,0 +1,30 @@
set -euo pipefail
umask 077
export GIT_TERMINAL_PROMPT=0 GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1
running=$1
[[ $running =~ ^[0-9a-f]{40}$ ]]
ref="refs/heads/$SEIUGW_UPDATE_BRANCH"
remote="$SEIUGW_UPDATE_REMOTE"
tip=$(timeout --kill-after=1s 8s git ls-remote --exit-code --refs -- "$remote" "$ref")
tip=${tip%%$'\t'*}
[[ $tip =~ ^[0-9a-f]{40}$ ]]
if [[ $tip == "$running" ]]; then
printf 'current %s\n' "$tip"
exit 0
fi
# Check ancestry in a temporary repository. The update worker owns the live checkout.
probe=$(mktemp -d)
trap 'rm -rf -- "$probe"' EXIT
git init --quiet --bare "$probe"
timeout --kill-after=1s 18s git -C "$probe" fetch --quiet --no-tags -- "$remote" "$ref"
tip=$(git -C "$probe" rev-parse FETCH_HEAD)
if [[ $tip == "$running" ]]; then
printf 'current %s\n' "$tip"
elif git -C "$probe" cat-file -e "$running^{commit}" 2>/dev/null &&
git -C "$probe" merge-base --is-ancestor "$running" "$tip"; then
printf 'available %s\n' "$tip"
else
printf 'incompatible %s\n' "$tip"
fi
+166
View File
@@ -0,0 +1,166 @@
set -euo pipefail
umask 077
export GIT_TERMINAL_PROMPT=0
state=/var/lib/seiugw-updater
repo="$SEIUGW_UPDATE_REPO"
profile=/nix/var/nix/profiles/system
database="$SEIUGW_UPDATE_DATA/seiugw.db"
gateway_units=(seiugw.service seiugw-bacnet.service)
commit=""
previous_commit=""
target=""
step="Vorprüfung"
checkout_changed=0
services_stopped=0
activation_started=0
snapshot_ready=0
exec 9>"$state/lock"
flock -n 9
work=$(mktemp -d "$state/run.XXXXXX")
cd "$work"
git_gateway() {
git -C "$repo" -c core.hooksPath=/dev/null "$@"
}
status() {
jq -n --arg phase "$1" --arg message "$2" --arg commit "$commit" --arg target "$target" \
--arg updatedAt "$(date --iso-8601=seconds)" --arg runId "${work##*/}" \
'{phase:$phase,message:$message,commit:$commit,target:$target,updatedAt:$updatedAt,runId:$runId}' >"$work/status.json"
chmod 0644 "$work/status.json"
mv -f "$work/status.json" "$state/status.json"
}
healthy() {
local attempt consecutive=0 heartbeat now
for ((attempt=0; attempt<30; attempt++)); do
now=$(date +%s%3N)
heartbeat=$(runuser -u seiugw -- sqlite3 -readonly -cmd '.timeout 1000' "$database" \
'SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1' 2>/dev/null) || heartbeat=""
if systemctl is-active --quiet seiugw.service &&
systemctl is-active --quiet seiugw-bacnet.service &&
[[ $heartbeat =~ ^[0-9]{13}$ ]] && ((now - heartbeat < 5000)) &&
curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/api/health" |
jq -e '.status == "ok" and .adminConfigured == true' >/dev/null &&
curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/" -o /dev/null; then
((consecutive+=1))
if ((consecutive >= 3)); then return 0; fi
else
consecutive=0
fi
sleep 2
done
return 1
}
finish() {
local code=$? restored=1
trap - EXIT
trap '' HUP INT TERM
if ((code != 0)); then
echo "Gateway update failed during $step (exit $code)." >&2
if ((checkout_changed || services_stopped)); then
status rollingBack "Fehler bei $step. Die vorherige Version wird wiederhergestellt." || true
if ((services_stopped)); then
if systemctl stop "${gateway_units[@]}"; then
if ((snapshot_ready)); then
runuser -u seiugw -- sqlite3 -bail "$database" ".restore '$work/database/gateway.db'" || restored=0
fi
else
restored=0
fi
fi
if ((checkout_changed)); then git_gateway reset --keep "$previous_commit" || restored=0; fi
commit=$previous_commit
if ((activation_started)); then
if [[ $(readlink -f "$profile") != "$previous_system" ]]; then
nix-env --profile "$profile" --set "$previous_system" || restored=0
fi
"$previous_system/bin/switch-to-configuration" switch || restored=0
fi
if ((services_stopped)); then
if ! systemctl start "${gateway_units[@]}" || ! healthy; then restored=0; fi
fi
if ((restored)); then
status rolledBack "Fehler bei $step. Die vorherige Version wurde wiederhergestellt." || true
else
status rollbackFailed "Fehler bei $step. Die Wiederherstellung konnte nicht bestätigt werden." || true
echo "Recovery files kept in $work." >&2
exit "$code"
fi
else
status failed "Fehler bei $step. Die installierte Version läuft weiter." || true
fi
fi
if [[ -d $work/database ]]; then
rm -f -- "$work/database/"{gateway.db,gateway.db-wal,gateway.db-shm,gateway.db-journal}
rmdir -- "$work/database"
fi
rm -f -- "$work/result" "$work/status.json"
rmdir -- "$work"
exit "$code"
}
trap finish EXIT
trap 'exit 130' HUP INT TERM
status checking "Der Repository- und Systemstand wird geprüft."
[[ $(git_gateway rev-parse --show-toplevel) == "$repo" ]]
commit=$(git_gateway rev-parse HEAD)
previous_commit=$commit
[[ $(git_gateway symbolic-ref --short HEAD) == "$SEIUGW_UPDATE_BRANCH" ]]
[[ -z $(git_gateway status --porcelain --untracked-files=all) ]]
previous_system=$(readlink -f /run/current-system)
[[ $(readlink -f "$profile") == "$previous_system" ]]
step="Git-Abruf"
status fetching "Neue Version wird aus Git abgerufen."
timeout 120 git -C "$repo" -c core.hooksPath=/dev/null -c credential.helper= \
fetch --no-tags -- "$SEIUGW_UPDATE_REMOTE" "refs/heads/$SEIUGW_UPDATE_BRANCH"
target=$(git_gateway rev-parse FETCH_HEAD)
if [[ $commit == "$target" ]]; then
status current "Das Gateway ist bereits auf dem aktuellen Stand."
exit 0
fi
if git_gateway merge-base --is-ancestor "$target" "$commit"; then
status unpublished "Die installierte Version ist neuer als der veröffentlichte Stand."
exit 0
fi
git_gateway merge-base --is-ancestor "$commit" "$target"
step="Systembau"
status building "Die neue NixOS-Generation wird gebaut."
checkout_changed=1
git_gateway merge --ff-only "$target"
timeout --kill-after=30s 60m nixos-rebuild build
candidate=$(readlink -f result)
[[ -x $candidate/bin/switch-to-configuration ]]
step="Datenbanksicherung"
status activating "Das Gateway wird kurz angehalten. Die Datenbank wird gesichert."
services_stopped=1
systemctl stop "${gateway_units[@]}"
[[ -f $database ]]
chgrp seiugw "$work"
chmod 0710 "$work"
install -d -o seiugw -g seiugw -m 0700 "$work/database"
runuser -u seiugw -- sqlite3 -bail "$database" ".backup '$work/database/gateway.db'"
[[ $(runuser -u seiugw -- sqlite3 -readonly -bail "$work/database/gateway.db" 'PRAGMA quick_check') == ok ]]
snapshot_ready=1
step="Aktivierung"
status activating "Die neue Version wird aktiviert und geprüft."
activation_started=1
"$candidate/bin/switch-to-configuration" test
[[ $(readlink -f /run/current-system) == "$candidate" ]]
systemctl restart "${gateway_units[@]}"
step="Funktionsprüfung"
healthy
step="Boot-Konfiguration"
nix-env --profile "$profile" --set "$candidate"
"$candidate/bin/switch-to-configuration" boot
[[ $(readlink -f "$profile") == "$candidate" ]]
commit=$target
status succeeded "Die neue Version ist aktiv und für den nächsten Start eingestellt."
@@ -4,6 +4,16 @@ public sealed record SetInitialAdminRequest(string Password, string ProjectNumbe
public sealed record LoginRequest(string Username, string Password);
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAtUtc);
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAtUtc, Gateway.Api.Domain.AuthenticatedGatewayUser User);
public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword);
public sealed record ChangePasswordRequest(string CurrentPassword, string NewPassword, string NewPasswordConfirmation);
public sealed record CreateUserRequest(string Username, string DisplayName, string? Email, string Password, string Role, bool Active = true);
public sealed record UpdateUserRequest(string? Username, string? DisplayName, string? Email, string? Password, string? Role, bool? Active, string? PasswordConfirmation = null);
public sealed record SaveRoleRequest(string Name, string Label, IReadOnlyList<string> Permissions);
public sealed record UpdateKomariEnrollmentTokenRequest(string EnrollmentToken);
public sealed record UpdateUserPreferencesRequest(string? Theme, string? CsvDelimiter, bool? SidebarPinned, decimal? TrendLineWidth);
+11
View File
@@ -0,0 +1,11 @@
namespace Gateway.Api.Domain;
public enum NotificationChannel { Mail, WhatsApp, Ntfy }
public enum AlarmCondition { Active, Inactive, Above, Below }
public sealed record NotificationIntegration(NotificationChannel Channel, string Endpoint, bool HasApiKey);
public sealed record UpdateNotificationKeyRequest(string? ApiKey, bool ClearApiKey = false);
public sealed record AlarmDestination(NotificationChannel Channel, string Recipient, string Template = "stoerung", string PersonName = "SE-Inno", int Priority = 0, string Tags = "alarm");
public sealed record AlarmRule(Guid Id, string Name, Guid PointId, AlarmCondition Condition, double Threshold,
double Hysteresis, bool Enabled, bool NotifyRecovery, string Message, IReadOnlyList<AlarmDestination> Destinations);
public sealed record NotificationDelivery(long Id, Guid RuleId, string Title, string Message,
AlarmDestination Destination, string State, DateTimeOffset CreatedAtUtc, string? Result);
+73
View File
@@ -0,0 +1,73 @@
namespace Gateway.Api.Domain;
/// <summary>A reusable group of trend logs, equivalent to an LTD saved selection.</summary>
public sealed record GatewayTrendSelection(
Guid Id,
string Name,
string? Description,
Guid OwnerId,
bool Shared,
IReadOnlyList<Guid> TrendLogIds,
DateTimeOffset CreatedAtUtc,
DateTimeOffset UpdatedAtUtc);
public sealed record CreateTrendSelectionRequest(string Name, string? Description, bool Shared, IReadOnlyList<Guid> TrendLogIds);
public sealed record UpdateTrendSelectionRequest(string? Name, string? Description, bool? Shared, IReadOnlyList<Guid>? TrendLogIds);
/// <summary>Scheduled CSV export and optional mail dispatch for one saved selection.</summary>
public sealed record CsvRunnerJob(
Guid Id,
string Name,
Guid SelectionId,
string Time,
int RangeHours,
string Delimiter,
bool Enabled,
bool MailEnabled,
string? MailTo,
string MailSubject,
string MailMessage,
string? LastRunLocalDate,
CsvRunnerJobResult? LastResult,
DateTimeOffset CreatedAtUtc,
DateTimeOffset UpdatedAtUtc);
public sealed record CsvRunnerJobResult(bool Success, string? FilePath, string? Error, DateTimeOffset RanAtUtc);
public sealed record CsvRunnerExecution(Guid Id, Guid JobId, string Name, string State, DateTimeOffset EnqueuedAtUtc);
public sealed record CreateCsvRunnerJobRequest(
string Name,
Guid SelectionId,
string Time,
int RangeHours,
string Delimiter,
bool Enabled,
bool MailEnabled,
string? MailTo,
string? MailSubject,
string? MailMessage);
public sealed record UpdateCsvRunnerJobRequest(
string? Name,
Guid? SelectionId,
string? Time,
int? RangeHours,
string? Delimiter,
bool? Enabled,
bool? MailEnabled,
string? MailTo,
string? MailSubject,
string? MailMessage);
public sealed record MailIntegrationView(bool MailConfigured, string Endpoint);
public sealed record UpdateMailIntegrationRequest(string? ApiKey, bool ClearApiKey = false);
public sealed record TrendExportRow(
DateTimeOffset TimestampUtc,
string TrendLogName,
uint BacnetObjectInstance,
string PointName,
System.Text.Json.JsonElement Value,
PointProtocol SourceProtocol,
string? Status,
string Unit = "");
+57 -4
View File
@@ -9,7 +9,9 @@ public sealed record GatewayConfiguration(
IReadOnlyList<ModbusServerConfiguration> ModbusServers,
KnxConfiguration Knx,
MqttConfiguration? Mqtt = null,
InstallationIdentity? Installation = null)
InstallationIdentity? Installation = null,
IReadOnlyList<SerialPortConfiguration>? SerialPorts = null,
IReadOnlyList<ModbusRtuServerConfiguration>? ModbusRtuServers = null)
{
public static GatewayConfiguration CreateDefault(int deviceInstance, int bacnetPort, int opcUaPort, string interfaceName) => new(
VendorId: 815,
@@ -20,7 +22,9 @@ public sealed record GatewayConfiguration(
ModbusServers: [],
Knx: new KnxConfiguration(false, false),
Mqtt: MqttConfiguration.CreateDefault(),
Installation: null);
Installation: null,
SerialPorts: [],
ModbusRtuServers: []);
}
/// <summary>
@@ -52,7 +56,26 @@ public sealed record OpcUaConfiguration(
int Port,
bool ClientEnabled,
bool ServerEnabled,
bool AllowAnonymous);
bool AllowAnonymous,
IReadOnlyList<OpcUaClientConfiguration>? Clients = null);
public enum OpcUaAuthenticationMode
{
Anonymous,
Username,
Certificate
}
public sealed record OpcUaClientConfiguration(
Guid Id,
string Name,
string EndpointUrl,
OpcUaAuthenticationMode AuthenticationMode,
string? Username,
bool AcceptUntrustedServerCertificate = false,
bool Enabled = true,
bool UseSecurity = true,
int PublishingIntervalMilliseconds = 1000);
public sealed record ModbusServerConfiguration(
Guid Id,
@@ -64,7 +87,37 @@ public sealed record ModbusServerConfiguration(
int HoldingRegisterCount,
IReadOnlyList<string> AllowedClientIps);
public sealed record KnxConfiguration(bool Enabled, bool Secure);
/// <summary>Named serial interface. The device path remains a Linux path such as /dev/ttyUSB0.</summary>
public sealed record SerialPortConfiguration(
Guid Id,
string Alias,
string DevicePath,
int BaudRate,
string Parity,
int DataBits,
int StopBits);
/// <summary>Modbus RTU slave configuration addressed through a configured serial alias.</summary>
public sealed record ModbusRtuServerConfiguration(
Guid Id,
string Name,
string SerialPortAlias,
int UnitId,
int FirstHoldingRegister,
int HoldingRegisterCount);
public enum KnxTransport
{
Ip,
Tp
}
public sealed record KnxConfiguration(
bool Enabled,
bool Secure,
KnxTransport Transport = KnxTransport.Ip,
string? SerialPortAlias = null,
string? LocalIpAddress = null);
public sealed record MqttConfiguration(
bool Enabled,
+53
View File
@@ -0,0 +1,53 @@
namespace Gateway.Api.Domain;
/// <summary>Locally managed account. Password material never leaves the store.</summary>
public sealed record GatewayUser(
Guid Id,
string Username,
string DisplayName,
string? Email,
string Role,
bool Active,
DateTimeOffset CreatedAtUtc,
DateTimeOffset UpdatedAtUtc);
public sealed record GatewayRole(
string Name,
string Label,
IReadOnlyList<string> Permissions,
bool IsSystem,
DateTimeOffset UpdatedAtUtc);
public sealed record AuthenticatedGatewayUser(
GatewayUser User,
IReadOnlyList<string> Permissions);
/// <summary>Personal presentation settings, kept server-side like the former LTD UI.</summary>
public sealed record GatewayUserPreferences(
string Theme,
string CsvDelimiter,
bool SidebarPinned,
decimal TrendLineWidth,
DateTimeOffset UpdatedAtUtc);
public static class GatewayPermissions
{
public const string ViewDashboard = "view_dashboard";
public const string ViewTrends = "view_trends";
public const string EditAliases = "edit_aliases";
public const string ManageSources = "manage_sources";
public const string ViewDebug = "view_debug";
public const string ManageAlarms = "manage_alarms";
public const string ManageUsers = "manage_users";
public const string ManageRoles = "manage_roles";
public const string ManageIntegrations = "manage_integrations";
public const string ManageRunner = "manage_runner";
public const string ManageGateway = "manage_gateway";
public static readonly IReadOnlyList<string> Catalog =
[
ViewDashboard, ViewTrends, EditAliases, ManageSources, ViewDebug,
ManageAlarms, ManageUsers, ManageRoles, ManageIntegrations,
ManageRunner, ManageGateway
];
}
+19 -5
View File
@@ -5,7 +5,8 @@ namespace Gateway.Api.Domain;
public enum MqttMappingFormat
{
SeMonitoring,
Json
Json,
SingleTopic
}
public enum MqttDirection
@@ -20,7 +21,8 @@ public enum SeMonitoringCategory
Analog,
Notify,
Alarm,
Setpoints
Setpoints,
Alarms
}
public enum MqttQualityOfService
@@ -44,7 +46,8 @@ public sealed record MqttMapping(
string? TopicName,
string? JsonTopic,
string? JsonProperty,
DateTimeOffset CreatedAtUtc);
DateTimeOffset CreatedAtUtc,
string? TopicTemplate = null);
public sealed record CreateMqttMappingRequest(
Guid PointId,
@@ -58,7 +61,8 @@ public sealed record CreateMqttMappingRequest(
SeMonitoringCategory? SeCategory,
string? TopicName,
string? JsonTopic,
string? JsonProperty);
string? JsonProperty,
string? TopicTemplate = null);
public sealed record UpdateMqttConfigurationRequest(
MqttConfiguration Configuration,
@@ -67,6 +71,14 @@ public sealed record UpdateMqttConfigurationRequest(
public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool HasPassword);
public sealed record MqttMonitoringSite(int? ProjectYear, string? ProjectNumber, string? IspNumber);
public sealed record MqttPointDefaults(Guid PointId, SeMonitoringCategory? Category, string TopicName);
public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList<MqttPointDefaults> Points, MqttTopicTemplateView TopicTemplate);
public sealed record MqttTopicPlaceholder(string Token, string Description);
public sealed record MqttTopicTemplateView(string Template, string DefaultTemplate, IReadOnlyList<MqttTopicPlaceholder> Placeholders,
IReadOnlyDictionary<string, string> PreviewValues);
public sealed record UpdateMqttTopicTemplateRequest(string Template);
public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc);
public sealed record MqttClientStatus(
@@ -76,4 +88,6 @@ public sealed record MqttClientStatus(
string? LastError,
DateTimeOffset? ConnectedAtUtc,
DateTimeOffset? LastReceivedAtUtc,
DateTimeOffset? LastPublishedAtUtc);
DateTimeOffset? LastPublishedAtUtc,
string? LastFailure = null,
DateTimeOffset? LastFailureAtUtc = null);
+7 -1
View File
@@ -67,12 +67,18 @@ public sealed record CreatePointRequest(
BacnetObjectKind? BacnetObjectKind = null,
uint? BacnetObjectInstance = null);
public sealed record PointDependencies(int Mappings, int MqttMappings, int Alarms, int TrendLogs)
{
public string Confirmation => $"{Mappings}-{MqttMappings}-{Alarms}-{TrendLogs}";
}
public sealed record PointValue(
Guid PointId,
JsonElement Value,
PointProtocol SourceProtocol,
DateTimeOffset UpdatedAtUtc,
string? Status);
string? Status,
Guid? OriginPointId = null);
public enum MappingDirection
{
+5
View File
@@ -0,0 +1,5 @@
namespace Gateway.Api.Domain;
public sealed record DisplayUnit(string Symbol, string Name, bool IsSystem = false);
public sealed record PointPresentation(Guid PointId, string Alias, string Unit, double Factor, string Kind, string Color);
public sealed record DashboardWidget(Guid Id, string Title, Guid SelectionId, int RangeHours, string Type);
+3 -1
View File
@@ -11,6 +11,7 @@ public sealed record GatewayTrendLog(
int IntervalSeconds,
int MaxRecords,
bool Enabled,
bool IsPublic,
DateTimeOffset CreatedAtUtc);
public sealed record CreateTrendLogRequest(
@@ -19,7 +20,8 @@ public sealed record CreateTrendLogRequest(
uint BacnetObjectInstance,
int IntervalSeconds,
int MaxRecords,
bool Enabled);
bool Enabled,
bool IsPublic = false);
public sealed record TrendRecord(
Guid TrendLogId,
+11
View File
@@ -2,5 +2,16 @@
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.31" />
<PackageReference Include="MQTTnet" Version="5.2.0.1603" />
<PackageReference Include="NModbus" Version="3.0.83" />
<PackageReference Include="NModbus.Serial" Version="3.0.83" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.5.378.182" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.378.182" />
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Content Include="../../*.md" TargetPath="Documentation/%(Filename)%(Extension)"
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../docs/**/*.md" TargetPath="Documentation/docs/%(RecursiveDir)%(Filename)%(Extension)"
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -3,6 +3,11 @@ namespace Gateway.Api.Options;
public sealed class GatewayOptions
{
public string DataDirectory { get; init; } = "data";
public string? RunningCommit { get; init; }
public string? UpdateSocketPath { get; init; }
public string? UpdateStatusPath { get; init; }
public string? UpdateAvailabilityCommand { get; init; }
public string UpdateBranch { get; init; } = "main";
public BacnetBootstrapOptions Bacnet { get; init; } = new();
+567 -25
View File
@@ -1,24 +1,85 @@
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Gateway.Api.Contracts;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
var builder = WebApplication.CreateBuilder(args);
// The service keeps its mutable data in /var/lib/seiugw on NixOS. Static web
// assets, however, are published beside this executable in the immutable Nix
// store. Explicitly use the executable directory as the content/web root so
// the web UI is available no matter which working directory systemd uses.
var applicationRoot = AppContext.BaseDirectory;
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ContentRootPath = applicationRoot,
WebRootPath = Path.Combine(applicationRoot, "wwwroot")
});
builder.Services.Configure<GatewayOptions>(builder.Configuration.GetSection("Gateway"));
builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddSingleton<GatewayDatabase>();
builder.Services.AddSingleton<PasswordService>();
builder.Services.AddSingleton<SessionService>();
builder.Services.AddSingleton<SystemUpdateService>();
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("system-update-password", context =>
{
var user = context.RequestServices.GetRequiredService<SessionService>().GetUser(context.Request.Headers.Authorization);
return RateLimitPartition.GetFixedWindowLimiter(user?.User.Id.ToString() ?? "anonymous", _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1)
});
});
});
builder.Services.AddSingleton<MappingValidator>();
builder.Services.AddSingleton<WriteJournal>();
builder.Services.AddSingleton<SecretProtector>();
builder.Services.AddSingleton<GatewayStore>();
builder.Services.AddSingleton<GatewayDocumentation>();
builder.Services.AddSingleton<HardwareDiscoveryService>();
builder.Services.AddSingleton<HostNetworkService>();
builder.Services.AddSingleton<BacnetBrowserService>();
builder.Services.AddHostedService<BacnetExternalPointService>();
builder.Services.AddHttpClient("seiugw-notifications", client => { client.Timeout = TimeSpan.FromSeconds(10); client.MaxResponseContentBufferSize = 64 * 1024; })
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddSingleton<NotificationTransport>();
builder.Services.AddHostedService<AlarmNotificationService>();
builder.Services.AddSingleton<CsvRunnerService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<CsvRunnerService>());
builder.Services.AddSingleton<MqttClientService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MqttClientService>());
builder.Services.AddSingleton<MqttTopicBrowserService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MqttTopicBrowserService>());
builder.Services.AddSingleton<MappingRuntimeService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<MappingRuntimeService>());
builder.Services.AddSingleton<ModbusProtocolService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<ModbusProtocolService>());
builder.Services.AddSingleton<OpcUaApplicationFactory>();
builder.Services.AddSingleton<OpcUaBrowserService>();
builder.Services.AddSingleton<OpcUaServerService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<OpcUaServerService>());
builder.Services.AddSingleton<OpcUaClientService>();
builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<OpcUaClientService>());
builder.Services.AddHostedService<BacnetNativeBridgeService>();
var app = builder.Build();
app.Services.GetRequiredService<GatewayStore>().Initialize();
var commandStore = app.Services.GetRequiredService<GatewayStore>();
if (args.Length == 2 && args[0] == "--materialize-komari-token")
{
Environment.ExitCode = commandStore.MaterializeKomariEnrollmentToken(args[1]) ? 0 : 1;
return;
}
if (args.Length == 2 && args[0] == "--import-komari-token")
{
commandStore.ImportKomariEnrollmentTokenFile(args[1]);
return;
}
commandStore.Initialize();
app.Use(async (context, next) =>
{
@@ -35,12 +96,141 @@ app.Use(async (context, next) =>
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseRateLimiter();
app.MapGet("/api/system/update", (HttpRequest request, HttpResponse response, SessionService sessions, SystemUpdateService updates) =>
{
var user = sessions.GetUser(request.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store";
return Results.Ok(updates.GetStatus() with { RunningCommit = updates.RunningCommit });
});
app.MapGet("/api/system/update/availability", async (bool? refresh, HttpRequest request, HttpResponse response, SessionService sessions,
SystemUpdateService updates, CancellationToken cancellationToken) =>
{
var user = sessions.GetUser(request.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store";
return Results.Ok(await updates.CheckAvailabilityAsync(refresh == true, cancellationToken));
});
app.MapPost("/api/system/update", async (SystemUpdateRequest request, HttpRequest http, SessionService sessions,
GatewayStore store, SystemUpdateService updates, CancellationToken cancellationToken) =>
{
var user = sessions.GetUser(http.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
if (!updates.Enabled) return Results.Conflict(new { error = "Der lokale Systemupdate-Dienst ist nicht eingerichtet." });
if (request.Password is not { Length: > 0 and <= 512 } || store.Authenticate(user.Username, request.Password)?.User.Id != user.Id)
return Results.Json(new { error = "Das Administrator-Passwort stimmt nicht." }, statusCode: StatusCodes.Status403Forbidden);
if (!await updates.StartAsync(cancellationToken))
return Results.Conflict(new { error = "Ein Update läuft bereits oder der Systemupdate-Dienst ist nicht erreichbar." });
return Results.Accepted("/api/system/update", new SystemUpdateStatus("queued", "Der Systemdienst hat das Update angenommen."));
}).RequireRateLimiting("system-update-password");
app.MapGet("/api/docs", (HttpRequest request, SessionService sessions, GatewayDocumentation docs) =>
sessions.IsValid(request.Headers.Authorization) ? Results.Ok(docs.Entries) : Results.Unauthorized());
app.MapGet("/api/docs/content", (string path, HttpRequest request, SessionService sessions, GatewayDocumentation docs) =>
{
if (!sessions.IsValid(request.Headers.Authorization)) return Results.Unauthorized();
return docs.Find(path) is { } file ? Results.Ok(file) : Results.NotFound();
});
app.MapGet("/api/presentation", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
? Results.Ok(new { units = store.ListDisplayUnits(), points = store.ListPointPresentations() }) : Results.Unauthorized());
app.MapPut("/api/presentation/units", (DisplayUnit unit, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases)
? Results.Ok(store.SaveDisplayUnit(unit)) : Results.StatusCode(403));
app.MapPut("/api/presentation/points", (PointPresentation[] points, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases)) return Results.StatusCode(403);
store.SavePointPresentations(points);
return Results.NoContent();
});
app.MapGet("/api/dashboard", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Contains(GatewayPermissions.ViewDashboard)
? Results.Ok(store.GetDashboard(user.User.Id)) : Results.StatusCode(403));
app.MapPut("/api/dashboard", (DashboardWidget[] widgets, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (sessions.GetUser(request.Headers.Authorization) is not { } user || !user.Permissions.Contains(GatewayPermissions.ViewDashboard)) return Results.StatusCode(403);
store.SaveDashboard(user.User.Id, user.User.Role == "admin", widgets);
return Results.NoContent();
});
app.MapGet("/api/points/catalog", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Any(permission => permission is GatewayPermissions.ManageSources or GatewayPermissions.EditAliases or GatewayPermissions.ManageAlarms or GatewayPermissions.ManageIntegrations)
? Results.Ok(store.ListPoints().Select(point => new { point.Id, point.DisplayName, point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable })) : Results.StatusCode(403));
app.MapGet("/api/points/status", (HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt,
OpcUaClientService opcUaClient, OpcUaServerService opcUaServer, ModbusProtocolService modbus) =>
{
var auth = request.Headers.Authorization;
var gateway = sessions.HasPermission(auth, GatewayPermissions.ManageGateway);
var sources = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageSources);
var integrations = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageIntegrations);
if (!sources && !integrations) return Results.StatusCode(403);
var configuration = store.GetGatewayConfiguration();
var clientStatus = opcUaClient.GetStatus().ToDictionary(client => client.ClientId);
var pointNames = sources ? store.ListPoints().ToDictionary(point => point.Id, point => point.DisplayName) : [];
return Results.Ok(new
{
checkedAtUtc = DateTimeOffset.UtcNow,
mqtt = integrations ? mqtt.GetStatus() : null,
bacnet = sources ? store.GetBacnetNativeStatus() : null,
opcUa = sources ? new
{
serverEnabled = configuration.OpcUa.ServerEnabled,
server = opcUaServer.GetStatus(),
clientsEnabled = configuration.OpcUa.ClientEnabled,
clients = (configuration.OpcUa.Clients ?? []).Select(client => new { client.Id, client.Name, client.Enabled, status = clientStatus.GetValueOrDefault(client.Id) })
} : null,
modbus = sources ? new
{
servers = configuration.ModbusServers.Select(server => new { server.Name, server.Port, listening = modbus.IsTcpListening(server), error = modbus.GetTcpError(server.Id) }),
pointErrors = modbus.GetPointErrors().Where(issue => pointNames.ContainsKey(issue.Id)).OrderByDescending(issue => issue.OccurredAtUtc)
.Select(issue => new { pointId = issue.Id, name = pointNames[issue.Id], issue.Error, issue.OccurredAtUtc }).ToArray()
} : null,
pointErrors = sources ? store.ListPointValues()
.Where(value => pointNames.ContainsKey(value.PointId) && value.Status is { Length: > 0 } quality &&
!quality.Equals("Good", StringComparison.OrdinalIgnoreCase) && !quality.Equals("ok", StringComparison.OrdinalIgnoreCase))
.Select(value => new { value.PointId, name = pointNames[value.PointId], value.SourceProtocol, value.Status, value.UpdatedAtUtc }).ToArray() : null
});
});
app.MapGet("/api/integrations/notifications", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms)
? Results.Ok(store.ListNotificationIntegrations()) : Results.StatusCode(403));
app.MapPut("/api/integrations/notifications/{channel}", (NotificationChannel channel, UpdateNotificationKeyRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
store.UpdateNotificationKey(channel, update);
return Results.NoContent();
});
app.MapGet("/api/alarms", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListAlarmRules()) : Results.StatusCode(403));
app.MapPut("/api/alarms", (AlarmRule rule, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.SaveAlarmRule(rule)) : Results.StatusCode(403));
app.MapDelete("/api/alarms/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms)) return Results.StatusCode(403);
store.DeleteAlarmRule(id);
return Results.NoContent();
});
app.MapGet("/api/alarms/deliveries", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListNotificationDeliveries()) : Results.StatusCode(403));
app.MapGet("/api/health", (GatewayStore store) => Results.Ok(new
{
status = "ok",
adminConfigured = store.HasAdmin(),
protocolDataPlane = "not-started"
protocolDataPlane = builder.Configuration["Gateway:ProtocolDataPlane"] ?? "not-started"
}));
app.MapGet("/api/setup", (GatewayStore store) => Results.Ok(new { adminConfigured = store.HasAdmin() }));
@@ -53,15 +243,21 @@ app.MapPost("/api/setup", (SetInitialAdminRequest request, GatewayStore store) =
app.MapPost("/api/auth/login", (LoginRequest request, GatewayStore store, SessionService sessions) =>
{
if (request.Username != "admin" || !store.VerifyAdminPassword(request.Password))
var user = store.Authenticate(request.Username, request.Password);
if (user is null)
{
return Results.Unauthorized();
}
var token = sessions.Create();
return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12)));
var token = sessions.Create(user);
return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12), user));
});
app.MapGet("/api/auth/me", (HttpRequest request, SessionService sessions) =>
sessions.GetUser(request.Headers.Authorization) is { } user
? Results.Ok(new { user })
: Results.Unauthorized());
app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) =>
{
sessions.Remove(request.Headers.Authorization);
@@ -70,24 +266,99 @@ app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) =
app.MapPost("/api/auth/password", (ChangePasswordRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(httpRequest.Headers.Authorization))
if (sessions.GetUser(httpRequest.Headers.Authorization) is not { } user)
{
return Results.Unauthorized();
}
store.ChangeAdminPassword(request.CurrentPassword, request.NewPassword);
if (string.IsNullOrEmpty(request.NewPasswordConfirmation) ||
!string.Equals(request.NewPassword, request.NewPasswordConfirmation, StringComparison.Ordinal))
{
return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." });
}
store.ChangeUserPassword(user.User.Id, request.CurrentPassword, request.NewPassword);
sessions.Remove(httpRequest.Headers.Authorization);
return Results.NoContent();
});
app.MapGet("/api/auth/preferences", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.GetUser(request.Headers.Authorization) is { } user
? Results.Ok(store.GetUserPreferences(user.User.Id))
: Results.Unauthorized());
app.MapPut("/api/auth/preferences", (UpdateUserPreferencesRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.GetUser(request.Headers.Authorization) is { } user
? Results.Ok(store.UpdateUserPreferences(user.User.Id, update))
: Results.Unauthorized());
app.MapGet("/api/system/komari", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
? Results.Ok(new { hasEnrollmentToken = store.HasKomariEnrollmentToken() })
: Results.Unauthorized());
app.MapPut("/api/system/komari", (UpdateKomariEnrollmentTokenRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(httpRequest.Headers.Authorization, GatewayPermissions.ManageGateway))
{
return Results.Unauthorized();
}
store.UpdateKomariEnrollmentToken(request.EnrollmentToken);
return Results.NoContent();
});
app.MapGet("/api/users", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers)
? Results.Ok(store.ListUsers())
: Results.Unauthorized());
app.MapPost("/api/users", (CreateUserRequest user, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers))
{
return Results.Unauthorized();
}
var created = store.CreateUser(user);
return Results.Created($"/api/users/{created.Id}", created);
});
app.MapPatch("/api/users/{userId:guid}", (Guid userId, UpdateUserRequest update, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
var actingUser = sessions.GetUser(request.Headers.Authorization);
if (actingUser is null || !actingUser.Permissions.Contains(GatewayPermissions.ManageUsers, StringComparer.Ordinal))
{
return Results.Unauthorized();
}
if (update.Password is not null &&
!string.Equals(update.Password, update.PasswordConfirmation, StringComparison.Ordinal))
{
return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." });
}
return Results.Ok(store.UpdateUser(userId, update, actingUser.User.Id));
});
app.MapGet("/api/roles", (HttpRequest request, GatewayStore store, SessionService sessions) =>
(sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers))
? Results.Ok(new { roles = store.ListRoles(), permissions = GatewayPermissions.Catalog })
: Results.Unauthorized());
app.MapPost("/api/roles", (SaveRoleRequest role, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles))
{
return Results.Unauthorized();
}
var saved = store.SaveRole(role);
return Results.Created($"/api/roles/{saved.Name}", saved);
});
app.MapGet("/api/gateway/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
? Results.Ok(store.GetGatewayConfiguration())
: Results.Unauthorized());
app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway))
{
return Results.Unauthorized();
}
@@ -96,14 +367,60 @@ app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, Ht
return Results.NoContent();
});
app.MapGet("/api/gateway/hardware", (HttpRequest request, HardwareDiscoveryService hardware, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
? Results.Ok(hardware.GetInventory())
: Results.Unauthorized());
app.MapPut("/api/gateway/installation", (InstallationIdentity identity, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)
? Results.Ok(store.UpdateInstallationIdentity(identity)) : Results.StatusCode(403));
var network = app.MapGroup("/api/system/network");
network.AddEndpointFilter(async (context, next) =>
{
var http = context.HttpContext;
return http.RequestServices.GetRequiredService<SessionService>()
.HasPermission(http.Request.Headers.Authorization, GatewayPermissions.ManageGateway)
? await next(context) : Results.StatusCode(403);
});
network.MapGet("", (HostNetworkService service, CancellationToken ct) => service.SendAsync(new { action = "status" }, ct));
network.MapPost("/apply", (HostNetworkProfile profile, HostNetworkService service, CancellationToken ct) =>
service.SendAsync(new { action = "apply", profile }, ct));
network.MapPost("/confirm", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) =>
service.SendAsync(new { action = "confirm", change.Id }, ct));
network.MapPost("/revert", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) =>
service.SendAsync(new { action = "revert", change.Id }, ct));
app.MapPost("/api/bacnet/scan", async (BacnetScanRequest scan, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized();
return Results.Ok(await browser.ScanAsync(scan, cancellationToken));
});
app.MapPost("/api/bacnet/browse", async (BacnetBrowseRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized();
return Results.Ok(await browser.BrowseObjectListAsync(browse, cancellationToken));
});
app.MapPost("/api/bacnet/objects", async (BacnetObjectsRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return Results.Ok(await browser.BrowseDetailsAsync(browse, cancellationToken));
});
app.MapPost("/api/bacnet/import", async (BacnetImportRequest import, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return Results.Ok(await browser.ImportAsync(import, cancellationToken));
});
app.MapGet("/api/points", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.ListPoints())
: Results.Unauthorized());
app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
@@ -111,54 +428,153 @@ app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, Gatew
var createdPoint = store.CreatePoint(point);
return Results.Created($"/api/points/{createdPoint.Id}", createdPoint);
});
app.MapGet("/api/points/{id:guid}/dependencies", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return store.GetPointDependencies(id) is { } dependencies ? Results.Ok(dependencies) : Results.NotFound();
});
app.MapPut("/api/points/{id:guid}", (Guid id, CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return store.UpdatePoint(id, point) is { } updated ? Results.Ok(updated) : Results.NotFound();
});
app.MapDelete("/api/points/{id:guid}", (Guid id, string? confirmation, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return store.DeletePoint(id, confirmation) ? Results.NoContent() : Results.NotFound();
});
app.MapGet("/api/imports/modbus-example.csv", (HttpRequest request, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.File(System.Text.Encoding.UTF8.GetBytes(ModbusCsvImporter.Example), "text/csv; charset=utf-8", "seiugw-modbus-beispiel.csv")
: Results.Unauthorized());
app.MapPost("/api/imports/modbus-csv", (ModbusCsvImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
return Results.Ok(ModbusCsvImporter.Import(import.Csv, store));
});
app.MapPost("/api/imports/knx-ets", (KnxEtsImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
return Results.Ok(KnxEtsImporter.Import(import, store));
});
app.MapPost("/api/opcua/browse", async (OpcUaBrowseRequest browse, HttpRequest request, OpcUaBrowserService browser, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
return Results.Ok(await browser.BrowseAsync(browse));
});
app.MapGet("/api/opcua/clients", (HttpRequest request, GatewayStore store, OpcUaClientService clients, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(new { clients = store.ListOpcUaClients(), status = clients.GetStatus() }) : Results.Unauthorized());
app.MapGet("/api/bacnet/status", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.GetBacnetNativeStatus()) : Results.Unauthorized());
app.MapPost("/api/opcua/clients", (SaveOpcUaClientRequest configuration, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.SaveOpcUaClient(configuration)) : Results.Unauthorized());
app.MapPost("/api/opcua/import", (OpcUaImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.ImportOpcUaPoints(import)) : Results.Unauthorized());
app.MapGet("/api/mqtt/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.GetMqttConfiguration())
: Results.Unauthorized());
app.MapPut("/api/mqtt/configuration", (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
app.MapPut("/api/mqtt/configuration", async (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store,
SessionService sessions, MqttClientService mqttClient, MqttTopicBrowserService browser) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations))
{
return Results.Unauthorized();
}
store.UpdateMqttConfiguration(mqtt);
mqttClient.RequestReconfigure();
await browser.ResetAsync(CancellationToken.None);
return Results.NoContent();
});
app.MapPost("/api/mqtt/browser", async (MqttTopicBrowseRequest browse, HttpRequest request, SessionService sessions,
MqttTopicBrowserService browser, CancellationToken cancellationToken) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(await browser.StartBrowseAsync(browse, cancellationToken)) : Results.StatusCode(403));
app.MapGet("/api/mqtt/browser/{id:guid}", (Guid id, HttpRequest request, SessionService sessions, MqttTopicBrowserService browser) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(browser.GetBrowse(id)) : Results.StatusCode(403));
app.MapPost("/api/mqtt/browser/import", async (MqttTopicImportRequest import, HttpRequest request, SessionService sessions,
MqttTopicBrowserService browser, CancellationToken cancellationToken) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) &&
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(await browser.ImportAsync(import, cancellationToken)) : Results.StatusCode(403));
app.MapGet("/api/mqtt/status", (HttpRequest request, SessionService sessions, MqttClientService mqttClient) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(mqttClient.GetStatus())
: Results.Unauthorized());
app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.ListMqttMappings().Select(mapping => new { Mapping = mapping, Topic = GatewayStore.GetMqttTopic(mapping) }))
: Results.Unauthorized());
app.MapGet("/api/mqtt/mapping-defaults", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.GetMqttMappingDefaults()) : Results.StatusCode(403));
app.MapPut("/api/mqtt/topic-template", (UpdateMqttTopicTemplateRequest template, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)
? Results.Ok(store.UpdateMqttTopicTemplate(template.Template)) : Results.StatusCode(403));
app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations))
{
return Results.Unauthorized();
}
var createdMapping = store.CreateMqttMapping(mapping);
if (createdMapping.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([createdMapping.Id]);
mqttClient.RequestReconfigure();
return Results.Created($"/api/mqtt/mappings/{createdMapping.Id}", new { Mapping = createdMapping, Topic = GatewayStore.GetMqttTopic(createdMapping) });
});
app.MapPut("/api/mqtt/mappings/{id:guid}", (Guid id, CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
if (store.UpdateMqttMapping(id, mapping) is not { } updated) return Results.NotFound();
if (updated.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([updated.Id]);
mqttClient.RequestReconfigure();
return Results.Ok(new { Mapping = updated, Topic = GatewayStore.GetMqttTopic(updated) });
});
app.MapDelete("/api/mqtt/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403);
if (!store.DeleteMqttMapping(id)) return Results.NotFound();
mqttClient.RequestReconfigure();
return Results.NoContent();
});
app.MapGet("/api/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.ListMappings())
: Results.Unauthorized());
app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
@@ -166,15 +582,59 @@ app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request,
var response = store.CreateMapping(mapping);
return Results.Created($"/api/mappings/{response.Mapping.Id}", response);
});
app.MapPut("/api/mappings/{id:guid}", (Guid id, CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return store.UpdateMapping(id, mapping) is { } updated ? Results.Ok(updated) : Results.NotFound();
});
app.MapDelete("/api/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403);
return store.DeleteMapping(id) ? Results.NoContent() : Results.NotFound();
});
app.MapGet("/api/mappings/bulk/modbus-servers", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)
? Results.Ok(store.GetGatewayConfiguration().ModbusServers.Select(server =>
new { server.Id, server.Name, server.FirstHoldingRegister, server.HoldingRegisterCount }))
: Results.StatusCode(403));
app.MapPost("/api/mappings/bulk", (BulkMappingRequest bulk, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) =>
{
var authorization = request.Headers.Authorization;
if (!sessions.HasPermission(authorization, GatewayPermissions.ManageSources) ||
bulk.Target == BulkMappingTarget.Mqtt && !sessions.HasPermission(authorization, GatewayPermissions.ManageIntegrations))
return Results.StatusCode(403);
var result = store.CreateBulkMappings(bulk);
mqtt.QueueInitialPublications(result.NewMqttMappings);
return Results.Ok(result);
});
MapConfigurationCsv("/api/points/csv", "seiugw-datenpunkte.csv", ConfigurationCsvKind.Points, GatewayPermissions.ManageSources);
MapConfigurationCsv("/api/mappings/csv", "seiugw-mappings.csv", ConfigurationCsvKind.Mappings, GatewayPermissions.ManageSources);
MapConfigurationCsv("/api/mqtt/mappings/csv", "seiugw-mqtt-mappings.csv", ConfigurationCsvKind.MqttMappings, GatewayPermissions.ManageIntegrations);
void MapConfigurationCsv(string route, string file, ConfigurationCsvKind kind, string permission)
{
app.MapGet(route, (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, permission)
? Results.File(Encoding.UTF8.GetBytes(store.ExportConfigurationCsv(kind)), "text/csv; charset=utf-8", file)
: Results.StatusCode(403));
app.MapPost(route, (ConfigurationCsvRequest input, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, permission)) return Results.StatusCode(403);
var result = store.ImportConfigurationCsv(kind, input.Csv);
if (kind == ConfigurationCsvKind.MqttMappings && result.Created + result.Updated > 0) mqtt.RequestReconfigure();
return Results.Ok(result);
});
}
app.MapGet("/api/trend-logs", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends)
? Results.Ok(store.ListTrendLogs())
: Results.Unauthorized());
app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
@@ -184,13 +644,22 @@ app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest requ
});
app.MapGet("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends)
? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500))
: Results.Unauthorized());
// Public trend access is deliberately opt-in per trend log. It exposes only sampled values,
// never gateway configuration, credentials, points, mappings, or write functions.
app.MapGet("/api/public/trend-logs", (GatewayStore store) => Results.Ok(store.ListPublicTrendLogs()));
app.MapGet("/api/public/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, GatewayStore store) =>
store.IsPublicTrendLog(trendLogId)
? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500))
: Results.NotFound());
app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, AppendTrendRecordRequest trendRecord, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.IsValid(request.Headers.Authorization))
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources))
{
return Results.Unauthorized();
}
@@ -199,8 +668,81 @@ app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, Appen
return createdRecord is null ? Results.NoContent() : Results.Created($"/api/trend-logs/{trendLogId}/records/{createdRecord.SequenceNumber}", createdRecord);
});
app.MapGet("/api/trend-selections", (HttpRequest request, GatewayStore store, SessionService sessions) =>
{
var user = sessions.GetUser(request.Headers.Authorization);
return user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)
? Results.Unauthorized()
: Results.Ok(store.ListTrendSelections(user.User.Id, user.User.Role == "admin"));
});
app.MapPost("/api/trend-selections", (CreateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
var user = sessions.GetUser(request.Headers.Authorization);
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
var created = store.CreateTrendSelection(selection, user.User.Id);
return Results.Created($"/api/trend-selections/{created.Id}", created);
});
app.MapPatch("/api/trend-selections/{selectionId:guid}", (Guid selectionId, UpdateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
var user = sessions.GetUser(request.Headers.Authorization);
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
return Results.Ok(store.UpdateTrendSelection(selectionId, selection, user.User.Id, user.User.Role == "admin"));
});
app.MapDelete("/api/trend-selections/{selectionId:guid}", (Guid selectionId, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
var user = sessions.GetUser(request.Headers.Authorization);
if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized();
store.DeleteTrendSelection(selectionId, user.User.Id, user.User.Role == "admin");
return Results.NoContent();
});
app.MapGet("/api/integrations/mail", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.GetMailIntegration()) : Results.Unauthorized());
app.MapPut("/api/integrations/mail", (UpdateMailIntegrationRequest integration, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.Unauthorized();
store.UpdateMailIntegration(integration);
return Results.NoContent();
});
app.MapGet("/api/runner/jobs", (HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(store.ListCsvRunnerJobs()) : Results.Unauthorized());
app.MapGet("/api/runner/queue", (HttpRequest request, CsvRunnerService runner, SessionService sessions) =>
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(runner.ListExecutions()) : Results.StatusCode(403));
app.MapPost("/api/runner/jobs", (CreateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
var created = store.CreateCsvRunnerJob(job);
return Results.Created($"/api/runner/jobs/{created.Id}", created);
});
app.MapPatch("/api/runner/jobs/{jobId:guid}", (Guid jobId, UpdateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
return Results.Ok(store.UpdateCsvRunnerJob(jobId, job));
});
app.MapPost("/api/runner/jobs/{jobId:guid}/test", async (Guid jobId, HttpRequest request, CsvRunnerService runner, SessionService sessions, CancellationToken cancellationToken) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
return Results.Ok(await runner.RunNowAsync(jobId, cancellationToken));
});
app.MapDelete("/api/runner/jobs/{jobId:guid}", (Guid jobId, HttpRequest request, GatewayStore store, SessionService sessions) =>
{
if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized();
store.DeleteCsvRunnerJob(jobId);
return Results.NoContent();
});
app.MapGet("/api/audit", (int? limit, HttpRequest request, GatewayStore store, SessionService sessions) =>
sessions.IsValid(request.Headers.Authorization)
sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewDebug)
? Results.Ok(store.ListAudit(limit ?? 100))
: Results.Unauthorized());
@@ -0,0 +1,435 @@
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed record BacnetScanRequest(string? Interface = null, int? TimeoutSeconds = null, string? TargetAddress = null, int? TargetPort = null);
public sealed record BacnetDiscoveredDevice(int DeviceInstance, string Address, int Port, int? VendorId, int? MaxApdu,
int Network = 0, string? Mac = null, string? DeviceName = null);
public sealed record BacnetBrowseRequest(string Address, int DeviceInstance, int? Port = null, int? MaxObjects = null,
string? Interface = null, int Network = 0, string? Mac = null);
public sealed record BacnetObjectReference(string ObjectType, int ObjectInstance, string ObjectIdentifier);
/// <summary>
/// BACnet/IP discovery and object-list reader. It sends standard BVLC/NPDU/APDU
/// requests from its own ephemeral UDP socket, so it never competes with the native
/// BACnet device service that owns the configured BACnet/IP port.
/// </summary>
public sealed partial class BacnetBrowserService
{
private readonly GatewayStore _store;
private readonly GatewayDatabase _database;
public BacnetBrowserService(GatewayStore store, GatewayDatabase database)
{
_store = store;
_database = database;
}
public async Task<IReadOnlyList<BacnetDiscoveredDevice>> ScanAsync(BacnetScanRequest request, CancellationToken cancellationToken = default)
{
var configuration = _store.GetGatewayConfiguration();
var port = request.TargetPort ?? configuration.Bacnet.IpPort;
if (port is < 1 or > 65535)
{
throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
}
var timeout = Math.Clamp(request.TimeoutSeconds ?? 5, 1, 30);
var localAddresses = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface);
if (localAddresses.Length == 0)
{
throw new DomainValidationException("Für die ausgewählte Schnittstelle wurde keine IPv4-Adresse gefunden.");
}
IPAddress? target = null;
if (!string.IsNullOrWhiteSpace(request.TargetAddress) &&
(!IPAddress.TryParse(request.TargetAddress, out target) ||
target.AddressFamily != AddressFamily.InterNetwork || target.Equals(IPAddress.Any)))
{
throw new DomainValidationException("Für einen direkten BACnet-Scan ist eine gültige IPv4-Adresse erforderlich.");
}
if (OperatingSystem.IsLinux() && (request.Interface ?? configuration.Bacnet.Interface) == configuration.Bacnet.Interface &&
(target is not null || port == configuration.Bacnet.IpPort))
{
var discovered = await ScanNativeAsync(target, port, timeout, cancellationToken);
return await ReadDeviceNamesAsync(discovered, localAddresses[0].Address, cancellationToken);
}
using var socket = CreateSocket(localAddresses[0].Address);
if (target is not null)
{
await socket.SendAsync(new byte[] { 0x81, 0x0a, 0, 8, 1, 0, 0x10, 0x08 }, new IPEndPoint(target, port), cancellationToken);
}
else
{
foreach (var address in localAddresses)
{
await socket.SendAsync(CreateWhoIsPacket(), new IPEndPoint(GetBroadcastAddress(address), port), cancellationToken);
}
}
var devices = new Dictionary<string, BacnetDiscoveredDevice>(StringComparer.Ordinal);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(TimeSpan.FromSeconds(timeout));
try
{
while (!timeoutSource.IsCancellationRequested)
{
var received = await socket.ReceiveAsync(timeoutSource.Token);
if (TryParseIAm(received.Buffer, received.RemoteEndPoint, out var device))
{
devices[$"{device.DeviceInstance}@{device.Address}:{device.Port}"] = device;
}
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// Expected end of discovery window.
}
return await ReadDeviceNamesAsync(devices.Values.OrderBy(device => device.DeviceInstance)
.ThenBy(device => device.Address, StringComparer.Ordinal).ToArray(), localAddresses[0].Address, cancellationToken);
}
private async Task<IReadOnlyList<BacnetDiscoveredDevice>> ScanNativeAsync(IPAddress? target, int port, int timeoutSeconds, CancellationToken cancellationToken)
{
var scanId = Guid.NewGuid().ToString("N");
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var deadline = now + (timeoutSeconds * 1000L) + 1500;
using (var connection = _database.OpenConnection())
using (var transaction = connection.BeginTransaction())
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
if (command.ExecuteScalar() is not long heartbeat || now - heartbeat >= 5000)
throw new DomainValidationException("Der native BACnet-Dienst ist nicht erreichbar.");
command.CommandText = "DELETE FROM bacnet_discovery WHERE expires_ms < $now";
command.Parameters.AddWithValue("$now", now);
command.ExecuteNonQuery();
command.CommandText = "INSERT OR IGNORE INTO bacnet_discovery(id,scan_id,target,port,expires_ms) VALUES(1,$id,$target,$port,$deadline)";
command.Parameters.Clear();
command.Parameters.AddWithValue("$id", scanId);
command.Parameters.AddWithValue("$target", (object?)target?.ToString() ?? DBNull.Value);
command.Parameters.AddWithValue("$port", port);
command.Parameters.AddWithValue("$deadline", deadline + 5000);
if (command.ExecuteNonQuery() != 1)
throw new DomainValidationException("Eine BACnet-Gerätesuche läuft bereits.");
command.CommandText = "DELETE FROM bacnet_discovered_devices WHERE scan_id <> $id";
command.ExecuteNonQuery();
transaction.Commit();
}
try
{
await Task.Delay(TimeSpan.FromMilliseconds(deadline - now), cancellationToken);
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT sent FROM bacnet_discovery WHERE scan_id=$id";
command.Parameters.AddWithValue("$id", scanId);
if (command.ExecuteScalar() is not 1L)
throw new DomainValidationException("Der native BACnet-Dienst hat die Suche nicht gestartet.");
command.CommandText = """
SELECT device_instance,address,port,vendor,max_apdu,network,mac FROM bacnet_discovered_devices
WHERE scan_id=$id ORDER BY device_instance,address,port
""";
using var reader = command.ExecuteReader();
var devices = new List<BacnetDiscoveredDevice>();
while (reader.Read())
devices.Add(new(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4),
reader.GetInt32(5), reader.IsDBNull(6) ? null : reader.GetString(6)));
return devices;
}
finally
{
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "DELETE FROM bacnet_discovery WHERE scan_id=$id";
command.Parameters.AddWithValue("$id", scanId);
command.ExecuteNonQuery();
}
}
public async Task<IReadOnlyList<BacnetObjectReference>> BrowseObjectListAsync(BacnetBrowseRequest request, CancellationToken cancellationToken = default)
{
if (!IPAddress.TryParse(request.Address, out var address) || address.AddressFamily != AddressFamily.InterNetwork || address.Equals(IPAddress.Any))
{
throw new DomainValidationException("Für das BACnet-Browsing ist eine erreichbare IPv4-Adresse erforderlich. 0.0.0.0 ist keine Zieladresse.");
}
if (request.DeviceInstance is < 0 or > 4_194_303)
{
throw new DomainValidationException("Die BACnet-Device-Instance ist ungültig.");
}
var configuration = _store.GetGatewayConfiguration();
var localAddresses = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface);
if (localAddresses.Length == 0)
{
throw new DomainValidationException("Für die konfigurierte BACnet-Schnittstelle wurde keine IPv4-Adresse gefunden.");
}
var port = request.Port ?? configuration.Bacnet.IpPort;
if (port is < 1 or > 65535) throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
var target = new IPEndPoint(address, port);
var route = ReadRoute(request);
using var socket = CreateSocket(localAddresses[0].Address);
var count = await ReadObjectListCountAsync(socket, target, request.DeviceInstance, route, cancellationToken);
var maximum = Math.Min(count, Math.Clamp(request.MaxObjects ?? 500, 1, 5_000));
var objects = new List<BacnetObjectReference>(maximum);
for (var index = 1; index <= maximum; index++)
{
var value = await ReadObjectListItemAsync(socket, target, request.DeviceInstance, index, route, cancellationToken);
if (value is { } objectId)
{
objects.Add(ToObjectReference(objectId));
}
}
return objects;
}
private sealed record BacnetRoute(int Network, byte[] Mac);
private static BacnetRoute? ReadRoute(BacnetBrowseRequest request)
{
if (request.Network == 0 && string.IsNullOrEmpty(request.Mac)) return null;
if (request.Network is < 1 or > 65534 || request.Mac is null ||
request.Mac.Length is < 2 or > 14 || request.Mac.Length % 2 != 0 ||
!request.Mac.All(Uri.IsHexDigit))
throw new DomainValidationException("BACnet-Netznummer oder Geräte-MAC ist ungültig.");
return new(request.Network, Convert.FromHexString(request.Mac));
}
private static UdpClient CreateSocket(IPAddress localAddress)
{
var socket = new UdpClient(AddressFamily.InterNetwork);
socket.EnableBroadcast = true;
socket.Client.Bind(new IPEndPoint(localAddress, 0));
return socket;
}
private static UnicastIPAddressInformation[] GetLocalAddresses(string? interfaceName)
{
var networks = NetworkInterface.GetAllNetworkInterfaces()
.Where(network => network.OperationalStatus == OperationalStatus.Up && network.NetworkInterfaceType != NetworkInterfaceType.Loopback);
if (!string.IsNullOrWhiteSpace(interfaceName))
{
networks = networks.Where(network => string.Equals(network.Name, interfaceName, StringComparison.Ordinal));
}
return networks.SelectMany(network => network.GetIPProperties().UnicastAddresses)
.Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork && address.IPv4Mask is not null)
.ToArray();
}
private static IPAddress GetBroadcastAddress(UnicastIPAddressInformation address)
{
var bytes = address.Address.GetAddressBytes();
var mask = address.IPv4Mask.GetAddressBytes();
for (var index = 0; index < bytes.Length; index++)
{
bytes[index] = (byte)(bytes[index] | ~mask[index]);
}
return new IPAddress(bytes);
}
private static byte[] CreateWhoIsPacket() => [
0x81, 0x0b, 0x00, 0x0c, // BVLC original-broadcast NPDU
0x01, 0x20, 0xff, 0xff, 0x00, 0xff, // global broadcast NPDU
0x10, 0x08 // unconfirmed-request / Who-Is
];
private static bool TryParseIAm(byte[] packet, IPEndPoint endpoint, out BacnetDiscoveredDevice device)
{
device = default!;
if (packet.Length < 16 || packet[0] != 0x81 || ((packet[2] << 8) | packet[3]) != packet.Length)
return false;
var position = packet[1] switch { 0x04 => 10, 0x0a or 0x0b => 4, _ => -1 };
if (position < 0 || position + 2 >= packet.Length || packet[position++] != 1) return false;
var control = packet[position++];
if ((control & 0x80) != 0) return false;
if ((control & 0x20) != 0 && !SkipNetworkAddress(packet, ref position)) return false;
var sourceNetwork = 0;
string? sourceMac = null;
if ((control & 0x08) != 0)
{
var start = position;
if (!SkipNetworkAddress(packet, ref position) || position == start + 3) return false;
sourceNetwork = (packet[start] << 8) | packet[start + 1];
sourceMac = Convert.ToHexString(packet.AsSpan(start + 3, position - start - 3));
}
if ((control & 0x20) != 0) position++; // Hop count follows both addresses.
if (position + 7 > packet.Length || packet[position] != 0x10 ||
packet[position + 1] != 0 || packet[position + 2] != 0xc4) return false;
var rawObject = ReadUInt32(packet, position + 3);
position += 7;
if ((rawObject >> 22) != 8 ||
!ReadApplicationNumber(packet, ref position, 0x20, out var maxApdu) ||
!ReadApplicationNumber(packet, ref position, 0x90, out var segmentation) ||
!ReadApplicationNumber(packet, ref position, 0x20, out var vendor) ||
maxApdu > ushort.MaxValue || segmentation > 3 || vendor > ushort.MaxValue) return false;
if (packet[1] == 0x04)
endpoint = new IPEndPoint(new IPAddress(packet.AsSpan(4, 4)), (packet[8] << 8) | packet[9]);
device = new BacnetDiscoveredDevice((int)(rawObject & 0x3f_ffff), endpoint.Address.ToString(), endpoint.Port, (int)vendor, (int)maxApdu, sourceNetwork, sourceMac);
return true;
}
private static bool SkipNetworkAddress(byte[] packet, ref int position)
{
if (position + 3 > packet.Length) return false;
position += 3 + packet[position + 2];
return position <= packet.Length;
}
private static bool ReadApplicationNumber(byte[] packet, ref int position, byte type, out uint value)
{
value = 0;
if (position >= packet.Length) return false;
var tag = packet[position++];
var length = tag & 7;
if ((tag & 0xf8) != type || length is < 1 or > 4 || position + length > packet.Length) return false;
for (var end = position + length; position < end; position++) value = (value << 8) | packet[position];
return true;
}
private static async Task<int> ReadObjectListCountAsync(UdpClient socket, IPEndPoint target, int deviceInstance, BacnetRoute? route, CancellationToken cancellationToken)
{
var response = await ReadPropertyAsync(socket, target, deviceInstance, 76, 0, route, cancellationToken);
var openTag = Array.IndexOf(response, (byte)0x3e);
if (openTag < 0 || openTag + 2 >= response.Length)
{
throw new DomainValidationException("Das BACnet-Gerät lieferte keine Object_List zurück.");
}
var tag = response[openTag + 1];
var length = tag & 0x07;
if ((tag & 0xf8) != 0x20 || length is < 1 or > 4 || openTag + 2 + length > response.Length)
{
throw new DomainValidationException("Die BACnet Object_List hat ein nicht unterstütztes Format.");
}
var count = 0;
for (var index = 0; index < length; index++) count = (count << 8) | response[openTag + 2 + index];
if (count < 0) throw new DomainValidationException("Die BACnet Object_List meldet eine ungültige Objektanzahl.");
return count;
}
private static async Task<uint?> ReadObjectListItemAsync(UdpClient socket, IPEndPoint target, int deviceInstance, int index, BacnetRoute? route, CancellationToken cancellationToken)
{
var response = await ReadPropertyAsync(socket, target, deviceInstance, 76, index, route, cancellationToken);
var openTag = Array.IndexOf(response, (byte)0x3e);
for (var position = openTag + 1; openTag >= 0 && position + 4 < response.Length; position++)
{
if (response[position] == 0xc4)
{
return ReadUInt32(response, position + 1);
}
if (response[position] == 0x3f) break;
}
return null;
}
private static async Task<byte[]> ReadPropertyAsync(UdpClient socket, IPEndPoint target, int deviceInstance, int propertyId, int arrayIndex, BacnetRoute? route, CancellationToken cancellationToken)
=> await ReadPropertyAsync(socket, target, 8, deviceInstance, propertyId, arrayIndex, route, cancellationToken);
private static async Task<byte[]> ReadPropertyAsync(UdpClient socket, IPEndPoint target, int objectType, int objectInstance,
int propertyId, int? arrayIndex, BacnetRoute? route, CancellationToken cancellationToken, int timeoutMilliseconds = 3000)
{
var invokeId = (byte)Random.Shared.Next(1, 255);
var packet = CreateReadPropertyPacket(objectType, objectInstance, propertyId, arrayIndex, invokeId, route);
await socket.SendAsync(packet, target, cancellationToken);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(timeoutMilliseconds);
try
{
while (!timeout.IsCancellationRequested)
{
var received = await socket.ReceiveAsync(timeout.Token);
if (!received.RemoteEndPoint.Equals(target)) continue;
var apdu = FindSequence(received.Buffer, 4, 0x30, invokeId, 0x0c);
if (apdu >= 0)
{
return received.Buffer[(apdu + 3)..];
}
if (FindSequence(received.Buffer, 4, 0x50, invokeId, 0x0c) >= 0)
{
throw new DomainValidationException("Das BACnet-Gerät hat die Object_List-Abfrage abgelehnt.");
}
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new DomainValidationException("Keine Antwort auf die BACnet Object_List-Abfrage.");
}
throw new DomainValidationException("Keine Antwort auf die BACnet Object_List-Abfrage.");
}
private static byte[] CreateReadPropertyPacket(int objectType, int objectInstance, int propertyId, int? arrayIndex, byte invokeId, BacnetRoute? route)
{
var parameters = new List<byte> { 0x0c };
WriteUInt32(parameters, (uint)((objectType << 22) | objectInstance));
parameters.Add(0x19);
parameters.Add((byte)propertyId);
if (arrayIndex.HasValue) WriteContextUnsigned(parameters, 2, arrayIndex.Value);
var payload = new List<byte> { 0x01, route is null ? (byte)0x04 : (byte)0x24 };
if (route is not null)
{
payload.Add((byte)(route.Network >> 8));
payload.Add((byte)route.Network);
payload.Add((byte)route.Mac.Length);
payload.AddRange(route.Mac);
payload.Add(0xff); // Hop count.
}
payload.AddRange(new byte[] { 0x00, 0x05, invokeId, 0x0c });
payload.AddRange(parameters);
var packet = new List<byte> { 0x81, 0x0a, 0x00, 0x00 };
packet.AddRange(payload);
packet[2] = (byte)(packet.Count >> 8);
packet[3] = (byte)packet.Count;
return packet.ToArray();
}
private static void WriteContextUnsigned(List<byte> output, int tagNumber, int value)
{
if (value <= byte.MaxValue)
{
output.Add((byte)((tagNumber << 4) | 0x09));
output.Add((byte)value);
}
else
{
output.Add((byte)((tagNumber << 4) | 0x0a));
output.Add((byte)(value >> 8));
output.Add((byte)value);
}
}
private static BacnetObjectReference ToObjectReference(uint objectId)
{
var type = (int)(objectId >> 22);
var instance = (int)(objectId & 0x3f_ffff);
return new BacnetObjectReference(BacnetObjectTypeName(type), instance, $"{type}:{instance}");
}
private static string BacnetObjectTypeName(int type) => type switch
{
0 => "AnalogInput", 1 => "AnalogOutput", 2 => "AnalogValue", 3 => "BinaryInput", 4 => "BinaryOutput", 5 => "BinaryValue",
8 => "Device", 13 => "MultiStateInput", 14 => "MultiStateOutput", 19 => "MultiStateValue", 17 => "Schedule", 6 => "Calendar", 20 => "TrendLog", _ => $"ObjectType{type}"
};
private static int FindSequence(IReadOnlyList<byte> value, int start, params byte[] sequence)
{
for (var index = start; index <= value.Count - sequence.Length; index++)
{
var matches = true;
for (var offset = 0; offset < sequence.Length; offset++)
{
if (value[index + offset] != sequence[offset]) { matches = false; break; }
}
if (matches) return index;
}
return -1;
}
private static uint ReadUInt32(IReadOnlyList<byte> value, int offset) =>
((uint)value[offset] << 24) | ((uint)value[offset + 1] << 16) | ((uint)value[offset + 2] << 8) | value[offset + 3];
private static void WriteUInt32(List<byte> value, uint number)
{
value.Add((byte)(number >> 24)); value.Add((byte)(number >> 16)); value.Add((byte)(number >> 8)); value.Add((byte)number);
}
}
@@ -0,0 +1,99 @@
using System.Net.Sockets;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
public int ImportNewBacnetPoints(IReadOnlyList<CreatePointRequest> requests)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var known = ReadPoints(connection, transaction).Where(point => point.Protocol == PointProtocol.Bacnet)
.Select(point => point.ExternalIdentity).ToHashSet(StringComparer.Ordinal);
var created = 0;
foreach (var request in requests)
{
if (!known.Add(request.ExternalIdentity)) continue;
InsertPoint(connection, transaction, request);
created++;
}
transaction.Commit();
return created;
}
}
public sealed class BacnetExternalPointService(GatewayStore store, BacnetBrowserService browser, ILogger<BacnetExternalPointService> logger) : BackgroundService
{
private readonly Dictionary<Guid, (string Address, DateTimeOffset Due)> _next = [];
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
var eligible = store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet &&
point.Scope == PointScope.External && point.Readable && point.Address.TryGetProperty("objectType", out _) &&
point.Address.TryGetProperty("host", out _)).ToDictionary(point => point.Id);
foreach (var id in _next.Keys.Except(eligible.Keys).ToArray()) _next.Remove(id);
var now = DateTimeOffset.UtcNow;
var due = eligible.Values
.Select(point => (Point: point, Due: _next.TryGetValue(point.Id, out var next) &&
next.Address == point.Address.GetRawText() ? next.Due : DateTimeOffset.MinValue))
.Where(item => item.Due <= now).OrderBy(item => item.Due).Take(20).Select(item => item.Point).ToArray();
if (due.Length == 0) continue;
var values = store.ListPointValues().ToDictionary(value => value.PointId);
foreach (var point in due)
_next[point.Id] = (point.Address.GetRawText(), now.AddSeconds(Math.Clamp(ReadInt(point.Address, "pollIntervalSeconds") ?? 15, 2, 3600)));
await Parallel.ForEachAsync(due, new ParallelOptions
{
CancellationToken = stoppingToken, MaxDegreeOfParallelism = 4
}, async (point, token) => await ObserveAsync(point, values.GetValueOrDefault(point.Id), token));
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Microsoft.Data.Sqlite.SqliteException exception)
{
#pragma warning disable CA1848
logger.LogWarning(exception, "BACnet polling could not read the gateway database.");
#pragma warning restore CA1848
}
}
}
private async Task ObserveAsync(GatewayPoint point, PointValue? previous, CancellationToken cancellationToken)
{
var address = point.Address;
var host = ReadString(address, "host");
var type = ReadInt(address, "objectType");
var instance = ReadInt(address, "objectInstance");
var device = ReadInt(address, "deviceInstance");
if (host is null || type is null or < 0 or > 1023 || instance is null or < 0 or > 4_194_303 || device is null)
return;
JsonElement? value = null;
try
{
value = await browser.ReadExternalValueAsync(new BacnetBrowseRequest(host, device.Value, ReadInt(address, "port"),
Interface: ReadString(address, "interface"), Network: ReadInt(address, "network") ?? 0, Mac: ReadString(address, "mac")),
type.Value, instance.Value, cancellationToken);
}
catch (Exception exception) when (exception is DomainValidationException or SocketException) { }
var status = value.HasValue ? "Good" : "BadNotConnected";
var effective = value ?? previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null);
if (previous?.Status == status && previous.Value.GetRawText() == effective.GetRawText())
{
store.RecordPointObservation(point.Id, effective, PointProtocol.Bacnet, status, DateTimeOffset.UtcNow);
return;
}
try { store.SetPointValue(point.Id, effective, PointProtocol.Bacnet, DateTimeOffset.UtcNow, status, expectedDefinition: point); }
catch (DomainValidationException) { /* The source was edited or removed during polling. */ }
}
private static string? ReadString(JsonElement address, string name) =>
address.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
private static int? ReadInt(JsonElement address, string name) =>
address.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var result) ? result : null;
}
@@ -0,0 +1,98 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
public object GetBacnetNativeStatus()
{
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
var heartbeat = command.ExecuteScalar() as long?;
command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE state='pending'";
var pending = (long)command.ExecuteScalar()!;
command.CommandText = "SELECT point_id,result,created_ms FROM bacnet_commands WHERE state='failed' ORDER BY id DESC LIMIT 10";
using var reader = command.ExecuteReader();
var failed = new List<object>();
while (reader.Read()) failed.Add(new { pointId = reader.GetString(0), result = reader.GetString(1), occurredAtUtc = DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64(2)) });
return new { connected = heartbeat.HasValue && DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - heartbeat.Value < 5000,
heartbeatUtc = heartbeat.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(heartbeat.Value) : (DateTimeOffset?)null, pendingCommands = pending, failedCommands = failed,
unsupportedPoints = ListPoints().Where(point => point.Scope == PointScope.Gateway && point.Protocol == PointProtocol.Bacnet && point.BacnetObjectKind is BacnetObjectKind.EventEnrollment or BacnetObjectKind.NotificationClass or BacnetObjectKind.TrendLog).Select(point => new { point.Id, point.DisplayName, point.BacnetObjectKind }).ToArray() };
}
private static void EnqueueBacnetCommand(SqliteConnection connection, SqliteTransaction transaction, GatewayPoint point, PointValue value, int priority)
{
if (!string.IsNullOrWhiteSpace(value.Status) && value.Status is not ("Good" or "ok")) return;
if (priority is < 1 or > 16 or 6) throw new DomainValidationException("BACnet-Priorität muss 1 bis 16 sein; Priorität 6 ist reserviert.");
var kind = point.BacnetObjectKind;
var valid = kind switch
{
BacnetObjectKind.AnalogInput or BacnetObjectKind.AnalogOutput or BacnetObjectKind.AnalogValue => value.Value.ValueKind == JsonValueKind.Number && value.Value.TryGetSingle(out var real) && float.IsFinite(real),
BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue => value.Value.ValueKind is JsonValueKind.True or JsonValueKind.False,
BacnetObjectKind.MultiStateInput or BacnetObjectKind.MultiStateOutput or BacnetObjectKind.MultiStateValue => value.Value.ValueKind == JsonValueKind.Number && value.Value.TryGetUInt32(out var state) && state > 0,
_ => false
};
var relinquish = value.Value.ValueKind == JsonValueKind.Null && kind is BacnetObjectKind.AnalogOutput or BacnetObjectKind.AnalogValue or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue or BacnetObjectKind.MultiStateOutput or BacnetObjectKind.MultiStateValue;
if (!valid && !relinquish) throw new DomainValidationException("Der Wert passt nicht zum nativen BACnet-Objekt.");
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO bacnet_commands(point_id,value_json,priority,created_ms) VALUES($id,$value,$priority,$time)";
command.Parameters.AddWithValue("$id", point.Id.ToString());
command.Parameters.AddWithValue("$value", value.Value.GetRawText());
command.Parameters.AddWithValue("$priority", priority);
command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
command.ExecuteNonQuery();
}
}
/// <summary>Only native effective values feed the shared mapping/trend store, never unarbitrated commands.</summary>
public sealed class BacnetNativeBridgeService(GatewayDatabase database, GatewayStore store, ILogger<BacnetNativeBridgeService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
var observations = new List<(long Id, Guid Point, JsonElement Value, string Status, long Time)>();
using var connection = database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT id,point_id,value_json,status,observed_ms FROM bacnet_observations ORDER BY id LIMIT 500";
using (var reader = command.ExecuteReader())
while (reader.Read()) observations.Add((reader.GetInt64(0), Guid.Parse(reader.GetString(1)), JsonSerializer.Deserialize<JsonElement>(reader.GetString(2)), reader.GetString(3), reader.GetInt64(4)));
var points = store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.Scope == PointScope.Gateway).ToArray();
foreach (var observation in observations)
{
if (points.Any(point => point.Id == observation.Point))
{
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == observation.Point);
if (previous is null || previous.UpdatedAtUtc.ToUnixTimeMilliseconds() < observation.Time || previous.Status != observation.Status || previous.Value.GetRawText() != observation.Value.GetRawText())
store.SetPointValue(observation.Point, observation.Value, PointProtocol.Bacnet, DateTimeOffset.FromUnixTimeMilliseconds(observation.Time), observation.Status);
}
command.CommandText = "DELETE FROM bacnet_observations WHERE id=$id";
command.Parameters.Clear(); command.Parameters.AddWithValue("$id", observation.Id); command.ExecuteNonQuery();
}
command.CommandText = "SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1";
command.Parameters.Clear();
var heartbeat = command.ExecuteScalar() as long? ?? 0;
if (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - heartbeat > 5000)
foreach (var point in points)
{
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == point.Id);
if (previous?.Status != "BadNotConnected") store.SetPointValue(point.Id, previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null), PointProtocol.Bacnet, DateTimeOffset.UtcNow, "BadNotConnected");
}
}
catch (Exception exception) when (exception is SqliteException or JsonException or DomainValidationException)
{
#pragma warning disable CA1848
logger.LogWarning("BACnet bridge read failed ({ErrorType}).", exception.GetType().Name);
#pragma warning restore CA1848
}
try { await Task.Delay(100, stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
}
@@ -0,0 +1,238 @@
using System.Buffers.Binary;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed record BacnetObjectsRequest(BacnetBrowseRequest Device, int Offset = 0, int Limit = 100);
public sealed record BacnetObjectDetails(string ObjectType, int ObjectTypeCode, int ObjectInstance,
string? Name, string? Description, JsonElement? Value, string? ValueType, Guid? PointId);
public sealed record BacnetObjectPage(string? DeviceName, int Total, int NextOffset, IReadOnlyList<BacnetObjectDetails> Objects);
public sealed record BacnetImportRequest(BacnetBrowseRequest Device, string[]? ObjectIds, bool All = false);
public sealed record BacnetImportResult(int Created, int Existing, int Unsupported);
public sealed partial class BacnetBrowserService
{
private const int MaxInventory = 5000;
private const int ObjectName = 77;
private const int Description = 28;
private const int PresentValue = 85;
private const int OptionalReadTimeout = 950;
private static async Task<BacnetDiscoveredDevice[]> ReadDeviceNamesAsync(IReadOnlyList<BacnetDiscoveredDevice> devices,
IPAddress local, CancellationToken cancellationToken)
{
var result = devices.ToArray();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(8));
try
{
await Parallel.ForEachAsync(Enumerable.Range(0, result.Length), new ParallelOptions
{
CancellationToken = timeout.Token, MaxDegreeOfParallelism = 8
}, async (index, token) =>
{
var device = result[index];
var request = new BacnetBrowseRequest(device.Address, device.DeviceInstance, device.Port, Network: device.Network, Mac: device.Mac);
try
{
using var socket = CreateSocket(local);
var target = new IPEndPoint(IPAddress.Parse(device.Address), device.Port);
var name = await ReadTextAsync(socket, target, 8, device.DeviceInstance, ObjectName, ReadRoute(request), token);
result[index] = device with { DeviceName = name };
}
catch (Exception exception) when (exception is DomainValidationException or SocketException) { }
});
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { }
return result;
}
public async Task<BacnetObjectPage> BrowseDetailsAsync(BacnetObjectsRequest request, CancellationToken cancellationToken)
{
var (endpoint, local, route) = ResolveDevice(request.Device);
using var socket = CreateSocket(local);
var deviceName = await ReadTextAsync(socket, endpoint, 8, request.Device.DeviceInstance, ObjectName, route, cancellationToken);
var count = await ReadObjectListCountAsync(socket, endpoint, request.Device.DeviceInstance, route, cancellationToken);
var total = Math.Min(count, MaxInventory);
var offset = Math.Clamp(request.Offset, 0, total);
var end = Math.Min(total, offset + Math.Clamp(request.Limit, 1, 200));
var ids = await ReadInventoryAsync(socket, endpoint, request.Device.DeviceInstance, route, offset, end, cancellationToken);
var imports = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.ExternalIdentity is not null)
.ToDictionary(point => point.ExternalIdentity!, point => point.Id, StringComparer.Ordinal);
var objects = new BacnetObjectDetails[ids.Count];
await Parallel.ForEachAsync(Enumerable.Range(0, ids.Count), new ParallelOptions
{
CancellationToken = cancellationToken, MaxDegreeOfParallelism = 4
}, async (index, token) =>
{
using var worker = CreateSocket(local);
var type = (int)(ids[index] >> 22);
var instance = (int)(ids[index] & 0x3f_ffff);
var name = await ReadTextAsync(worker, endpoint, type, instance, ObjectName, route, token);
var description = await ReadTextAsync(worker, endpoint, type, instance, Description, route, token);
var valueType = ScalarType(type);
var value = valueType is null ? null : await ReadScalarAsync(worker, endpoint, type, instance, route, token);
imports.TryGetValue(ExternalIdentity(endpoint, request.Device, type, instance), out var pointId);
objects[index] = new(BacnetObjectTypeName(type), type, instance, name, description, value, valueType,
pointId == Guid.Empty ? null : pointId);
});
return new(deviceName, count, end, objects);
}
public async Task<BacnetImportResult> ImportAsync(BacnetImportRequest request, CancellationToken cancellationToken)
{
var (endpoint, local, route) = ResolveDevice(request.Device);
using var socket = CreateSocket(local);
var count = await ReadObjectListCountAsync(socket, endpoint, request.Device.DeviceInstance, route, cancellationToken);
if (count > MaxInventory) throw new DomainValidationException($"Geräte mit mehr als {MaxInventory} Objekten können nicht vollständig importiert werden.");
var objects = await ReadInventoryAsync(socket, endpoint, request.Device.DeviceInstance, route, 0, count, cancellationToken);
var desired = request.ObjectIds?.ToHashSet(StringComparer.Ordinal) ?? [];
if (!request.All && desired.Count == 0) throw new DomainValidationException("Bitte mindestens ein BACnet-Objekt auswählen.");
var selected = objects.Select(id => (Type: (int)(id >> 22), Instance: (int)(id & 0x3f_ffff)))
.Where(obj => request.All || desired.Contains($"{obj.Type}:{obj.Instance}")).Distinct().ToArray();
if (!request.All && selected.Length != desired.Count)
throw new DomainValidationException("Die Auswahl enthält Objekte, die dieses Gerät nicht mehr meldet.");
var create = new List<CreatePointRequest>();
var existing = 0;
var unsupported = 0;
var known = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Bacnet && point.ExternalIdentity is not null)
.Select(point => point.ExternalIdentity!).ToHashSet(StringComparer.Ordinal);
foreach (var (type, instance) in selected)
{
if (ScalarType(type) is not { } valueType) { unsupported++; continue; }
var identity = ExternalIdentity(endpoint, request.Device, type, instance);
if (!known.Add(identity)) { existing++; continue; }
var name = await ReadTextAsync(socket, endpoint, type, instance, ObjectName, route, cancellationToken);
var kind = Enum.Parse<BacnetObjectKind>(BacnetObjectTypeName(type));
create.Add(new(ShortName(name, $"{BacnetObjectTypeName(type)} {instance}"), PointProtocol.Bacnet, PointScope.External,
valueType, true, false, identity, JsonSerializer.SerializeToElement(new
{
host = endpoint.Address.ToString(), port = endpoint.Port, deviceInstance = request.Device.DeviceInstance,
@interface = request.Device.Interface, network = request.Device.Network, mac = request.Device.Mac,
objectType = type, objectInstance = instance, pollIntervalSeconds = 15
}), kind, (uint)instance));
}
var created = _store.ImportNewBacnetPoints(create);
return new(created, existing + create.Count - created, unsupported);
}
internal async Task<JsonElement?> ReadExternalValueAsync(BacnetBrowseRequest device, int type, int instance, CancellationToken token)
{
var (endpoint, local, route) = ResolveDevice(device);
using var socket = CreateSocket(local);
return await ReadScalarAsync(socket, endpoint, type, instance, route, token);
}
private (IPEndPoint Endpoint, IPAddress Local, BacnetRoute? Route) ResolveDevice(BacnetBrowseRequest request)
{
ArgumentNullException.ThrowIfNull(request);
if (!IPAddress.TryParse(request.Address, out var address) || address.AddressFamily != AddressFamily.InterNetwork ||
address.Equals(IPAddress.Any) || request.DeviceInstance is < 0 or > 4_194_303)
throw new DomainValidationException("BACnet-Gerät oder IPv4-Adresse ist ungültig.");
var configuration = _store.GetGatewayConfiguration();
var port = request.Port ?? configuration.Bacnet.IpPort;
if (port is < 1 or > 65535) throw new DomainValidationException("Der BACnet/IP-Port ist ungültig.");
var local = GetLocalAddresses(request.Interface ?? configuration.Bacnet.Interface).FirstOrDefault()?.Address
?? throw new DomainValidationException("Für die BACnet-Schnittstelle wurde keine IPv4-Adresse gefunden.");
return (new IPEndPoint(address, port), local, ReadRoute(request));
}
private static async Task<List<uint>> ReadInventoryAsync(UdpClient socket, IPEndPoint endpoint, int device,
BacnetRoute? route, int offset, int end, CancellationToken token)
{
var objects = new List<uint>(end - offset);
for (var index = offset + 1; index <= end; index++)
if (await ReadObjectListItemAsync(socket, endpoint, device, index, route, token) is { } id) objects.Add(id);
return objects;
}
private static string ExternalIdentity(IPEndPoint endpoint, BacnetBrowseRequest device, int type, int instance) =>
$"bip:{endpoint}/{device.Network}/{device.Mac?.ToUpperInvariant()}/{type}:{instance}";
private static string ShortName(string? value, string fallback) =>
string.IsNullOrWhiteSpace(value) ? fallback : value.Trim()[..Math.Min(value.Trim().Length, 160)];
private static string? ScalarType(int type) => type switch
{
0 or 1 or 2 => "Real",
3 or 4 or 5 => "Boolean",
13 or 14 or 19 => "UInt32",
_ => null
};
private static async Task<string?> ReadTextAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
int property, BacnetRoute? route, CancellationToken token)
{
var bytes = await TryReadApplicationAsync(socket, endpoint, type, instance, property, route, token);
if (bytes is not { Length: > 0 } || !TryApplicationValue(bytes, out var tag, out var data) || tag != 7 || data.Length < 1)
return null;
var encoding = data[0] switch
{
0 => Encoding.UTF8, 3 => new UTF32Encoding(true, false), 4 => Encoding.BigEndianUnicode, 5 => Encoding.Latin1, _ => null
};
return encoding?.GetString(data[1..]).TrimEnd('\0');
}
private static async Task<JsonElement?> ReadScalarAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
BacnetRoute? route, CancellationToken token)
{
var bytes = await TryReadApplicationAsync(socket, endpoint, type, instance, PresentValue, route, token);
if (bytes is not { Length: > 0 }) return null;
if (ScalarType(type) == "Boolean" && bytes[0] is 0x10 or 0x11)
return JsonSerializer.SerializeToElement(bytes[0] == 0x11);
if (!TryApplicationValue(bytes, out var tag, out var data)) return null;
if (tag == 4 && data.Length == 4)
{
var value = BinaryPrimitives.ReadSingleBigEndian(data);
return float.IsFinite(value) ? JsonSerializer.SerializeToElement(value) : null;
}
if (tag is 2 or 9 && data.Length is >= 1 and <= 4)
{
uint value = 0;
foreach (var octet in data) value = (value << 8) | octet;
return ScalarType(type) == "Boolean" ? JsonSerializer.SerializeToElement(value != 0) : JsonSerializer.SerializeToElement(value);
}
return null;
}
private static async Task<byte[]?> TryReadApplicationAsync(UdpClient socket, IPEndPoint endpoint, int type, int instance,
int property, BacnetRoute? route, CancellationToken token)
{
try
{
var response = await ReadPropertyAsync(socket, endpoint, type, instance, property, null, route, token, OptionalReadTimeout);
// A scalar ReadProperty-ACK begins with object-id (5 bytes), property-id (2), then opening tag [3].
return response.Length > 8 && response[0] == 0x0c && ReadUInt32(response, 1) == (uint)((type << 22) | instance) && response[5] == 0x19 &&
response[6] == property && response[7] == 0x3e ? response[8..] : null;
}
catch (Exception exception) when (exception is DomainValidationException or SocketException) { return null; }
}
private static bool TryApplicationValue(byte[] bytes, out int tag, out byte[] data)
{
tag = bytes[0] >> 4;
data = [];
if ((bytes[0] & 8) != 0) return false;
var length = bytes[0] & 7;
var offset = 1;
if (length == 5)
{
if (bytes.Length < 2) return false;
length = bytes[offset++];
if (length == 254)
{
if (bytes.Length < 4) return false;
length = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2, 2));
offset = 4;
}
else if (length == 255) return false;
}
if (length > bytes.Length - offset - 1 || bytes[offset + length] != 0x3f) return false;
data = bytes[offset..(offset + length)];
return true;
}
}
@@ -0,0 +1,176 @@
using System.Globalization;
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Microsoft.Extensions.Options;
namespace Gateway.Api.Services;
/// <summary>Gateway-native replacement for the LTD CSV runner. Exports a saved group of trend logs and may mail it through the fixed SE-Inno mail API.</summary>
public sealed class CsvRunnerService : BackgroundService
{
private static readonly TimeZoneInfo BerlinTimeZone = ResolveBerlinTimeZone();
private static readonly char[] MailRecipientSeparators = [';', ','];
private readonly GatewayStore _store;
private readonly NotificationTransport _transport;
private readonly string _exportDirectory;
private readonly SemaphoreSlim _executionLock = new(1, 1);
private readonly ConcurrentDictionary<Guid, CsvRunnerExecution> _executions = new();
public IReadOnlyList<CsvRunnerExecution> ListExecutions() => _executions.Values.OrderBy(item => item.EnqueuedAtUtc).ToArray();
public CsvRunnerService(GatewayStore store, NotificationTransport transport, IOptions<GatewayOptions> options)
{
_store = store;
_transport = transport;
_exportDirectory = Path.Combine(Path.GetFullPath(options.Value.DataDirectory), "exports");
}
public async Task<CsvRunnerJobResult> RunNowAsync(Guid jobId, CancellationToken cancellationToken = default)
{
var job = _store.GetCsvRunnerJob(jobId) ?? throw new DomainValidationException("Der CSV-Runner-Job existiert nicht.");
return await ExecuteJobAsync(job, cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await CheckScheduleAsync(stoppingToken);
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await CheckScheduleAsync(stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// Normal shutdown.
}
}
private async Task CheckScheduleAsync(CancellationToken cancellationToken)
{
var now = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, BerlinTimeZone);
var time = now.ToString("HH:mm", CultureInfo.InvariantCulture);
var date = now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
foreach (var job in _store.ListCsvRunnerJobs().Where(job => job.Enabled && job.Time == time))
{
if (!_store.TryClaimScheduledCsvRunnerJob(job.Id, date)) continue;
await ExecuteJobAsync(job, cancellationToken);
}
}
private async Task<CsvRunnerJobResult> ExecuteJobAsync(CsvRunnerJob job, CancellationToken cancellationToken)
{
var execution = new CsvRunnerExecution(Guid.NewGuid(), job.Id, job.Name, "Pending", DateTimeOffset.UtcNow);
_executions[execution.Id] = execution;
var locked = false;
try
{
await _executionLock.WaitAsync(cancellationToken);
locked = true;
_executions[execution.Id] = execution with { State = "Running" };
var selection = _store.GetTrendSelection(job.SelectionId) ?? throw new DomainValidationException("Die Trend-Gruppe des CSV-Runner-Jobs existiert nicht mehr.");
var filePath = await ExportSelectionAsync(job, selection, cancellationToken);
if (job.MailEnabled) await MailExportAsync(job, filePath, cancellationToken);
var result = new CsvRunnerJobResult(true, filePath, null, DateTimeOffset.UtcNow);
_store.SetCsvRunnerJobResult(job.Id, result);
return result;
}
catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
var result = new CsvRunnerJobResult(false, null, exception.Message, DateTimeOffset.UtcNow);
_store.SetCsvRunnerJobResult(job.Id, result);
return result;
}
finally
{
_executions.TryRemove(execution.Id, out _);
if (locked) _executionLock.Release();
}
}
private async Task<string> ExportSelectionAsync(CsvRunnerJob job, GatewayTrendSelection selection, CancellationToken cancellationToken)
{
var since = DateTimeOffset.UtcNow.AddHours(-job.RangeHours);
var rows = _store.ListTrendExportRows(selection.TrendLogIds, since);
var delimiter = job.Delimiter;
var output = new StringBuilder("\uFEFFZeit");
output.Append(delimiter).Append("Tabelle").Append(delimiter).Append("Wertnummer").Append(delimiter).Append("Alias").Append(delimiter).Append("Wert").Append(delimiter).Append("Einheit");
foreach (var row in rows)
{
output.Append("\r\n");
AppendCell(output, FormatTimestamp(row.TimestampUtc), delimiter);
output.Append(delimiter); AppendCell(output, row.TrendLogName, delimiter);
output.Append(delimiter); AppendCell(output, row.BacnetObjectInstance.ToString(CultureInfo.InvariantCulture), delimiter);
output.Append(delimiter); AppendCell(output, row.PointName, delimiter);
output.Append(delimiter); AppendCell(output, FormatValue(row.Value), delimiter);
output.Append(delimiter); AppendCell(output, row.Unit, delimiter);
}
Directory.CreateDirectory(_exportDirectory);
var stamp = DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH-mm-ssZ", CultureInfo.InvariantCulture);
var fileName = $"{SafeFileName(selection.Name)}-{stamp}.csv";
var filePath = Path.Combine(_exportDirectory, fileName);
await File.WriteAllTextAsync(filePath, output.ToString(), new UTF8Encoding(true), cancellationToken);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(filePath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead);
return filePath;
}
private async Task MailExportAsync(CsvRunnerJob job, string filePath, CancellationToken cancellationToken)
{
var apiKey = _store.GetMailApiKey();
if (string.IsNullOrWhiteSpace(apiKey)) throw new DomainValidationException("Der Mail-API-Key ist nicht hinterlegt.");
var recipients = (job.MailTo ?? string.Empty).Split(MailRecipientSeparators, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
if (recipients.Length == 0) throw new DomainValidationException("Für den CSV-Mailversand ist kein Empfänger hinterlegt.");
foreach (var recipient in recipients)
{
using var content = new MultipartFormDataContent();
content.Add(new StringContent(apiKey), "api_key");
content.Add(new StringContent(recipient), "address");
content.Add(new StringContent(job.MailSubject), "subject");
content.Add(new StringContent(job.MailMessage), "message");
await using var file = File.OpenRead(filePath);
using var attachment = new StreamContent(file);
attachment.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/csv");
content.Add(attachment, "attachment", Path.GetFileName(filePath));
await _transport.PostAsync(NotificationChannel.Mail, content, cancellationToken);
}
}
private static void AppendCell(StringBuilder output, string value, string delimiter)
{
if (value.Contains('"') || value.Contains('\r') || value.Contains('\n') || value.Contains(delimiter, StringComparison.Ordinal))
{
output.Append('"').Append(value.Replace("\"", "\"\"", StringComparison.Ordinal)).Append('"');
}
else output.Append(value);
}
private static string FormatValue(JsonElement value) => value.ValueKind switch
{
JsonValueKind.Number when value.TryGetDecimal(out var decimalValue) => decimalValue.ToString("0.##########", CultureInfo.GetCultureInfo("de-DE")),
JsonValueKind.String => value.GetString() ?? string.Empty,
JsonValueKind.True => "1",
JsonValueKind.False => "0",
JsonValueKind.Null => string.Empty,
_ => value.GetRawText()
};
private static string FormatTimestamp(DateTimeOffset timestamp) => TimeZoneInfo.ConvertTime(timestamp, BerlinTimeZone).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
private static string SafeFileName(string value)
{
var invalid = Path.GetInvalidFileNameChars().ToHashSet();
var safe = new string(value.Select(character => invalid.Contains(character) || !char.IsLetterOrDigit(character) && character is not '-' and not '_' and not '.' ? '_' : character).ToArray()).Trim('_');
return string.IsNullOrWhiteSpace(safe) ? "trend-export" : safe[..Math.Min(safe.Length, 100)];
}
private static TimeZoneInfo ResolveBerlinTimeZone()
{
try { return TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); }
catch (TimeZoneNotFoundException) { return TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); }
}
}
+110 -6
View File
@@ -38,10 +38,45 @@ public sealed class GatewayDatabase
using var command = connection.CreateCommand();
command.CommandText = """
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS bacnet_commands (
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL,
priority INTEGER NOT NULL, created_ms INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'pending', result TEXT NULL
);
CREATE TABLE IF NOT EXISTS bacnet_properties (
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, property INTEGER NOT NULL,
array_index INTEGER NOT NULL, priority INTEGER NOT NULL, payload BLOB NOT NULL,
UNIQUE(point_id, property, array_index, priority)
);
CREATE TABLE IF NOT EXISTS bacnet_observations (
id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL,
status TEXT NOT NULL, observed_ms INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS bacnet_runtime (
id INTEGER PRIMARY KEY CHECK(id=1), heartbeat_ms INTEGER NOT NULL, state TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS bacnet_discovery (
id INTEGER PRIMARY KEY CHECK(id=1), scan_id TEXT NOT NULL, target TEXT,
port INTEGER NOT NULL, expires_ms INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS bacnet_discovered_devices (
scan_id TEXT NOT NULL, device_instance INTEGER NOT NULL, address TEXT NOT NULL,
port INTEGER NOT NULL, vendor INTEGER NOT NULL, max_apdu INTEGER NOT NULL,
network INTEGER NOT NULL DEFAULT 0, mac TEXT,
PRIMARY KEY(scan_id, device_instance, address, port)
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT NOT NULL PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS alarm_rules (
id TEXT PRIMARY KEY, point_id TEXT NOT NULL REFERENCES points(id), enabled INTEGER NOT NULL,
configuration_json TEXT NOT NULL, active INTEGER NULL, observed_at_utc TEXT NULL
);
CREATE TABLE IF NOT EXISTS notification_outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT, rule_id TEXT NOT NULL, title TEXT NOT NULL, message TEXT NOT NULL,
destination_json TEXT NOT NULL, state TEXT NOT NULL, created_at_utc TEXT NOT NULL, result TEXT NULL
);
CREATE INDEX IF NOT EXISTS idx_notification_pending ON notification_outbox(state, id);
CREATE TABLE IF NOT EXISTS admin_account (
id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1),
username TEXT NOT NULL UNIQUE CHECK(username = 'admin'),
@@ -50,6 +85,34 @@ public sealed class GatewayDatabase
password_iterations INTEGER NOT NULL,
changed_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS app_roles (
name TEXT NOT NULL PRIMARY KEY,
label TEXT NOT NULL,
permissions_json TEXT NOT NULL,
is_system INTEGER NOT NULL,
updated_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS app_users (
id TEXT NOT NULL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
email TEXT NULL UNIQUE,
password_hash BLOB NOT NULL,
password_salt BLOB NOT NULL,
password_iterations INTEGER NOT NULL,
role_name TEXT NOT NULL REFERENCES app_roles(name) ON UPDATE CASCADE ON DELETE RESTRICT,
active INTEGER NOT NULL,
created_at_utc TEXT NOT NULL,
updated_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS app_user_preferences (
user_id TEXT NOT NULL PRIMARY KEY REFERENCES app_users(id) ON DELETE CASCADE,
theme TEXT NOT NULL DEFAULT 'system',
csv_delimiter TEXT NOT NULL DEFAULT ';',
sidebar_pinned INTEGER NOT NULL DEFAULT 1,
trend_line_width REAL NOT NULL DEFAULT 1.8,
updated_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS points (
id TEXT NOT NULL PRIMARY KEY,
display_name TEXT NOT NULL,
@@ -62,7 +125,8 @@ public sealed class GatewayDatabase
address_json TEXT NOT NULL,
created_at_utc TEXT NOT NULL,
bacnet_object_kind TEXT NULL,
bacnet_object_instance INTEGER NULL
bacnet_object_instance INTEGER NULL,
deleted_at_utc TEXT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_points_external_identity
ON points(protocol, external_identity)
@@ -92,7 +156,8 @@ public sealed class GatewayDatabase
topic_name TEXT NULL,
json_topic TEXT NULL,
json_property TEXT NULL,
created_at_utc TEXT NOT NULL
created_at_utc TEXT NOT NULL,
topic_template TEXT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_mqtt_mapping_point_topic
ON mqtt_mappings(point_id, format, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property);
@@ -117,6 +182,7 @@ public sealed class GatewayDatabase
interval_seconds INTEGER NOT NULL,
max_records INTEGER NOT NULL,
enabled INTEGER NOT NULL,
public_access INTEGER NOT NULL DEFAULT 0,
created_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS trend_records (
@@ -130,18 +196,56 @@ public sealed class GatewayDatabase
);
CREATE INDEX IF NOT EXISTS idx_trend_records_query
ON trend_records(trend_log_id, sequence_number DESC);
CREATE TABLE IF NOT EXISTS trend_selections (
id TEXT NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NULL,
owner_id TEXT NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
shared INTEGER NOT NULL,
trend_log_ids_json TEXT NOT NULL,
created_at_utc TEXT NOT NULL,
updated_at_utc TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS csv_runner_jobs (
id TEXT NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
selection_id TEXT NOT NULL REFERENCES trend_selections(id) ON DELETE RESTRICT,
time TEXT NOT NULL,
range_hours INTEGER NOT NULL,
delimiter TEXT NOT NULL,
enabled INTEGER NOT NULL,
mail_enabled INTEGER NOT NULL,
mail_to TEXT NULL,
mail_subject TEXT NOT NULL,
mail_message TEXT NOT NULL,
last_run_local_date TEXT NULL,
last_result_json TEXT NULL,
created_at_utc TEXT NOT NULL,
updated_at_utc TEXT NOT NULL
);
""";
command.ExecuteNonQuery();
EnsureColumn(connection, "points", "bacnet_object_kind", "TEXT NULL");
EnsureColumn(connection, "points", "bacnet_object_instance", "INTEGER NULL");
using var bacnetObjectIndex = connection.CreateCommand();
bacnetObjectIndex.CommandText = """
EnsureColumn(connection, "points", "deleted_at_utc", "TEXT NULL");
EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0");
EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0");
EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL");
EnsureColumn(connection, "mqtt_mappings", "topic_template", "TEXT NULL");
using var indexMigration = connection.BeginTransaction();
using var pointIndexes = connection.CreateCommand();
pointIndexes.Transaction = indexMigration;
pointIndexes.CommandText = """
DROP INDEX IF EXISTS idx_points_external_identity;
CREATE UNIQUE INDEX idx_points_external_identity ON points(protocol, external_identity)
WHERE external_identity IS NOT NULL AND deleted_at_utc IS NULL;
DROP INDEX IF EXISTS idx_points_bacnet_object;
CREATE UNIQUE INDEX idx_points_bacnet_object
ON points(bacnet_object_kind, bacnet_object_instance)
WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL;
WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL AND deleted_at_utc IS NULL;
""";
bacnetObjectIndex.ExecuteNonQuery();
pointIndexes.ExecuteNonQuery();
indexMigration.Commit();
}
private static void EnsureColumn(SqliteConnection connection, string tableName, string columnName, string definition)
@@ -0,0 +1,37 @@
namespace Gateway.Api.Services;
public sealed record DocumentationEntry(string Path, string Title);
public sealed record DocumentationFile(string Path, string Markdown);
public sealed class GatewayDocumentation
{
private readonly Dictionary<string, DocumentationFile> _files;
public IReadOnlyList<DocumentationEntry> Entries { get; }
public GatewayDocumentation()
{
var directory = Path.Combine(AppContext.BaseDirectory, "Documentation");
var paths = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md", SearchOption.AllDirectories) : [];
_files = paths.Select(path => new DocumentationFile(Path.GetRelativePath(directory, path).Replace('\\', '/'),
File.ReadAllText(path)))
.ToDictionary(file => file.Path, StringComparer.Ordinal);
Entries = _files.Values
.OrderBy(file => file.Path != "README.md")
.ThenBy(file => file.Path, StringComparer.Ordinal)
.Select(file => new DocumentationEntry(file.Path, ReadTitle(file))).ToArray();
}
public DocumentationFile? Find(string path) => _files.GetValueOrDefault(path);
private static string ReadTitle(DocumentationFile file)
{
using var reader = new StringReader(file.Markdown);
while (reader.ReadLine() is { } line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
if (line.StartsWith("# ", StringComparison.Ordinal)) return line[2..].Trim();
break;
}
return Path.GetFileNameWithoutExtension(file.Path);
}
}
@@ -0,0 +1,252 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Opc.Ua;
using Opc.Ua.Server;
using StatusCodes = Opc.Ua.StatusCodes;
namespace Gateway.Api.Services;
#pragma warning disable CS0618 // Pinned SDK 1.5 compatibility API.
/// <summary>A real UA address space backed by the common point store, not a second writer.</summary>
public sealed class GatewayOpcUaServer(GatewayStore store) : StandardServer
{
public const string PointsNamespace = "urn:se-inno:universalgateway:points";
private GatewayNodeManager? _points;
protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration)
{
_points = new GatewayNodeManager(server, configuration, store);
return new MasterNodeManager(server, configuration, null, _points);
}
protected override void OnServerStarted(IServerInternal server)
{
base.OnServerStarted(server);
server.SessionManager.ImpersonateUser += (_, args) =>
{
if (args.NewIdentity is AnonymousIdentityToken && store.GetGatewayConfiguration().OpcUa.AllowAnonymous)
{
args.Identity = new UserIdentity();
return;
}
if (args.NewIdentity is UserNameIdentityToken token)
{
var user = token.DecryptedPassword is null ? null : store.Authenticate(token.UserName, Encoding.UTF8.GetString(token.DecryptedPassword));
if (user is not null && (user.Permissions.Contains(GatewayPermissions.ViewDashboard) || user.Permissions.Contains(GatewayPermissions.ManageSources)))
{
args.Identity = new GatewayIdentity(user);
return;
}
}
throw new ServiceResultException(StatusCodes.BadUserAccessDenied, "OPC-UA-Anmeldung abgewiesen.");
};
}
public void RefreshPoints(bool reconcile)
{
if (reconcile)
{
// Close revoked sessions including their monitored items. Checking writes
// alone would leave already established subscriptions alive.
foreach (var session in CurrentInstance.SessionManager.GetSessions())
{
if (session.Identity is not GatewayIdentity identity) continue;
var current = store.GetAuthenticatedUser(identity.UserId);
if (current is null || current.User.UpdatedAtUtc != identity.Revision || !current.Permissions.Order(StringComparer.Ordinal).SequenceEqual(identity.Permissions))
CurrentInstance.CloseSession(null, session.Id, true);
}
}
_points?.Refresh(reconcile);
}
private sealed class GatewayIdentity(AuthenticatedGatewayUser user) : UserIdentity(new UserNameIdentityToken { UserName = user.User.Username })
{
public Guid UserId { get; } = user.User.Id;
public DateTimeOffset Revision { get; } = user.User.UpdatedAtUtc;
public string[] Permissions { get; } = user.Permissions.Order(StringComparer.Ordinal).ToArray();
}
private sealed class GatewayNodeManager : CustomNodeManager2
{
private readonly GatewayStore _store;
private readonly ConcurrentDictionary<Guid, PointValue> _pending = new();
private readonly Dictionary<Guid, BaseDataVariableState> _variables = [];
private FolderState? _folder;
public GatewayNodeManager(IServerInternal server, ApplicationConfiguration configuration, GatewayStore store)
: base(server, configuration, PointsNamespace)
{
_store = store;
_store.PointValueUpdated += OnPointValue;
}
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
_folder = new FolderState(null)
{
NodeId = new NodeId("Gateway", NamespaceIndex),
BrowseName = new QualifiedName("Gateway", NamespaceIndex),
DisplayName = "SE-Inno Universalgateway",
TypeDefinitionId = ObjectTypeIds.FolderType,
ReferenceTypeId = ReferenceTypeIds.Organizes
};
_folder.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder);
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out var references))
{
references = new List<IReference>();
externalReferences[ObjectIds.ObjectsFolder] = references;
}
references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, _folder.NodeId));
AddPredefinedNode(SystemContext, _folder);
Refresh(true);
}
}
// Never acquire the UA lock in a store callback: other protocol drivers may
// already own their locks. Coalescing changes affects UA delivery only, not trends.
private void OnPointValue(object? sender, PointValue value) => _pending[value.PointId] = value;
public void Refresh(bool reconcile)
{
lock (Lock)
{
if (_folder is null) return;
if (reconcile)
{
var points = _store.ListPoints().Where(point => point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.Gateway).ToArray();
var values = _store.ListPointValues().ToDictionary(value => value.PointId);
foreach (var point in points)
{
var type = OpcUaPointTypes.Resolve(point.ValueType);
var access = (byte)((point.Readable ? AccessLevels.CurrentRead : 0) | (point.Writable && type != BuiltInType.Null ? AccessLevels.CurrentWrite : 0));
var dataType = type == BuiltInType.Null ? DataTypeIds.BaseDataType : new NodeId((uint)type);
if (_variables.TryGetValue(point.Id, out var existing))
{
existing.DisplayName = point.DisplayName;
ConfigureVariable(existing, point, type, access, dataType);
if (!values.ContainsKey(point.Id) && StatusCode.IsGood(existing.StatusCode))
{
existing.Value = null;
existing.StatusCode = StatusCodes.BadWaitingForInitialData;
existing.Timestamp = DateTime.UtcNow;
}
existing.ClearChangeMasks(SystemContext, false);
continue;
}
var variable = new BaseDataVariableState(_folder)
{
NodeId = new NodeId(point.Id, NamespaceIndex),
BrowseName = new QualifiedName(point.Id.ToString(), NamespaceIndex),
DisplayName = point.DisplayName,
ReferenceTypeId = ReferenceTypeIds.Organizes,
TypeDefinitionId = VariableTypeIds.BaseDataVariableType,
ValueRank = ValueRanks.Scalar,
MinimumSamplingInterval = 100,
StatusCode = type == BuiltInType.Null ? StatusCodes.BadNotSupported : StatusCodes.BadWaitingForInitialData,
Timestamp = DateTime.UtcNow
};
ConfigureVariable(variable, point, type, access, dataType);
_variables.Add(point.Id, variable);
_folder.AddChild(variable);
AddPredefinedNode(SystemContext, variable);
if (values.TryGetValue(point.Id, out var current)) Apply(variable, current);
}
foreach (var removed in _variables.Keys.Except(points.Select(point => point.Id)).ToArray())
{
_folder.RemoveChild(_variables[removed]);
DeleteNode(SystemContext, _variables[removed].NodeId);
_variables.Remove(removed);
}
_folder.ClearChangeMasks(SystemContext, false);
}
foreach (var id in _pending.Keys)
{
if (_pending.TryRemove(id, out var value) && _variables.TryGetValue(id, out var variable)) Apply(variable, value);
}
}
}
private void ConfigureVariable(BaseDataVariableState variable, GatewayPoint point, BuiltInType type, byte access, NodeId dataType)
{
variable.DataType = dataType;
variable.AccessLevel = access;
variable.UserAccessLevel = access;
variable.OnWriteValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding, ref object value, ref StatusCode status, ref DateTime timestamp) =>
WriteValue(context, point, type, range, ref value, ref status, ref timestamp);
variable.OnReadUserAccessLevel = (ISystemContext context, NodeState node, ref byte level) =>
{
level = AccessFor(context, access);
return ServiceResult.Good;
};
variable.OnReadValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding, ref object value, ref StatusCode status, ref DateTime timestamp) =>
(AccessFor(context, access) & AccessLevels.CurrentRead) != 0 ? ServiceResult.Good : StatusCodes.BadUserAccessDenied;
}
private byte AccessFor(ISystemContext context, byte access)
{
var caller = (context as ServerSystemContext)?.UserIdentity;
if (caller?.TokenType == UserTokenType.Anonymous)
return _store.GetGatewayConfiguration().OpcUa.AllowAnonymous ? (byte)(access & AccessLevels.CurrentRead) : (byte)0;
if (caller is not GatewayIdentity identity) return 0;
var user = _store.GetAuthenticatedUser(identity.UserId);
if (user is null || user.User.UpdatedAtUtc != identity.Revision) return 0;
if (user.Permissions.Contains(GatewayPermissions.ManageSources)) return access;
return user.Permissions.Contains(GatewayPermissions.ViewDashboard) ? (byte)(access & AccessLevels.CurrentRead) : (byte)0;
}
private ServiceResult WriteValue(ISystemContext context, GatewayPoint point, BuiltInType type, NumericRange range, ref object value, ref StatusCode status, ref DateTime timestamp)
{
if (!point.Writable) return StatusCodes.BadNotWritable;
if ((AccessFor(context, AccessLevels.CurrentWrite) & AccessLevels.CurrentWrite) == 0) return StatusCodes.BadUserAccessDenied;
if (range != NumericRange.Empty) return StatusCodes.BadIndexRangeInvalid;
if (value is null || TypeInfo.Construct(value).BuiltInType != type || value is Array) return StatusCodes.BadTypeMismatch;
// UA writes carry the value, not an arbitrary client quality or source time.
if (status != StatusCodes.Good || timestamp != DateTime.MinValue) return StatusCodes.BadWriteNotSupported;
JsonElement json;
try
{
json = JsonSerializer.SerializeToElement(value);
_ = OpcUaPointTypes.Convert(json, type);
}
catch (Exception exception) when (exception is ArgumentException or FormatException or InvalidOperationException or OverflowException)
{
return StatusCodes.BadTypeMismatch;
}
var observed = DateTimeOffset.UtcNow;
try { _store.SetPointValue(point.Id, json, PointProtocol.OpcUa, observed, "Good", expectedDefinition: point); }
catch (DomainValidationException) { return StatusCodes.BadNodeIdUnknown; }
status = StatusCodes.Good;
timestamp = observed.UtcDateTime;
return ServiceResult.Good;
}
private void Apply(BaseDataVariableState variable, PointValue value)
{
try
{
variable.Value = OpcUaPointTypes.Convert(value.Value, (BuiltInType)(uint)variable.DataType.Identifier);
variable.StatusCode = string.IsNullOrWhiteSpace(value.Status) || value.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) || value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)
? StatusCodes.Good : StatusCodes.BadNoCommunication;
}
catch (Exception exception) when (exception is FormatException or InvalidOperationException or OverflowException)
{
variable.StatusCode = StatusCodes.BadTypeMismatch;
}
variable.Timestamp = value.UpdatedAtUtc.UtcDateTime;
variable.ClearChangeMasks(SystemContext, false);
}
protected override void Dispose(bool disposing)
{
if (disposing) _store.PointValueUpdated -= OnPointValue;
base.Dispose(disposing);
}
}
}
#pragma warning restore CS0618
@@ -0,0 +1,259 @@
using System.Globalization;
using System.Net.Mail;
using System.Text.Json;
using System.Text.RegularExpressions;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
public static string NotificationEndpoint(NotificationChannel channel) => channel switch
{
NotificationChannel.Mail => "https://mailapi.se-inno.de",
NotificationChannel.WhatsApp => "https://whatsappapi.se-inno.de",
NotificationChannel.Ntfy => "https://ntfy.api.se-inno.de",
_ => throw new DomainValidationException("Unbekannter Nachrichtenkanal.")
};
private static string NotificationKeyName(NotificationChannel channel)
{
_ = NotificationEndpoint(channel);
return $"integration.{channel.ToString().ToLowerInvariant()}.api-key";
}
public IReadOnlyList<NotificationIntegration> ListNotificationIntegrations()
{
using var connection = _database.OpenConnection();
return Enum.GetValues<NotificationChannel>().Select(channel => new NotificationIntegration(
channel, NotificationEndpoint(channel), GetSetting(connection, NotificationKeyName(channel)) is not null)).ToArray();
}
public void UpdateNotificationKey(NotificationChannel channel, UpdateNotificationKeyRequest request)
{
var name = NotificationKeyName(channel);
var key = request.ApiKey?.Trim();
if (!request.ClearApiKey && string.IsNullOrEmpty(key)) return;
if (!request.ClearApiKey && (string.IsNullOrEmpty(key) || key.Length > 4096 || key.Any(char.IsControl)))
throw new DomainValidationException("Bitte einen gültigen API-Key mit höchstens 4096 Zeichen eingeben.");
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
if (request.ClearApiKey) DeleteSetting(connection, name, transaction);
else SetSetting(connection, name, _secretProtector.Protect(key!), transaction);
WriteAudit(connection, "integration", $"{channel} API key {(request.ClearApiKey ? "removed" : "updated")}.", transaction);
transaction.Commit();
}
public string? GetNotificationKey(NotificationChannel channel)
{
using var connection = _database.OpenConnection();
var encrypted = GetSetting(connection, NotificationKeyName(channel));
return encrypted is null ? null : _secretProtector.Unprotect(encrypted);
}
public IReadOnlyList<AlarmRule> ListAlarmRules()
{
using var connection = _database.OpenConnection();
return ReadAlarmRules(connection);
}
private static List<AlarmRule> ReadAlarmRules(SqliteConnection connection, SqliteTransaction? transaction = null)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "SELECT configuration_json FROM alarm_rules ORDER BY rowid;";
using var reader = command.ExecuteReader();
var rules = new List<AlarmRule>();
while (reader.Read()) rules.Add(JsonSerializer.Deserialize<AlarmRule>(reader.GetString(0), JsonOptions)!);
return rules;
}
public AlarmRule SaveAlarmRule(AlarmRule rule)
{
if (string.IsNullOrWhiteSpace(rule.Name) || rule.Name.Length > 120 || rule.Message is null || rule.Message.Length > 8000 || !Enum.IsDefined(rule.Condition))
throw new DomainValidationException("Alarmname, Bedingung oder Nachricht ist ungültig.");
if (!double.IsFinite(rule.Threshold) || !double.IsFinite(rule.Hysteresis) || rule.Hysteresis < 0)
throw new DomainValidationException("Schwellwert und Hysterese müssen gültige Zahlen sein; Hysterese darf nicht negativ sein.");
if (!ListPoints().Any(point => point.Id == rule.PointId && point.Readable))
throw new DomainValidationException("Für den Alarm einen lesbaren Gateway-Datenpunkt auswählen.");
if (rule.Destinations is not { Count: > 0 and <= 20 })
throw new DomainValidationException("Ein Alarm benötigt 1 bis 20 Ziele.");
foreach (var destination in rule.Destinations)
{
ValidateAlarmDestination(destination);
if (destination.Channel == NotificationChannel.WhatsApp)
_ = NotificationTransport.NormalizeTemplateText($"Entwarnung: {rule.Name}\n{rule.Message}\nWert: {double.MinValue.ToString("R", CultureInfo.InvariantCulture)}\nZeit: {DateTimeOffset.MaxValue:O}");
if (rule.Enabled && GetNotificationKey(destination.Channel) is null)
throw new DomainValidationException($"Für {destination.Channel} zuerst einen API-Key hinterlegen.");
}
if (rule.Destinations.Select(d => (d.Channel, d.Recipient)).Distinct().Count() != rule.Destinations.Count)
throw new DomainValidationException("Dasselbe Alarmziel darf nicht mehrfach eingetragen werden.");
rule = rule with { Id = rule.Id == Guid.Empty ? Guid.NewGuid() : rule.Id, Name = rule.Name.Trim() };
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
if (FindActivePoint(connection, transaction, rule.PointId) is not { Readable: true })
throw new DomainValidationException("Der Alarm-Datenpunkt ist nicht mehr lesbar.");
using var command = connection.CreateCommand();
command.Transaction = transaction;
// Keep edge state on descriptive edits. Only a changed condition/source or enable transition
// establishes a fresh baseline, so merely editing a recipient does not repeat an alarm.
var previousRule = ListAlarmRules().SingleOrDefault(item => item.Id == rule.Id);
var keepState = previousRule is not null && previousRule.Enabled == rule.Enabled && previousRule.PointId == rule.PointId &&
previousRule.Condition == rule.Condition && previousRule.Threshold == rule.Threshold && previousRule.Hysteresis == rule.Hysteresis;
command.CommandText = """
UPDATE notification_outbox SET state = 'Cancelled', result = 'Alarm rule changed.' WHERE rule_id = $id AND state = 'Pending';
INSERT INTO alarm_rules(id, point_id, enabled, configuration_json) VALUES($id, $point, $enabled, $json)
ON CONFLICT(id) DO UPDATE SET point_id = excluded.point_id, enabled = excluded.enabled,
configuration_json = excluded.configuration_json,
active = CASE WHEN $keepState = 1 THEN alarm_rules.active ELSE NULL END,
observed_at_utc = CASE WHEN $keepState = 1 THEN alarm_rules.observed_at_utc ELSE NULL END;
""";
command.Parameters.AddWithValue("$id", rule.Id.ToString());
command.Parameters.AddWithValue("$keepState", keepState ? 1 : 0);
command.Parameters.AddWithValue("$point", rule.PointId.ToString());
command.Parameters.AddWithValue("$enabled", rule.Enabled ? 1 : 0);
command.Parameters.AddWithValue("$json", JsonSerializer.Serialize(rule, JsonOptions));
command.ExecuteNonQuery();
WriteAudit(connection, "alarm", $"Alarm '{rule.Name}' saved.", transaction);
transaction.Commit();
return rule;
}
public void DeleteAlarmRule(Guid id)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
UPDATE notification_outbox SET state = 'Cancelled', result = 'Alarm rule removed.' WHERE rule_id = $id AND state = 'Pending';
DELETE FROM alarm_rules WHERE id = $id;
""";
command.Parameters.AddWithValue("$id", id.ToString());
command.ExecuteNonQuery();
transaction.Commit();
}
public static void ValidateAlarmDestination(AlarmDestination destination)
{
_ = NotificationEndpoint(destination.Channel);
if (string.IsNullOrWhiteSpace(destination.Recipient) || destination.Recipient.Length > 254 || destination.Recipient.Any(char.IsControl))
throw new DomainValidationException("Ein gültiges Alarmziel ist erforderlich.");
if (destination.Channel == NotificationChannel.Mail && (!MailAddress.TryCreate(destination.Recipient, out var address) || address.Address != destination.Recipient))
throw new DomainValidationException("Pro Mailziel eine einzelne E-Mail-Adresse eingeben.");
if (destination.Channel == NotificationChannel.WhatsApp)
{
if (!Regex.IsMatch(destination.Recipient, @"^\+[1-9][0-9]{6,14}$", RegexOptions.CultureInvariant))
throw new DomainValidationException("WhatsApp-Rufnummer im internationalen Format +49… eingeben.");
if (!NotificationTransport.WhatsAppTemplates.Contains(destination.Template, StringComparer.Ordinal))
throw new DomainValidationException("Ein unterstütztes, bei Meta freigegebenes WhatsApp-Template auswählen.");
_ = NotificationTransport.NormalizeTemplateText(destination.PersonName, 60);
}
if (destination.Channel == NotificationChannel.Ntfy && (!Regex.IsMatch(destination.Recipient, @"^[A-Za-z0-9_-]{1,64}$", RegexOptions.CultureInvariant) || destination.Priority is < 0 or > 5 || destination.Tags is null || destination.Tags.Length > 200 || destination.Tags.Any(char.IsControl)))
throw new DomainValidationException("ntfy-Topic, Priorität (0–5) oder Tags sind ungültig.");
}
private static void EvaluateAlarms(SqliteConnection connection, SqliteTransaction transaction, PointValue value)
{
var numeric = value.Value.ValueKind switch
{
JsonValueKind.True => 1d, JsonValueKind.False => 0d,
JsonValueKind.Number when value.Value.TryGetDouble(out var number) && double.IsFinite(number) => number,
_ => (double?)null
};
if (numeric is null || value.Status is not null && !value.Status.Equals("good", StringComparison.OrdinalIgnoreCase) && !value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) return;
using var query = connection.CreateCommand();
query.Transaction = transaction;
query.CommandText = "SELECT configuration_json, active, observed_at_utc FROM alarm_rules WHERE point_id = $point AND enabled = 1;";
query.Parameters.AddWithValue("$point", value.PointId.ToString());
var records = new List<(AlarmRule Rule, bool? Active, DateTimeOffset? At)>();
using (var reader = query.ExecuteReader())
while (reader.Read()) records.Add((JsonSerializer.Deserialize<AlarmRule>(reader.GetString(0), JsonOptions)!, reader.IsDBNull(1) ? null : reader.GetBoolean(1), reader.IsDBNull(2) ? null : ParseTimestamp(reader.GetString(2))));
foreach (var (rule, previous, observedAt) in records)
{
if (observedAt >= value.UpdatedAtUtc) continue;
var active = rule.Condition switch
{
AlarmCondition.Active => numeric != 0, AlarmCondition.Inactive => numeric == 0,
AlarmCondition.Above => previous == true ? numeric > rule.Threshold - rule.Hysteresis : numeric > rule.Threshold,
AlarmCondition.Below => previous == true ? numeric < rule.Threshold + rule.Hysteresis : numeric < rule.Threshold,
_ => false
};
using var update = connection.CreateCommand();
update.Transaction = transaction;
update.CommandText = "UPDATE alarm_rules SET active = $active, observed_at_utc = $at WHERE id = $id;";
update.Parameters.AddWithValue("$active", active ? 1 : 0);
update.Parameters.AddWithValue("$at", value.UpdatedAtUtc.ToString("O"));
update.Parameters.AddWithValue("$id", rule.Id.ToString());
update.ExecuteNonQuery();
if (active == previous || !active && (previous is null || !rule.NotifyRecovery)) continue;
var title = $"{(active ? "Alarm" : "Entwarnung")}: {rule.Name}";
var message = $"{title}\n{rule.Message}\nWert: {numeric.Value.ToString(CultureInfo.InvariantCulture)}\nZeit: {value.UpdatedAtUtc:O}";
foreach (var destination in rule.Destinations) EnqueueNotification(connection, transaction, rule.Id, title, message, destination);
}
}
private static void EnqueueNotification(SqliteConnection connection, SqliteTransaction transaction, Guid ruleId, string title, string message, AlarmDestination destination)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO notification_outbox(rule_id, title, message, destination_json, state, created_at_utc) VALUES($rule, $title, $message, $destination, 'Pending', $at);";
command.Parameters.AddWithValue("$rule", ruleId.ToString());
command.Parameters.AddWithValue("$title", title);
command.Parameters.AddWithValue("$message", message);
command.Parameters.AddWithValue("$destination", JsonSerializer.Serialize(destination, JsonOptions));
command.Parameters.AddWithValue("$at", DateTimeOffset.UtcNow.ToString("O"));
command.ExecuteNonQuery();
}
public IReadOnlyList<NotificationDelivery> ListNotificationDeliveries()
{
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT id, rule_id, title, message, destination_json, state, created_at_utc, result FROM notification_outbox ORDER BY id DESC LIMIT 200;";
using var reader = command.ExecuteReader();
var results = new List<NotificationDelivery>();
while (reader.Read()) results.Add(ReadDelivery(reader));
return results;
}
public NotificationDelivery? ClaimNotification()
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
UPDATE notification_outbox SET state = 'Sending'
WHERE id = (SELECT id FROM notification_outbox WHERE state = 'Pending' ORDER BY id LIMIT 1)
RETURNING id, rule_id, title, message, destination_json, state, created_at_utc, result;
""";
NotificationDelivery? delivery;
using (var reader = command.ExecuteReader()) delivery = reader.Read() ? ReadDelivery(reader) : null;
transaction.Commit();
return delivery;
}
private static NotificationDelivery ReadDelivery(SqliteDataReader reader) => new(reader.GetInt64(0), Guid.Parse(reader.GetString(1)), reader.GetString(2), reader.GetString(3),
JsonSerializer.Deserialize<AlarmDestination>(reader.GetString(4), JsonOptions)!, reader.GetString(5), ParseTimestamp(reader.GetString(6)), reader.IsDBNull(7) ? null : reader.GetString(7));
public void CompleteNotification(long id, string state, string result)
{
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "UPDATE notification_outbox SET state = $state, result = $result WHERE id = $id AND state = 'Sending';";
command.Parameters.AddWithValue("$id", id);
command.Parameters.AddWithValue("$state", state);
command.Parameters.AddWithValue("$result", result);
command.ExecuteNonQuery();
}
public void RecoverInterruptedNotifications()
{
using var connection = _database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "UPDATE notification_outbox SET state = 'Unknown', result = 'Dienst während Versand beendet; Zustellung unbekannt. Kein automatischer Doppelversand.' WHERE state = 'Sending';";
command.ExecuteNonQuery();
}
}
@@ -0,0 +1,194 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public enum BulkMappingTarget { Mqtt, Modbus, Bacnet, OpcUa }
public sealed record BulkMappingRequest(Guid[] SourcePointIds, BulkMappingTarget Target,
Guid? ModbusServerId = null, int? FirstRegister = null, string? MqttTopicPrefix = null,
MqttMappingFormat? MqttFormat = null, MqttMonitoringSite? MqttSite = null);
public sealed record BulkMappingResult(int Created, int Existing, IReadOnlyList<string> Assignments)
{
[JsonIgnore]
public IReadOnlyList<Guid> NewMqttMappings { get; init; } = [];
}
public sealed partial class GatewayStore
{
public BulkMappingResult CreateBulkMappings(BulkMappingRequest request)
{
if (request.SourcePointIds is not { Length: > 0 } || request.SourcePointIds.Distinct().Count() != request.SourcePointIds.Length ||
!Enum.IsDefined(request.Target))
throw new DomainValidationException("Bitte Datenpunkte ohne Duplikate und ein gültiges Ziel auswählen.");
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var points = ReadPoints(connection, transaction).ToDictionary(point => point.Id);
var links = ReadMappings(connection, transaction);
var mqtt = ReadMqttMappings(connection, transaction);
var configuration = ReadGatewayConfiguration(connection, transaction);
var server = request.Target == BulkMappingTarget.Modbus
? configuration.ModbusServers.SingleOrDefault(item => item.Id == request.ModbusServerId) ??
throw new DomainValidationException("Bitte zuerst eine Modbus-TCP-Serverinstanz auswählen.")
: null;
var prefix = request.MqttTopicPrefix?.Trim().TrimEnd('/');
var mqttFormat = request.MqttFormat ?? (prefix is null ? MqttMappingFormat.SeMonitoring : MqttMappingFormat.Json);
var site = request.MqttSite ?? DefaultMonitoringSite(configuration.Installation);
var topicTemplate = ReadMqttTopicTemplate(connection, transaction);
var alarms = request.Target == BulkMappingTarget.Mqtt && mqttFormat == MqttMappingFormat.SeMonitoring
? ReadMqttAlarmPoints(connection, transaction) : [];
if (request.Target == BulkMappingTarget.Mqtt && mqttFormat != MqttMappingFormat.SeMonitoring &&
(string.IsNullOrWhiteSpace(prefix) || !IsValidMqttTopic(prefix) || prefix.Length > 850))
throw new DomainValidationException("Für MQTT ein gültiges Topic-Präfix ohne Wildcards eingeben.");
var usedRegisters = new HashSet<(ModbusArea Area, int Index)>();
if (server is not null)
{
foreach (var point in points.Values)
{
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId != server.Id) continue;
for (var offset = 0; offset < address.RegisterCount; offset++) usedRegisters.Add((address.Area, address.Address + offset));
}
}
var nextRegister = request.FirstRegister ?? server?.FirstHoldingRegister ?? 0;
var nextDiscrete = nextRegister;
if (server is not null && (nextRegister < server.FirstHoldingRegister || nextRegister >= server.FirstHoldingRegister + server.HoldingRegisterCount))
throw new DomainValidationException("Die Startadresse liegt außerhalb des Registerbereichs der Modbus-Instanz.");
var saved = new List<string>();
var seed = new List<PointMapping>();
var mqttCreated = new List<Guid>();
var skipped = 0;
foreach (var id in request.SourcePointIds)
{
if (!points.TryGetValue(id, out var source) || !source.Readable)
throw new DomainValidationException("Die Auswahl enthält einen fehlenden oder nicht lesbaren Datenpunkt.");
if (request.Target == BulkMappingTarget.Mqtt)
{
var slug = Regex.Replace(source.DisplayName.ToLowerInvariant(), "[^a-z0-9_-]+", "-").Trim('-');
if (slug.Length > 80) slug = slug[..80];
var pointDefaults = GetMqttPointDefaults(source, alarms);
var monitoring = mqttFormat == MqttMappingFormat.SeMonitoring;
if (monitoring && pointDefaults.Category is null)
throw new DomainValidationException($"'{source.DisplayName}' benötigt das MQTT-Format JSON.");
var topicName = pointDefaults.TopicName;
var topic = monitoring ? BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName) :
$"{prefix}/{(slug.Length == 0 ? "punkt" : slug)}-{source.Id:N}";
var occupied = mqtt.Where(mapping => GetMqttTopic(mapping) == topic).ToArray();
if (occupied.Any(mapping => mapping.PointId == source.Id && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
{
skipped++;
continue;
}
if (monitoring && occupied.Length > 0)
{
topicName = $"{topicName}-{source.Id:N}";
topic = BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName);
if (mqtt.Any(mapping => mapping.PointId == source.Id && GetMqttTopic(mapping) == topic &&
mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional))
{
skipped++;
continue;
}
if (mqtt.Any(mapping => GetMqttTopic(mapping) == topic))
throw new DomainValidationException($"Das erzeugte MQTT-Topic für '{source.DisplayName}' ist bereits belegt.");
}
var mqttMapping = SaveMqttMapping(connection, transaction, null, new CreateMqttMappingRequest(source.Id, mqttFormat,
MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false,
monitoring ? site.ProjectYear : null, monitoring ? site.ProjectNumber : null, monitoring ? site.IspNumber : null,
monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null,
monitoring ? topicTemplate : null))!;
mqtt.Add(mqttMapping);
mqttCreated.Add(mqttMapping.Id);
saved.Add($"{source.DisplayName} → {topic}");
continue;
}
var protocol = request.Target switch
{
BulkMappingTarget.Modbus => PointProtocol.Modbus,
BulkMappingTarget.Bacnet => PointProtocol.Bacnet,
_ => PointProtocol.OpcUa
};
if (links.Any(link => link.Enabled && link.SourcePointId == source.Id &&
points.TryGetValue(link.TargetPointId, out var target) && target.Protocol == protocol && target.Scope == PointScope.Gateway &&
(server is null || ModbusAddressing.TryParse(target, out var bound) && bound.ServerId == server.Id)))
{
skipped++;
continue;
}
var name = $"{source.DisplayName[..Math.Min(114, source.DisplayName.Length)]} [{source.Id:N}]";
var type = OpcUaPointTypes.Resolve(source.ValueType);
var binary = type == Opc.Ua.BuiltInType.Boolean;
CreatePointRequest targetRequest;
string? assignment = null;
if (server is not null)
{
var dataType = type switch
{
Opc.Ua.BuiltInType.Boolean => ModbusDataType.Boolean,
Opc.Ua.BuiltInType.Byte or Opc.Ua.BuiltInType.UInt16 => ModbusDataType.UInt16,
Opc.Ua.BuiltInType.SByte or Opc.Ua.BuiltInType.Int16 => ModbusDataType.Int16,
Opc.Ua.BuiltInType.Int32 => ModbusDataType.Int32,
Opc.Ua.BuiltInType.UInt32 => ModbusDataType.UInt32,
Opc.Ua.BuiltInType.Float or Opc.Ua.BuiltInType.Double => ModbusDataType.Float32,
_ => throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten Modbus-Werttyp.")
};
var area = binary ? ModbusArea.DiscreteInput : ModbusArea.InputRegister;
var width = dataType is ModbusDataType.UInt32 or ModbusDataType.Int32 or ModbusDataType.Float32 ? 2 : 1;
ref var cursor = ref (binary ? ref nextDiscrete : ref nextRegister);
var limit = server.FirstHoldingRegister + server.HoldingRegisterCount;
while (cursor + width <= limit && Enumerable.Range(cursor, width).Any(index => usedRegisters.Contains((area, index)))) cursor++;
if (cursor + width > limit)
throw new DomainValidationException($"Für '{source.DisplayName}' ist im Modbus-Server kein freier Adressbereich mehr verfügbar.");
var register = cursor;
cursor += width;
for (var offset = 0; offset < width; offset++) usedRegisters.Add((area, register + offset));
targetRequest = new(name, protocol, PointScope.Gateway, dataType.ToString(), true, false, null,
JsonSerializer.SerializeToElement(new { serverId = server.Id, unitId = server.UnitId, area = area.ToString(), address = register, dataType = dataType.ToString() }));
assignment = $"{area} {register}" + (width > 1 ? $"–{register + width - 1}" : "");
}
else if (protocol == PointProtocol.Bacnet)
{
if (type is Opc.Ua.BuiltInType.Null or Opc.Ua.BuiltInType.String)
throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten BACnet-Werttyp.");
targetRequest = new(name, protocol, PointScope.Gateway, binary ? "Boolean" : "Real", true, false, null,
EmptyObject(), binary ? BacnetObjectKind.BinaryValue : BacnetObjectKind.AnalogValue);
}
else
{
targetRequest = new(name, protocol, PointScope.Gateway, source.ValueType, true, false, null, EmptyObject());
}
var targetPoint = InsertPoint(connection, transaction, targetRequest);
var mapping = SaveMapping(connection, transaction, null,
new CreateMappingRequest(source.Id, targetPoint.Id, MappingDirection.OneWay, true, null, false, EmptyObject()))!.Mapping;
seed.Add(mapping);
saved.Add($"{source.DisplayName} → {assignment ?? (protocol == PointProtocol.Bacnet ? $"{targetPoint.BacnetObjectKind} {targetPoint.BacnetObjectInstance}" : targetPoint.DisplayName)}");
}
transaction.Commit();
SeedNewMappings(seed);
return new(saved.Count, skipped, saved) { NewMqttMappings = mqttCreated };
}
private void SeedNewMappings(List<PointMapping> mappings)
{
if (mappings.Count == 0) return;
var values = ListPointValues().ToDictionary(value => value.PointId);
foreach (var mapping in mappings)
{
if (!values.TryGetValue(mapping.SourcePointId, out var value) || value.Value.ValueKind == JsonValueKind.Null ||
value.Status is not (null or "Good" or "ok")) continue;
try
{
SetPointValue(mapping.TargetPointId, value.Value, value.SourceProtocol, DateTimeOffset.UtcNow, value.Status,
mapping.SourcePointId, expectedMapping: mapping);
}
catch (DomainValidationException) { /* An edited route or incompatible first sample can wait for the next value. */ }
}
}
}
@@ -0,0 +1,174 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
using Microsoft.VisualBasic.FileIO;
namespace Gateway.Api.Services;
public enum ConfigurationCsvKind { Points, Mappings, MqttMappings }
public sealed record ConfigurationCsvRequest(string Csv);
public sealed record ConfigurationCsvResult(int Created, int Updated);
public sealed partial class GatewayStore
{
private static readonly string[] PointColumns =
["Id", "Name", "Protocol", "Scope", "ValueType", "Readable", "Writable", "ExternalIdentity", "Address", "BacnetObjectKind", "BacnetObjectInstance"];
private static readonly string[] MappingColumns =
["Id", "SourcePointId", "TargetPointId", "Direction", "Enabled", "BacnetPriority", "AcknowledgeMultipleExternalWriters", "Transform"];
private static readonly string[] MqttMappingColumns =
["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty", "TopicTemplate"];
public string ExportConfigurationCsv(ConfigurationCsvKind kind)
{
IEnumerable<object?[]> records = kind switch
{
ConfigurationCsvKind.Points => ListPoints().Select(point => new object?[] { point.Id, point.DisplayName,
point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable, point.ExternalIdentity,
point.Address.GetRawText(), point.BacnetObjectKind, point.BacnetObjectInstance }),
ConfigurationCsvKind.Mappings => ListMappings().Select(mapping => new object?[] { mapping.Id, mapping.SourcePointId,
mapping.TargetPointId, mapping.Direction, mapping.Enabled, mapping.BacnetPriority,
mapping.AcknowledgeMultipleExternalWriters, mapping.Transform.GetRawText() }),
_ => ListMqttMappings().Select(mapping => new object?[] { mapping.Id, mapping.PointId, mapping.Format,
mapping.Direction, mapping.QualityOfService, mapping.Retain, mapping.ProjectYear, mapping.ProjectNumber,
mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty,
mapping.Format == MqttMappingFormat.SeMonitoring ? mapping.TopicTemplate ?? DefaultMqttTopicTemplate : null })
};
var output = new StringBuilder("\uFEFF");
output.AppendJoin(';', CsvColumns(kind)).Append("\r\n");
foreach (var record in records)
{
output.AppendJoin(';', record.Select(field =>
{
var value = Convert.ToString(field, CultureInfo.InvariantCulture) ?? "";
if (NeedsCsvEscape(value)) value = "'" + value;
return "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";
})).Append("\r\n");
}
return output.ToString();
}
public ConfigurationCsvResult ImportConfigurationCsv(ConfigurationCsvKind kind, string csv)
{
if (string.IsNullOrWhiteSpace(csv) || Encoding.UTF8.GetByteCount(csv) > 4 * 1024 * 1024)
throw new DomainValidationException("CSV fehlt oder überschreitet 4 MB.");
var content = csv.TrimStart('\uFEFF');
var endOfHeader = content.IndexOfAny(['\r', '\n']);
var header = endOfHeader < 0 ? content : content[..endOfHeader];
using var parser = new TextFieldParser(new StringReader(content))
{
HasFieldsEnclosedInQuotes = true,
TrimWhiteSpace = false
};
parser.SetDelimiters(header.Contains(';') ? ";" : ",");
var columns = CsvColumns(kind);
try
{
var importedColumns = (parser.ReadFields() ?? []).Select(value => value.Trim()).ToArray();
if (kind == ConfigurationCsvKind.MqttMappings && importedColumns.Length == columns.Length - 1)
columns = columns[..^1];
if (!importedColumns.SequenceEqual(columns, StringComparer.OrdinalIgnoreCase))
throw new DomainValidationException("Die CSV-Spalten stimmen mit der exportierten Vorlage nicht überein.");
}
catch (MalformedLineException) { throw new DomainValidationException("Ungültiger CSV-Kopf."); }
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var existing = kind switch
{
ConfigurationCsvKind.Points => ReadPoints(connection, transaction).Select(point => point.Id).ToHashSet(),
ConfigurationCsvKind.Mappings => ReadMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet(),
_ => ReadMqttMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet()
};
var seen = new HashSet<Guid>();
var created = 0;
var updated = 0;
while (!parser.EndOfData)
{
var line = parser.LineNumber;
try
{
if (created + updated >= 5000) throw new DomainValidationException("Maximal 5.000 Einträge pro Import.");
var fields = parser.ReadFields() ?? [];
if (fields.Length != columns.Length) throw new DomainValidationException($"Erwartet werden {columns.Length} Spalten.");
for (var index = 0; index < fields.Length; index++)
if (fields[index].StartsWith('\'') && NeedsCsvEscape(fields[index][1..])) fields[index] = fields[index][1..];
var id = string.IsNullOrWhiteSpace(fields[0]) ? (Guid?)null : CsvGuid(fields[0], columns[0]);
if (id is { } entry && !seen.Add(entry)) throw new DomainValidationException("Diese ID kommt mehrfach in der Datei vor.");
var update = id.HasValue && existing.Contains(id.Value);
ImportCsvRow(connection, transaction, kind, fields, id, update);
if (update) updated++;
else created++;
}
catch (Exception exception) when (exception is DomainValidationException or MalformedLineException or JsonException)
{
var message = exception is DomainValidationException ? exception.Message : "Ungültige CSV- oder JSON-Syntax.";
throw new DomainValidationException($"CSV-Zeile {line}: {message}");
}
}
transaction.Commit();
return new(created, updated);
}
private void ImportCsvRow(SqliteConnection connection, SqliteTransaction transaction, ConfigurationCsvKind kind,
string[] fields, Guid? id, bool update)
{
switch (kind)
{
case ConfigurationCsvKind.Points:
var point = new CreatePointRequest(fields[1], CsvEnum<PointProtocol>(fields[2], "Protocol"),
CsvEnum<PointScope>(fields[3], "Scope"), fields[4], CsvBool(fields[5], "Readable"), CsvBool(fields[6], "Writable"),
CsvOptional(fields[7]), JsonSerializer.Deserialize<JsonElement>(fields[8]),
CsvOptional(fields[9]) is { } objectKind ? CsvEnum<BacnetObjectKind>(objectKind, "BacnetObjectKind") : null,
CsvInteger(fields[10], "BacnetObjectInstance") is int instance and >= 0 ? (uint)instance :
string.IsNullOrWhiteSpace(fields[10]) ? null : throw new DomainValidationException("BacnetObjectInstance erwartet eine nichtnegative Ganzzahl."));
if (update) UpdatePoint(connection, transaction, id!.Value, point);
else InsertPoint(connection, transaction, point, id);
break;
case ConfigurationCsvKind.Mappings:
var mapping = new CreateMappingRequest(CsvGuid(fields[1], "SourcePointId"), CsvGuid(fields[2], "TargetPointId"),
CsvEnum<MappingDirection>(fields[3], "Direction"), CsvBool(fields[4], "Enabled"),
CsvInteger(fields[5], "BacnetPriority"), CsvBool(fields[6], "AcknowledgeMultipleExternalWriters"),
JsonSerializer.Deserialize<JsonElement>(fields[7]));
SaveMapping(connection, transaction, update ? id : null, mapping, update ? null : id);
break;
case ConfigurationCsvKind.MqttMappings:
var mqtt = new CreateMqttMappingRequest(CsvGuid(fields[1], "PointId"), CsvEnum<MqttMappingFormat>(fields[2], "Format"),
CsvEnum<MqttDirection>(fields[3], "Direction"), CsvEnum<MqttQualityOfService>(fields[4], "QualityOfService"),
CsvBool(fields[5], "Retain"), CsvInteger(fields[6], "ProjectYear"), CsvOptional(fields[7]), CsvOptional(fields[8]),
CsvOptional(fields[9]) is { } category ? CsvEnum<SeMonitoringCategory>(category, "SeCategory") : null,
CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12]),
fields.Length > 13 ? CsvOptional(fields[13]) : DefaultMqttTopicTemplate);
SaveMqttMapping(connection, transaction, update ? id : null, mqtt, update ? null : id);
break;
}
}
private static string[] CsvColumns(ConfigurationCsvKind kind) => kind switch
{
ConfigurationCsvKind.Points => PointColumns,
ConfigurationCsvKind.Mappings => MappingColumns,
_ => MqttMappingColumns
};
private static string? CsvOptional(string text) => string.IsNullOrWhiteSpace(text) ? null : text;
private static Guid CsvGuid(string text, string field) => Guid.TryParse(text, out var value) && value != Guid.Empty
? value : throw new DomainValidationException($"{field} erwartet eine gültige ID.");
private static int? CsvInteger(string text, string field) => string.IsNullOrWhiteSpace(text) ? null :
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)
? value : throw new DomainValidationException($"{field} erwartet eine Ganzzahl.");
private static bool CsvBool(string text, string field) => text.Trim().ToLowerInvariant() switch
{
"true" or "1" => true,
"false" or "0" => false,
_ => throw new DomainValidationException($"{field} erwartet True oder False.")
};
private static T CsvEnum<T>(string text, string field) where T : struct, Enum =>
Enum.TryParse<T>(text, true, out var value) && Enum.IsDefined(value)
? value : throw new DomainValidationException($"{field} enthält einen unbekannten Wert.");
private static bool NeedsCsvEscape(string value) => value.AsSpan().TrimStart(' ') is ['=' or '+' or '-' or '@' or '\t' or '\r' or '\n' or '\'', ..];
}
@@ -0,0 +1,53 @@
using System.Globalization;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
public MqttMappingDefaults GetMqttMappingDefaults()
{
using var connection = _database.OpenConnection();
var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection).Installation);
var alarms = ReadMqttAlarmPoints(connection);
return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray(),
TopicTemplateView(ReadMqttTopicTemplate(connection), site));
}
internal GatewayPoint? GetMqttPoint(Guid id)
{
using var connection = _database.OpenConnection();
return FindActivePoint(connection, null, id);
}
internal static bool IsBooleanMqttPoint(GatewayPoint point) =>
point.BacnetObjectKind is BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue ||
OpcUaPointTypes.Resolve(point.ValueType) == Opc.Ua.BuiltInType.Boolean;
private static MqttMonitoringSite DefaultMonitoringSite(InstallationIdentity? installation)
{
var project = installation?.ProjectNumber;
var year = project is { Length: >= 7 } && IsProjectNumber(project) &&
int.TryParse(project.AsSpan(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out var projectYear)
? 2000 + projectYear : (int?)null;
return new(year, project, installation is null ? null : $"ISP{installation.IspNumber}");
}
private static HashSet<Guid> ReadMqttAlarmPoints(SqliteConnection connection, SqliteTransaction? transaction = null) =>
ReadAlarmRules(connection, transaction).Where(rule => rule.Enabled).Select(rule => rule.PointId).ToHashSet();
private static MqttPointDefaults GetMqttPointDefaults(GatewayPoint point, HashSet<Guid> alarms)
{
var category = GetMqttPointClassification(point) switch
{
MqttPointClassification.Analog => SeMonitoringCategory.Analog,
MqttPointClassification.Digital => alarms.Contains(point.Id) ? SeMonitoringCategory.Alarms : SeMonitoringCategory.Notify,
_ => (SeMonitoringCategory?)null
};
var name = new string(point.DisplayName.Select(character => char.IsLetterOrDigit(character) || character is '_' or '-' ? character : '_').ToArray()).Trim('_');
if (name.EndsWith("_Wert", StringComparison.OrdinalIgnoreCase)) name = name[..^5];
return new(point.Id, category, name.Length == 0 ? "Punkt" : name);
}
}
@@ -0,0 +1,58 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
internal List<GatewayPoint> ListMqttExternalPoints()
{
using var connection = _database.OpenConnection();
return ReadMqttExternalPoints(connection);
}
private static List<GatewayPoint> ReadMqttExternalPoints(SqliteConnection connection, SqliteTransaction? transaction = null)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = PointSelect + " WHERE deleted_at_utc IS NULL AND protocol = 'Mqtt' AND scope = 'External';";
using var reader = command.ExecuteReader();
var points = new List<GatewayPoint>();
while (reader.Read())
{
var point = ReadPoint(reader);
if (MqttExternalTopics.Address(point) is not null) points.Add(point);
}
return points;
}
internal MqttTopicImportResult ImportMqttExternalPoints(MqttConfiguration broker, ObservedMqttTopic[] topics, int unavailable)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
if (ReadGatewayConfiguration(connection, transaction).Mqtt != broker)
throw new DomainValidationException("Die MQTT-Broker-Konfiguration wurde während des Imports geändert.");
var known = ReadMqttExternalPoints(connection, transaction).Select(MqttExternalTopics.Address).ToHashSet(StringComparer.Ordinal);
var created = 0;
var existing = 0;
foreach (var topic in topics)
{
if (!known.Add(topic.Topic)) { existing++; continue; }
var leaf = topic.Topic[(topic.Topic.LastIndexOf('/') + 1)..].Trim();
if (leaf.Length == 0) leaf = topic.Topic.Trim();
if (leaf.Length == 0) leaf = "MQTT-Datenpunkt";
var identity = "mqtt-topic:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(topic.Topic)));
var point = InsertPoint(connection, transaction, new CreatePointRequest(leaf[..Math.Min(leaf.Length, 160)],
PointProtocol.Mqtt, PointScope.External, topic.ValueType!, true, false, identity,
JsonSerializer.SerializeToElement(new { topic = topic.Topic })));
WritePointValue(connection, transaction, new(point.Id, topic.Value!.Value, PointProtocol.Mqtt,
topic.ReceivedAtUtc, "Good", point.Id));
created++;
}
transaction.Commit();
return new(created, existing, unavailable);
}
}
@@ -0,0 +1,97 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
private const string MqttTopicTemplateKey = "mqtt_topic_template";
private const string DefaultMqttTopicTemplate = "Projekte{Jahr}/{Projekt}/{ISP}/{Kategorie}/{Datenpunkt}_Wert";
private static readonly Regex MqttTemplateTokenPattern = new(@"\{([^{}]*)\}", RegexOptions.CultureInvariant);
private static readonly MqttTopicPlaceholder[] MqttTopicPlaceholders =
[
new("{Jahr}", "Projektjahr"),
new("{Projekt}", "Projektnummer mit P"),
new("{ISP}", "ISP mit Präfix"),
new("{Kategorie}", "Analog, Notify, Alarms oder Setpoints"),
new("{Datenpunkt}", "Punktname aus dem Mapping"),
new("{Rechnername}", "Aus Projekt und ISP")
];
public MqttTopicTemplateView UpdateMqttTopicTemplate(string template)
{
var normalized = template?.Trim() ?? "";
ValidateMqttTopicTemplate(normalized);
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection, transaction).Installation);
SetSetting(connection, MqttTopicTemplateKey, normalized, transaction);
WriteAudit(connection, "mqtt", "Default MQTT topic template updated.", transaction);
transaction.Commit();
return TopicTemplateView(normalized, site);
}
private static string ReadMqttTopicTemplate(SqliteConnection connection, SqliteTransaction? transaction = null) =>
GetSetting(connection, MqttTopicTemplateKey, transaction) ?? DefaultMqttTopicTemplate;
private static MqttTopicTemplateView TopicTemplateView(string template, MqttMonitoringSite site) =>
new(template, DefaultMqttTopicTemplate, MqttTopicPlaceholders, TopicTemplateValues(
new(site.ProjectYear ?? DateTimeOffset.UtcNow.Year, site.ProjectNumber ?? "P190726", site.IspNumber ?? "ISP1"),
SeMonitoringCategory.Analog, "Vorlauftemperatur"));
private static Dictionary<string, string> TopicTemplateValues(MqttMonitoringSite site, SeMonitoringCategory category, string name)
{
var isp = site.IspNumber ?? "";
var project = site.ProjectNumber ?? "";
return new(StringComparer.Ordinal)
{
["{Jahr}"] = site.ProjectYear?.ToString(CultureInfo.InvariantCulture) ?? "",
["{Projekt}"] = project,
["{ISP}"] = isp,
["{Kategorie}"] = GetCategorySegment(category),
["{Datenpunkt}"] = name,
["{Rechnername}"] = isp.StartsWith("ISP", StringComparison.Ordinal) && project.Length > 0
? $"SE-UGW-{project}-ISP{isp[3..].PadLeft(2, '0')}" : ""
};
}
private static void ValidateMqttTopicTemplate(string template)
{
if (template.Length is 0 or > 1024 || template.Any(char.IsControl))
throw new DomainValidationException("Der MQTT-Standardpfad muss 1 bis 1024 Zeichen enthalten, ohne Steuerzeichen.");
if (!template.Contains("{Datenpunkt}", StringComparison.Ordinal))
throw new DomainValidationException("Der MQTT-Standardpfad benötigt den Platzhalter {Datenpunkt}.");
var sample = BuildMonitoringTopic(template, new(2019, "P190726", "ISP1"), SeMonitoringCategory.Analog, "Vorlauftemperatur");
if (!MqttExternalTopics.IsTopic(sample))
throw new DomainValidationException("Der erzeugte MQTT-Pfad ist zu lang oder enthält Wildcards (+ oder #).");
}
private static void ValidateMqttTopicInputs(string template, CreateMqttMappingRequest mapping)
{
ValidateMqttTopicTemplate(template);
var needsHost = template.Contains("{Rechnername}", StringComparison.Ordinal);
if (template.Contains("{Jahr}", StringComparison.Ordinal) && mapping.ProjectYear is not (>= 2000 and <= 2100))
throw new DomainValidationException("Für {Jahr} ein Projektjahr zwischen 2000 und 2100 eingeben.");
if (needsHost || template.Contains("{Projekt}", StringComparison.Ordinal))
{
var project = mapping.ProjectNumber;
var valid = template == DefaultMqttTopicTemplate ? IsProjectNumber(project)
: project is not null && Regex.IsMatch(project, "^P[A-Z0-9_-]{1,32}$", RegexOptions.CultureInvariant);
if (!valid) throw new DomainValidationException("Für den MQTT-Pfad eine gültige Projektnummer mit Präfix P eingeben.");
}
if ((needsHost || template.Contains("{ISP}", StringComparison.Ordinal)) && !IsIspNumber(mapping.IspNumber))
throw new DomainValidationException("Für den MQTT-Pfad eine gültige ISP-Nummer mit Präfix ISP eingeben.");
}
private static string BuildMonitoringTopic(string template, MqttMonitoringSite site, SeMonitoringCategory category, string name)
{
var values = TopicTemplateValues(site, category, name);
var topic = MqttTemplateTokenPattern.Replace(template, match => values.TryGetValue(match.Value, out var value) ? value :
throw new DomainValidationException($"Unbekannter MQTT-Platzhalter '{match.Value}'."));
if (topic.IndexOfAny(['{', '}']) >= 0)
throw new DomainValidationException("Ein MQTT-Platzhalter enthält eine unvollständige Klammer.");
return topic;
}
}
@@ -0,0 +1,78 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Opc.Ua;
namespace Gateway.Api.Services;
public sealed record SaveOpcUaClientRequest(OpcUaClientConfiguration Configuration, string? Password = null, bool ClearPassword = false);
public sealed record OpcUaClientView(OpcUaClientConfiguration Configuration, bool HasPassword);
public sealed record OpcUaImportPoint(string NodeId, string DisplayName, string ValueType, bool Readable, bool Writable);
public sealed record OpcUaImportRequest(Guid ClientId, IReadOnlyList<OpcUaImportPoint> Points);
public sealed partial class GatewayStore
{
public IReadOnlyList<OpcUaClientView> ListOpcUaClients()
{
using var connection = _database.OpenConnection();
return (GetGatewayConfiguration().OpcUa.Clients ?? []).Select(client => new OpcUaClientView(client, GetSetting(connection, $"opcua.password.{client.Id}") is not null)).ToArray();
}
public OpcUaClientView SaveOpcUaClient(SaveOpcUaClientRequest request)
{
var client = request.Configuration with { Id = request.Configuration.Id == Guid.Empty ? Guid.NewGuid() : request.Configuration.Id, Name = request.Configuration.Name.Trim(), EndpointUrl = request.Configuration.EndpointUrl.Trim() };
if (client.AuthenticationMode is not (OpcUaAuthenticationMode.Anonymous or OpcUaAuthenticationMode.Username))
throw new DomainValidationException("Der OPC-UA-Client unterstützt derzeit Anonym oder Benutzer/Passwort.");
if (client.AuthenticationMode == OpcUaAuthenticationMode.Username && !client.UseSecurity)
throw new DomainValidationException("Benutzer/Passwort erfordert einen gesicherten Kanal.");
if (client.PublishingIntervalMilliseconds is < 100 or > 60_000)
throw new DomainValidationException("OPC-UA-Publishing-Intervall: 100 bis 60000 ms.");
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var configuration = JsonSerializer.Deserialize<GatewayConfiguration>(GetSetting(connection, GatewayConfigurationKey)!, JsonOptions)!;
var clients = (configuration.OpcUa.Clients ?? []).Where(item => item.Id != client.Id).Append(client).ToArray();
configuration = configuration with { OpcUa = configuration.OpcUa with { Clients = clients } };
ValidateGatewayConfiguration(configuration);
var key = $"opcua.password.{client.Id}";
if (request.ClearPassword) DeleteSetting(connection, key, transaction);
else if (request.Password is not null) SetSetting(connection, key, _secretProtector.Protect(request.Password), transaction);
if (client.AuthenticationMode == OpcUaAuthenticationMode.Username && GetSetting(connection, key) is null)
throw new DomainValidationException("Bitte ein OPC-UA-Passwort hinterlegen.");
SetSetting(connection, GatewayConfigurationKey, JsonSerializer.Serialize(configuration, JsonOptions), transaction);
// Password rotations also invalidate running client sessions, without exposing a secret in status.
SetSetting(connection, $"opcua.revision.{client.Id}", Guid.NewGuid().ToString(), transaction);
WriteAudit(connection, "opcua", $"Client '{client.Name}' saved.", transaction);
transaction.Commit();
return new OpcUaClientView(client, GetSetting(connection, key) is not null);
}
public (string? Password, string Revision) GetOpcUaClientCredentials(Guid id)
{
using var connection = _database.OpenConnection();
var encrypted = GetSetting(connection, $"opcua.password.{id}");
return (encrypted is null ? null : _secretProtector.Unprotect(encrypted), GetSetting(connection, $"opcua.revision.{id}") ?? "");
}
public IReadOnlyList<GatewayPoint> ImportOpcUaPoints(OpcUaImportRequest request)
{
var client = (GetGatewayConfiguration().OpcUa.Clients ?? []).SingleOrDefault(item => item.Id == request.ClientId)
?? throw new DomainValidationException("Bitte zuerst eine OPC-UA-Verbindung speichern.");
if (request.Points.Count is < 1 or > 5000) throw new DomainValidationException("Zwischen 1 und 5000 Punkte je Import sind erlaubt.");
foreach (var item in request.Points)
{
if (OpcUaPointTypes.Resolve(item.ValueType) == BuiltInType.Null || !item.Readable || string.IsNullOrWhiteSpace(item.DisplayName))
throw new DomainValidationException("Nur lesbare skalare OPC-UA-Variablen können importiert werden.");
try { _ = ExpandedNodeId.Parse(item.NodeId); }
catch (Exception exception) when (exception is ServiceResultException or FormatException) { throw new DomainValidationException("Ungültige OPC-UA-NodeId."); }
}
var points = ListPoints();
var imported = new List<GatewayPoint>();
foreach (var item in request.Points.DistinctBy(item => item.NodeId))
{
var identity = $"opcua:{new Uri(client.EndpointUrl).AbsoluteUri}:{item.NodeId}";
if (points.Any(point => point.ExternalIdentity == identity)) continue;
imported.Add(CreatePoint(new CreatePointRequest(item.DisplayName, PointProtocol.OpcUa, PointScope.External, item.ValueType, true, item.Writable, identity,
JsonSerializer.SerializeToElement(new { clientId = client.Id, nodeId = item.NodeId }))));
}
return imported;
}
}
@@ -0,0 +1,201 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Gateway.Api.Domain;
using Microsoft.Data.Sqlite;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
private const string PointSelect = """
SELECT id, display_name, protocol, scope, value_type, readable, writable, external_identity,
address_json, created_at_utc, bacnet_object_kind, bacnet_object_instance FROM points
""";
private static GatewayPoint? FindActivePoint(SqliteConnection connection, SqliteTransaction? transaction, Guid id)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = PointSelect + " WHERE id = $id AND deleted_at_utc IS NULL;";
command.Parameters.AddWithValue("$id", id.ToString());
using var reader = command.ExecuteReader();
return reader.Read() ? ReadPoint(reader) : null;
}
private static bool MatchesPointDefinition(GatewayPoint current, GatewayPoint expected) =>
current.Protocol == expected.Protocol && current.Scope == expected.Scope &&
current.Readable == expected.Readable && current.Writable == expected.Writable &&
string.Equals(current.ValueType, expected.ValueType, StringComparison.OrdinalIgnoreCase) &&
current.ExternalIdentity == expected.ExternalIdentity && current.BacnetObjectKind == expected.BacnetObjectKind &&
current.BacnetObjectInstance == expected.BacnetObjectInstance &&
current.Address.GetRawText() == expected.Address.GetRawText();
public bool IsPointDefinitionCurrent(GatewayPoint expected)
{
using var connection = _database.OpenConnection();
return FindActivePoint(connection, null, expected.Id) is { } current && MatchesPointDefinition(current, expected);
}
private static GatewayPoint PreparePoint(SqliteConnection connection, SqliteTransaction transaction,
CreatePointRequest request, GatewayPoint? existing)
{
ValidatePointRequest(request);
var name = request.DisplayName.Trim();
var instance = request.BacnetObjectKind is null ? null : request.BacnetObjectInstance;
if (request.Protocol == PointProtocol.Bacnet && request.Scope == PointScope.Gateway)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
SELECT EXISTS(SELECT 1 FROM points WHERE deleted_at_utc IS NULL AND protocol = 'Bacnet'
AND scope = 'Gateway' AND display_name = $name AND id <> $id);
""";
command.Parameters.AddWithValue("$name", name);
command.Parameters.AddWithValue("$id", existing?.Id.ToString() ?? "");
if ((long)command.ExecuteScalar()! != 0 || ReadGatewayConfiguration(connection, transaction).DeviceName == name)
throw new DomainValidationException("BACnet-Object_Name muss innerhalb des Gateway-Geräts eindeutig sein.");
var kind = request.BacnetObjectKind!.Value;
instance ??= existing is { Protocol: PointProtocol.Bacnet, Scope: PointScope.Gateway } && existing.BacnetObjectKind == kind
? existing.BacnetObjectInstance : null;
instance ??= GetNextBacnetObjectInstance(connection, transaction, kind);
}
return new GatewayPoint(existing?.Id ?? Guid.NewGuid(), name, request.Protocol, request.Scope,
request.ValueType.Trim(), request.Readable, request.Writable, NormalizeNullable(request.ExternalIdentity),
request.Address.Clone(), existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow, request.BacnetObjectKind, instance);
}
private static void BindPoint(SqliteCommand command, GatewayPoint point)
{
command.Parameters.AddWithValue("$id", point.Id.ToString());
command.Parameters.AddWithValue("$displayName", point.DisplayName);
command.Parameters.AddWithValue("$protocol", point.Protocol.ToString());
command.Parameters.AddWithValue("$scope", point.Scope.ToString());
command.Parameters.AddWithValue("$valueType", point.ValueType);
command.Parameters.AddWithValue("$readable", point.Readable ? 1 : 0);
command.Parameters.AddWithValue("$writable", point.Writable ? 1 : 0);
command.Parameters.AddWithValue("$externalIdentity", (object?)point.ExternalIdentity ?? DBNull.Value);
command.Parameters.AddWithValue("$address", point.Address.GetRawText());
command.Parameters.AddWithValue("$bacnetObjectKind", (object?)point.BacnetObjectKind?.ToString() ?? DBNull.Value);
command.Parameters.AddWithValue("$bacnetObjectInstance", (object?)point.BacnetObjectInstance ?? DBNull.Value);
}
private static DomainValidationException PointIdentityConflict(GatewayPoint point) =>
new(point.Scope == PointScope.Gateway && point.BacnetObjectKind is not null
? "BACnet-Objekttyp und -instanz sind bereits vergeben."
: "Die externe Punktadresse existiert bereits.");
public GatewayPoint? UpdatePoint(Guid id, CreatePointRequest request)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var updated = UpdatePoint(connection, transaction, id, request);
transaction.Commit();
return updated;
}
private static GatewayPoint? UpdatePoint(SqliteConnection connection, SqliteTransaction transaction, Guid id, CreatePointRequest request)
{
var current = FindActivePoint(connection, transaction, id);
if (current is null) return null;
var updated = PreparePoint(connection, transaction, request, current);
bool signalChanged = current.Protocol != updated.Protocol || current.Scope != updated.Scope ||
!string.Equals(current.ValueType, updated.ValueType, StringComparison.OrdinalIgnoreCase) ||
current.ExternalIdentity != updated.ExternalIdentity || current.BacnetObjectKind != updated.BacnetObjectKind ||
current.BacnetObjectInstance != updated.BacnetObjectInstance ||
!JsonNode.DeepEquals(JsonNode.Parse(current.Address.GetRawText()), JsonNode.Parse(updated.Address.GetRawText()));
var dependencies = ReadPointDependencies(connection, transaction, id);
if ((signalChanged || current.Readable != updated.Readable || current.Writable != updated.Writable) &&
(dependencies.Mappings + dependencies.MqttMappings + dependencies.Alarms > 0))
throw new DomainValidationException("Der Punkt ist mit Mappings oder Alarmen verknüpft. Seine Adresse, sein Typ und seine Zugriffe sind in dieser Zuordnung fest. Der Name kann geändert werden.");
if (!updated.Readable && current.Readable && dependencies.TrendLogs > 0)
throw new DomainValidationException("Der Datenpunkt wird von einem Trendlog gelesen.");
// Preserve identical address JSON so a formatting-only edit never recreates a native object.
if (!signalChanged) updated = updated with { Address = current.Address };
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
UPDATE points SET display_name=$displayName, protocol=$protocol, scope=$scope, value_type=$valueType,
readable=$readable, writable=$writable, external_identity=$externalIdentity,
address_json=$address, bacnet_object_kind=$bacnetObjectKind, bacnet_object_instance=$bacnetObjectInstance
WHERE id=$id AND deleted_at_utc IS NULL;
""";
BindPoint(command, updated);
try { command.ExecuteNonQuery(); }
catch (SqliteException exception) when (exception.SqliteErrorCode == 19) { throw PointIdentityConflict(updated); }
if (signalChanged) ClearPointRuntime(connection, transaction, id);
else if (current.Writable && !updated.Writable)
ExecutePointSql(connection, transaction, id, "DELETE FROM bacnet_commands WHERE point_id=$id AND state='pending';");
WriteAudit(connection, "point", $"Point '{updated.DisplayName}' updated ({id}).", transaction);
return updated;
}
public PointDependencies? GetPointDependencies(Guid id)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction(deferred: true);
if (FindActivePoint(connection, transaction, id) is null) return null;
return ReadPointDependencies(connection, transaction, id);
}
private static PointDependencies ReadPointDependencies(SqliteConnection connection, SqliteTransaction transaction, Guid id)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
SELECT (SELECT COUNT(*) FROM mappings WHERE source_point_id=$id OR target_point_id=$id),
(SELECT COUNT(*) FROM mqtt_mappings WHERE point_id=$id),
(SELECT COUNT(*) FROM alarm_rules WHERE point_id=$id),
(SELECT COUNT(*) FROM trend_logs WHERE source_point_id=$id);
""";
command.Parameters.AddWithValue("$id", id.ToString());
using var reader = command.ExecuteReader();
reader.Read();
return new(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3));
}
public bool DeletePoint(Guid id, string? confirmation)
{
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var point = FindActivePoint(connection, transaction, id);
if (point is null) return false;
var dependencies = ReadPointDependencies(connection, transaction, id);
if (!string.Equals(confirmation, dependencies.Confirmation, StringComparison.Ordinal) &&
(confirmation is not null || dependencies is not { Mappings: 0, MqttMappings: 0, Alarms: 0, TrendLogs: 0 }))
throw new DomainValidationException("Der Punkt wird verwendet. Bitte prüfe die Verknüpfungen und bestätige das Löschen erneut.");
ExecutePointSql(connection, transaction, id, """
DELETE FROM mappings WHERE source_point_id=$id OR target_point_id=$id;
DELETE FROM mqtt_mappings WHERE point_id=$id;
UPDATE notification_outbox SET state='Cancelled', result='Alarm point removed.'
WHERE state='Pending' AND rule_id IN (SELECT id FROM alarm_rules WHERE point_id=$id);
DELETE FROM alarm_rules WHERE point_id=$id;
UPDATE trend_logs SET enabled=0 WHERE source_point_id=$id;
UPDATE points SET deleted_at_utc=$now WHERE id=$id;
""");
ClearPointRuntime(connection, transaction, id);
WriteAudit(connection, "point", $"Point '{point.DisplayName}' deleted ({id}).", transaction);
transaction.Commit();
return true;
}
private static void ClearPointRuntime(SqliteConnection connection, SqliteTransaction transaction, Guid id) =>
ExecutePointSql(connection, transaction, id, """
DELETE FROM point_values WHERE point_id=$id;
DELETE FROM bacnet_commands WHERE point_id=$id;
DELETE FROM bacnet_properties WHERE point_id=$id;
DELETE FROM bacnet_observations WHERE point_id=$id;
""");
private static void ExecutePointSql(SqliteConnection connection, SqliteTransaction transaction, Guid id, string sql)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = sql;
command.Parameters.AddWithValue("$id", id.ToString());
command.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow.ToString("O"));
command.ExecuteNonQuery();
}
}
@@ -0,0 +1,84 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed partial class GatewayStore
{
private static readonly DisplayUnit[] DefaultUnits =
[new("%", "Prozent", true), new("°C", "Grad Celsius", true), new("A", "Ampere", true),
new("bool", "Digital / Bool", true), new("K", "Kelvin", true), new("Pa", "Pascal", true), new("V", "Volt", true)];
public IReadOnlyList<DisplayUnit> ListDisplayUnits()
{
using var connection = _database.OpenConnection();
var json = GetSetting(connection, "presentation.units");
return json is null ? DefaultUnits : JsonSerializer.Deserialize<DisplayUnit[]>(json, JsonOptions)!;
}
public DisplayUnit SaveDisplayUnit(DisplayUnit unit)
{
if (string.IsNullOrWhiteSpace(unit.Symbol) || unit.Symbol.Length > 24 || unit.Symbol.Any(char.IsControl) ||
string.IsNullOrWhiteSpace(unit.Name) || unit.Name.Length > 100)
throw new DomainValidationException("Symbol (1–24 Zeichen) und Bezeichnung (1–100 Zeichen) angeben.");
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var json = GetSetting(connection, "presentation.units");
var units = (json is null ? DefaultUnits : JsonSerializer.Deserialize<DisplayUnit[]>(json, JsonOptions)!).ToList();
var saved = unit with { Symbol = unit.Symbol.Trim(), Name = unit.Name.Trim(), IsSystem = DefaultUnits.Any(item => item.Symbol == unit.Symbol.Trim()) };
units.RemoveAll(item => item.Symbol == saved.Symbol);
units.Add(saved);
SetSetting(connection, "presentation.units", JsonSerializer.Serialize(units.OrderBy(item => item.Symbol), JsonOptions), transaction);
transaction.Commit();
return saved;
}
public IReadOnlyList<PointPresentation> ListPointPresentations()
{
using var connection = _database.OpenConnection();
var json = GetSetting(connection, "presentation.points");
return json is null ? [] : JsonSerializer.Deserialize<PointPresentation[]>(json, JsonOptions)!;
}
public void SavePointPresentations(IReadOnlyList<PointPresentation> updates)
{
if (updates.Count > 10000 || updates.Select(item => item.PointId).Distinct().Count() != updates.Count)
throw new DomainValidationException("Maximal 10000 eindeutige Datenpunkte gleichzeitig bearbeiten.");
var points = ListPoints().Select(point => point.Id).ToHashSet();
var units = ListDisplayUnits().Select(unit => unit.Symbol).Append("").ToHashSet(StringComparer.Ordinal);
foreach (var item in updates)
{
if (!points.Contains(item.PointId) || string.IsNullOrWhiteSpace(item.Alias) || item.Alias.Length > 160 ||
!units.Contains(item.Unit) || !double.IsFinite(item.Factor) || item.Factor == 0 ||
item.Kind is not ("analog" or "digital") || !Regex.IsMatch(item.Color ?? "", "^#[0-9a-fA-F]{6}$"))
throw new DomainValidationException("Alias, Einheit, Faktor, Typ oder Farbe ist ungültig.");
}
using var connection = _database.OpenConnection();
using var transaction = connection.BeginTransaction();
var json = GetSetting(connection, "presentation.points");
var existing = (json is null ? [] : JsonSerializer.Deserialize<PointPresentation[]>(json, JsonOptions)!).ToDictionary(item => item.PointId);
foreach (var item in updates) existing[item.PointId] = item;
SetSetting(connection, "presentation.points", JsonSerializer.Serialize(existing.Values, JsonOptions), transaction);
WriteAudit(connection, "aliases", $"Updated presentation for {updates.Count} points.", transaction);
transaction.Commit();
}
public IReadOnlyList<DashboardWidget> GetDashboard(Guid userId)
{
using var connection = _database.OpenConnection();
var json = GetSetting(connection, $"dashboard.{userId}");
return json is null ? [] : JsonSerializer.Deserialize<DashboardWidget[]>(json, JsonOptions)!;
}
public void SaveDashboard(Guid userId, bool isAdministrator, IReadOnlyList<DashboardWidget> widgets)
{
var visible = ListTrendSelections(userId, isAdministrator).Select(selection => selection.Id).ToHashSet();
if (widgets.Count > 24 || widgets.Select(widget => widget.Id).Distinct().Count() != widgets.Count ||
widgets.Any(widget => widget.Id == Guid.Empty || string.IsNullOrWhiteSpace(widget.Title) || widget.Title.Length > 120 ||
!visible.Contains(widget.SelectionId) || widget.RangeHours is < 1 or > 720 || widget.Type is not ("Graph" or "Values")))
throw new DomainValidationException("Ungültiges Widget: Titel, sichtbare Auswahl, Typ und Zeitraum prüfen (maximal 24 Widgets).");
using var connection = _database.OpenConnection();
SetSetting(connection, $"dashboard.{userId}", JsonSerializer.Serialize(widgets, JsonOptions));
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,81 @@
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Gateway.Api.Services;
/// <summary>Read-only inventory of interfaces that are visible to the local gateway process.</summary>
public sealed class HardwareDiscoveryService
{
public GatewayHardwareInventory GetInventory()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(network => network.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(network => new GatewayNetworkInterface(
network.Name,
network.Description,
network.OperationalStatus == OperationalStatus.Up,
network.GetPhysicalAddress().ToString(),
network.GetIPProperties().UnicastAddresses
.Where(address => address.Address.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6)
.Select(address => address.Address.ToString())
.OrderBy(address => address, StringComparer.Ordinal)
.ToArray()))
.OrderBy(network => network.Name, StringComparer.Ordinal)
.ToArray();
var serialPaths = new HashSet<string>(StringComparer.Ordinal);
if (OperatingSystem.IsLinux())
{
if (Directory.Exists("/dev/serial/by-id"))
{
foreach (var path in Directory.EnumerateFileSystemEntries("/dev/serial/by-id"))
{
serialPaths.Add(path);
}
}
if (Directory.Exists("/dev"))
{
foreach (var path in Directory.EnumerateFiles("/dev", "tty*"))
{
var name = Path.GetFileName(path);
if (name.StartsWith("ttyUSB", StringComparison.Ordinal) ||
name.StartsWith("ttyACM", StringComparison.Ordinal) ||
name.StartsWith("ttyS", StringComparison.Ordinal) ||
name.StartsWith("ttyAMA", StringComparison.Ordinal))
{
serialPaths.Add(path);
}
}
}
}
return new GatewayHardwareInventory(
interfaces,
serialPaths.OrderBy(path => path, StringComparer.Ordinal).Select(path => new GatewaySerialDevice(path, GetSerialTarget(path))).ToArray());
}
private static string? GetSerialTarget(string path)
{
try
{
return File.ResolveLinkTarget(path, false)?.FullName;
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
}
public sealed record GatewayHardwareInventory(
IReadOnlyList<GatewayNetworkInterface> NetworkInterfaces,
IReadOnlyList<GatewaySerialDevice> SerialDevices);
public sealed record GatewayNetworkInterface(string Name, string Description, bool IsUp, string MacAddress, IReadOnlyList<string> Addresses);
public sealed record GatewaySerialDevice(string DevicePath, string? TargetPath);
@@ -0,0 +1,39 @@
using System.Net.Sockets;
using System.Text.Json;
namespace Gateway.Api.Services;
public sealed record HostNetworkProfile(string Interface, string Mode, string? Address, int? PrefixLength,
string? Gateway, string[]? Dns, int? Metric);
public sealed record HostNetworkConfirmation(string Id);
public sealed class HostNetworkService
{
private const string SocketPath = "/run/seiugw-network/control.sock";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public async Task<IResult> SendAsync(object request, CancellationToken cancellationToken)
{
if (!OperatingSystem.IsLinux())
return Results.Json(new { error = "Die Netzwerkkonfiguration benötigt den NixOS-Netzwerkdienst." }, statusCode: 503);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(8));
try
{
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
await socket.ConnectAsync(new UnixDomainSocketEndPoint(SocketPath), timeout.Token);
using var stream = new NetworkStream(socket);
await stream.WriteAsync(JsonSerializer.SerializeToUtf8Bytes(request, JsonOptions), timeout.Token);
socket.Shutdown(SocketShutdown.Send);
using var response = await JsonDocument.ParseAsync(stream, cancellationToken: timeout.Token);
var result = response.RootElement;
return Results.Json(result.Clone(), statusCode: result.TryGetProperty("error", out _) ? 400 : 200);
}
catch (Exception ex) when (ex is SocketException or IOException or JsonException ||
ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)
{
return Results.Json(new { error = "Der NixOS-Netzwerkdienst ist gerade nicht erreichbar." }, statusCode: 503);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed record KnxEtsImportRequest(string FileName, string ContentBase64);
public sealed record KnxEtsImportResult(int Imported, IReadOnlyList<string> Errors);
/// <summary>Imports ETS group-address exports (.knxproj ZIP or XML) without trusting project metadata as executable content.</summary>
public static class KnxEtsImporter
{
public static KnxEtsImportResult Import(KnxEtsImportRequest request, GatewayStore store)
{
if (string.IsNullOrWhiteSpace(request.FileName) || request.FileName.Length > 260)
{
throw new DomainValidationException("Eine ETS-Datei mit gültigem Dateinamen wird benötigt.");
}
byte[] content;
try { content = Convert.FromBase64String(request.ContentBase64); }
catch (FormatException) { throw new DomainValidationException("Die ETS-Datei ist nicht gültig kodiert."); }
if (content.Length is 0 or > 25 * 1024 * 1024)
{
throw new DomainValidationException("Die ETS-Datei darf maximal 25 MiB groß sein.");
}
var documents = ReadXmlDocuments(request.FileName, content);
var imported = 0;
var errors = new List<string>();
foreach (var document in documents)
{
foreach (var element in document.Descendants().Where(item => item.Name.LocalName == "GroupAddress"))
{
var name = element.Attribute("Name")?.Value?.Trim();
var address = NormalizeAddress(element.Attribute("Address")?.Value);
if (string.IsNullOrWhiteSpace(name) || address is null)
{
continue;
}
var dpt = element.Attribute("DatapointType")?.Value?.Trim() ?? element.Attribute("DPT")?.Value?.Trim();
var identity = $"knx:{address}";
try
{
using var addressJson = JsonDocument.Parse(JsonSerializer.Serialize(new { groupAddress = address, datapointType = dpt }));
store.CreatePoint(new CreatePointRequest(
name,
PointProtocol.Knx,
PointScope.External,
GetValueType(dpt),
true,
IsWritableDpt(dpt),
identity,
addressJson.RootElement.Clone()));
imported++;
}
catch (DomainValidationException exception)
{
errors.Add($"{address}: {exception.Message}");
}
}
}
return new KnxEtsImportResult(imported, errors);
}
private static List<XDocument> ReadXmlDocuments(string fileName, byte[] content)
{
if (fileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
{
return [XDocument.Parse(Encoding.UTF8.GetString(content), LoadOptions.None)];
}
if (!fileName.EndsWith(".knxproj", StringComparison.OrdinalIgnoreCase))
{
throw new DomainValidationException("Unterstützt werden ETS-Projekte (.knxproj) und ETS-XML-Exporte (.xml).");
}
try
{
using var memory = new MemoryStream(content, writable: false);
using var archive = new ZipArchive(memory, ZipArchiveMode.Read, leaveOpen: false);
var documents = new List<XDocument>();
foreach (var entry in archive.Entries.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && entry.Length <= 10 * 1024 * 1024))
{
using var stream = entry.Open();
documents.Add(XDocument.Load(stream, LoadOptions.None));
}
if (documents.Count == 0)
{
throw new DomainValidationException("Das ETS-Projekt enthält keine lesbare XML-Datei.");
}
return documents;
}
catch (InvalidDataException)
{
throw new DomainValidationException("Die .knxproj-Datei ist kein gültiges ETS-ZIP-Archiv.");
}
catch (System.Xml.XmlException)
{
throw new DomainValidationException("Die ETS-XML-Datei ist ungültig.");
}
}
private static string? NormalizeAddress(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var trimmed = value.Trim();
if (trimmed.Split('/').Length == 3 && trimmed.Split('/').All(part => int.TryParse(part, out _))) return trimmed;
if (!ushort.TryParse(trimmed, out var encoded)) return null;
return $"{(encoded >> 11) & 31}/{(encoded >> 8) & 7}/{encoded & 255}";
}
private static string GetValueType(string? dpt) => dpt?.StartsWith("DPT-1", StringComparison.OrdinalIgnoreCase) == true ? "Boolean" : "Real";
private static bool IsWritableDpt(string? dpt) => !string.IsNullOrWhiteSpace(dpt);
}
@@ -0,0 +1,86 @@
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
/// <summary>
/// Executes the configured mapping graph in-process. A journal entry is made
/// before every forwarded value so the reverse edge of a bidirectional mapping
/// consumes exactly the returning update instead of writing it back again.
/// </summary>
public sealed class MappingRuntimeService : IHostedService, IDisposable
{
private readonly GatewayStore _store;
private readonly WriteJournal _journal;
private int _running;
public MappingRuntimeService(GatewayStore store, WriteJournal journal)
{
_store = store;
_journal = journal;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_store.PointValueUpdated += OnPointValueUpdated;
Interlocked.Exchange(ref _running, 1);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Interlocked.Exchange(ref _running, 0);
_store.PointValueUpdated -= OnPointValueUpdated;
return Task.CompletedTask;
}
public void Dispose() => _store.PointValueUpdated -= OnPointValueUpdated;
private void OnPointValueUpdated(object? sender, PointValue update)
{
if (Volatile.Read(ref _running) == 0)
{
return;
}
// Configurations are intentionally read for every update. This keeps a
// newly saved mapping live without requiring a process restart.
Dictionary<Guid, GatewayPoint>? points = null;
foreach (var mapping in _store.ListMappings().Where(candidate => candidate.Enabled))
{
var targetId = mapping.SourcePointId == update.PointId
? mapping.TargetPointId
: mapping.Direction == MappingDirection.Bidirectional && mapping.TargetPointId == update.PointId
? mapping.SourcePointId
: Guid.Empty;
if (targetId == Guid.Empty)
{
continue;
}
var valueText = update.Value.GetRawText();
var journalPrefix = $"mapping:{mapping.Id}:{mapping.SourcePointId}:{mapping.TargetPointId}:{mapping.Direction}:{mapping.BacnetPriority}";
var reflectionKey = $"{journalPrefix}:{update.PointId}";
if (_journal.ConsumeReflection(reflectionKey, valueText))
{
continue;
}
try
{
points ??= _store.ListPoints().ToDictionary(point => point.Id);
if (!points.ContainsKey(update.PointId) || !points.TryGetValue(targetId, out var target)) continue;
if (target.Scope == PointScope.External && !string.IsNullOrWhiteSpace(update.Status) && !update.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) && !update.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) continue;
_journal.Register($"{journalPrefix}:{targetId}", valueText, TimeSpan.FromSeconds(15));
_store.SetPointValue(targetId, update.Value, update.SourceProtocol, update.UpdatedAtUtc, update.Status,
update.OriginPointId ?? update.PointId, mapping.BacnetPriority, expectedDefinition: target, expectedMapping: mapping);
}
catch (Exception)
{
// A broken external mapping must not bring down the protocol
// adapters. It remains visible in the audit trail on its next
// configuration validation/update.
}
}
}
}
@@ -0,0 +1,166 @@
using System.Globalization;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
internal enum ModbusArea
{
Coil,
DiscreteInput,
InputRegister,
HoldingRegister
}
internal enum ModbusDataType
{
Boolean,
UInt16,
Int16,
UInt32,
Int32,
Float32,
Float32WordSwap
}
internal sealed record ModbusAddress(
string Transport,
Guid? ServerId,
string? Host,
int Port,
byte UnitId,
string? SerialPortAlias,
ModbusArea Area,
ushort Address,
ModbusDataType DataType,
int PollIntervalSeconds)
{
public int RegisterCount => Area is ModbusArea.Coil or ModbusArea.DiscreteInput ? 1 : DataType is ModbusDataType.UInt32 or ModbusDataType.Int32 or ModbusDataType.Float32 or ModbusDataType.Float32WordSwap ? 2 : 1;
}
internal static class ModbusAddressing
{
public static bool TryParse(GatewayPoint point, out ModbusAddress address)
{
address = null!;
if (point.Protocol != PointProtocol.Modbus || point.Address.ValueKind != JsonValueKind.Object)
{
return false;
}
try
{
var transport = GetString(point.Address, "transport")?.ToLowerInvariant() ?? "tcp";
var serverIdText = GetString(point.Address, "serverId");
var serverId = Guid.TryParse(serverIdText, out var parsedServerId) ? parsedServerId : (Guid?)null;
var host = GetString(point.Address, "host");
var port = GetInt(point.Address, "port") ?? 502;
var unitId = GetInt(point.Address, "unitId") ?? 1;
var serialPortAlias = GetString(point.Address, "serialPortAlias");
var area = ParseArea(GetString(point.Address, "area"));
var register = GetInt(point.Address, "address") ?? GetInt(point.Address, "register") ?? -1;
var dataType = ParseDataType(GetString(point.Address, "dataType"), area);
var interval = GetInt(point.Address, "pollIntervalSeconds") ?? 5;
if (transport is not ("tcp" or "rtu") || port is < 1 or > 65_535 || unitId is < 1 or > 247 || register is < 0 or > 65_535 || interval is < 1 or > 86_400)
{
return false;
}
if (transport == "tcp" && serverId is null && string.IsNullOrWhiteSpace(host))
{
return false;
}
if (transport == "rtu" && string.IsNullOrWhiteSpace(serialPortAlias))
{
return false;
}
address = new ModbusAddress(transport, serverId, host, port, (byte)unitId, serialPortAlias, area, (ushort)register, dataType, interval);
return true;
}
catch
{
return false;
}
}
public static JsonElement Encode(ushort[] registers, bool? coil, ModbusAddress address)
{
object value = address.Area is ModbusArea.Coil or ModbusArea.DiscreteInput
? coil ?? false
: address.DataType switch
{
ModbusDataType.UInt16 => registers[0],
ModbusDataType.Int16 => unchecked((short)registers[0]),
ModbusDataType.UInt32 => ((uint)registers[0] << 16) | registers[1],
ModbusDataType.Int32 => unchecked((int)(((uint)registers[0] << 16) | registers[1])),
ModbusDataType.Float32 => BitConverter.Int32BitsToSingle((int)(((uint)registers[0] << 16) | registers[1])),
ModbusDataType.Float32WordSwap => BitConverter.Int32BitsToSingle((int)(((uint)registers[1] << 16) | registers[0])),
_ => registers[0]
};
return JsonSerializer.SerializeToElement(value);
}
public static (ushort[] Registers, bool? Coil) Decode(JsonElement value, ModbusAddress address)
{
if (address.Area is ModbusArea.Coil or ModbusArea.DiscreteInput)
{
var coil = value.ValueKind == JsonValueKind.True || value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && Math.Abs(number) > double.Epsilon ||
value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed;
return ([], coil);
}
var numberValue = value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var numeric)
? numeric
: value.ValueKind == JsonValueKind.String && double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedNumber)
? parsedNumber
: throw new DomainValidationException("Der Modbus-Wert muss numerisch sein.");
return address.DataType switch
{
ModbusDataType.UInt16 => ([checked((ushort)Math.Round(numberValue))], null),
ModbusDataType.Int16 => ([unchecked((ushort)checked((short)Math.Round(numberValue)))], null),
ModbusDataType.UInt32 => ToRegisters(checked((uint)Math.Round(numberValue)), false),
ModbusDataType.Int32 => ToRegisters(unchecked((uint)checked((int)Math.Round(numberValue))), false),
ModbusDataType.Float32 => ToRegisters(unchecked((uint)BitConverter.SingleToInt32Bits(checked((float)numberValue))), false),
ModbusDataType.Float32WordSwap => ToRegisters(unchecked((uint)BitConverter.SingleToInt32Bits(checked((float)numberValue))), true),
_ => ([checked((ushort)Math.Round(numberValue))], null)
};
}
private static (ushort[] Registers, bool? Coil) ToRegisters(uint value, bool wordSwap)
{
var high = (ushort)(value >> 16);
var low = (ushort)value;
return (wordSwap ? [low, high] : [high, low], null);
}
private static string? GetString(JsonElement element, string name) =>
element.TryGetProperty(name, out var property) && property.ValueKind == JsonValueKind.String ? property.GetString()?.Trim() : null;
private static int? GetInt(JsonElement element, string name) =>
element.TryGetProperty(name, out var property) && property.TryGetInt32(out var value) ? value : null;
private static ModbusArea ParseArea(string? raw) => raw?.Trim().ToLowerInvariant() switch
{
"coil" or "coils" => ModbusArea.Coil,
"discrete" or "discreteinput" or "discrete-input" => ModbusArea.DiscreteInput,
"input" or "inputregister" or "input-register" => ModbusArea.InputRegister,
_ => ModbusArea.HoldingRegister
};
private static ModbusDataType ParseDataType(string? raw, ModbusArea area)
{
if (area is ModbusArea.Coil or ModbusArea.DiscreteInput)
{
return ModbusDataType.Boolean;
}
return raw?.Trim().ToLowerInvariant() switch
{
"int16" => ModbusDataType.Int16,
"uint32" => ModbusDataType.UInt32,
"int32" => ModbusDataType.Int32,
"float32" or "real" => ModbusDataType.Float32,
"float32wordswap" or "float32-swap" or "float32_swap" => ModbusDataType.Float32WordSwap,
_ => ModbusDataType.UInt16
};
}
}
@@ -0,0 +1,128 @@
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed record ModbusCsvImportRequest(string Csv, bool ReplaceExisting = false);
public sealed record ModbusCsvImportResult(int Imported, IReadOnlyList<string> Errors);
/// <summary>Imports an intentionally small, documented CSV dialect for field Modbus point lists.</summary>
public static class ModbusCsvImporter
{
public const string Example = """
Name;Transport;Host;Port;SerialPortAlias;UnitId;Area;Address;DataType;Writable;PollIntervalSeconds
Zulufttemperatur;tcp;192.168.10.20;502;;1;InputRegister;0;Float32;false;10
Zuluft Sollwert;tcp;192.168.10.20;502;;1;HoldingRegister;20;Float32WordSwap;true;5
Anlage Freigabe;rtu;;;RS485-Hauptstrang;1;Coil;0;Boolean;true;5
""";
public static ModbusCsvImportResult Import(string csv, GatewayStore store)
{
if (string.IsNullOrWhiteSpace(csv))
{
throw new DomainValidationException("Die Modbus-CSV ist leer.");
}
var rows = ReadRows(csv).ToArray();
if (rows.Length < 2)
{
throw new DomainValidationException("Die Modbus-CSV benötigt eine Kopfzeile und mindestens einen Datenpunkt.");
}
var header = rows[0].Select((value, index) => new { Key = value.Trim(), index })
.Where(item => item.Key.Length > 0)
.ToDictionary(item => item.Key, item => item.index, StringComparer.OrdinalIgnoreCase);
foreach (var required in new[] { "Name", "Transport", "UnitId", "Area", "Address" })
{
if (!header.ContainsKey(required))
{
throw new DomainValidationException($"Der CSV-Header '{required}' fehlt.");
}
}
var errors = new List<string>();
var imported = 0;
for (var rowIndex = 1; rowIndex < rows.Length; rowIndex++)
{
var row = rows[rowIndex];
if (row.All(string.IsNullOrWhiteSpace))
{
continue;
}
try
{
var get = new Func<string, string>(name => header.TryGetValue(name, out var index) && index < row.Length ? row[index].Trim() : string.Empty);
var transport = get("Transport").ToLowerInvariant();
var port = ParseInt(get("Port"), 502);
var unitId = ParseInt(get("UnitId"), 1);
var address = ParseInt(get("Address"), -1);
var pollInterval = ParseInt(get("PollIntervalSeconds"), 5);
var area = string.IsNullOrWhiteSpace(get("Area")) ? "HoldingRegister" : get("Area");
var dataType = string.IsNullOrWhiteSpace(get("DataType")) ? "UInt16" : get("DataType");
var writable = bool.TryParse(get("Writable"), out var parsedWritable) && parsedWritable;
if (transport is not ("tcp" or "rtu") || unitId is < 1 or > 247 || address is < 0 or > 65_535 || pollInterval is < 1 or > 86_400)
{
throw new DomainValidationException("Transport, UnitId, Adresse oder Pollintervall ist ungültig.");
}
var host = get("Host");
var alias = get("SerialPortAlias");
if (transport == "tcp" && string.IsNullOrWhiteSpace(host)) throw new DomainValidationException("Für Modbus TCP fehlt Host.");
if (transport == "rtu" && string.IsNullOrWhiteSpace(alias)) throw new DomainValidationException("Für Modbus RTU fehlt SerialPortAlias.");
var addressJson = JsonSerializer.SerializeToElement(new Dictionary<string, object?>
{
["transport"] = transport,
["host"] = transport == "tcp" ? host : null,
["port"] = transport == "tcp" ? port : null,
["serialPortAlias"] = transport == "rtu" ? alias : null,
["unitId"] = unitId,
["area"] = area,
["address"] = address,
["dataType"] = dataType,
["pollIntervalSeconds"] = pollInterval
});
var externalIdentity = transport == "tcp"
? $"tcp:{host}:{port}:{unitId}:{area}:{address}:{dataType}"
: $"rtu:{alias}:{unitId}:{area}:{address}:{dataType}";
store.CreatePoint(new CreatePointRequest(
get("Name"), PointProtocol.Modbus, PointScope.External,
dataType, true, writable, externalIdentity, addressJson));
imported++;
}
catch (Exception exception)
{
errors.Add($"Zeile {rowIndex + 1}: {exception.Message}");
}
}
return new ModbusCsvImportResult(imported, errors);
}
private static int ParseInt(string value, int fallback) => string.IsNullOrWhiteSpace(value) ? fallback : int.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
private static IEnumerable<string[]> ReadRows(string csv)
{
var delimiter = csv.Contains(';') ? ';' : ',';
using var reader = new StringReader(csv.Replace("\r\n", "\n", StringComparison.Ordinal));
string? line;
while ((line = reader.ReadLine()) is not null)
{
var values = new List<string>();
var cell = new StringBuilder();
var quoted = false;
for (var index = 0; index < line.Length; index++)
{
var current = line[index];
if (current == '"' && index + 1 < line.Length && line[index + 1] == '"' && quoted)
{
cell.Append('"'); index++; continue;
}
if (current == '"') { quoted = !quoted; continue; }
if (current == delimiter && !quoted) { values.Add(cell.ToString()); cell.Clear(); continue; }
cell.Append(current);
}
if (quoted) throw new DomainValidationException("Die CSV enthält ein nicht geschlossenes Anführungszeichen.");
values.Add(cell.ToString());
yield return values.ToArray();
}
}
}
@@ -0,0 +1,563 @@
using System.Collections.Concurrent;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
using Gateway.Api.Domain;
using NModbus;
using NModbus.Serial;
namespace Gateway.Api.Services;
public sealed record ModbusRuntimeIssue(Guid Id, string Error, DateTimeOffset OccurredAtUtc);
#pragma warning disable CA1848 // This adapter logs rare field-bus failures; source-generated log methods add no operational value here.
/// <summary>
/// Native Modbus TCP server/client and RTU client. TCP listeners deliberately
/// parse MBAP frames here instead of accepting the library's default listener:
/// this is what makes a per-instance IP allow-list enforceable before a Modbus
/// request is ever processed.
/// </summary>
public sealed class ModbusProtocolService : BackgroundService
{
private readonly GatewayStore _store;
private readonly WriteJournal _journal;
private readonly ILogger<ModbusProtocolService> _logger;
private readonly ConcurrentDictionary<Guid, TcpServerRuntime> _servers = new();
private readonly ConcurrentDictionary<Guid, ModbusRuntimeIssue> _serverErrors = new();
private readonly ConcurrentDictionary<Guid, ModbusRuntimeIssue> _pointErrors = new();
private readonly ConcurrentDictionary<Guid, DateTimeOffset> _nextPollAt = new();
private readonly ModbusFactory _factory = new();
private CancellationToken _serviceStopping;
private int _disposed;
public ModbusProtocolService(GatewayStore store, WriteJournal journal, ILogger<ModbusProtocolService> logger)
{
_store = store;
_journal = journal;
_logger = logger;
_store.PointValueUpdated += OnPointValueUpdated;
}
public bool IsTcpListening(ModbusServerConfiguration configuration) =>
_servers.TryGetValue(configuration.Id, out var runtime) && runtime.ConfigurationEquals(configuration);
public ModbusRuntimeIssue? GetTcpError(Guid id) => _serverErrors.GetValueOrDefault(id);
public ModbusRuntimeIssue[] GetPointErrors() => _pointErrors.Values.ToArray();
public override void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_store.PointValueUpdated -= OnPointValueUpdated;
foreach (var server in _servers.Values)
{
server.Dispose();
}
base.Dispose();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_serviceStopping = stoppingToken;
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ReconcileServersAsync(stoppingToken);
await PollExternalPointsAsync(stoppingToken);
}
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
{
_logger.LogWarning(exception, "Modbus scheduling cycle failed.");
}
try
{
await Task.Delay(TimeSpan.FromMilliseconds(250), stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
}
}
private Task ReconcileServersAsync(CancellationToken cancellationToken)
{
var configured = _store.GetGatewayConfiguration().ModbusServers;
var desired = configured.ToDictionary(server => server.Id);
foreach (var id in _serverErrors.Keys)
if (!desired.ContainsKey(id)) _serverErrors.TryRemove(id, out _);
foreach (var (id, existing) in _servers)
{
if (!desired.TryGetValue(id, out var next) || !existing.ConfigurationEquals(next))
{
if (_servers.TryRemove(id, out var removed))
{
removed.Dispose();
}
}
}
foreach (var server in configured)
{
if (_servers.ContainsKey(server.Id))
{
continue;
}
var runtime = new TcpServerRuntime(server, _store, _logger);
try
{
runtime.Start(cancellationToken);
if (!_servers.TryAdd(server.Id, runtime)) runtime.Dispose();
_serverErrors.TryRemove(server.Id, out _);
}
catch (SocketException exception)
{
runtime.Dispose();
_serverErrors[server.Id] = new(server.Id, exception.Message, DateTimeOffset.UtcNow);
_logger.LogDebug(exception, "Modbus server {Server} could not bind.", server.Name);
}
}
return Task.CompletedTask;
}
private async Task PollExternalPointsAsync(CancellationToken cancellationToken)
{
var now = DateTimeOffset.UtcNow;
var points = _store.ListPoints().Where(point => point.Protocol == PointProtocol.Modbus && point.Scope == PointScope.External && point.Readable).ToArray();
foreach (var id in _pointErrors.Keys.Except(points.Select(point => point.Id)))
_pointErrors.TryRemove(id, out _);
foreach (var point in points)
{
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId is not null)
{
_pointErrors[point.Id] = new(point.Id, "Ungültige Modbus-Adresse.", now);
continue;
}
if (_nextPollAt.TryGetValue(point.Id, out var next) && next > now)
{
continue;
}
_nextPollAt[point.Id] = now.AddSeconds(address.PollIntervalSeconds);
try
{
var value = address.Transport == "rtu"
? await ReadRtuAsync(point, address, cancellationToken)
: await ReadTcpAsync(point, address, cancellationToken);
var identity = GetEndpointIdentity(point);
if (!_journal.ConsumeReflection(identity, value.GetRawText()))
{
_store.SetPointValue(point.Id, value, PointProtocol.Modbus, DateTimeOffset.UtcNow, expectedDefinition: point);
}
_pointErrors.TryRemove(point.Id, out _);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
_pointErrors[point.Id] = new(point.Id, exception.Message, DateTimeOffset.UtcNow);
_logger.LogDebug(exception, "Modbus read failed for {Point}.", point.DisplayName);
}
}
}
private async Task<JsonElement> ReadTcpAsync(GatewayPoint point, ModbusAddress address, CancellationToken cancellationToken)
{
using var client = new TcpClient();
await client.ConnectAsync(address.Host!, address.Port, cancellationToken);
var master = _factory.CreateMaster(client);
try
{
return await ReadValueAsync(master, address);
}
finally
{
if (master is IDisposable disposable)
{
disposable.Dispose();
}
}
}
private async Task<JsonElement> ReadRtuAsync(GatewayPoint point, ModbusAddress address, CancellationToken cancellationToken)
{
var serial = ResolveSerialPort(address.SerialPortAlias!);
using var port = CreateSerialPort(serial);
port.Open();
var master = _factory.CreateRtuMaster(port);
try
{
return await ReadValueAsync(master, address);
}
finally
{
if (master is IDisposable disposable)
{
disposable.Dispose();
}
}
}
private static async Task<JsonElement> ReadValueAsync(IModbusMaster master, ModbusAddress address)
{
if (address.Area == ModbusArea.Coil)
{
return ModbusAddressing.Encode([], (await master.ReadCoilsAsync(address.UnitId, address.Address, 1))[0], address);
}
if (address.Area == ModbusArea.DiscreteInput)
{
return ModbusAddressing.Encode([], (await master.ReadInputsAsync(address.UnitId, address.Address, 1))[0], address);
}
var registers = address.Area == ModbusArea.InputRegister
? await master.ReadInputRegistersAsync(address.UnitId, address.Address, (ushort)address.RegisterCount)
: await master.ReadHoldingRegistersAsync(address.UnitId, address.Address, (ushort)address.RegisterCount);
return ModbusAddressing.Encode(registers, null, address);
}
private void OnPointValueUpdated(object? sender, PointValue update)
{
if (!string.IsNullOrWhiteSpace(update.Status) && !update.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) && !update.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) return;
var point = _store.ListPoints().SingleOrDefault(candidate => candidate.Id == update.PointId);
if (point is null)
{
return;
}
if (point.Protocol == PointProtocol.Modbus && ModbusAddressing.TryParse(point, out var address))
{
if (address.ServerId is not null && _servers.TryGetValue(address.ServerId.Value, out var server))
{
server.WriteGatewayValue(point, address, update.Value);
}
else if (point.Scope == PointScope.External && point.Writable && !(update.SourceProtocol == PointProtocol.Modbus && update.OriginPointId == point.Id))
{
_ = WriteExternalSafelyAsync(point, address, update.Value, _serviceStopping);
}
}
}
private async Task WriteExternalSafelyAsync(GatewayPoint point, ModbusAddress address, JsonElement value, CancellationToken cancellationToken)
{
try
{
var identity = GetEndpointIdentity(point);
var valueText = value.GetRawText();
_journal.Register(identity, valueText, TimeSpan.FromSeconds(15));
if (address.Transport == "rtu")
{
var serial = ResolveSerialPort(address.SerialPortAlias!);
using var port = CreateSerialPort(serial);
port.Open();
var master = _factory.CreateRtuMaster(port);
try { if (_store.IsPointDefinitionCurrent(point)) await WriteValueAsync(master, address, value); }
finally { if (master is IDisposable disposable) disposable.Dispose(); }
}
else
{
using var client = new TcpClient();
await client.ConnectAsync(address.Host!, address.Port, cancellationToken);
var master = _factory.CreateMaster(client);
try { if (_store.IsPointDefinitionCurrent(point)) await WriteValueAsync(master, address, value); }
finally { if (master is IDisposable disposable) disposable.Dispose(); }
}
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
_logger.LogWarning(exception, "Modbus write failed for {Point}.", point.DisplayName);
}
}
private static async Task WriteValueAsync(IModbusMaster master, ModbusAddress address, JsonElement value)
{
var encoded = ModbusAddressing.Decode(value, address);
if (address.Area == ModbusArea.Coil)
{
await master.WriteSingleCoilAsync(address.UnitId, address.Address, encoded.Coil ?? false);
return;
}
if (address.Area != ModbusArea.HoldingRegister)
{
throw new DomainValidationException("Auf Input-Register und Discrete Inputs kann nicht geschrieben werden.");
}
if (encoded.Registers.Length == 1)
{
await master.WriteSingleRegisterAsync(address.UnitId, address.Address, encoded.Registers[0]);
}
else
{
await master.WriteMultipleRegistersAsync(address.UnitId, address.Address, encoded.Registers);
}
}
private SerialPortConfiguration ResolveSerialPort(string alias) =>
(_store.GetGatewayConfiguration().SerialPorts ?? []).SingleOrDefault(port => string.Equals(port.Alias, alias, StringComparison.OrdinalIgnoreCase))
?? throw new DomainValidationException($"Der serielle Port-Alias '{alias}' ist nicht konfiguriert.");
private static SerialPort CreateSerialPort(SerialPortConfiguration configuration) => new(
configuration.DevicePath,
configuration.BaudRate,
Enum.Parse<Parity>(configuration.Parity, true),
configuration.DataBits,
Enum.Parse<StopBits>(configuration.StopBits == 2 ? "Two" : "One", true))
{
ReadTimeout = 2_000,
WriteTimeout = 2_000
};
private static string GetEndpointIdentity(GatewayPoint point) => $"modbus:{point.ExternalIdentity ?? point.Id.ToString()}";
private sealed class TcpServerRuntime : IDisposable
{
private readonly ModbusServerConfiguration _configuration;
private readonly GatewayStore _store;
private readonly ILogger _logger;
private readonly TcpListener _listener;
private readonly CancellationTokenSource _stopping = new();
private int _disposed;
private readonly object _gate = new();
private readonly ushort[] _holding;
private readonly ushort[] _input;
private readonly bool[] _coils;
private readonly bool[] _discretes;
private Task? _acceptTask;
public TcpServerRuntime(ModbusServerConfiguration configuration, GatewayStore store, ILogger logger)
{
_configuration = configuration;
_store = store;
_logger = logger;
_listener = new TcpListener(IPAddress.Parse(configuration.BindAddress), configuration.Port);
_holding = new ushort[configuration.HoldingRegisterCount];
_input = new ushort[configuration.HoldingRegisterCount];
_coils = new bool[configuration.HoldingRegisterCount];
_discretes = new bool[configuration.HoldingRegisterCount];
}
public bool ConfigurationEquals(ModbusServerConfiguration other) =>
_configuration.Id == other.Id &&
string.Equals(_configuration.Name, other.Name, StringComparison.Ordinal) &&
string.Equals(_configuration.BindAddress, other.BindAddress, StringComparison.Ordinal) &&
_configuration.Port == other.Port &&
_configuration.UnitId == other.UnitId &&
_configuration.FirstHoldingRegister == other.FirstHoldingRegister &&
_configuration.HoldingRegisterCount == other.HoldingRegisterCount &&
_configuration.AllowedClientIps.SequenceEqual(other.AllowedClientIps, StringComparer.OrdinalIgnoreCase);
public void Start(CancellationToken applicationStopping)
{
_listener.Start();
_acceptTask = Task.Run(() => AcceptLoopAsync(_stopping.Token), applicationStopping);
}
public void WriteGatewayValue(GatewayPoint point, ModbusAddress address, JsonElement value)
{
if (address.Address < _configuration.FirstHoldingRegister || address.Address - _configuration.FirstHoldingRegister + address.RegisterCount > _holding.Length)
{
return;
}
var offset = address.Address - _configuration.FirstHoldingRegister;
var encoded = ModbusAddressing.Decode(value, address);
lock (_gate)
{
switch (address.Area)
{
case ModbusArea.Coil: _coils[offset] = encoded.Coil ?? false; break;
case ModbusArea.DiscreteInput: _discretes[offset] = encoded.Coil ?? false; break;
case ModbusArea.InputRegister: Array.Copy(encoded.Registers, 0, _input, offset, encoded.Registers.Length); break;
default: Array.Copy(encoded.Registers, 0, _holding, offset, encoded.Registers.Length); break;
}
}
}
private async Task AcceptLoopAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
var client = await _listener.AcceptTcpClientAsync(cancellationToken);
_ = Task.Run(() => HandleClientAsync(client, cancellationToken), cancellationToken);
}
}
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Modbus TCP listener {Name} stopped unexpectedly.", _configuration.Name);
}
}
private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken)
{
using (client)
{
var remote = (client.Client.RemoteEndPoint as IPEndPoint)?.Address;
if (remote is null || !IsAllowed(remote))
{
return;
}
var stream = client.GetStream();
var header = new byte[7];
while (!cancellationToken.IsCancellationRequested)
{
try
{
await stream.ReadExactlyAsync(header, cancellationToken);
}
catch (EndOfStreamException)
{
return;
}
var length = (header[4] << 8) | header[5];
if (header[2] != 0 || header[3] != 0 || length is < 2 or > 254)
{
return;
}
var pdu = new byte[length - 1];
try
{
await stream.ReadExactlyAsync(pdu, cancellationToken);
}
catch (EndOfStreamException)
{
return;
}
var response = HandleRequest(header[6], pdu);
var responseHeader = new byte[7];
responseHeader[0] = header[0]; responseHeader[1] = header[1];
responseHeader[4] = (byte)(((response.Length + 1) >> 8) & 0xff);
responseHeader[5] = (byte)((response.Length + 1) & 0xff);
responseHeader[6] = header[6];
await stream.WriteAsync(responseHeader, cancellationToken);
await stream.WriteAsync(response, cancellationToken);
}
}
}
private byte[] HandleRequest(byte unitId, byte[] request)
{
if (unitId != _configuration.UnitId || request.Length < 5)
{
return ExceptionResponse(request.FirstOrDefault(), 2);
}
var function = request[0];
var address = (ushort)((request[1] << 8) | request[2]);
var quantity = (ushort)((request[3] << 8) | request[4]);
return function switch
{
1 or 2 => ReadBits(function, address, quantity),
3 or 4 => ReadRegisters(function, address, quantity),
5 => WriteSingleCoil(address, quantity == 0xff00),
6 => WriteSingleRegister(address, quantity),
15 => WriteMultipleCoils(address, quantity, request),
16 => WriteMultipleRegisters(address, quantity, request),
_ => ExceptionResponse(function, 1)
};
}
private byte[] ReadBits(byte function, ushort address, ushort quantity)
{
if (!IsInRange(address, quantity) || quantity is < 1 or > 2_000) return ExceptionResponse(function, 2);
var data = new byte[(quantity + 7) / 8];
var offset = address - _configuration.FirstHoldingRegister;
lock (_gate)
{
var source = function == 1 ? _coils : _discretes;
for (var index = 0; index < quantity; index++) if (source[offset + index]) data[index / 8] |= (byte)(1 << (index % 8));
}
return [function, (byte)data.Length, .. data];
}
private byte[] ReadRegisters(byte function, ushort address, ushort quantity)
{
if (!IsInRange(address, quantity) || quantity is < 1 or > 125) return ExceptionResponse(function, 2);
var data = new byte[quantity * 2];
var offset = address - _configuration.FirstHoldingRegister;
lock (_gate)
{
var source = function == 3 ? _holding : _input;
for (var index = 0; index < quantity; index++)
{
data[index * 2] = (byte)(source[offset + index] >> 8);
data[index * 2 + 1] = (byte)source[offset + index];
}
}
return [function, (byte)data.Length, .. data];
}
private byte[] WriteSingleCoil(ushort address, bool value)
{
if (!IsInRange(address, 1)) return ExceptionResponse(5, 2);
lock (_gate) _coils[address - _configuration.FirstHoldingRegister] = value;
PropagateWrites(ModbusArea.Coil, address, 1);
return [5, (byte)(address >> 8), (byte)address, value ? (byte)0xff : (byte)0, 0];
}
private byte[] WriteSingleRegister(ushort address, ushort value)
{
if (!IsInRange(address, 1)) return ExceptionResponse(6, 2);
lock (_gate) _holding[address - _configuration.FirstHoldingRegister] = value;
PropagateWrites(ModbusArea.HoldingRegister, address, 1);
return [6, (byte)(address >> 8), (byte)address, (byte)(value >> 8), (byte)value];
}
private byte[] WriteMultipleCoils(ushort address, ushort quantity, byte[] request)
{
if (!IsInRange(address, quantity) || quantity is < 1 or > 1_968 || request.Length < 6 || request[5] != (quantity + 7) / 8 || request.Length != 6 + request[5]) return ExceptionResponse(15, 3);
lock (_gate) for (var index = 0; index < quantity; index++) _coils[address - _configuration.FirstHoldingRegister + index] = (request[6 + index / 8] & (1 << (index % 8))) != 0;
PropagateWrites(ModbusArea.Coil, address, quantity);
return [15, (byte)(address >> 8), (byte)address, (byte)(quantity >> 8), (byte)quantity];
}
private byte[] WriteMultipleRegisters(ushort address, ushort quantity, byte[] request)
{
if (!IsInRange(address, quantity) || quantity is < 1 or > 123 || request.Length < 6 || request[5] != quantity * 2 || request.Length != 6 + request[5]) return ExceptionResponse(16, 3);
lock (_gate) for (var index = 0; index < quantity; index++) _holding[address - _configuration.FirstHoldingRegister + index] = (ushort)((request[6 + index * 2] << 8) | request[7 + index * 2]);
PropagateWrites(ModbusArea.HoldingRegister, address, quantity);
return [16, (byte)(address >> 8), (byte)address, (byte)(quantity >> 8), (byte)quantity];
}
private void PropagateWrites(ModbusArea area, ushort start, ushort count)
{
foreach (var point in _store.ListPoints().Where(point => point.Protocol == PointProtocol.Modbus && point.Writable))
{
if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId != _configuration.Id || address.Area != area || address.Address < start || address.Address + address.RegisterCount > start + count)
{
continue;
}
try
{
var offset = address.Address - _configuration.FirstHoldingRegister;
JsonElement value;
lock (_gate)
{
value = area == ModbusArea.Coil
? ModbusAddressing.Encode([], _coils[offset], address)
: ModbusAddressing.Encode(_holding[offset..(offset + address.RegisterCount)], null, address);
}
_store.SetPointValue(point.Id, value, PointProtocol.Modbus, DateTimeOffset.UtcNow, expectedDefinition: point);
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Could not apply Modbus server write to {Point}.", point.DisplayName);
}
}
}
private bool IsAllowed(IPAddress remote) => _configuration.AllowedClientIps.Count == 0 || _configuration.AllowedClientIps.Any(value => IPAddress.TryParse(value, out var allowed) && allowed.Equals(remote));
private bool IsInRange(ushort address, ushort quantity) => address >= _configuration.FirstHoldingRegister && quantity > 0 && (uint)(address - _configuration.FirstHoldingRegister) + quantity <= _holding.Length;
private static byte[] ExceptionResponse(byte function, byte code) => [(byte)(function | 0x80), code];
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stopping.Cancel();
_listener.Stop();
_stopping.Dispose();
}
}
}
#pragma warning restore CA1848
+183 -48
View File
@@ -1,4 +1,5 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
@@ -10,14 +11,16 @@ namespace Gateway.Api.Services;
/// <summary>
/// One outbound MQTT client for the appliance. It intentionally does not host an MQTT broker.
/// Mappings are exact topics only; wildcard subscriptions are deliberately not created.
/// Mapping and external point subscriptions use exact topics.
/// </summary>
public sealed class MqttClientService : BackgroundService
{
private readonly GatewayStore _store;
private readonly MqttClientFactory _factory = new();
private readonly SemaphoreSlim _publishGate = new(1, 1);
private readonly ConcurrentDictionary<Guid, byte> _initialPublications = new();
private readonly object _clientLock = new();
private Dictionary<string, GatewayPoint[]> _externalPoints = new(StringComparer.Ordinal);
private IMqttClient? _client;
private MqttClientStatus _status = new(false, false, null, null, null, null, null);
private int _reconfigureRequested = 1;
@@ -34,6 +37,11 @@ public sealed class MqttClientService : BackgroundService
/// <summary>Applies changed broker or subscription configuration without a process restart.</summary>
public void RequestReconfigure() => Interlocked.Exchange(ref _reconfigureRequested, 1);
public void QueueInitialPublications(IReadOnlyList<Guid> mappingIds)
{
foreach (var id in mappingIds) _initialPublications.TryAdd(id, 0);
}
public async Task<int> PublishPointValueAsync(PointValue pointValue, CancellationToken cancellationToken = default)
{
var client = GetConnectedClient();
@@ -42,25 +50,20 @@ public sealed class MqttClientService : BackgroundService
return 0;
}
var mappings = _store.ListMqttMappings()
.Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)
.ToArray();
var published = 0;
await _publishGate.WaitAsync(cancellationToken);
try
{
var mappings = _store.ListMqttMappings()
.Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional);
foreach (var mapping in mappings)
{
var payload = CreateOutboundPayload(mapping, pointValue);
var message = _factory.CreateApplicationMessageBuilder()
.WithTopic(GatewayStore.GetMqttTopic(mapping))
.WithPayload(payload)
.WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService))
.WithRetainFlag(mapping.Retain)
.Build();
await client.PublishAsync(message, cancellationToken);
try
{
await PublishMappedValueAsync(client, mapping, pointValue, cancellationToken);
published++;
UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null });
}
catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); }
}
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
@@ -84,20 +87,33 @@ public sealed class MqttClientService : BackgroundService
try
{
var (configuration, password) = _store.GetMqttConnectionConfiguration();
if (configuration.Enabled)
{
var sources = _store.ListMqttExternalPoints()
.Where(point => point.Readable)
.GroupBy(point => MqttExternalTopics.Address(point)!, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal);
var previous = Interlocked.Exchange(ref _externalPoints, sources);
if (sources.Count != previous.Count || sources.Keys.Any(topic => !previous.ContainsKey(topic)))
RequestReconfigure();
}
if (!configuration.Enabled)
{
await DisconnectCurrentAsync(stoppingToken);
SetStatus(new MqttClientStatus(false, false, null, null, null, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
UpdateStatus(status => status with { Enabled = false, Connected = false, Endpoint = null, ConnectedAtUtc = null, LastError = null });
}
else if (Interlocked.Exchange(ref _reconfigureRequested, 0) == 1 || GetConnectedClient() is null)
{
await DisconnectCurrentAsync(stoppingToken);
UpdateStatus(status => status with { Enabled = true, Connected = false, Endpoint = $"{configuration.Host}:{configuration.Port}", ConnectedAtUtc = null });
await ConnectAsync(configuration, password, stoppingToken);
}
if (configuration.Enabled && !_initialPublications.IsEmpty && GetConnectedClient() is not null)
await PublishInitialValuesAsync(stoppingToken);
}
catch (Exception exception) when (!stoppingToken.IsCancellationRequested)
{
UpdateStatus(status => status with { Connected = false, LastError = exception.Message });
UpdateStatus(status => status with { Connected = GetConnectedClient() is not null, LastError = exception.Message });
}
try
@@ -113,6 +129,46 @@ public sealed class MqttClientService : BackgroundService
await DisconnectCurrentAsync(CancellationToken.None);
}
private async Task PublishInitialValuesAsync(CancellationToken cancellationToken)
{
await _publishGate.WaitAsync(cancellationToken);
try
{
if (GetConnectedClient() is not { } client) return;
var mappings = _store.ListMqttMappings().Where(mapping => mapping.Direction == MqttDirection.Publish)
.ToDictionary(mapping => mapping.Id);
var values = _store.ListPointValues().ToDictionary(value => value.PointId);
foreach (var id in _initialPublications.Keys)
{
if (mappings.TryGetValue(id, out var mapping) && values.TryGetValue(mapping.PointId, out var value) &&
value.SourceProtocol != PointProtocol.Mqtt && IsGoodValue(value))
{
try
{
await PublishMappedValueAsync(client, mapping, value, cancellationToken);
continue;
}
catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); }
}
_initialPublications.TryRemove(id, out _);
}
}
finally { _publishGate.Release(); }
}
private async Task PublishMappedValueAsync(IMqttClient client, MqttMapping mapping, PointValue pointValue, CancellationToken cancellationToken)
{
var message = _factory.CreateApplicationMessageBuilder()
.WithTopic(GatewayStore.GetMqttTopic(mapping))
.WithPayload(CreateOutboundPayload(mapping, pointValue))
.WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService))
.WithRetainFlag(mapping.Retain)
.Build();
await client.PublishAsync(message, cancellationToken);
_initialPublications.TryRemove(mapping.Id, out _);
UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null });
}
public override void Dispose()
{
_store.PointValueUpdated -= OnPointValueUpdated;
@@ -120,10 +176,10 @@ public sealed class MqttClientService : BackgroundService
base.Dispose();
}
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
internal static MqttClientOptions BuildClientOptions(MqttClientFactory factory, MqttConfiguration configuration, string? password, string clientId)
{
var builder = _factory.CreateClientOptionsBuilder()
.WithClientId(configuration.ClientId)
var builder = factory.CreateClientOptionsBuilder()
.WithClientId(clientId)
.WithTcpServer(configuration.Host, configuration.Port)
// MQTT 3.1.1 gives the widest compatibility with existing field brokers.
.WithProtocolVersion(MqttProtocolVersion.V311);
@@ -145,25 +201,39 @@ public sealed class MqttClientService : BackgroundService
});
}
return builder.Build();
}
private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken)
{
var client = _factory.CreateMqttClient();
client.ApplicationMessageReceivedAsync += HandleReceivedMessageAsync;
client.DisconnectedAsync += HandleDisconnectedAsync;
await client.ConnectAsync(builder.Build(), cancellationToken);
lock (_clientLock)
{
_client = client;
}
var now = DateTimeOffset.UtcNow;
SetStatus(new MqttClientStatus(true, true, $"{configuration.Host}:{configuration.Port}", null, now, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc));
await SubscribeMappedTopicsAsync(client, cancellationToken);
client.DisconnectedAsync += arguments => HandleDisconnectedAsync(client, arguments);
try
{
var result = await client.ConnectAsync(BuildClientOptions(_factory, configuration, password, configuration.ClientId), cancellationToken);
if (!client.IsConnected) throw new DomainValidationException($"Broker-Verbindung abgewiesen ({result.ResultCode}).");
var subscriptionError = await SubscribeMappedTopicsAsync(client, cancellationToken);
UpdateStatus(status => status with { Connected = client.IsConnected, LastError = subscriptionError, ConnectedAtUtc = DateTimeOffset.UtcNow });
}
catch
{
await DisconnectCurrentAsync(cancellationToken);
throw;
}
}
private async Task SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken)
private async Task<string?> SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken)
{
var subscriptions = _store.ListMqttMappings()
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
.GroupBy(GatewayStore.GetMqttTopic, StringComparer.Ordinal)
.Select(mapping => (Topic: GatewayStore.GetMqttTopic(mapping), mapping.QualityOfService))
.Concat(Volatile.Read(ref _externalPoints).Keys.Select(topic => (Topic: topic, QualityOfService: MqttQualityOfService.AtLeastOnce)))
.GroupBy(subscription => subscription.Topic, StringComparer.Ordinal)
.Select(group => new
{
Topic = group.Key,
@@ -172,18 +242,21 @@ public sealed class MqttClientService : BackgroundService
.ToArray();
if (subscriptions.Length == 0)
{
return;
return null;
}
var builder = _factory.CreateSubscribeOptionsBuilder();
foreach (var subscription in subscriptions)
var rejected = new List<string>();
foreach (var batch in subscriptions.Chunk(100))
{
builder.WithTopicFilter(filter => filter
.WithTopic(subscription.Topic)
var builder = _factory.CreateSubscribeOptionsBuilder();
foreach (var subscription in batch)
builder.WithTopicFilter(filter => filter.WithTopic(subscription.Topic)
.WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService)));
var result = await client.SubscribeAsync(builder.Build(), cancellationToken);
rejected.AddRange(result.Items.Where(item => (int)item.ResultCode >= 128).Select(item => item.TopicFilter.Topic));
}
await client.SubscribeAsync(builder.Build(), cancellationToken);
return rejected.Count == 0 ? null :
$"Broker hat {rejected.Count} Abonnement(s) abgelehnt · {string.Join(", ", rejected.Take(3))}";
}
private async Task HandleReceivedMessageAsync(MqttApplicationMessageReceivedEventArgs arguments)
@@ -191,27 +264,57 @@ public sealed class MqttClientService : BackgroundService
try
{
var topic = arguments.ApplicationMessage.Topic;
var payload = arguments.ApplicationMessage.Payload;
var receivedAt = DateTimeOffset.UtcNow;
var stored = false;
if (Volatile.Read(ref _externalPoints).TryGetValue(topic, out var sources))
{
var sample = MqttExternalTopics.Read(topic, payload, inferDigital: false);
foreach (var source in sources)
{
if (sample.Value is not { } value || MqttExternalTopics.ConvertToPoint(value, source.ValueType) is not { } converted)
{
UpdateStatus(status => status with { LastError = $"Empfang · {topic} · Wert passt nicht zum Typ '{source.ValueType}'." });
continue;
}
try
{
_store.SetPointValue(source.Id, converted, PointProtocol.Mqtt, receivedAt, "Good", expectedDefinition: source);
stored = true;
}
catch (DomainValidationException exception)
{
UpdateStatus(status => status with { LastError = $"Empfang · {topic} · {exception.Message}" });
}
}
}
var mappings = _store.ListMqttMappings()
.Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional)
.Where(mapping => string.Equals(GatewayStore.GetMqttTopic(mapping), topic, StringComparison.Ordinal))
.ToArray();
if (mappings.Length == 0)
{
if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt });
return;
}
var payload = arguments.ApplicationMessage.Payload;
var payloadBytes = new byte[checked((int)payload.Length)];
payload.CopyTo(payloadBytes);
var rawPayload = Encoding.UTF8.GetString(payloadBytes);
using var document = ParsePayload(rawPayload);
foreach (var mapping in mappings)
{
var value = ExtractInboundValue(document.RootElement, mapping);
_store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, DateTimeOffset.UtcNow);
try
{
var point = _store.GetMqttPoint(mapping.PointId);
if (point is not { Writable: true }) continue;
var value = ExtractInboundValue(document.RootElement, mapping, point);
_store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, receivedAt, expectedDefinition: point);
stored = true;
}
UpdateStatus(status => status with { LastReceivedAtUtc = DateTimeOffset.UtcNow, LastError = null });
catch (DomainValidationException exception) { RecordPayloadError("Empfang", mapping, exception); }
}
if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt });
}
catch (Exception exception)
{
@@ -221,11 +324,11 @@ public sealed class MqttClientService : BackgroundService
await Task.CompletedTask;
}
private Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs arguments)
private Task HandleDisconnectedAsync(IMqttClient client, MqttClientDisconnectedEventArgs arguments)
{
lock (_clientLock)
{
_client = null;
if (!ReferenceEquals(client, _client)) return Task.CompletedTask;
}
if (arguments.Exception is not null)
@@ -275,8 +378,9 @@ public sealed class MqttClientService : BackgroundService
private void OnPointValueUpdated(object? sender, PointValue pointValue)
{
if (!IsGoodValue(pointValue)) return;
// MQTT-originated values must not be reflected to the same broker again.
if (pointValue.SourceProtocol == PointProtocol.Mqtt || !GetStatus().Connected)
if ((pointValue.SourceProtocol == PointProtocol.Mqtt && pointValue.OriginPointId == pointValue.PointId) || !GetStatus().Connected)
{
return;
}
@@ -284,6 +388,9 @@ public sealed class MqttClientService : BackgroundService
_ = PublishPointValueSafelyAsync(pointValue);
}
private static bool IsGoodValue(PointValue value) => string.IsNullOrWhiteSpace(value.Status) ||
value.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) || value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase);
private async Task PublishPointValueSafelyAsync(PointValue pointValue)
{
try
@@ -299,7 +406,7 @@ public sealed class MqttClientService : BackgroundService
}
}
private static JsonDocument ParsePayload(string rawPayload)
internal static JsonDocument ParsePayload(string rawPayload)
{
try
{
@@ -311,7 +418,7 @@ public sealed class MqttClientService : BackgroundService
}
}
private static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping)
internal static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping, GatewayPoint point)
{
if (mapping.Format == MqttMappingFormat.Json && !string.IsNullOrWhiteSpace(mapping.JsonProperty))
{
@@ -323,14 +430,30 @@ public sealed class MqttClientService : BackgroundService
return property.Clone();
}
if (mapping.Format == MqttMappingFormat.Json) return payload.Clone();
if (GatewayStore.IsBooleanMqttPoint(point))
{
if (payload.ValueKind is JsonValueKind.True or JsonValueKind.False) return payload.Clone();
if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var digital) && digital is 0 or 1)
return JsonSerializer.SerializeToElement(digital == 1);
throw new DomainValidationException("Der digitale Datenpunkt erwartet 0 oder 1.");
}
if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var analog) && double.IsFinite(analog))
return payload.Clone();
throw new DomainValidationException("Der Datenpunkt erwartet eine endliche Zahl.");
}
private static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
internal static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue)
{
if (mapping.Format == MqttMappingFormat.SeMonitoring)
if (mapping.Format is MqttMappingFormat.SeMonitoring or MqttMappingFormat.SingleTopic)
{
return pointValue.Value.GetRawText();
return pointValue.Value.ValueKind switch
{
JsonValueKind.True => "1",
JsonValueKind.False => "0",
JsonValueKind.Number when pointValue.Value.TryGetDouble(out var number) && double.IsFinite(number) => pointValue.Value.GetRawText(),
_ => throw new DomainValidationException("Das Topic erwartet eine endliche Zahl oder einen digitalen Zustand.")
};
}
if (string.IsNullOrWhiteSpace(mapping.JsonProperty))
@@ -354,7 +477,19 @@ public sealed class MqttClientService : BackgroundService
_ => throw new ArgumentOutOfRangeException(nameof(qualityOfService))
};
private void SetStatus(MqttClientStatus status) => Volatile.Write(ref _status, status);
private void RecordPayloadError(string direction, MqttMapping mapping, DomainValidationException exception) =>
UpdateStatus(status => status with { LastError = $"{direction} · {GatewayStore.GetMqttTopic(mapping)} · {exception.Message}" });
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update) => SetStatus(update(GetStatus()));
private void UpdateStatus(Func<MqttClientStatus, MqttClientStatus> update)
{
MqttClientStatus before;
MqttClientStatus after;
do
{
before = GetStatus();
after = update(before);
if (after.LastError is { } error && error != before.LastError)
after = after with { LastFailure = error, LastFailureAtUtc = DateTimeOffset.UtcNow };
} while (!ReferenceEquals(Interlocked.CompareExchange(ref _status, after, before), before));
}
}
@@ -0,0 +1,71 @@
using System.Buffers;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
internal static class MqttExternalTopics
{
internal const int MaxTopicLength = 1024;
private const int MaxPayloadLength = 16 * 1024;
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
internal static bool IsTopic(string topic) =>
topic.Length is > 0 and <= MaxTopicLength && topic.IndexOfAny(['+', '#', '\0']) < 0;
internal static string? Address(GatewayPoint point) =>
point is { Protocol: PointProtocol.Mqtt, Scope: PointScope.External } &&
point.Address.TryGetProperty("topic", out var topic) && topic.ValueKind == JsonValueKind.String &&
topic.GetString() is { } address && IsTopic(address) ? address : null;
internal static (JsonElement? Value, string? Type, string Preview) Read(string topic, ReadOnlySequence<byte> payload, bool inferDigital = true)
{
if (payload.IsEmpty) return (null, null, "Leere Nachricht");
if (payload.Length > MaxPayloadLength) return (null, null, $"Nachricht zu groß ({payload.Length} Bytes)");
string text;
try { text = StrictUtf8.GetString(payload.IsSingleSegment ? payload.FirstSpan : payload.ToArray()); }
catch (DecoderFallbackException) { return (null, null, $"Binärdaten ({payload.Length} Bytes)"); }
var preview = text.Length > 240 ? text[..240] + "…" : text;
using var document = MqttClientService.ParsePayload(text);
var value = document.RootElement;
var type = value.ValueKind switch
{
JsonValueKind.True or JsonValueKind.False => "Boolean",
JsonValueKind.Number when value.TryGetDouble(out var number) && double.IsFinite(number) => "Double",
JsonValueKind.String => "String",
JsonValueKind.Object or JsonValueKind.Array => "Json",
_ => null
};
if (inferDigital && type == "Double" && IsSeDigitalTopic(topic) && value.GetDouble() is 0 or 1)
return (JsonSerializer.SerializeToElement(value.GetDouble() == 1), "Boolean", preview);
return (type is null ? null : value.Clone(), type, preview);
}
private static bool IsSeDigitalTopic(string topic)
{
var levels = topic.Split('/');
return levels is [var projectYear, var project, var isp, "Notify" or "Alarm" or "Alarms", _] &&
projectYear.StartsWith("Projekte", StringComparison.Ordinal) &&
project.StartsWith('P') && isp.StartsWith("ISP", StringComparison.Ordinal);
}
internal static JsonElement? ConvertToPoint(JsonElement value, string type)
{
if (OpcUaPointTypes.Resolve(type) == Opc.Ua.BuiltInType.Boolean)
{
if (value.ValueKind is JsonValueKind.True or JsonValueKind.False) return value;
if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var state) && state is 0 or 1)
return JsonSerializer.SerializeToElement(state == 1);
return null;
}
return OpcUaPointTypes.Resolve(type) switch
{
>= Opc.Ua.BuiltInType.SByte and <= Opc.Ua.BuiltInType.Double when value.ValueKind == JsonValueKind.Number => value,
Opc.Ua.BuiltInType.String when value.ValueKind == JsonValueKind.String => value,
_ when type.Equals("Json", StringComparison.OrdinalIgnoreCase) && value.ValueKind is JsonValueKind.Object or JsonValueKind.Array => value,
_ => null
};
}
}
@@ -0,0 +1,204 @@
using System.Text.Json;
using Gateway.Api.Domain;
using MQTTnet;
using MQTTnet.Protocol;
namespace Gateway.Api.Services;
public sealed record MqttTopicBrowseRequest(string? Filter);
public sealed record MqttTopicImportRequest(Guid SessionId, string[] Topics);
public sealed record MqttTopicImportResult(int Created, int Existing, int Unavailable);
public sealed record MqttTopicBrowserItem(string Topic, string Preview, string? ValueType, DateTimeOffset ReceivedAtUtc, bool Retained, Guid? PointId);
public sealed record MqttTopicBrowserView(Guid SessionId, string Filter, bool Connected, bool LimitReached, string? Error, IReadOnlyList<MqttTopicBrowserItem> Topics);
internal sealed record ObservedMqttTopic(string Topic, string Preview, string? ValueType, JsonElement? Value, DateTimeOffset ReceivedAtUtc, bool Retained);
public sealed class MqttTopicBrowserService(GatewayStore store) : BackgroundService
{
private const int MaxTopics = 3000;
private readonly MqttClientFactory _factory = new();
private readonly SemaphoreSlim _lifecycle = new(1, 1);
private BrowserSession? _current;
public async Task<MqttTopicBrowserView> StartBrowseAsync(MqttTopicBrowseRequest request, CancellationToken cancellationToken)
{
var filter = string.IsNullOrEmpty(request.Filter) ? "#" : request.Filter;
ValidateFilter(filter);
await _lifecycle.WaitAsync(cancellationToken);
try
{
var (configuration, password) = store.GetMqttConnectionConfiguration();
if (!configuration.Enabled) throw new DomainValidationException("Zuerst den MQTT-Client aktivieren und den Broker speichern.");
if (_current is { } active && active.Client.IsConnected && active.Filter == filter && active.Configuration == configuration)
return ReadView(active);
await StopCurrentAsync();
var session = new BrowserSession(configuration, filter, _factory.CreateMqttClient());
session.Client.ApplicationMessageReceivedAsync += message =>
{
var publish = message.ApplicationMessage;
Capture(session, publish.Topic, publish.Payload, publish.Retain);
return Task.CompletedTask;
};
session.Client.DisconnectedAsync += notification =>
{
lock (session.Topics) session.Error = notification.Exception?.Message ?? "Die Broker-Verbindung wurde getrennt.";
return Task.CompletedTask;
};
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(12));
try
{
var clientId = "seiugwBrowse" + session.Id.ToString("N")[..10];
var result = await session.Client.ConnectAsync(MqttClientService.BuildClientOptions(_factory, configuration, password, clientId), timeout.Token);
if (!session.Client.IsConnected)
throw new DomainValidationException($"Broker-Verbindung abgewiesen ({result.ResultCode}).");
var options = _factory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(topic => topic.WithTopic(filter).WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)).Build();
var subscription = await session.Client.SubscribeAsync(options, timeout.Token);
if (subscription.Items.Count != 1 || subscription.Items.Any(item => (int)item.ResultCode >= 128))
throw new DomainValidationException($"Der Broker hat den Topic-Filter '{filter}' abgelehnt.");
Volatile.Write(ref _current, session);
return ReadView(session);
}
catch (Exception exception)
{
await CloseAsync(session);
if (cancellationToken.IsCancellationRequested || exception is DomainValidationException) throw;
throw new DomainValidationException(exception is OperationCanceledException
? "Der Broker hat beim Öffnen des Topic-Browsers nicht rechtzeitig geantwortet."
: $"MQTT-Topic-Browser: {exception.Message}");
}
}
finally { _lifecycle.Release(); }
}
public MqttTopicBrowserView GetBrowse(Guid id) => ReadView(RequireSession(id));
public async Task<MqttTopicImportResult> ImportAsync(MqttTopicImportRequest request, CancellationToken cancellationToken)
{
if (request.Topics is not { Length: >= 1 and <= MaxTopics } || request.Topics.Any(topic => topic is null || !MqttExternalTopics.IsTopic(topic)))
throw new DomainValidationException($"Bitte 1 bis {MaxTopics} beobachtete MQTT-Topics auswählen.");
await _lifecycle.WaitAsync(cancellationToken);
try
{
var session = RequireSession(request.SessionId);
ObservedMqttTopic[] samples;
var selection = request.Topics.ToHashSet(StringComparer.Ordinal);
lock (session.Topics)
samples = session.Topics.Values.Where(sample => selection.Contains(sample.Topic) && sample.Value.HasValue).ToArray();
return store.ImportMqttExternalPoints(session.Configuration, samples, selection.Count - samples.Length);
}
finally { _lifecycle.Release(); }
}
public async Task ResetAsync(CancellationToken cancellationToken)
{
await _lifecycle.WaitAsync(cancellationToken);
try { await StopCurrentAsync(); }
finally { _lifecycle.Release(); }
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
if (Volatile.Read(ref _current) is not { } session || !session.IsIdle) continue;
await _lifecycle.WaitAsync(stoppingToken);
try
{
if (ReferenceEquals(session, _current) && session.IsIdle) await StopCurrentAsync();
}
finally { _lifecycle.Release(); }
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally { await ResetAsync(CancellationToken.None); }
}
private BrowserSession RequireSession(Guid id)
{
if (Volatile.Read(ref _current) is not { } session || session.Id != id || session.IsIdle)
throw new DomainValidationException("Die Topic-Beobachtung ist abgelaufen. Bitte erneut starten.");
if (store.GetGatewayConfiguration().Mqtt != session.Configuration)
throw new DomainValidationException("Die Broker-Konfiguration wurde geändert. Bitte die Topic-Beobachtung neu starten.");
session.Touch();
return session;
}
private MqttTopicBrowserView ReadView(BrowserSession session)
{
var points = store.ListMqttExternalPoints()
.ToLookup(point => MqttExternalTopics.Address(point)!, StringComparer.Ordinal);
session.Touch();
lock (session.Topics)
{
var topics = session.Topics.Values.OrderBy(sample => sample.Topic, StringComparer.Ordinal)
.Select(sample => new MqttTopicBrowserItem(sample.Topic, sample.Preview, sample.ValueType, sample.ReceivedAtUtc,
sample.Retained, points[sample.Topic].FirstOrDefault()?.Id)).ToArray();
return new(session.Id, session.Filter, session.Client.IsConnected, session.LimitReached, session.Error, topics);
}
}
private static void Capture(BrowserSession session, string topic, System.Buffers.ReadOnlySequence<byte> payload, bool retained)
{
if (!MqttExternalTopics.IsTopic(topic)) return;
lock (session.Topics)
{
if (!session.Topics.ContainsKey(topic) && session.Topics.Count >= MaxTopics)
{
session.LimitReached = true;
return;
}
var (value, type, preview) = MqttExternalTopics.Read(topic, payload);
session.Topics[topic] = new(topic, preview, type, value, DateTimeOffset.UtcNow, retained);
}
}
private static void ValidateFilter(string filter)
{
if (filter.Length > MqttExternalTopics.MaxTopicLength || filter.Contains('\0'))
throw new DomainValidationException("Der MQTT-Topic-Filter ist ungültig.");
var levels = filter.Split('/');
for (var index = 0; index < levels.Length; index++)
{
var level = levels[index];
if ((level.Contains('#') && (level != "#" || index != levels.Length - 1)) ||
(level.Contains('+') && level != "+"))
throw new DomainValidationException("MQTT-Wildcards müssen ganze Ebenen belegen. # gehört ans Ende des Filters.");
}
}
private async Task StopCurrentAsync()
{
if (Interlocked.Exchange(ref _current, null) is { } session) await CloseAsync(session);
}
private async Task CloseAsync(BrowserSession session)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
if (session.Client.IsConnected)
await session.Client.DisconnectAsync(_factory.CreateClientDisconnectOptionsBuilder().Build(), timeout.Token);
}
catch (Exception) { /* The client still has to release its broker connection. */ }
finally { session.Client.Dispose(); }
}
private sealed class BrowserSession(MqttConfiguration configuration, string filter, IMqttClient client)
{
private long _lastAccess = Environment.TickCount64;
public Guid Id { get; } = Guid.NewGuid();
public MqttConfiguration Configuration { get; } = configuration;
public string Filter { get; } = filter;
public IMqttClient Client { get; } = client;
public Dictionary<string, ObservedMqttTopic> Topics { get; } = new(StringComparer.Ordinal);
public bool LimitReached { get; set; }
public string? Error { get; set; }
public bool IsIdle => Environment.TickCount64 - Interlocked.Read(ref _lastAccess) >= 45000;
public void Touch() => Interlocked.Exchange(ref _lastAccess, Environment.TickCount64);
}
}
@@ -0,0 +1,126 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
/// <summary>SE-Inno APIs use PHP-style multipart form fields, not Meta's direct JSON API.</summary>
public sealed class NotificationTransport(IHttpClientFactory clients)
{
public static readonly IReadOnlyList<string> WhatsAppTemplates = ["infomessagegroup", "infoapp", "meldung", "stoerung", "se_portal_admin", "contact_form", "se_portal_manage", "se_portal"];
// Template variables cannot contain line breaks/tabs or runs of more than four spaces.
// Keep Unicode letters, punctuation and emoji; normalize whitespace instead of stripping umlauts.
public static string NormalizeTemplateText(string text, int maximumLength = 1024)
{
if (text is null) throw new DomainValidationException("WhatsApp-Template-Text fehlt.");
var output = new StringBuilder();
var space = false;
foreach (var rune in text.Normalize(NormalizationForm.FormC).EnumerateRunes())
{
if (Rune.IsWhiteSpace(rune) || Rune.IsControl(rune)) { space = output.Length > 0; continue; }
if (space) output.Append(' ');
space = false;
output.Append(rune);
}
var normalized = output.ToString();
if (normalized.Length == 0 || normalized.Length > maximumLength)
throw new DomainValidationException($"WhatsApp-Template-Text muss nach Bereinigung 1 bis {maximumLength} Zeichen enthalten. Bitte die Nachricht kürzen.");
return normalized;
}
public static MultipartFormDataContent BuildAlarmForm(string key, NotificationDelivery delivery)
{
GatewayStore.ValidateAlarmDestination(delivery.Destination);
if (string.IsNullOrWhiteSpace(key)) throw new DomainValidationException("Für diesen Versandkanal ist kein API-Key hinterlegt.");
var fields = new Dictionary<string, string> { ["api_key"] = key };
var destination = delivery.Destination;
switch (destination.Channel)
{
case NotificationChannel.Mail:
fields["address"] = destination.Recipient;
fields["subject"] = delivery.Title;
fields["message"] = delivery.Message;
break;
case NotificationChannel.WhatsApp:
fields["number"] = destination.Recipient;
fields["message"] = NormalizeTemplateText(delivery.Message);
fields["template"] = destination.Template;
fields["pn"] = NormalizeTemplateText(destination.PersonName, 60);
break;
case NotificationChannel.Ntfy:
fields["topic"] = destination.Recipient;
fields["message"] = delivery.Message;
fields["title"] = delivery.Title;
fields["priority"] = destination.Priority.ToString(CultureInfo.InvariantCulture);
fields["tags"] = destination.Tags;
break;
}
var form = new MultipartFormDataContent();
foreach (var (name, value) in fields) form.Add(new StringContent(value, Encoding.UTF8), name);
return form;
}
public async Task SendAlarmAsync(string key, NotificationDelivery delivery, CancellationToken cancellationToken)
{
using var form = BuildAlarmForm(key, delivery);
await PostAsync(delivery.Destination.Channel, form, cancellationToken);
}
public async Task PostAsync(NotificationChannel channel, MultipartFormDataContent form, CancellationToken cancellationToken)
{
using var client = clients.CreateClient("seiugw-notifications");
using var response = await client.PostAsync(GatewayStore.NotificationEndpoint(channel), form, cancellationToken);
if (!response.IsSuccessStatusCode)
throw new DomainValidationException($"{channel}-API: HTTP {(int)response.StatusCode}.");
// Do not persist or echo arbitrary API bodies: they can contain credentials and personal data.
var body = await response.Content.ReadAsStringAsync(cancellationToken);
try
{
using var json = JsonDocument.Parse(body);
if (json.RootElement.ValueKind == JsonValueKind.Object &&
((json.RootElement.TryGetProperty("success", out var success) && success.ValueKind == JsonValueKind.False) ||
(json.RootElement.TryGetProperty("error", out var error) && error.ValueKind is not (JsonValueKind.Null or JsonValueKind.False) && error.ToString().Length > 0)))
throw new DomainValidationException($"{channel}-API meldet einen Fehler trotz HTTP-Erfolg.");
}
catch (JsonException) { /* The supplied APIs may respond with plain text. HTTP remains the available acceptance signal. */ }
}
}
public sealed class AlarmNotificationService(GatewayStore store, NotificationTransport transport) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
store.RecoverInterruptedNotifications();
while (!stoppingToken.IsCancellationRequested)
{
var delivery = store.ClaimNotification();
if (delivery is null)
{
try { await Task.Delay(500, stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
continue;
}
try
{
var key = store.GetNotificationKey(delivery.Destination.Channel);
if (key is null)
{
store.CompleteNotification(delivery.Id, "Blocked", "API-Key fehlt; Kanal gesperrt.");
continue;
}
await transport.SendAlarmAsync(key, delivery, stoppingToken);
store.CompleteNotification(delivery.Id, "Accepted", "Von API angenommen; Endzustellung nicht bestätigt.");
}
catch (DomainValidationException exception)
{
store.CompleteNotification(delivery.Id, "Failed", exception.Message);
}
catch (Exception exception) when (exception is HttpRequestException or OperationCanceledException)
{
store.CompleteNotification(delivery.Id, "Unknown", "Verbindung unterbrochen oder Zeitlimit erreicht; Zustellung unbekannt. Kein automatischer Doppelversand.");
}
}
}
}
@@ -0,0 +1,121 @@
using Opc.Ua;
using Opc.Ua.Configuration;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Gateway.Api.Services;
#pragma warning disable CS0618 // OPC UA 1.5 retains this constructor while its telemetry migration is in progress.
/// <summary>Creates one persistent PKI layout for both OPC UA client and server roles.</summary>
public sealed class OpcUaApplicationFactory
{
private static readonly SemaphoreSlim CertificateGate = new(1, 1);
private readonly GatewayDatabase _database;
public OpcUaApplicationFactory(GatewayDatabase database)
{
_database = database;
}
public async Task<ApplicationConfiguration> CreateClientConfigurationAsync()
{
var configuration = CreateBaseConfiguration(ApplicationType.Client);
await configuration.ValidateAsync(ApplicationType.Client);
await EnsureCertificateAsync(configuration);
return configuration;
}
public async Task<ApplicationConfiguration> CreateServerConfigurationAsync(int port, bool allowAnonymous)
{
var configuration = CreateBaseConfiguration(ApplicationType.Server);
var addresses = NetworkInterface.GetAllNetworkInterfaces().Where(adapter => adapter.OperationalStatus == OperationalStatus.Up)
.SelectMany(adapter => adapter.GetIPProperties().UnicastAddresses)
.Select(address => address.Address)
.Where(address => address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6 && !address.IsIPv6LinkLocal)
.Select(address => address.ToString())
.Concat(["localhost", "127.0.0.1", "::1"])
.Distinct(StringComparer.OrdinalIgnoreCase);
configuration.ServerConfiguration = new ServerConfiguration
{
// The SDK binds a DNS base address on all interfaces and matches discovery requests against the IP aliases.
BaseAddresses = [new UriBuilder("opc.tcp", Utils.GetHostName(), port).Uri.AbsoluteUri],
AlternateBaseAddresses = new StringCollection(addresses.Select(address => new UriBuilder("opc.tcp", address, port).Uri.AbsoluteUri)),
SecurityPolicies = [
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.Sign, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 },
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.SignAndEncrypt, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }
],
UserTokenPolicies = allowAnonymous
? [new UserTokenPolicy(UserTokenType.UserName), new UserTokenPolicy(UserTokenType.Anonymous)]
: [new UserTokenPolicy(UserTokenType.UserName)],
DiagnosticsEnabled = false,
MaxSessionCount = 100,
MaxChannelCount = 100
};
await configuration.ValidateAsync(ApplicationType.Server);
await EnsureCertificateAsync(configuration);
return configuration;
}
private ApplicationConfiguration CreateBaseConfiguration(ApplicationType type)
{
var pkiDirectory = Path.Combine(_database.DataDirectory, "pki", "opcua");
Directory.CreateDirectory(pkiDirectory);
return new ApplicationConfiguration
{
ApplicationName = "SE-Inno Universalgateway",
ApplicationUri = $"urn:{Utils.GetHostName()}:se-inno:universalgateway" + (type == ApplicationType.Server ? ":server" : ""),
ApplicationType = type,
ProductUri = "urn:se-inno:universalgateway",
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = CertificateStoreType.Directory,
// Client certificates can lack server DNS names. Keep the existing
// client identity, and create a separate server identity without deleting it.
StorePath = Path.Combine(pkiDirectory, type == ApplicationType.Server ? "server-own" : "own"),
SubjectName = $"CN=SE-Inno Universalgateway{(type == ApplicationType.Server ? " Server" : "")}, DC={Utils.GetHostName()}"
},
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "trusted") },
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "issuers") },
RejectedCertificateStore = new CertificateStoreIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "rejected") },
AutoAcceptUntrustedCertificates = false,
AddAppCertToTrustedStore = true
},
ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = 60_000,
WellKnownDiscoveryUrls = []
},
TransportQuotas = new TransportQuotas { OperationTimeout = 15_000, MaxMessageSize = 4 * 1024 * 1024 },
TransportConfigurations = []
};
}
private static async Task EnsureCertificateAsync(ApplicationConfiguration configuration)
{
await CertificateGate.WaitAsync();
try
{
var identity = configuration.SecurityConfiguration.ApplicationCertificate;
if (configuration.ApplicationType == ApplicationType.Server && await identity.Find(false) is null)
{
var names = configuration.GetServerDomainNames().Append("localhost").Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
using var certificate = CertificateFactory.CreateCertificate(configuration.ApplicationUri, configuration.ApplicationName, identity.SubjectName, names)
.SetLifeTime(24).SetRSAKeySize(2048).CreateForRSA();
using var certificateStore = identity.OpenStore();
await certificateStore.AddAsync(certificate);
}
var application = new ApplicationInstance(configuration);
if (!await application.CheckApplicationInstanceCertificatesAsync(false, null, CancellationToken.None))
throw new DomainValidationException("Das OPC-UA-Anwendungszertifikat konnte nicht erzeugt oder geladen werden.");
}
finally
{
CertificateGate.Release();
}
}
}
#pragma warning restore CS0618
@@ -0,0 +1,169 @@
using System.Text.Json;
using System.Text;
using Gateway.Api.Domain;
using Opc.Ua;
using Opc.Ua.Client;
namespace Gateway.Api.Services;
#pragma warning disable CS0618 // The OPC Foundation 1.5 fluent/async replacement is still evolving; these stable calls remain supported.
public sealed record OpcUaBrowseRequest(
string EndpointUrl,
string? NodeId = null,
bool UseSecurity = true,
OpcUaAuthenticationMode AuthenticationMode = OpcUaAuthenticationMode.Anonymous,
string? Username = null,
string? Password = null,
bool AcceptUntrustedServerCertificate = false,
Guid? ClientId = null);
public sealed record OpcUaBrowseItem(string NodeId, string BrowseName, string DisplayName, string NodeClass, bool HasChildren, JsonElement? Value,
string? StableNodeId = null, string? ValueType = null, bool Readable = false, bool Writable = false);
public sealed class OpcUaBrowserService
{
private readonly OpcUaApplicationFactory _applications;
private readonly GatewayStore? _store;
public OpcUaBrowserService(OpcUaApplicationFactory applications, GatewayStore? store = null)
{
_applications = applications;
_store = store;
}
public async Task<IReadOnlyList<OpcUaBrowseItem>> BrowseAsync(OpcUaBrowseRequest request)
{
try { return await BrowseCoreAsync(request); }
catch (OperationCanceledException) { throw new DomainValidationException("OPC-UA-Abfrage nach 15 Sekunden abgebrochen. Bitte einen kleineren Teilbaum öffnen."); }
catch (ServiceResultException exception) { throw new DomainValidationException($"OPC-UA-Abfrage fehlgeschlagen: {exception.StatusCode}. Anmeldung, Endpunkt und Zertifikatsvertrauen prüfen."); }
catch (FormatException) { throw new DomainValidationException("Die OPC-UA-NodeId ist ungültig."); }
}
private async Task<IReadOnlyList<OpcUaBrowseItem>> BrowseCoreAsync(OpcUaBrowseRequest request)
{
if (request.ClientId is { } clientId)
{
var saved = _store?.ListOpcUaClients().SingleOrDefault(item => item.Configuration.Id == clientId)?.Configuration
?? throw new DomainValidationException("OPC-UA-Verbindung nicht gefunden.");
request = request with { EndpointUrl = saved.EndpointUrl, UseSecurity = saved.UseSecurity, AuthenticationMode = saved.AuthenticationMode,
Username = saved.Username, Password = _store!.GetOpcUaClientCredentials(clientId).Password, AcceptUntrustedServerCertificate = saved.AcceptUntrustedServerCertificate };
}
if (!Uri.TryCreate(request.EndpointUrl, UriKind.Absolute, out var endpointUri) || endpointUri.Scheme != "opc.tcp")
{
throw new DomainValidationException("Die OPC-UA-Endpunktadresse muss mit opc.tcp:// beginnen.");
}
if (request.AuthenticationMode == OpcUaAuthenticationMode.Username && (string.IsNullOrWhiteSpace(request.Username) || request.Password is null))
{
throw new DomainValidationException("Für OPC-UA-Benutzeranmeldung werden Benutzername und Passwort benötigt.");
}
if (request.AuthenticationMode is not (OpcUaAuthenticationMode.Anonymous or OpcUaAuthenticationMode.Username))
throw new DomainValidationException("Benutzerzertifikate werden im Browser noch nicht unterstützt. Bitte Anonym oder Benutzer/Passwort wählen.");
if (request.AuthenticationMode == OpcUaAuthenticationMode.Username && !request.UseSecurity)
throw new DomainValidationException("Benutzer/Passwort erfordert einen gesicherten OPC-UA-Kanal.");
var configuration = await _applications.CreateClientConfigurationAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
if (request.AcceptUntrustedServerCertificate)
{
// Explicit per-request exception, never a global trust relaxation.
configuration.CertificateValidator.CertificateValidation += (_, args) => args.Accept = args.Error.StatusCode == Opc.Ua.StatusCodes.BadCertificateUntrusted;
}
EndpointDescription selected;
try
{
selected = await CoreClientUtils.SelectEndpointAsync(configuration, request.EndpointUrl, request.UseSecurity, 15_000, timeout.Token);
}
catch (OperationCanceledException)
{
throw new DomainValidationException("Der OPC-UA-Endpunkt hat nicht innerhalb von 15 Sekunden geantwortet.");
}
var endpoint = new ConfiguredEndpoint(null, selected, EndpointConfiguration.Create(configuration));
if (request.UseSecurity && selected.SecurityMode is not (MessageSecurityMode.Sign or MessageSecurityMode.SignAndEncrypt))
throw new DomainValidationException("Der Server bietet keinen gesicherten OPC-UA-Endpunkt an.");
var identity = request.AuthenticationMode == OpcUaAuthenticationMode.Username
? new UserIdentity(request.Username!, Encoding.UTF8.GetBytes(request.Password!))
: new UserIdentity();
Session session;
try
{
session = await Session.Create(configuration, endpoint, false, true, "SE-Inno Universalgateway Browser", 60_000, identity, null, timeout.Token);
}
catch (OperationCanceledException)
{
throw new DomainValidationException("Der OPC-UA-Endpunkt hat keine Sitzung innerhalb von 15 Sekunden aufgebaut.");
}
try
{
var node = string.IsNullOrWhiteSpace(request.NodeId) ? ObjectIds.ObjectsFolder : ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(request.NodeId), session.NamespaceUris);
var browser = new Browser(session)
{
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true,
NodeClassMask = 0,
MaxReferencesReturned = 250,
ContinueUntilDone = true
};
var references = await browser.BrowseAsync(node, timeout.Token);
if (references.Count > 5000) throw new DomainValidationException("Mehr als 5000 Nodes in einer Ebene. Bitte den Teilbaum gezielt eingrenzen.");
var readableNodes = references.Where(reference => reference.NodeClass == NodeClass.Variable && !reference.NodeId.IsAbsolute)
.Select(reference => ExpandedNodeId.ToNodeId(reference.NodeId, session.NamespaceUris)).Distinct().ToArray();
var values = new Dictionary<NodeId, DataValue>();
var metadata = new Dictionary<NodeId, (string? Type, byte Access)>();
foreach (var batch in readableNodes.Chunk(25))
{
var reads = new ReadValueIdCollection(batch.SelectMany(id => new[] { Attributes.Value, Attributes.DataType, Attributes.ValueRank, Attributes.UserAccessLevel }
.Select(attribute => new ReadValueId { NodeId = id, AttributeId = attribute })));
var result = await session.ReadAsync(null, 0, TimestampsToReturn.Both, reads, timeout.Token);
for (var i = 0; i < batch.Length; i++)
{
values[batch[i]] = result.Results[i * 4];
var type = result.Results[i * 4 + 1].Value is NodeId typeId ? TypeInfo.GetBuiltInType(typeId, session.TypeTree).ToString() : null;
if (result.Results[i * 4 + 2].Value is not int rank || rank != ValueRanks.Scalar || type is null || OpcUaPointTypes.Resolve(type) == BuiltInType.Null) type = null;
metadata[batch[i]] = (type, result.Results[i * 4 + 3].Value is byte access ? access : (byte)0);
}
}
var items = new List<OpcUaBrowseItem>();
foreach (var reference in references)
{
timeout.Token.ThrowIfCancellationRequested();
var localId = ExpandedNodeId.ToNodeId(reference.NodeId, session.NamespaceUris);
var meta = localId is not null && metadata.TryGetValue(localId, out var found) ? found : default;
JsonElement? value = null;
if (localId is not null && values.TryGetValue(localId, out var dataValue))
{
try
{
if (StatusCode.IsGood(dataValue.StatusCode) && dataValue.Value is not null)
{
value = JsonSerializer.SerializeToElement(dataValue.Value);
}
}
catch (Exception exception) when (exception is NotSupportedException or JsonException)
{
// Browsing should remain usable if one variable rejects a read.
}
}
items.Add(new OpcUaBrowseItem(
localId?.ToString() ?? reference.NodeId.ToString(),
reference.BrowseName?.Name ?? reference.NodeId.ToString(),
reference.DisplayName?.Text ?? reference.BrowseName?.Name ?? reference.NodeId.ToString(),
reference.NodeClass.ToString(),
reference.NodeClass is NodeClass.Object or NodeClass.Variable,
value,
localId is null ? null : NodeId.ToExpandedNodeId(localId, session.NamespaceUris).ToString(),
meta.Type, (meta.Access & AccessLevels.CurrentRead) != 0, (meta.Access & AccessLevels.CurrentWrite) != 0));
}
return items;
}
finally
{
await session.CloseAsync();
session.Dispose();
}
}
}
#pragma warning restore CS0618
@@ -0,0 +1,229 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using Gateway.Api.Domain;
using Opc.Ua;
using Opc.Ua.Client;
using StatusCodes = Opc.Ua.StatusCodes;
namespace Gateway.Api.Services;
#pragma warning disable CS0618
#pragma warning disable CA1848
public sealed record OpcUaClientStatus(Guid ClientId, bool Connected, int SubscribedPoints, string State, DateTimeOffset UpdatedAtUtc);
/// <summary>One long-lived secure session/subscription per connection. Writes are never retried after an ambiguous result.</summary>
public sealed class OpcUaClientService(GatewayStore store, OpcUaApplicationFactory applications, ILogger<OpcUaClientService> logger) : BackgroundService
{
private readonly ConcurrentDictionary<Guid, OpcUaClientStatus> _status = new();
private readonly ConcurrentDictionary<Guid, Worker> _workers = new();
private int _disposed;
public IReadOnlyList<OpcUaClientStatus> GetStatus() => _status.Values.ToArray();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
store.PointValueUpdated += OnPointValue;
try
{
while (!stoppingToken.IsCancellationRequested)
{
var configuration = store.GetGatewayConfiguration().OpcUa;
var clients = configuration.ClientEnabled ? (configuration.Clients ?? []).Where(client => client.Enabled).ToArray() : [];
var points = store.ListPoints();
foreach (var id in _workers.Keys.Except(clients.Select(client => client.Id))) await RemoveAsync(id);
foreach (var client in clients)
{
var selected = points.Where(point => point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.External && ClientId(point) == client.Id).ToArray();
var credentials = store.GetOpcUaClientCredentials(client.Id);
var signature = JsonSerializer.Serialize(new { client, selected, credentials.Revision });
if (_workers.TryGetValue(client.Id, out var current) && current.Signature == signature) continue;
await RemoveAsync(client.Id);
var worker = new Worker(signature, CancellationTokenSource.CreateLinkedTokenSource(stoppingToken));
_workers[client.Id] = worker;
worker.Task = RunClientAsync(client, selected, credentials.Password, worker);
}
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally
{
store.PointValueUpdated -= OnPointValue;
foreach (var id in _workers.Keys) await RemoveAsync(id);
}
}
private static Guid? ClientId(GatewayPoint point) => point.Address.TryGetProperty("clientId", out var id) && id.ValueKind == JsonValueKind.String && id.TryGetGuid(out var result) ? result : null;
private void OnPointValue(object? sender, PointValue value)
{
if (value.OriginPointId == value.PointId || !IsGood(value.Status)) return;
var point = store.ListPoints().SingleOrDefault(point => point.Id == value.PointId && point.Protocol == PointProtocol.OpcUa && point.Scope == PointScope.External && point.Writable);
if (point is null || ClientId(point) is not { } clientId) return;
if (!_workers.TryGetValue(clientId, out var worker) || !worker.Connected || !worker.Writes.Writer.TryWrite(value))
MarkPoint(point, "BadNotConnected");
}
private async Task RunClientAsync(OpcUaClientConfiguration client, GatewayPoint[] points, string? password, Worker worker)
{
var token = worker.Cancellation.Token;
var retrySeconds = 1;
while (!token.IsCancellationRequested)
{
Session? session = null;
try
{
SetStatus(client.Id, false, 0, "Verbindungsaufbau");
var configuration = await applications.CreateClientConfigurationAsync();
if (client.AcceptUntrustedServerCertificate)
configuration.CertificateValidator.CertificateValidation += (_, args) => args.Accept = args.Error.StatusCode == StatusCodes.BadCertificateUntrusted;
using var connectTimeout = CancellationTokenSource.CreateLinkedTokenSource(token);
connectTimeout.CancelAfter(TimeSpan.FromSeconds(15));
var endpoint = await CoreClientUtils.SelectEndpointAsync(configuration, client.EndpointUrl, client.UseSecurity, 15_000, connectTimeout.Token);
if (client.UseSecurity && endpoint.SecurityMode is not (MessageSecurityMode.Sign or MessageSecurityMode.SignAndEncrypt)) throw new ServiceResultException(StatusCodes.BadSecurityModeInsufficient);
var identity = client.AuthenticationMode switch
{
OpcUaAuthenticationMode.Anonymous => new UserIdentity(),
OpcUaAuthenticationMode.Username when client.UseSecurity && password is not null => new UserIdentity(client.Username!, Encoding.UTF8.GetBytes(password)),
_ => throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected)
};
session = await Session.Create(configuration, new ConfiguredEndpoint(null, endpoint, EndpointConfiguration.Create(configuration)), false, true, $"SE-UGW {client.Name}", 60_000, identity, null, connectTimeout.Token);
session.KeepAliveInterval = 5000;
var faulted = 0;
session.KeepAlive += (_, args) => { if (ServiceResult.IsBad(args.Status)) Interlocked.Exchange(ref faulted, 1); };
var observations = new ConcurrentQueue<(GatewayPoint Point, DataValue Value)>();
var nodes = points.ToDictionary(point => point.Id, point => ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(point.Address.GetProperty("nodeId").GetString()!), session.NamespaceUris)
?? throw new ServiceResultException(StatusCodes.BadNodeIdUnknown));
using var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = client.PublishingIntervalMilliseconds, KeepAliveCount = 10, LifetimeCount = 60 };
foreach (var point in points.Where(point => point.Readable))
{
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodes[point.Id], AttributeId = Attributes.Value, SamplingInterval = client.PublishingIntervalMilliseconds, QueueSize = 100, DiscardOldest = true };
item.Notification += (_, _) => { foreach (var value in item.DequeueValues()) observations.Enqueue((point, value)); };
subscription.AddItem(item);
}
session.AddSubscription(subscription);
await subscription.CreateAsync(token);
var rejected = subscription.MonitoredItems.Count(item => ServiceResult.IsBad(item.Status.Error));
var echoes = new Dictionary<Guid, List<(string Value, DateTimeOffset Expires)>>();
var seen = new Dictionary<Guid, (DateTime Time, string Value, uint Status)>();
// Drop queued commands from an old connection. Reconnect is a fresh read, never a replay of writes.
while (worker.Writes.Reader.TryRead(out _)) { }
worker.Connected = true;
retrySeconds = 1;
SetStatus(client.Id, true, points.Length - rejected, rejected == 0 ? "Abonniert" : $"{rejected} Nodes abgewiesen");
while (!token.IsCancellationRequested && Volatile.Read(ref faulted) == 0 && session.Connected)
{
// Process a bounded batch so ongoing notifications cannot starve writes.
for (var i = 0; i < 1000 && observations.TryDequeue(out var observation); i++)
{
var point = observation.Point;
var value = observation.Value;
if (!StatusCode.IsGood(value.StatusCode) || value.Value is null) { MarkPoint(point, value.Value is null && StatusCode.IsGood(value.StatusCode) ? "BadWaitingForInitialData" : value.StatusCode.ToString()); continue; }
JsonElement json;
try { json = JsonSerializer.SerializeToElement(value.Value); _ = OpcUaPointTypes.Convert(json, OpcUaPointTypes.Resolve(point.ValueType)); }
catch (Exception exception) when (exception is FormatException or InvalidOperationException or JsonException or NotSupportedException or OverflowException) { MarkPoint(point, "BadTypeMismatch"); continue; }
var text = json.GetRawText();
var timestamp = value.SourceTimestamp == DateTime.MinValue ? value.ServerTimestamp : value.SourceTimestamp;
if (timestamp == DateTime.MinValue) timestamp = DateTime.UtcNow;
if (seen.TryGetValue(point.Id, out var prior) && timestamp <= prior.Time && text == prior.Value && value.StatusCode.Code == prior.Status) continue;
seen[point.Id] = (timestamp, text, value.StatusCode.Code);
if (echoes.TryGetValue(point.Id, out var pending))
{
pending.RemoveAll(entry => entry.Expires < DateTimeOffset.UtcNow);
var match = pending.FindIndex(entry => entry.Value == text);
if (match >= 0) { pending.RemoveAt(match); continue; }
}
try
{
store.SetPointValue(point.Id, json, PointProtocol.OpcUa, new DateTimeOffset(DateTime.SpecifyKind(timestamp, DateTimeKind.Utc)), "Good", expectedDefinition: point);
}
catch (DomainValidationException) { /* The subscription will reconcile the edited point. */ }
}
if (worker.Writes.Reader.TryRead(out var write))
{
var point = points.SingleOrDefault(candidate => candidate.Id == write.PointId);
if (point is null || !store.IsPointDefinitionCurrent(point)) continue;
var converted = OpcUaPointTypes.Convert(write.Value, OpcUaPointTypes.Resolve(point.ValueType));
var text = JsonSerializer.Serialize(converted);
if (!echoes.TryGetValue(point.Id, out var pending)) echoes[point.Id] = pending = [];
pending.Add((text, DateTimeOffset.UtcNow.AddSeconds(30)));
try
{
var response = await session.WriteAsync(null, [new WriteValue { NodeId = nodes[point.Id], AttributeId = Attributes.Value, Value = new DataValue(new Variant(converted)) }], token);
if (StatusCode.IsBad(response.Results[0])) { pending.RemoveAll(entry => entry.Value == text); MarkPoint(point, response.Results[0].ToString()); }
}
catch (Exception exception) when (exception is ServiceResultException or OperationCanceledException)
{
MarkPoint(point, "BadWriteOutcomeUnknown");
throw; // May already have reached the server. Never retry this command.
}
}
else await Task.Delay(25, token);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception exception)
{
SetStatus(client.Id, false, 0, exception is ServiceResultException ua ? new StatusCode(ua.StatusCode).ToString() : "Verbindung unterbrochen");
logger.LogWarning("OPC UA client {ClientId} disconnected ({ErrorType}).", client.Id, exception.GetType().Name);
}
finally
{
worker.Connected = false;
if (_status.TryGetValue(client.Id, out var state) && state.Connected) SetStatus(client.Id, false, 0, "Verbindung unterbrochen");
foreach (var point in points) MarkPoint(point, "BadNotConnected");
while (worker.Writes.Reader.TryRead(out _)) { }
if (session is not null)
{
try { using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); await session.CloseAsync(closeTimeout.Token); }
catch (Exception exception) when (exception is ServiceResultException or OperationCanceledException) { }
session.Dispose();
}
}
try { await Task.Delay(TimeSpan.FromSeconds(retrySeconds), token); }
catch (OperationCanceledException) when (token.IsCancellationRequested) { break; }
retrySeconds = Math.Min(30, retrySeconds * 2);
}
}
private void MarkPoint(GatewayPoint point, string status)
{
var previous = store.ListPointValues().SingleOrDefault(value => value.PointId == point.Id);
if (previous?.Status == status) return;
try
{
store.SetPointValue(point.Id, previous?.Value ?? JsonSerializer.SerializeToElement<object?>(null), PointProtocol.OpcUa,
DateTimeOffset.UtcNow, status, expectedDefinition: point);
}
catch (DomainValidationException) { /* The point was edited or removed while this session was connected. */ }
}
private void SetStatus(Guid id, bool connected, int count, string state) => _status[id] = new(id, connected, count, state, DateTimeOffset.UtcNow);
private static bool IsGood(string? status) => string.IsNullOrWhiteSpace(status) || status.Equals("Good", StringComparison.OrdinalIgnoreCase) || status.Equals("ok", StringComparison.OrdinalIgnoreCase);
private async Task RemoveAsync(Guid id)
{
if (!_workers.TryRemove(id, out var worker)) return;
await worker.Cancellation.CancelAsync();
await worker.Task;
worker.Cancellation.Dispose();
_status.TryRemove(id, out _);
}
public override void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
store.PointValueUpdated -= OnPointValue;
base.Dispose();
}
private sealed class Worker(string signature, CancellationTokenSource cancellation)
{
public string Signature { get; } = signature;
public CancellationTokenSource Cancellation { get; } = cancellation;
public Channel<PointValue> Writes { get; } = Channel.CreateBounded<PointValue>(new BoundedChannelOptions(128) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true });
public Task Task { get; set; } = Task.CompletedTask;
public volatile bool Connected;
}
}
#pragma warning restore CS0618
#pragma warning restore CA1848
@@ -0,0 +1,45 @@
using System.Text.Json;
using Opc.Ua;
namespace Gateway.Api.Services;
/// <summary>Explicit scalar conversions; no implicit Boolean/numeric or string/numeric coercion.</summary>
public static class OpcUaPointTypes
{
public static BuiltInType Resolve(string valueType) => valueType.ToUpperInvariant() switch
{
"BOOL" or "BOOLEAN" => BuiltInType.Boolean,
"REAL" or "FLOAT" or "SINGLE" or "FLOAT32" or "FLOAT32WORDSWAP" or "FLOAT32-SWAP" or "FLOAT32_SWAP" => BuiltInType.Float,
"DOUBLE" => BuiltInType.Double,
"SBYTE" => BuiltInType.SByte,
"BYTE" => BuiltInType.Byte,
"INT16" => BuiltInType.Int16,
"UINT16" => BuiltInType.UInt16,
"INTEGER" or "INT32" => BuiltInType.Int32,
"UNSIGNED" or "UINT32" => BuiltInType.UInt32,
"INT64" => BuiltInType.Int64,
"UINT64" => BuiltInType.UInt64,
"STRING" => BuiltInType.String,
_ => BuiltInType.Null
};
public static object? Convert(JsonElement value, BuiltInType type) => type switch
{
BuiltInType.Boolean => value.GetBoolean(),
BuiltInType.Float => Finite(value.GetSingle()),
BuiltInType.Double => Finite(value.GetDouble()),
BuiltInType.SByte => value.GetSByte(),
BuiltInType.Byte => value.GetByte(),
BuiltInType.Int16 => value.GetInt16(),
BuiltInType.UInt16 => value.GetUInt16(),
BuiltInType.Int32 => value.GetInt32(),
BuiltInType.UInt32 => value.GetUInt32(),
BuiltInType.Int64 => value.GetInt64(),
BuiltInType.UInt64 => value.GetUInt64(),
BuiltInType.String => value.ValueKind == JsonValueKind.String ? value.GetString() : throw new FormatException("String required."),
_ => throw new FormatException("Unsupported OPC UA scalar type.")
};
private static float Finite(float value) => float.IsFinite(value) ? value : throw new FormatException("Finite value required.");
private static double Finite(double value) => double.IsFinite(value) ? value : throw new FormatException("Finite value required.");
}
@@ -0,0 +1,99 @@
using Gateway.Api.Domain;
using Opc.Ua.Configuration;
namespace Gateway.Api.Services;
public sealed record OpcUaServerStatus(bool Listening, int? Port, string? LastError);
#pragma warning disable CS0618 // OPC Foundation 1.5 keeps this constructor during its telemetry migration.
#pragma warning disable CA1848 // Server lifecycle messages are rare and intentionally simple.
/// <summary>
/// Hosts the native OPC UA endpoint with persistent application certificate and
/// trust stores. Anonymous sessions are opt-in; otherwise the server exposes
/// username authentication over secured channels.
/// </summary>
public sealed class OpcUaServerService : BackgroundService
{
private readonly GatewayStore _store;
private readonly OpcUaApplicationFactory _applications;
private readonly ILogger<OpcUaServerService> _logger;
private ApplicationInstance? _application;
private OpcUaServerStatus _status = new(false, null, null);
public OpcUaServerStatus GetStatus() => Volatile.Read(ref _status);
public OpcUaServerService(GatewayStore store, OpcUaApplicationFactory applications, ILogger<OpcUaServerService> logger)
{
_store = store;
_applications = applications;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var configuration = _store.GetGatewayConfiguration().OpcUa;
if (!configuration.ServerEnabled)
{
Volatile.Write(ref _status, new(false, null, null));
await DelayAsync(stoppingToken);
continue;
}
try
{
var applicationConfiguration = await _applications.CreateServerConfigurationAsync(configuration.Port, configuration.AllowAnonymous);
var application = new ApplicationInstance(applicationConfiguration);
_application = application;
var server = new GatewayOpcUaServer(_store);
await application.StartAsync(server);
Volatile.Write(ref _status, new(true, configuration.Port, null));
_logger.LogInformation("OPC UA server listening on TCP {Port}.", configuration.Port);
// Configuration changes are picked up by a controlled restart.
var ticks = 0;
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMilliseconds(100), stoppingToken);
server.RefreshPoints(++ticks % 20 == 0);
if (ticks % 20 != 0) continue;
var next = _store.GetGatewayConfiguration().OpcUa;
if (!next.ServerEnabled || next.Port != configuration.Port || next.AllowAnonymous != configuration.AllowAnonymous)
{
break;
}
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
Volatile.Write(ref _status, new(false, configuration.Port, exception.Message));
_logger.LogWarning(exception, "OPC UA server start failed.");
await DelayAsync(stoppingToken);
}
finally
{
if (GetStatus().Listening) Volatile.Write(ref _status, new(false, configuration.Port, null));
var application = Interlocked.Exchange(ref _application, null);
if (application is not null)
{
await application.StopAsync();
}
}
}
}
private static async Task DelayAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
}
#pragma warning restore CS0618
#pragma warning restore CA1848
+5 -1
View File
@@ -25,13 +25,17 @@ public sealed class SecretProtector
else
{
_key = RandomNumberGenerator.GetBytes(KeyLength);
File.WriteAllBytes(keyPath, _key);
var fileOptions = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None };
if (!OperatingSystem.IsWindows()) fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
using var file = new FileStream(keyPath, fileOptions);
file.Write(_key);
}
if (_key.Length != KeyLength)
{
throw new InvalidOperationException("The gateway secret key is invalid.");
}
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(keyPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
public string Protect(string secret)
+31 -8
View File
@@ -1,17 +1,18 @@
using System.Collections.Concurrent;
using System.Security.Cryptography;
using Gateway.Api.Domain;
namespace Gateway.Api.Services;
public sealed class SessionService
public sealed class SessionService(GatewayStore store)
{
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, SessionEntry> _sessions = new(StringComparer.Ordinal);
public string Create()
public string Create(AuthenticatedGatewayUser user)
{
PruneExpired();
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
_sessions[token] = DateTimeOffset.UtcNow.AddHours(12);
_sessions[token] = new SessionEntry(user, DateTimeOffset.UtcNow.AddHours(12));
return token;
}
@@ -22,10 +23,30 @@ public sealed class SessionService
return false;
}
var token = authorizationHeader[7..];
return _sessions.TryGetValue(token, out var expiresAt) && expiresAt > DateTimeOffset.UtcNow;
return GetUser(authorizationHeader) is not null;
}
public AuthenticatedGatewayUser? GetUser(string? authorizationHeader)
{
if (string.IsNullOrWhiteSpace(authorizationHeader) || !authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
{
return null;
}
var token = authorizationHeader[7..];
if (!_sessions.TryGetValue(token, out var entry) || entry.ExpiresAtUtc <= DateTimeOffset.UtcNow) return null;
var current = store.GetAuthenticatedUser(entry.User.User.Id);
if (current is null || current.User.UpdatedAtUtc != entry.User.User.UpdatedAtUtc)
{
_sessions.TryRemove(token, out _);
return null;
}
return current;
}
public bool HasPermission(string? authorizationHeader, string permission) =>
GetUser(authorizationHeader)?.Permissions.Contains(permission, StringComparer.Ordinal) == true;
public void Remove(string? authorizationHeader)
{
if (!string.IsNullOrWhiteSpace(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
@@ -37,12 +58,14 @@ public sealed class SessionService
private void PruneExpired()
{
var now = DateTimeOffset.UtcNow;
foreach (var (token, expiresAt) in _sessions)
foreach (var (token, entry) in _sessions)
{
if (expiresAt <= now)
if (entry.ExpiresAtUtc <= now)
{
_sessions.TryRemove(token, out _);
}
}
}
private sealed record SessionEntry(AuthenticatedGatewayUser User, DateTimeOffset ExpiresAtUtc);
}
@@ -0,0 +1,119 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text.Json;
using Gateway.Api.Options;
using Microsoft.Extensions.Options;
namespace Gateway.Api.Services;
public sealed record SystemUpdateRequest(string Password);
public sealed record SystemUpdateStatus(string Phase, string Message, string? Commit = null, string? Target = null,
DateTimeOffset? UpdatedAt = null, string? RunId = null, string? RunningCommit = null);
public sealed record SystemUpdateAvailability(string State, string Branch, string? RemoteCommit = null);
public sealed class SystemUpdateService(IOptions<GatewayOptions> options) : IDisposable
{
private static readonly JsonSerializerOptions StatusJson = new(JsonSerializerDefaults.Web);
private readonly SemaphoreSlim _availabilityLock = new(1, 1);
private SystemUpdateAvailability? _availability;
private DateTimeOffset _checkedAt;
public bool Enabled => OperatingSystem.IsLinux()
&& !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath)
&& !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath);
public string? RunningCommit => IsCommit(options.Value.RunningCommit) ? options.Value.RunningCommit!.ToLowerInvariant() : null;
public SystemUpdateStatus GetStatus()
{
if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet.");
try
{
var status = JsonSerializer.Deserialize<SystemUpdateStatus>(File.ReadAllText(options.Value.UpdateStatusPath!), StatusJson);
if (status is not null) return status;
}
catch (FileNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
catch (DirectoryNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
catch (JsonException) { }
return new("unavailable", "Der Update-Status konnte nicht gelesen werden.");
}
public async Task<SystemUpdateAvailability> CheckAvailabilityAsync(bool refresh, CancellationToken cancellationToken)
{
var branch = options.Value.UpdateBranch;
if (!Enabled || string.IsNullOrWhiteSpace(options.Value.UpdateAvailabilityCommand)) return new("disabled", branch);
if (RunningCommit is not { } running) return new("unknown", branch);
await _availabilityLock.WaitAsync(cancellationToken);
try
{
if (!refresh && _availability is not null && DateTimeOffset.UtcNow - _checkedAt < TimeSpan.FromSeconds(15))
return _availability;
_availability = await ProbeAsync(running, branch, cancellationToken);
_checkedAt = DateTimeOffset.UtcNow;
return _availability;
}
finally { _availabilityLock.Release(); }
}
private async Task<SystemUpdateAvailability> ProbeAsync(string running, string branch, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(32));
var start = new ProcessStartInfo(options.Value.UpdateAvailabilityCommand!)
{
UseShellExecute = false,
RedirectStandardOutput = true
};
start.ArgumentList.Add(running);
try
{
using var process = Process.Start(start);
if (process is null) return new("unavailable", branch);
try
{
var output = await process.StandardOutput.ReadToEndAsync(timeout.Token);
await process.WaitForExitAsync(timeout.Token);
var parts = output.Trim().Split(' ');
if (process.ExitCode == 0 && parts is ["current" or "available" or "incompatible", var tip] && IsCommit(tip))
return new(parts[0], branch, tip);
}
catch (OperationCanceledException)
{
try { if (!process.HasExited) process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { }
catch (Win32Exception) { }
cancellationToken.ThrowIfCancellationRequested();
}
}
catch (Win32Exception) { }
catch (IOException) { }
return new("unavailable", branch);
}
private static bool IsCommit(string? value) => value is { Length: 40 } && value.All(Uri.IsHexDigit);
public void Dispose() => _availabilityLock.Dispose();
public async Task<bool> StartAsync(CancellationToken cancellationToken)
{
if (!Enabled) return false;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
try
{
await socket.ConnectAsync(new UnixDomainSocketEndPoint(options.Value.UpdateSocketPath!), timeout.Token);
using var stream = new NetworkStream(socket);
using var response = new StreamReader(stream);
return string.Equals(await response.ReadLineAsync(timeout.Token), "accepted", StringComparison.Ordinal);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return false; }
catch (SocketException) { return false; }
catch (IOException) { return false; }
}
}
+727 -50
View File
@@ -1,12 +1,41 @@
const app = document.querySelector('#app');
const state = { token: sessionStorage.getItem('seiugw-token'), view: 'overview', points: [], mappings: [], trendLogs: [], configuration: null, mqtt: null, mqttMappings: [], mqttStatus: null };
const state = { token: sessionStorage.getItem('seiugw-token'), user: null, preferences: null, view: 'overview', points: [], mappings: [], trendLogs: [], trendSelections: [], runnerJobs: [], mailIntegration: null, configuration: null, hardware: { networkInterfaces: [], serialDevices: [] }, mqtt: null, mqttMappings: [], mqttStatus: null, users: [], roles: [], permissionCatalog: [], userEditId: null };
const can = permission => state.user?.permissions?.includes(permission);
Object.assign(state, { adminTab: 'aliases', pointsTab: 'points', presentation: { points: [], units: [] }, dashboard: [], notifications: [], alarms: [], deliveries: [], komari: null, alarmPointId: null, alarmEditId: null, alarmSource: '', aliasSource: '', runnerEditId: null });
function resolveTheme(theme) {
return theme === 'system' ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme;
}
function applyTheme(theme) {
const selected = ['system', 'light', 'dark'].includes(theme) ? theme : 'system';
document.documentElement.dataset.theme = resolveTheme(selected);
document.documentElement.dataset.themeMode = selected;
try { localStorage.setItem('seiugw-theme', selected); } catch { /* Private browsers may disable storage. */ }
document.querySelectorAll('button[data-theme]').forEach(button => {
const active = button.dataset.theme === selected;
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', String(active));
});
}
function applyStoredTheme() {
let theme = 'dark';
try { theme = localStorage.getItem('seiugw-theme') || theme; } catch { /* Use the dark default. */ }
applyTheme(theme);
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (document.documentElement.dataset.themeMode === 'system') applyTheme('system');
});
applyStoredTheme();
async function api(path, options = {}) {
const headers = { ...(options.headers || {}) };
if (state.token) headers.Authorization = `Bearer ${state.token}`;
if (options.body) headers['Content-Type'] = 'application/json';
const response = await fetch(path, { ...options, headers });
if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); throw new Error('Sitzung abgelaufen.'); }
if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); throw new Error('Sitzung abgelaufen.'); }
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error || `Anfrage fehlgeschlagen (${response.status})`);
@@ -29,12 +58,21 @@ async function boot() {
const setup = await api('/api/setup');
if (!setup.adminConfigured) return renderSetup();
if (!state.token) return renderLogin();
if (!state.user) state.user = (await api('/api/auth/me')).user;
if (!state.preferences) {
state.preferences = await api('/api/auth/preferences');
applyTheme(state.preferences.theme);
}
state.view = can('view_dashboard') ? 'overview' : can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system';
await loadData();
if (!can('view_dashboard')) state.view = can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system';
if (can('manage_gateway') && new URLSearchParams(location.search).has('network-confirm')) state.view = 'system';
if (state.user?.user?.role === 'admin' && sessionStorage.getItem(updateReturnKey)) state.view = 'system';
renderShell();
}
function renderSetup() {
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><h1>Erstinbetriebnahme</h1><p>Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.</p><form id="setup-form" class="form"><div class="row"><label>Projektnummer<input id="setup-project" value="P" maxlength="33" pattern="P[A-Za-z0-9_-]{1,32}" placeholder="P190726" required autofocus></label><label>ISP<input id="setup-isp" type="number" min="1" max="99" value="1" required></label></div><div class="notice blue">Der Rechner wird als <code id="setup-hostname">SE-UGW-P-ISP01</code> in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.</div><label>Neues Passwort<input id="setup-password" type="password" minlength="12" autocomplete="new-password" required></label><label>Passwort wiederholen<input id="setup-confirm" type="password" minlength="12" autocomplete="new-password" required></label><div class="buttons"><button class="btn primary">Einrichten</button></div><div id="setup-message"></div></form></div></section>`;
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><h1>Erstinbetriebnahme</h1><p>Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.</p><form id="setup-form" class="form"><div class="row"><label>Projektnummer<input id="setup-project" value="P" maxlength="33" pattern="P[A-Za-z0-9_-]{1,32}" placeholder="P190726" required autofocus></label><label>ISP<input id="setup-isp" type="number" min="1" max="99" value="1" required></label></div><div class="notice blue">Der Rechner wird als <code id="setup-hostname">SE-UGW-P-ISP01</code> in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.</div><label>Neues Passwort<input id="setup-password" type="password" minlength="12" autocomplete="new-password" required></label><label>Passwort wiederholen<input id="setup-confirm" type="password" minlength="12" autocomplete="new-password" required></label><div class="buttons"><button class="btn primary">Einrichten</button></div><div id="setup-message"></div></form></div></section>`;
const updateHostName = () => {
const project = document.querySelector('#setup-project').value.trim().toUpperCase() || 'P';
const isp = String(document.querySelector('#setup-isp').value || '1').padStart(2, '0');
@@ -52,40 +90,71 @@ function renderSetup() {
}
function renderLogin() {
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><h1>Anmelden</h1><p>Lokaler Administrationszugang.</p><form id="login-form" class="form"><label>Benutzer<input value="admin" disabled></label><label>Passwort<input id="login-password" type="password" autocomplete="current-password" required autofocus></label><div class="buttons"><button class="btn primary">Anmelden</button></div><div id="login-message"></div></form></div></section>`;
app.innerHTML = `<section class="auth"><div class="auth-card"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><h1>Anmelden</h1><p>Lokaler Zugang zum Gateway.</p><form id="login-form" class="form"><label>Benutzer<input id="login-username" value="admin" autocomplete="username" required autofocus></label><label>Passwort<input id="login-password" type="password" autocomplete="current-password" required></label><div class="buttons"><button class="btn primary">Anmelden</button></div><div id="login-message"></div></form></div></section>`;
document.querySelector('#login-form').addEventListener('submit', async event => {
event.preventDefault();
try {
const result = await api('/api/auth/login', { method: 'POST', body: JSON.stringify({ username: 'admin', password: document.querySelector('#login-password').value }) });
state.token = result.accessToken; sessionStorage.setItem('seiugw-token', state.token); await boot();
const result = await api('/api/auth/login', { method: 'POST', body: JSON.stringify({ username: document.querySelector('#login-username').value, password: document.querySelector('#login-password').value }) });
state.token = result.accessToken; state.user = result.user; sessionStorage.setItem('seiugw-token', state.token); await boot();
} catch (error) { errorTarget('login-message', 'Anmeldung fehlgeschlagen.'); }
});
}
async function loadData() {
[state.configuration, state.points, state.mappings, state.trendLogs, state.mqtt, state.mqttMappings, state.mqttStatus] = await Promise.all([
api('/api/gateway/configuration'), api('/api/points'), api('/api/mappings'), api('/api/trend-logs'), api('/api/mqtt/configuration'), api('/api/mqtt/mappings'), api('/api/mqtt/status')
]);
if (!can('manage_sources')) { state.points = []; state.mappings = []; }
if (!can('manage_gateway')) { state.configuration = null; state.komari = null; }
if (!can('manage_users')) state.users = [];
if (!can('manage_roles') && !can('manage_users')) { state.roles = []; state.permissionCatalog = []; }
if (!can('manage_alarms')) { state.alarms = []; state.deliveries = []; }
if (!can('view_trends')) { state.trendLogs = []; state.trendSelections = []; }
if (!can('manage_runner')) state.runnerJobs = [];
const jobs = [];
jobs.push(api('/api/presentation').then(value => { state.presentation = value; }));
if (can('view_dashboard')) jobs.push(api('/api/dashboard').then(value => { state.dashboard = value; }));
if (!can('manage_sources') && (can('edit_aliases') || can('manage_alarms') || can('manage_integrations'))) jobs.push(api('/api/points/catalog').then(value => { state.points = value; }));
if (can('manage_gateway')) jobs.push(api('/api/system/komari').then(value => { state.komari = value; }));
if (can('manage_integrations') || can('manage_alarms')) jobs.push(api('/api/integrations/notifications').then(value => { state.notifications = value; }));
if (can('manage_alarms')) jobs.push(api('/api/alarms').then(value => { state.alarms = value; }), api('/api/alarms/deliveries').then(value => { state.deliveries = value; }));
if (can('manage_gateway')) jobs.push(api('/api/gateway/configuration').then(value => { state.configuration = value; }), api('/api/gateway/hardware').then(value => { state.hardware = value; }));
if (can('manage_sources')) jobs.push(api('/api/points').then(value => { state.points = value; }), api('/api/mappings').then(value => { state.mappings = value; }));
if (can('manage_sources')) jobs.push(api('/api/opcua/clients').then(value => { state.opcuaClients = value; }));
if (can('view_trends')) jobs.push(api('/api/trend-logs').then(value => { state.trendLogs = value; }), api('/api/trend-selections').then(value => { state.trendSelections = value; }));
if (can('manage_runner')) jobs.push(api('/api/runner/jobs').then(value => { state.runnerJobs = value; }));
if (can('manage_integrations')) jobs.push(api('/api/mqtt/configuration').then(value => { state.mqtt = value; }), api('/api/mqtt/mappings').then(value => { state.mqttMappings = value; }), api('/api/mqtt/status').then(value => { state.mqttStatus = value; }), api('/api/mqtt/mapping-defaults').then(value => { state.mqttMappingDefaults = value; }));
if (can('manage_integrations')) jobs.push(api('/api/integrations/mail').then(value => { state.mailIntegration = value; }));
if (can('manage_users')) jobs.push(api('/api/users').then(value => { state.users = value; }));
if (can('manage_roles') || can('manage_users')) jobs.push(api('/api/roles').then(value => { state.roles = value.roles; state.permissionCatalog = value.permissions; }));
await Promise.all(jobs);
}
function themeControls(theme) {
return `<div class="theme-control"><span class="theme-caption">Darstellung</span><div class="theme-toggle" role="group" aria-label="Farbschema">${[['light','Hell'],['dark','Dunkel'],['system','System']].map(([value, label]) => `<button class="theme-option ${value === theme ? 'active' : ''}" type="button" data-theme="${value}" aria-pressed="${value === theme}">${label}</button>`).join('')}</div></div>`;
}
function renderShell() {
app.innerHTML = `<section class="shell"><aside class="sidebar"><div class="brand"><span class="mark">SG</span> SEIU GATEWAY</div><nav class="nav">
<button data-view="overview">Übersicht</button><button data-view="points">Datenpunkte</button><button data-view="mappings">Mappings</button><button data-view="mqtt">MQTT</button><button data-view="trends">Trend Logs</button><button data-view="protocols">Protokolle</button><button data-view="system">System</button>
</nav><div class="sidebar-foot">Vendor ID 815<br>Linux / Hostnetz</div></aside><section id="content" class="content"></section></section>`;
const nav = `${can('view_dashboard') ? '<button data-view="overview">Dashboard</button>' : ''}${can('view_trends') ? '<button data-view="trends">Trend</button>' : ''}${can('manage_sources') || can('manage_gateway') || can('manage_integrations') ? '<button data-view="points">Datenpunkte</button>' : ''}${can('manage_sources') ? '<button data-view="mappings">Mappings</button>' : ''}${adminTabs().length ? '<button data-view="admin">Admin</button>' : ''}<button data-view="system">Einstellungen</button>`;
const theme = state.preferences?.theme || 'system';
app.innerHTML = `<section class="shell"><aside class="sidebar"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"><div><span class="eyebrow">SE-INNO</span><br>Universal&shy;gateway</div><button class="btn pin" id="sidebar-pin" title="Seitenleiste anheften" aria-pressed="${state.preferences?.sidebarPinned !== false}">⌖</button></div><nav class="nav">${nav}</nav><div class="sidebar-foot">${themeControls(theme)}<div id="theme-message" role="status"></div><div class="user-caption"><strong>${escapeHtml(state.user?.user?.displayName || '')} · @${escapeHtml(state.user?.user?.username || '')}</strong><span>${escapeHtml(state.user?.user?.role || '')}</span></div><button class="btn" id="sidebar-logout">Abmelden</button><small>by J.H. | SE Inno GmbH</small></div></aside><section id="content" class="content"></section></section>`;
document.querySelector('.sidebar-foot').insertAdjacentHTML('afterbegin',
'<nav class="nav" aria-label="Dokumentation"><button type="button" data-view="docs">Doku</button></nav>');
document.querySelector('#sidebar-logout').addEventListener('click', logout);
document.querySelector('.shell').classList.toggle('unpinned', state.preferences?.sidebarPinned === false);
document.querySelector('#sidebar-pin').addEventListener('click', async () => { try { state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ sidebarPinned: state.preferences?.sidebarPinned === false }) }); renderShell(); } catch (error) { window.alert(error.message); } });
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => { state.view = button.dataset.view; renderView(); }));
document.querySelectorAll('button[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme)));
renderView();
}
function renderView() {
document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view));
const content = document.querySelector('#content');
const views = { overview: viewOverview, points: viewPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, protocols: viewProtocols, system: viewSystem };
const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem, docs: viewDocumentation };
content.innerHTML = views[state.view]();
bindView(state.view);
}
function header(title, status = 'Konfiguration geladen') {
return `<header class="topline"><h1>${title}</h1><span class="status"><i class="dot"></i>${status}</span></header>`;
return `<header class="topline"><div><span class="eyebrow">ANSICHT</span><h1>${title}</h1></div><span class="status">SE-Inno Universalgateway · ${escapeHtml(status)}</span></header>`;
}
function viewOverview() {
@@ -98,78 +167,440 @@ function viewOverview() {
<article class="card"><div class="metric-label">Datenpunkte</div><div class="metric-value">${state.points.length}</div><div class="metric-sub">${state.points.filter(point => point.scope === 'External').length} extern</div></article>
<article class="card"><div class="metric-label">Mappings</div><div class="metric-value">${state.mappings.length}</div><div class="metric-sub">Schreibownership geprüft</div></article>
<article class="card"><div class="metric-label">MQTT-Mappings</div><div class="metric-value">${state.mqttMappings.length}</div><div class="metric-sub">${escapeHtml(mqttStatus)}</div></article>
</section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Inbetriebnahme</h2></div><table><tbody><tr><td>Projekt / ISP</td><td>${installation}</td></tr><tr><td>Rechnername</td><td><code>${hostName}</code></td></tr></tbody></table><div class="notice blue" style="margin-top:12px">Der MQTT-Client kann Daten an einen vorhandenen Broker senden und von exakt gemappten Topics annehmen. Die nativen BACnet-, OPC-UA- und Modbus-Adapter werden separat aktiviert; bis dahin wird keine externe Steuerung simuliert.</div></article><article class="card"><div class="card-head"><h2>Schreibregeln</h2></div><p class="note">Ein externes Ziel erhält grundsätzlich genau einen schreibenden Pfad. Mehrere BACnet-Prioritäten sind nur bei ausdrücklich quittierter Konfiguration zulässig. MQTT-Echo wird nicht erneut an denselben Broker gespiegelt.</p></article></section>`;
</section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Inbetriebnahme</h2></div><table><tbody><tr><td>Projekt / ISP</td><td>${installation}</td></tr><tr><td>Rechnername</td><td><code>${hostName}</code></td></tr></tbody></table><div class="notice blue" style="margin-top:12px">Der native BACnet/IP-Dienst läuft mit Vendor-ID 815. Aktuell stellt er ausschließlich Device und Network-Port bereit; freigegebene Gateway-Datenpunkte werden mit dem Mapping-Adapter als BACnet-Objekte materialisiert.</div></article><article class="card"><div class="card-head"><h2>Schreibregeln</h2></div><p class="note">Ein externes Ziel erhält grundsätzlich genau einen schreibenden Pfad. Mehrere BACnet-Prioritäten sind nur bei ausdrücklich quittierter Konfiguration zulässig. MQTT-Echo wird nicht erneut an denselben Broker gespiegelt.</p></article></section>`;
}
function viewPoints() {
const rows = state.points.map(point => `<tr><td>${escapeHtml(point.displayName)}</td><td><span class="tag">${point.protocol}</span></td><td><span class="tag gray">${point.scope}</span></td><td>${escapeHtml(point.valueType)}</td><td>${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance !== null && point.bacnetObjectInstance !== undefined ? ` · ${point.bacnetObjectInstance}` : ''}</td><td>${point.writable ? 'R/W' : 'R'}</td><td>${escapeHtml(point.externalIdentity || '—')}</td></tr>`).join('');
return `${header('Datenpunkte')}<section class="grid two"><article class="card"><div class="card-head"><h2>Neuer Datenpunkt</h2></div><form id="point-form" class="form"><label>Name<input name="displayName" required maxlength="160" placeholder="z. B. Zuluft Sollwert"></label><div class="row"><label>Protokoll<select name="protocol"><option>Bacnet</option><option>OpcUa</option><option>Modbus</option><option>Knx</option><option>Mqtt</option><option>Internal</option></select></label><label>Bereich<select name="scope"><option>External</option><option>Gateway</option><option>Internal</option></select></label></div><div class="row"><label>Werttyp<input name="valueType" value="Real" required></label><label>Externe Identität<input name="externalIdentity" placeholder="device:23/av:1"></label></div><div class="row"><label>BACnet-Objekttyp<select name="bacnetObjectKind"><option value="">— nur Gateway/BACnet —</option><option>AnalogInput</option><option>AnalogOutput</option><option>AnalogValue</option><option>BinaryInput</option><option>BinaryOutput</option><option>BinaryValue</option><option>MultiStateInput</option><option>MultiStateOutput</option><option>MultiStateValue</option><option>Schedule</option><option>Calendar</option><option>EventEnrollment</option><option>NotificationClass</option></select></label><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" placeholder="z. B. 1"></label></div><label>Adresse (JSON)<textarea name="address" required>{}</textarea></label><label class="switch"><input type="checkbox" name="writable"> Beschreibbar</label><div class="buttons"><button class="btn primary">Punkt anlegen</button></div><div id="point-message"></div></form></article><article class="card"><div class="card-head"><h2>Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2></div>${state.points.length ? `<table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th><th>BACnet-Objekt</th><th>Zugriff</th><th>Identität</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Datenpunkte.</div>'}</article></section>`;
const editing = state.points.find(point => point.id === state.pointEditId);
const select = (options, value) => options.map(option =>
`<option ${option === value ? 'selected' : ''}>${option}</option>`).join('');
const bacnetKinds = ['AnalogInput', 'AnalogOutput', 'AnalogValue', 'BinaryInput', 'BinaryOutput', 'BinaryValue',
'MultiStateInput', 'MultiStateOutput', 'MultiStateValue', 'Schedule', 'Calendar', 'EventEnrollment', 'NotificationClass'];
if (editing?.bacnetObjectKind === 'TrendLog') bacnetKinds.push('TrendLog');
const rows = state.points.map(point => `<tr>
<td>${escapeHtml(point.displayName)}</td>
<td><span class="tag">${escapeHtml(point.protocol)}</span></td>
<td><span class="tag gray">${escapeHtml(point.scope)}</span></td>
<td>${escapeHtml(point.valueType)}</td>
<td>${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance == null ? '' : ` · ${point.bacnetObjectInstance}`}</td>
<td>${(point.readable ? 'R' : '') + (point.readable && point.writable ? '/' : '') + (point.writable ? 'W' : '') || '—'}</td>
<td>${escapeHtml((point.protocol === 'Mqtt' && point.address?.topic) || point.externalIdentity || '—')}</td>
<td><div class="buttons"><button type="button" class="btn" data-edit-point="${point.id}">Bearbeiten</button>
<button type="button" class="btn danger" data-delete-point="${point.id}">Löschen</button></div></td>
</tr>`).join('');
return `${header('Datenpunkte')}<section class="grid two">
<article class="card"><div class="card-head"><h2>${editing ? 'Datenpunkt bearbeiten' : 'Neuer Datenpunkt'}</h2></div>
<form id="point-form" class="form">
<label>Name<input name="displayName" required maxlength="160" value="${escapeHtml(editing?.displayName || '')}" placeholder="z. B. Zuluft Sollwert"></label>
<div class="row">
<label>Protokoll<select name="protocol">${select(['Bacnet', 'OpcUa', 'Modbus', 'Knx', 'Mqtt', 'Internal'], editing?.protocol)}</select></label>
<label>Bereich<select name="scope">${select(['External', 'Gateway', 'Internal'], editing?.scope)}</select></label>
</div>
<div class="row">
<label>Werttyp<input name="valueType" value="${escapeHtml(editing?.valueType || 'Real')}" required maxlength="80"></label>
<label data-point-external>Externe Identität<input name="externalIdentity" value="${escapeHtml(editing?.externalIdentity || '')}" placeholder="device:23/av:1"></label>
</div>
<div class="row" data-point-bacnet>
<label>BACnet-Objekttyp<select name="bacnetObjectKind"><option value="">—</option>${select(bacnetKinds, editing?.bacnetObjectKind)}</select></label>
<label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" value="${editing?.bacnetObjectInstance ?? ''}" placeholder="automatisch"></label>
</div>
<label>Adresse (JSON)<textarea name="address" required>${escapeHtml(JSON.stringify(editing?.address ?? {}, null, 2))}</textarea></label>
<div class="row">
<label class="switch"><input type="checkbox" name="readable" ${(editing?.readable ?? true) ? 'checked' : ''}> Lesbar</label>
<label class="switch"><input type="checkbox" name="writable" ${editing?.writable ? 'checked' : ''}> Beschreibbar</label>
</div>
<div class="buttons"><button type="submit" class="btn primary">${editing ? 'Änderungen speichern' : 'Punkt anlegen'}</button>
${editing ? '<button type="button" class="btn" id="cancel-point-edit">Abbrechen</button>' : ''}</div>
<div id="point-message" role="status"></div>
</form>
</article>
<article class="card point-inventory"><div class="card-head"><h2 id="point-inventory-title">Registrierte Punkte <span class="tag gray">${state.points.length}</span></h2>${configurationCsvButtons('points')}</div>
<div id="point-list-message" role="status"></div>
${rows ? `<div class="table-scroll point-inventory-scroll" tabindex="0" role="region" aria-labelledby="point-inventory-title"><table><thead><tr><th>Name</th><th>Protokoll</th><th>Bereich</th><th>Werttyp</th>
<th>BACnet-Objekt</th><th>Zugriff</th><th>Identität</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>`
: '<div class="empty">Noch keine Datenpunkte.</div>'}
</article>
</section>`;
}
function mappingPointOptions(selected, detail) {
const options = state.points.map(point =>
`<option value="${point.id}" ${point.id === selected ? 'selected' : ''}>${escapeHtml(point.displayName)} · ${escapeHtml(point[detail])}</option>`);
if (selected && !state.points.some(point => point.id === selected))
options.unshift(`<option value="${escapeHtml(selected)}" selected>${escapeHtml(selected)}</option>`);
return options.join('');
}
function mappingActions(id, kind) {
return `<div class="buttons">
<button type="button" class="btn" data-edit-${kind}="${id}">Bearbeiten</button>
<button type="button" class="btn danger" data-delete-${kind}="${id}">Löschen</button>
</div>`;
}
function viewMappings() {
const pointOptions = state.points.map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${point.protocol}</option>`).join('');
const editing = state.mappings.find(mapping => mapping.id === state.mappingEditId);
const names = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
const rows = state.mappings.map(mapping => `<tr><td>${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)}</td><td>${mapping.direction === 'Bidirectional' ? '⇄' : '→'}</td><td>${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)}</td><td>${mapping.bacnetPriority || '—'}</td><td>${mapping.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
return `${header('Mappings')}<section class="grid two"><article class="card"><div class="card-head"><h2>Mapping anlegen</h2></div>${state.points.length < 2 ? '<div class="notice">Mindestens zwei Punkte anlegen, bevor ein Mapping erzeugt werden kann.</div>' : `<form id="mapping-form" class="form"><label>Quelle<select name="sourcePointId">${pointOptions}</select></label><label>Ziel<select name="targetPointId">${pointOptions}</select></label><div class="row"><label>Richtung<select name="direction"><option value="OneWay">Einweg</option><option value="Bidirectional">Bidirektional</option></select></label><label>BACnet-Priorität (optional)<input type="number" name="bacnetPriority" min="1" max="16" placeholder="z. B. 16"></label></div><label class="switch"><input type="checkbox" name="acknowledge"> Mehrfachschreiben bei unterschiedlichen BACnet-Prioritäten bewusst zulassen</label><label>Transformation (JSON)<textarea name="transform">{}</textarea></label><div class="buttons"><button class="btn primary">Mapping speichern</button></div><div id="mapping-message"></div></form>`}</article><article class="card"><div class="card-head"><h2>Aktive Mapping-Tabelle</h2></div>${state.mappings.length ? `<table><thead><tr><th>Quelle</th><th></th><th>Ziel</th><th>Prio</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Mappings.</div>'}</article></section>`;
const rows = state.mappings.map(mapping => `<tr>
<td>${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)}</td>
<td>${mapping.direction === 'Bidirectional' ? '⇄' : '→'}</td>
<td>${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)}</td>
<td>${mapping.bacnetPriority ?? '—'}</td>
<td>${mapping.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td>
<td>${mappingActions(mapping.id, 'mapping')}</td>
</tr>`).join('');
const form = state.points.length < 2 && !editing ? '<div class="notice">Für ein Mapping werden zwei Datenpunkte benötigt.</div>' : `
<form id="mapping-form" class="form">
<label>Quelle<select name="sourcePointId" required>${mappingPointOptions(editing?.sourcePointId, 'protocol')}</select></label>
<label>Ziel<select name="targetPointId" required>${mappingPointOptions(editing?.targetPointId ?? state.points[1]?.id, 'protocol')}</select></label>
<div class="row">
<label>Richtung<select name="direction"><option value="OneWay">Einweg</option><option value="Bidirectional" ${editing?.direction === 'Bidirectional' ? 'selected' : ''}>Bidirektional</option></select></label>
<label>BACnet-Priorität (optional)<input type="number" name="bacnetPriority" min="1" max="16" value="${editing?.bacnetPriority ?? ''}" placeholder="z. B. 16"></label>
</div>
<label class="switch"><input type="checkbox" name="enabled" ${(editing?.enabled ?? true) ? 'checked' : ''}> Mapping aktiv</label>
<label class="switch"><input type="checkbox" name="acknowledge" ${editing?.acknowledgeMultipleExternalWriters ? 'checked' : ''}> Mehrfachschreiben bei unterschiedlichen BACnet-Prioritäten bewusst zulassen</label>
<label>Transformation (JSON)<textarea name="transform">${escapeHtml(JSON.stringify(editing ? editing.transform : {}, null, 2))}</textarea></label>
<div class="buttons"><button class="btn primary">Mapping speichern</button>
${editing ? '<button type="button" class="btn" id="cancel-mapping-edit">Abbrechen</button>' : ''}</div>
<div id="mapping-message" role="status"></div>
</form>`;
return `${header('Mappings')}${viewMappingBatch()}<section class="grid two">
<article class="card"><div class="card-head"><h2>${editing ? 'Mapping bearbeiten' : 'Mapping anlegen'}</h2></div>${form}</article>
<article class="card"><div class="card-head"><h2>Mapping-Tabelle</h2>${configurationCsvButtons('mappings')}</div><div id="mapping-list-message" role="status"></div>
${rows ? `<div class="table-scroll"><table><thead><tr><th>Quelle</th><th></th><th>Ziel</th><th>Prio</th><th>Status</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>`
: '<div class="empty">Noch keine Mappings.</div>'}
</article>
</section>`;
}
function viewMqtt() {
const broker = state.mqtt.configuration;
const status = state.mqttStatus;
const pointNames = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
const pointOptions = state.points.map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${escapeHtml(point.valueType)}</option>`).join('');
const editing = state.mqttMappings.find(entry => entry.mapping.id === state.mqttMappingEditId)?.mapping;
const connection = status.connected ? `verbunden · ${escapeHtml(status.endpoint || '')}` : broker.enabled ? `nicht verbunden${status.lastError ? ` · ${escapeHtml(status.lastError)}` : ''}` : 'deaktiviert';
const rows = state.mqttMappings.map(entry => {
const mapping = entry.mapping;
return `<tr><td>${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}</td><td>${mapping.format === 'SeMonitoring' ? 'SE-Monitoring' : 'JSON'}</td><td>${escapeHtml(mapping.direction)}</td><td><code>${escapeHtml(entry.topic)}</code></td><td>${escapeHtml(mapping.qualityOfService)}</td><td>${mapping.retain ? 'ja' : 'nein'}</td></tr>`;
return `<tr><td>${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}</td><td>${escapeHtml(mqttMappingFormatLabel(mapping.format))}</td><td>${escapeHtml(mapping.direction)}</td><td><code>${escapeHtml(entry.topic)}</code></td><td>${escapeHtml(mapping.qualityOfService)}</td><td>${mapping.retain ? 'ja' : 'nein'}</td><td>${mappingActions(mapping.id, 'mqtt-mapping')}</td></tr>`;
}).join('');
return `${header('MQTT / MQTTS', connection)}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarm</td><td>Nur digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>MQTT-Mapping anlegen</h2></div>${pointOptions ? `<form id="mqtt-mapping-form" class="form"><label>Datenpunkt<select name="pointId">${pointOptions}</select></label><div class="row"><label>Format<select name="format"><option value="SeMonitoring">SE-Monitoring</option><option value="Json">JSON</option></select></label><label>Richtung<select name="direction"><option value="Publish">Nur senden</option><option value="Subscribe">Nur empfangen</option><option value="Bidirectional">Senden und empfangen</option></select></label></div><div class="row"><label>QoS<select name="qualityOfService"><option value="AtMostOnce">0 · höchstens einmal</option><option value="AtLeastOnce" selected>1 · mindestens einmal</option><option value="ExactlyOnce">2 · genau einmal</option></select></label><label class="switch"><input type="checkbox" name="retain"> Retained Message</label></div><div class="card-head" style="margin-top:4px"><h2>SE-Monitoring</h2></div><div class="row three"><label>Jahr<input name="projectYear" type="number" min="2000" max="2100" value="2019"></label><label>Projekt<input name="projectNumber" value="P1909015"></label><label>ISP<input name="ispNumber" value="ISP1"></label></div><div class="row"><label>Kategorie<select name="seCategory"><option>Analog</option><option>Notify</option><option>Alarm</option><option>Setpoints</option></select></label><label>Punktname<input name="topicName" placeholder="iVlTempFuehler4Speicher"></label></div><div class="card-head" style="margin-top:4px"><h2>JSON</h2></div><div class="row"><label>Topic<input name="jsonTopic" placeholder="site/plant/telemetry"></label><label>Eigenschaft (optional)<input name="jsonProperty" placeholder="supplyTemperature"></label></div><div class="buttons"><button class="btn primary">MQTT-Mapping speichern</button></div><div id="mqtt-mapping-message"></div></form>` : '<div class="notice">Zuerst einen Datenpunkt anlegen.</div>'}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2></div>${state.mqttMappings.length ? `<table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}<section class="grid two"><article class="card"><div class="card-head"><h2>Broker-Verbindung</h2><span class="tag ${status.connected ? '' : 'gray'}">${status.connected ? 'online' : 'offline'}</span></div><form id="mqtt-configuration-form" class="form"><label class="switch"><input type="checkbox" name="enabled" ${broker.enabled ? 'checked' : ''}> MQTT-Client aktivieren</label><div class="row"><label>Broker-Host<input name="host" value="${escapeHtml(broker.host || '')}" placeholder="mqtt.example.local"></label><label>Port<input name="port" type="number" min="1" max="65535" value="${broker.port}" required></label></div><div class="row"><label>Client-ID<input name="clientId" value="${escapeHtml(broker.clientId)}" required maxlength="128"></label><label>Benutzername<input name="username" value="${escapeHtml(broker.username || '')}" autocomplete="username"></label></div><label>Passwort ${state.mqtt.hasPassword ? '<span class="tag">gespeichert</span>' : ''}<input name="password" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><div class="row"><label class="switch"><input type="checkbox" name="useTls" ${broker.useTls ? 'checked' : ''}> TLS verwenden</label><label class="switch"><input type="checkbox" name="clearPassword"> Broker-Passwort löschen</label></div><label class="switch"><input type="checkbox" name="ignoreCertificateErrors" ${broker.ignoreCertificateErrors ? 'checked' : ''}> TLS-Zertifikatsfehler ignorieren</label><div class="notice">Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.</div><div class="buttons"><button class="btn primary">MQTT speichern und verbinden</button></div><div id="mqtt-configuration-message"></div></form></article><article class="card"><div class="card-head"><h2>SE-Monitoring-Schema</h2></div><p class="note"><code>${escapeHtml(mqttTopicTemplate() || '—')}</code></p><table><tbody><tr><td>Analog</td><td>Nur analoge Punkte (AI/AO/AV usw.)</td></tr><tr><td>Notify</td><td>Nur digitale Zustände, keine Störungen</td></tr><tr><td>Alarms</td><td>Digitale Alarm-Punkte</td></tr><tr><td>Setpoints</td><td>Analoge oder digitale Sollwerte, immer senden und empfangen</td></tr></tbody></table><p class="note">Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.</p></article></section><section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}</h2></div>${mqttMappingForm(editing)}</article><article class="card"><div class="card-head"><h2>Konfigurierte MQTT-Mappings <span class="tag gray">${state.mqttMappings.length}</span></h2>${configurationCsvButtons('mqtt')}</div><div id="mqtt-mapping-list-message" role="status"></div>${state.mqttMappings.length ? `<div class="table-scroll"><table><thead><tr><th>Punkt</th><th>Format</th><th>Richtung</th><th>Topic</th><th>QoS</th><th>Retain</th><th>Aktionen</th></tr></thead><tbody>${rows}</tbody></table></div>` : '<div class="empty">Noch keine MQTT-Mappings.</div>'}</article></section>`;
}
function viewTrends() {
const pointNames = Object.fromEntries(state.points.map(point => [point.id, point.displayName]));
const sourceOptions = state.points.filter(point => point.readable).map(point => `<option value="${point.id}">${escapeHtml(point.displayName)} · ${point.protocol}</option>`).join('');
const rows = state.trendLogs.map(log => `<tr><td>${escapeHtml(log.name)}</td><td>${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}</td><td>${log.bacnetObjectInstance}</td><td>${log.intervalSeconds}s</td><td>${log.maxRecords.toLocaleString('de-DE')}</td><td>${log.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
return `${header('Trend Logs')}<section class="grid two"><article class="card"><div class="card-head"><h2>Internes Trend Log</h2></div>${sourceOptions ? `<form id="trend-form" class="form"><label>Quellpunkt<select name="sourcePointId">${sourceOptions}</select></label><label>Name<input name="name" required maxlength="160" placeholder="z. B. Zuluft Sollwert Verlauf"></label><div class="row three"><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" required></label><label>Intervall (s)<input name="intervalSeconds" type="number" min="1" max="86400" value="60" required></label><label>Max. Werte<input name="maxRecords" type="number" min="1" max="1000000" value="10000" required></label></div><div class="notice blue">Die Historie wird bei eingehenden Werten höchstens einmal je Intervall ergänzt. Sie ist schreibgeschützt und kann später als BACnet Trend Log bereitgestellt werden.</div><div class="buttons"><button class="btn primary">Trend Log anlegen</button></div><div id="trend-message"></div></form>` : '<div class="notice">Zuerst mindestens einen lesbaren Datenpunkt anlegen.</div>'}</article><article class="card"><div class="card-head"><h2>Konfigurierte Trend Logs</h2></div>${state.trendLogs.length ? `<table><thead><tr><th>Name</th><th>Quelle</th><th>BACnet</th><th>Intervall</th><th>Retention</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Trend Logs.</div>'}</article></section>`;
const rows = state.trendLogs.map(log => `<tr><td>${escapeHtml(log.name)}</td><td>${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}</td><td>${log.bacnetObjectInstance}</td><td>${log.intervalSeconds}s</td><td>${log.maxRecords.toLocaleString('de-DE')}</td><td>${log.isPublic ? `<a class="tag" href="/public-trends.html?log=${encodeURIComponent(log.id)}" target="_blank" rel="noopener">öffentlich</a>` : '<span class="tag gray">intern</span>'}</td><td>${log.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td></tr>`).join('');
const createPanel = can('manage_sources') ? (sourceOptions ? `<form id="trend-form" class="form"><label>Quellpunkt<select name="sourcePointId">${sourceOptions}</select></label><label>Name<input name="name" required maxlength="160" placeholder="z. B. Zuluft Sollwert Verlauf"></label><div class="row three"><label>BACnet-Instanz<input name="bacnetObjectInstance" type="number" min="0" max="4194303" required></label><label>Intervall (s)<input name="intervalSeconds" type="number" min="1" max="86400" value="60" required></label><label>Max. Werte<input name="maxRecords" type="number" min="1" max="1000000" value="10000" required></label></div><label class="switch"><input name="isPublic" type="checkbox"> Ohne Anmeldung veröffentlichen</label><div class="notice blue">Die Freigabe gilt nur für dieses Log und veröffentlicht ausschließlich die aufgezeichneten Werte. Die Historie wird bei eingehenden Werten höchstens einmal je Intervall ergänzt.</div><div class="buttons"><button class="btn primary">Trend Log anlegen</button></div><div id="trend-message"></div></form>` : '<div class="notice">Zuerst mindestens einen lesbaren Datenpunkt anlegen.</div>') : '<div class="notice blue">Ihre Rolle darf Trenddaten ansehen, aber keine Trend Logs anlegen oder verändern.</div>';
const selectionOptions = state.trendLogs.map(log => `<option value="${log.id}">${escapeHtml(log.name)} · BACnet TL ${log.bacnetObjectInstance}</option>`).join('');
const selectionRows = state.trendSelections.map(selection => `<tr><td>${escapeHtml(selection.name)}</td><td>${selection.trendLogIds.length}</td><td>${selection.shared ? '<span class="tag">geteilt</span>' : '<span class="tag gray">privat</span>'}</td><td>${selection.ownerId === state.user?.user?.id || state.user?.user?.role === 'admin' ? `<button class="btn danger" data-delete-selection="${selection.id}">Löschen</button>` : '—'}</td></tr>`).join('');
const selectionPanel = state.trendLogs.length ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Trend-Gruppe speichern</h2></div><form id="trend-selection-form" class="form"><label>Name<input name="name" required maxlength="120" placeholder="Tagesexport Lüftung"></label><label>Beschreibung (optional)<input name="description" maxlength="600"></label><label>Trend Logs<select name="trendLogIds" multiple size="6" required>${selectionOptions}</select></label><label class="switch"><input name="shared" type="checkbox"> Mit anderen Benutzern teilen</label><div class="buttons"><button class="btn primary">Gruppe speichern</button></div><div id="trend-selection-message"></div></form></article><article class="card"><div class="card-head"><h2>Gespeicherte Gruppen</h2><span class="tag gray">${state.trendSelections.length}</span></div>${selectionRows ? `<table><thead><tr><th>Name</th><th>Logs</th><th>Zugriff</th><th></th></tr></thead><tbody>${selectionRows}</tbody></table>` : '<div class="empty">Noch keine Trend-Gruppe gespeichert.</div>'}</article></section>` : '';
return `${header('Trend Logs')}<section class="grid two"><article class="card"><div class="card-head"><h2>Internes Trend Log</h2></div>${createPanel}</article><article class="card"><div class="card-head"><h2>Konfigurierte Trend Logs</h2></div>${state.trendLogs.length ? `<table><thead><tr><th>Name</th><th>Quelle</th><th>BACnet</th><th>Intervall</th><th>Retention</th><th>Freigabe</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Noch keine Trend Logs.</div>'}</article></section>${selectionPanel}`;
}
function viewRunner() {
const selections = state.trendSelections;
const selectionOptions = selections.map(selection => `<option value="${selection.id}">${escapeHtml(selection.name)} · ${selection.trendLogIds.length} Trend Logs</option>`).join('');
const rows = state.runnerJobs.map(job => `<tr><td>${escapeHtml(job.name)}</td><td>${escapeHtml(selections.find(selection => selection.id === job.selectionId)?.name || job.selectionId)}</td><td>${escapeHtml(job.time)} · ${job.rangeHours}h</td><td>${job.mailEnabled ? escapeHtml(job.mailTo || '—') : 'kein Mailversand'}</td><td>${job.enabled ? '<span class="tag">aktiv</span>' : '<span class="tag gray">inaktiv</span>'}</td><td>${job.lastResult ? (job.lastResult.success ? `<span class="tag">${escapeHtml(new Date(job.lastResult.ranAtUtc).toLocaleString())}</span>` : `<span class="tag warn">${escapeHtml(job.lastResult.error || 'Fehler')}</span>`) : 'noch nicht gelaufen'}</td><td><div class="buttons"><button class="btn" data-test-runner="${job.id}">Test</button><button class="btn danger" data-delete-runner="${job.id}">Löschen</button></div></td></tr>`).join('');
const mail = state.mailIntegration || { mailConfigured: false, endpoint: 'https://mailapi.se-inno.de' };
const mailPanel = can('manage_integrations') ? `<article class="card"><div class="card-head"><h2>Mail-API</h2><span class="tag ${mail.mailConfigured ? '' : 'gray'}">${mail.mailConfigured ? 'Key gespeichert' : 'kein Key'}</span></div><form id="mail-integration-form" class="form"><label>API-Key<input name="apiKey" type="password" autocomplete="new-password" placeholder="leer lassen = beibehalten"></label><label class="switch"><input name="clearApiKey" type="checkbox"> Gespeicherten API-Key löschen</label><p class="note">Endpoint: <code>${escapeHtml(mail.endpoint)}</code>. Der Key wird verschlüsselt in der lokalen Datenbank abgelegt.</p><div class="buttons"><button class="btn primary">Mail-API speichern</button></div><div id="mail-integration-message"></div></form></article>` : '';
const create = selections.length ? `<form id="runner-form" class="form"><label>Name<input name="name" required maxlength="120" placeholder="Tagesexport Lüftung"></label><label>Auswahl<select name="selectionId">${selectionOptions}</select></label><div class="row"><label>Uhrzeit (Europe/Berlin)<input name="time" type="time" value="06:00" required></label><label>Zeitraum<select name="rangeHours"><option value="24">letzte 24 h</option><option value="48">letzte 48 h</option><option value="168">letzte 7 Tage</option><option value="720">letzte 30 Tage</option></select></label></div><div class="row"><label>CSV-Trennzeichen<select name="delimiter"><option value=";">Semikolon ;</option><option value=",">Komma ,</option><option value="\t">Tabulator</option></select></label><label class="switch"><input name="enabled" type="checkbox" checked> aktiv</label></div><label class="switch"><input name="mailEnabled" type="checkbox"> CSV per Mail verschicken</label><label>Mail an (Komma oder Semikolon)<input name="mailTo" placeholder="kunde@example.com; service@example.com"></label><label>Betreff<input name="mailSubject" value="SE-Inno Universalgateway CSV Export"></label><label>Nachricht<textarea name="mailMessage">Automatischer CSV Export aus dem SE-Inno Universalgateway.</textarea></label><div class="buttons"><button class="btn primary">Runner-Job anlegen</button></div><div id="runner-message"></div></form>` : '<div class="notice">Zuerst in Trend Logs eine gespeicherte Trend-Gruppe anlegen.</div>';
return `${header('CSV Runner')}<section class="grid two"><article class="card"><div class="card-head"><h2>Neuer Job</h2></div>${create}</article>${mailPanel}</section><section class="card" style="margin-top:14px"><div class="card-head"><h2>Vorhandene Runner</h2><span class="tag gray">${state.runnerJobs.length}</span></div>${rows ? `<table><thead><tr><th>Name</th><th>Auswahl</th><th>Laufzeit</th><th>Mail</th><th>Status</th><th>Letztes Ergebnis</th><th></th></tr></thead><tbody>${rows}</tbody></table>` : '<div class="empty">Keine Runner-Jobs angelegt.</div>'}</section>`;
}
function bacnetInterfaceOptions(selected) {
const interfaces = state.hardware.networkInterfaces;
const missing = selected && !interfaces.some(card => card.name === selected)
? `<option value="" selected disabled>${escapeHtml(selected)} · nicht verfügbar</option>` : '';
return missing + interfaces.map(card =>
`<option value="${escapeHtml(card.name)}" ${card.name === selected ? 'selected' : ''}>${escapeHtml(card.name)} · ${escapeHtml(card.addresses.join(', ') || 'keine IP')} · ${card.isUp ? 'aktiv' : 'inaktiv'}</option>`
).join('');
}
function viewProtocols() {
const c = state.configuration;
return `${header('Protokolle')}<section class="grid two"><article class="card"><div class="card-head"><h2>BACnet/IP</h2><span class="tag">B-BC</span></div><form id="bacnet-form" class="form"><label>Linux-Interface<input name="interface" value="${escapeHtml(c.bacnet.interface)}" required></label><div class="row"><label>UDP-Port<input name="ipPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label><label>Device-Instance<input name="deviceInstance" type="number" min="0" max="4194303" value="${c.deviceInstance}"></label></div><label>BBMD-Modus<select name="bbmdMode"><option ${c.bacnet.bbmdMode === 'Disabled' ? 'selected' : ''}>Disabled</option><option ${c.bacnet.bbmdMode === 'Bbmd' ? 'selected' : ''}>Bbmd</option><option ${c.bacnet.bbmdMode === 'ForeignDevice' ? 'selected' : ''}>ForeignDevice</option></select></label><label>BBMD-Adresse (bei Foreign Device)<input name="bbmdAddress" value="${escapeHtml(c.bacnet.bbmdAddress || '')}"></label><label>Foreign-Device TTL in Sekunden<input name="ttl" type="number" min="1" max="65535" value="${c.bacnet.foreignDeviceTtlSeconds || ''}"></label><div class="buttons"><button class="btn primary">BACnet speichern</button></div><div id="bacnet-message"></div></form></article><article class="card"><div class="card-head"><h2>OPC UA & Modbus</h2></div><p class="notice blue">OPC UA ist als Client und Server mit persistentem Zertifikatsspeicher vorgesehen. Modbus-TCP wird mehrere Serverinstanzen, frei wählbare Bind-Adressen, Ports und Registerbereiche sowie eine optionale Client-IP-Allowlist unterstützen.</p><div class="card-head" style="margin-top:18px"><h2>KNXnet/IP</h2><span class="tag gray">vorgesehen</span></div><p class="note">Routing, Tunneling und KNX Secure bleiben vorbereitet, werden aber erst nach BACnet, OPC UA und Modbus aktiviert.</p></article></section>`;
const servers = c.modbusServers || [];
const serialPorts = c.serialPorts || [];
const aliases = serialPorts.map(port => `<option value="${escapeHtml(port.alias)}">${escapeHtml(port.alias)} · ${escapeHtml(port.devicePath)}</option>`).join('');
const serialDeviceOptions = (state.hardware?.serialDevices || []).map(device => `<option value="${escapeHtml(device.devicePath)}">${escapeHtml(device.targetPath || device.devicePath)}</option>`).join('');
const serverRows = servers.map(server => `<tr><td>${escapeHtml(server.name)}</td><td><code>${escapeHtml(server.bindAddress)}:${server.port}</code></td><td>${server.unitId}</td><td>${server.firstHoldingRegister}–${server.firstHoldingRegister + server.holdingRegisterCount - 1}</td><td>${server.allowedClientIps?.length ? escapeHtml(server.allowedClientIps.join(', ')) : 'alle'}</td><td><button class="btn danger" data-remove-modbus-server="${server.id}">Entfernen</button></td></tr>`).join('');
const serialRows = serialPorts.map(port => `<tr><td>${escapeHtml(port.alias)}</td><td><code>${escapeHtml(port.devicePath)}</code></td><td>${port.baudRate}, ${escapeHtml(port.parity)}, ${port.dataBits}/${port.stopBits}</td><td><button class="btn danger" data-remove-serial-port="${port.id}">Entfernen</button></td></tr>`).join('');
return `${header('Protokolle')}<datalist id="serial-device-list">${serialDeviceOptions}</datalist>
${pointPanel('bacnet', `<div class="bacnet-layout"><article class="card bacnet-settings"><div class="card-head"><h2>BACnet/IP</h2><span class="tag">Native Objekte</span></div><form id="bacnet-form" class="form"><label>Netzwerkkarte<select name="interface" required>${bacnetInterfaceOptions(c.bacnet.interface)}</select></label><div class="row"><label>UDP-Port<input name="ipPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label><label>Device-Instance<input name="deviceInstance" type="number" min="0" max="4194303" value="${c.deviceInstance}"></label></div><label>BBMD-Modus<select name="bbmdMode"><option ${c.bacnet.bbmdMode === 'Disabled' ? 'selected' : ''}>Disabled</option><option ${c.bacnet.bbmdMode === 'Bbmd' ? 'selected' : ''}>Bbmd</option><option ${c.bacnet.bbmdMode === 'ForeignDevice' ? 'selected' : ''}>ForeignDevice</option></select></label><label>BBMD-Adresse (bei Foreign Device)<input name="bbmdAddress" value="${escapeHtml(c.bacnet.bbmdAddress || '')}"></label><label>Foreign-Device TTL in Sekunden<input name="ttl" type="number" min="1" max="65535" value="${c.bacnet.foreignDeviceTtlSeconds || ''}"></label><p class="note">Die Liste bietet alle auf diesem Gateway sichtbaren Netzwerkschnittstellen an.</p><div class="buttons"><button class="btn primary">BACnet speichern</button></div><div id="bacnet-message"></div></form></article><div id="bacnet-browser"></div></div>`)}
${pointPanel('opcua', `<section class="grid equal"><article class="card"><div class="card-head"><h2>OPC UA</h2><span class="tag">Client + Server</span></div><form id="opcua-form" class="form"><label>Server-Port<input name="port" type="number" min="1" max="65535" value="${c.opcUa.port}"></label><div class="row"><label class="switch"><input name="clientEnabled" type="checkbox" ${c.opcUa.clientEnabled ? 'checked' : ''}> OPC-UA-Client aktiv</label><label class="switch"><input name="serverEnabled" type="checkbox" ${c.opcUa.serverEnabled ? 'checked' : ''}> OPC-UA-Server aktiv</label></div><label class="switch"><input name="allowAnonymous" type="checkbox" ${c.opcUa.allowAnonymous ? 'checked' : ''}> Anonymer Serverzugriff</label><div class="notice blue">Serverzertifikat, Trustlist und Clientzertifikate liegen persistent unter <code>/var/lib/seiugw/pki</code>. Für den Produktivbetrieb bleibt anonymer Zugriff deaktiviert.</div><div class="buttons"><button class="btn primary">OPC UA speichern</button></div><div id="opcua-message"></div></form></article></section><div id="opcua-browser"></div>`)}
${pointPanel('modbus', `<section class="grid equal"><article class="card"><div class="card-head"><h2>Modbus-TCP-Server</h2><span class="tag">${servers.length}</span></div><form id="modbus-server-form" class="form"><label>Name<input name="name" required placeholder="GLT Server"></label><div class="row three"><label>Bind-IP<input name="bindAddress" value="0.0.0.0" required></label><label>Port<input name="port" type="number" min="1" max="65535" value="502" required></label><label>Unit-ID<input name="unitId" type="number" min="1" max="247" value="1" required></label></div><div class="row"><label>Erstes Holding-Register<input name="firstHoldingRegister" type="number" min="0" max="65535" value="0" required></label><label>Anzahl Register<input name="holdingRegisterCount" type="number" min="1" max="65536" value="1000" required></label></div><label>Erlaubte Client-IPs (eine je Zeile, leer = alle)<textarea name="allowedClientIps"></textarea></label><div class="buttons"><button class="btn primary">TCP-Server hinzufügen</button></div><div id="modbus-server-message"></div></form></article>
<article class="card"><div class="card-head"><h2>TCP-Serverinstanzen</h2></div>${servers.length ? `<table><thead><tr><th>Name</th><th>Bindung</th><th>Unit</th><th>Holding</th><th>Client-Allowlist</th><th></th></tr></thead><tbody>${serverRows}</tbody></table>` : '<div class="empty">Keine Modbus-TCP-Serverinstanz angelegt.</div>'}</article>
<article class="card"><div class="card-head"><h2>Modbus-Datenpunkte importieren</h2></div><form id="modbus-import-form" class="form"><label>CSV-Datei<input name="csvFile" type="file" accept=".csv,text/csv" required></label><p class="note">Unterstützt TCP und RTU, Coil, Discrete Input, Input/Holding Register sowie UInt16/Int16/UInt32/Int32/Float32/Word-Swap.</p><div class="buttons"><button type="button" class="btn" id="download-modbus-example">Beispiel-CSV laden</button><button class="btn primary">CSV importieren</button></div><div id="modbus-import-message"></div></form></article></section>`)}
${pointPanel('knx', `<section class="grid equal"><article class="card"><div class="card-head"><h2>KNX</h2></div><form id="knx-form" class="form"><label class="switch"><input name="enabled" type="checkbox" ${c.knx.enabled ? 'checked' : ''}> KNX aktivieren</label><div class="row"><label>Transport<select name="transport"><option value="Ip" ${c.knx.transport !== 'Tp' ? 'selected' : ''}>KNX IP</option><option value="Tp" ${c.knx.transport === 'Tp' ? 'selected' : ''}>KNX TP via USB</option></select></label><label>TP-Alias<select name="serialPortAlias"><option value="">—</option>${aliases}</select></label></div><label class="switch"><input name="secure" type="checkbox" ${c.knx.secure ? 'checked' : ''}> KNX Secure</label><label>ETS-Projekt oder XML-Export<input id="knx-ets-file" type="file" accept=".knxproj,.xml,application/zip,text/xml,application/xml"></label><div class="buttons"><button class="btn primary">KNX speichern</button><button id="knx-ets-import" type="button" class="btn">ETS importieren</button></div><div id="knx-message"></div><div id="knx-import-message"></div></form><p class="note">Der Import übernimmt Gruppenadresse und DPT als externe KNX-Datenpunkte. Bereits vorhandene Gruppenadressen werden übersprungen.</p></article></section>`)}
${pointPanel('serial', `<section class="grid equal"><article class="card"><div class="card-head"><h2>USB / COM-Aliase</h2></div><form id="serial-port-form" class="form"><div class="row"><label>Alias<input name="alias" required placeholder="RS485-Hauptstrang" pattern="[A-Za-z0-9_-]{1,64}"></label><label>Linux-Gerät<input name="devicePath" list="serial-device-list" required placeholder="/dev/ttyUSB0"></label></div><div class="row three"><label>Baud<input name="baudRate" type="number" value="9600" min="1200" max="921600"></label><label>Parity<select name="parity"><option>None</option><option>Even</option><option>Odd</option></select></label><label>Bits<input name="dataBits" type="number" value="8" min="5" max="8"></label></div><label>Stop-Bits<select name="stopBits"><option value="1">1</option><option value="2">2</option></select></label><p class="note">Die Liste enthält die aktuell sichtbaren USB-/COM-Geräte. Ein stabiler <code>/dev/serial/by-id/…</code>-Pfad ist vorzuziehen.</p><div class="buttons"><button class="btn primary">Alias anlegen</button></div><div id="serial-port-message"></div></form></article>
<article class="card"><div class="card-head"><h2>Serielle Schnittstellen</h2></div>${serialPorts.length ? `<table><thead><tr><th>Alias</th><th>Gerät</th><th>Parameter</th><th></th></tr></thead><tbody>${serialRows}</tbody></table>` : '<div class="empty">Noch kein USB-/COM-Port aliasiert.</div>'}<div class="notice blue" style="margin-top:12px">Modbus RTU verwendet diese Aliase direkt in der CSV (<code>SerialPortAlias</code>). KNX TP verwendet denselben Alias für einen USB-TP-Adapter.</div></article></section>`)}`;
}
function viewSystem() {
return `${header('System')}<section class="grid two"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" required></label><label>Neues Passwort<input type="password" name="next" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button><button id="logout" type="button" class="btn danger">Abmelden</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Audit</h2></div><div id="audit-content" class="empty">Wird geladen …</div></article></section>`;
function viewSystem(section = 'settings') {
const theme = state.preferences?.theme || 'system';
const roleOptions = state.roles.map(role => `<option value="${escapeHtml(role.name)}">${escapeHtml(role.label)} · ${escapeHtml(role.name)}</option>`).join('');
const editUser = state.users.find(user => user.id === state.userEditId) || null;
const userRows = state.users.map(user => `<tr><td>${escapeHtml(user.username)}</td><td>${escapeHtml(user.displayName)}</td><td>${escapeHtml(user.email || '—')}</td><td><span class="tag gray">${escapeHtml(user.role)}</span></td><td>${user.active ? '<span class="tag">aktiv</span>' : '<span class="tag gray">deaktiviert</span>'}</td><td><div class="buttons"><button class="btn" data-edit-user="${user.id}">Bearbeiten</button>${user.id === state.user?.user?.id ? '' : `<button class="btn" data-toggle-user="${user.id}" data-active="${user.active}">${user.active ? 'Deaktivieren' : 'Aktivieren'}</button>`}</div></td></tr>`).join('');
const roleRows = state.roles.map(role => `<tr><td>${escapeHtml(role.label)}</td><td><code>${escapeHtml(role.name)}</code></td><td>${role.permissions.map(permission => `<span class="tag gray">${escapeHtml(permission)}</span>`).join(' ')}</td><td>${role.isSystem ? 'System' : 'Benutzerdefiniert'}</td></tr>`).join('');
const auditPanel = can('view_debug') ? '<article class="card"><div class="card-head"><h2>Audit</h2></div><div id="audit-content" class="empty">Wird geladen …</div></article>' : '';
const userPanel = can('manage_users') ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>${editUser ? `Benutzer bearbeiten · ${escapeHtml(editUser.username)}` : 'Benutzer anlegen'}</h2></div><form id="user-form" class="form"><div class="row"><label>Benutzername<input name="username" value="${escapeHtml(editUser?.username || '')}" required minlength="3" maxlength="80" pattern="[A-Za-z0-9._-]+"></label><label>Anzeigename<input name="displayName" value="${escapeHtml(editUser?.displayName || '')}" required maxlength="120"></label></div><div class="row"><label>E-Mail (optional)<input name="email" value="${escapeHtml(editUser?.email || '')}" type="email" maxlength="160"></label><label>Rolle<select name="role">${state.roles.map(role => `<option value="${escapeHtml(role.name)}" ${role.name === editUser?.role ? 'selected' : ''}>${escapeHtml(role.label)} · ${escapeHtml(role.name)}</option>`).join('')}</select></label></div><label>${editUser ? 'Neues Passwort (leer lassen = unverändert)' : 'Startpasswort'}<input name="password" type="password" minlength="12" ${editUser ? '' : 'required'}></label>${editUser ? '<label>Neues Passwort wiederholen<input name="passwordConfirmation" type="password" autocomplete="new-password" minlength="12"></label>' : ''}<label class="switch"><input name="active" type="checkbox" ${editUser ? (editUser.active ? 'checked' : '') : 'checked'}> Konto aktiv</label><div class="buttons"><button class="btn primary">${editUser ? 'Änderungen speichern' : 'Benutzer anlegen'}</button>${editUser ? '<button id="cancel-user-edit" type="button" class="btn">Abbrechen</button>' : ''}</div><div id="user-message"></div></form></article><article class="card"><div class="card-head"><h2>Konten</h2><span class="tag gray">${state.users.length}</span></div>${userRows ? `<table><thead><tr><th>Benutzer</th><th>Name</th><th>E-Mail</th><th>Rolle</th><th>Status</th><th></th></tr></thead><tbody>${userRows}</tbody></table>` : '<div class="empty">Keine Konten.</div>'}</article></section>` : '';
const rolePanel = can('manage_roles') ? `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>Benutzerdefinierte Rolle</h2></div><form id="role-form" class="form"><label>Name<input name="name" required pattern="[A-Za-z0-9_-]+" placeholder="service"></label><label>Bezeichnung<input name="label" required placeholder="Service"></label><label>Berechtigungen (kommagetrennt)<textarea name="permissions" placeholder="view_trends,manage_sources"></textarea></label><p class="note">Verfügbar: ${state.permissionCatalog.map(permission => `<code>${escapeHtml(permission)}</code>`).join(', ')}</p><div class="buttons"><button class="btn primary">Rolle speichern</button></div><div id="role-message"></div></form></article><article class="card"><div class="card-head"><h2>Rollen</h2></div><table><thead><tr><th>Bezeichnung</th><th>Name</th><th>Berechtigungen</th><th>Typ</th></tr></thead><tbody>${roleRows}</tbody></table></article></section>` : '';
if (section === 'users') return userPanel;
if (section === 'roles') return rolePanel;
if (section === 'debug') return auditPanel;
return `${header('Einstellungen')}<section class="grid equal"><article class="card"><div class="card-head"><h2>Passwort ändern</h2></div><form id="password-form" class="form"><label>Aktuelles Passwort<input type="password" name="current" autocomplete="current-password" required></label><label>Neues Passwort<input type="password" name="next" autocomplete="new-password" minlength="12" required></label><label>Neues Passwort wiederholen<input type="password" name="confirmation" autocomplete="new-password" minlength="12" required></label><div class="buttons"><button class="btn primary">Passwort ändern</button></div><div id="password-message"></div></form></article><article class="card"><div class="card-head"><h2>Darstellung</h2></div><div class="theme-toggle settings-theme" aria-label="Farbschema"><button class="theme-option ${theme === 'system' ? 'active' : ''}" data-theme="system" type="button">System</button><button class="theme-option ${theme === 'light' ? 'active' : ''}" data-theme="light" type="button">Hell</button><button class="theme-option ${theme === 'dark' ? 'active' : ''}" data-theme="dark" type="button">Dunkel</button></div><div id="system-message"></div></article>${can('manage_gateway') ? viewInstallationSettings() : ''}${can('manage_integrations') ? viewMqttTopicTemplateSettings() : ''}</section>${can('manage_gateway') ? '<section class="card" id="host-network" style="margin-top:10px"><h2>Netzwerk · IPv4</h2><p class="note">Netzwerkstatus wird geladen …</p></section>' : ''}`;
}
function bindView(view) {
if (view === 'points') document.querySelector('#point-form')?.addEventListener('submit', submitPoint);
if (view === 'mappings') document.querySelector('#mapping-form')?.addEventListener('submit', submitMapping);
if (view === 'mqtt') { document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration); document.querySelector('#mqtt-mapping-form')?.addEventListener('submit', submitMqttMapping); }
if (view === 'trends') document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog);
if (view === 'protocols') document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet);
if (view === 'system') { document.querySelector('#password-form').addEventListener('submit', submitPassword); document.querySelector('#logout').addEventListener('click', logout); loadAudit(); }
if (view === 'docs') return bindDocumentation();
if (view === 'overview') return bindDashboard();
if (view === 'admin') return bindAdmin();
if (view === 'points') {
bindPointTabs();
bindGatewayStatus();
// Keep each panel mounted: tab/theme changes must not discard forms or browse results.
if (can('manage_gateway')) bindView('protocols');
if (can('manage_integrations')) bindView('mqtt');
}
if (view === 'points' && can('manage_sources')) {
bindPointEditor();
bindConfigurationCsv('points', 'point-list-message');
}
if (view === 'mappings') {
bindMappingEditor('mapping', submitMapping);
bindMappingBatch();
bindConfigurationCsv('mappings', 'mapping-list-message');
}
if (view === 'mqtt') {
bindMqttTopicBrowser();
document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration);
bindMqttMappingOptions(document.querySelector('#mqtt-mapping-form'));
bindMappingEditor('mqtt-mapping', submitMqttMapping);
bindConfigurationCsv('mqtt', 'mqtt-mapping-list-message');
}
if (view === 'trends') {
bindTrendViewer();
document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog);
document.querySelector('#trend-selection-form')?.addEventListener('submit', submitTrendSelection);
document.querySelectorAll('[data-delete-selection]').forEach(button => button.addEventListener('click', deleteTrendSelection));
}
if (view === 'runner') {
document.querySelector('#runner-form')?.addEventListener('submit', submitRunnerJob);
document.querySelector('#mail-integration-form')?.addEventListener('submit', submitMailIntegration);
document.querySelectorAll('[data-test-runner]').forEach(button => button.addEventListener('click', testRunnerJob));
document.querySelectorAll('[data-delete-runner]').forEach(button => button.addEventListener('click', deleteRunnerJob));
}
if (view === 'protocols') {
if (can('manage_sources')) { renderBacnetBrowser(); renderOpcUaBrowser(); }
document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet);
document.querySelector('#bacnet-scan-form')?.addEventListener('submit', submitBacnetScan);
document.querySelector('#opcua-form')?.addEventListener('submit', submitOpcUa);
document.querySelector('#opcua-browse-form')?.addEventListener('submit', submitOpcUaBrowse);
document.querySelector('#modbus-server-form')?.addEventListener('submit', submitModbusServer);
document.querySelector('#serial-port-form')?.addEventListener('submit', submitSerialPort);
document.querySelector('#modbus-import-form')?.addEventListener('submit', submitModbusImport);
document.querySelector('#download-modbus-example')?.addEventListener('click', downloadModbusExample);
document.querySelector('#knx-form')?.addEventListener('submit', submitKnx);
document.querySelector('#knx-ets-import')?.addEventListener('click', submitKnxEtsImport);
document.querySelectorAll('[data-remove-modbus-server]').forEach(button => button.addEventListener('click', removeModbusServer));
document.querySelectorAll('[data-remove-serial-port]').forEach(button => button.addEventListener('click', removeSerialPort));
}
if (view === 'system') {
if (state.user?.user?.role === 'admin') bindSystemUpdate();
document.querySelector('#password-form')?.addEventListener('submit', submitPassword);
bindInstallationSettings();
bindMqttTopicTemplateSettings();
const networkPanel = document.querySelector('#host-network');
if (networkPanel) bindHostNetwork(networkPanel);
document.querySelector('#content').querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme)));
document.querySelector('#user-form')?.addEventListener('submit', submitUser);
const userPassword = document.querySelector('#user-form [name=password]');
const userConfirmation = document.querySelector('#user-form [name=passwordConfirmation]');
if (userConfirmation) userPassword.addEventListener('input', () => {
userConfirmation.required = Boolean(userPassword.value);
});
document.querySelector('#cancel-user-edit')?.addEventListener('click', () => { state.userEditId = null; renderView(); });
document.querySelector('#role-form')?.addEventListener('submit', submitRole);
document.querySelectorAll('[data-edit-user]').forEach(button => button.addEventListener('click', () => { state.userEditId = button.dataset.editUser; renderView(); }));
document.querySelectorAll('[data-toggle-user]').forEach(button => button.addEventListener('click', toggleUser));
if (document.querySelector('#audit-content')) loadAudit();
}
}
function renderBacnetBrowser() {
const card = document.querySelector('#bacnet-form')?.closest('article');
if (card) {
card.querySelector('.tag').textContent = 'Native Objekte';
card.insertAdjacentHTML('beforeend', '<p class="note" id="bacnet-runtime-status">Laufzeitstatus wird gelesen …</p>');
api('/api/bacnet/status').then(status => {
const target = document.querySelector('#bacnet-runtime-status');
if (target) target.textContent = `${status.connected ? 'Nativer BACnet-Dienst verbunden' : 'Nativer BACnet-Dienst nicht verbunden'} · ${status.pendingCommands} offene Befehle · ${status.failedCommands.length} zuletzt abgewiesene/abgelaufene Befehle${status.unsupportedPoints.length ? ` · ${status.unsupportedPoints.length} noch nicht unterstützte Objekte` : ''}`;
}).catch(error => errorTarget('bacnet-runtime-status', error.message));
}
const c = state.configuration;
document.querySelector('#bacnet-browser').insertAdjacentHTML('beforeend', `<article class="card bacnet-search"><div class="card-head"><h2>BACnet/IP-Browser</h2></div><form id="bacnet-scan-form" class="form"><div class="row"><label>Direkte Ziel-IP (optional)<input name="targetAddress" placeholder="leer = Broadcast auf der BACnet-Schnittstelle"></label><label>UDP-Port<input name="targetPort" type="number" min="1" max="65535" value="${c.bacnet.ipPort}"></label></div><div class="row"><label>Netzwerkkarte<select name="interface" required>${bacnetInterfaceOptions(c.bacnet.interface)}</select></label><label>Antwortfenster (Sekunden)<input name="timeoutSeconds" type="number" min="1" max="30" value="5"></label></div><p class="note">Auf der konfigurierten BACnet-Netzwerkkarte sucht der native Dienst über seinen UDP-Port ${c.bacnet.ipPort}. Für Geräte in einem anderen Subnetz eine direkte Ziel-IP oder einen BBMD verwenden.</p><div class="buttons"><button class="btn primary">BACnet-Geräte suchen</button></div><div id="bacnet-scan-message"></div></form></article><aside class="card bacnet-devices"><div class="card-head"><h2 id="bacnet-device-heading">Gefundene Geräte</h2><button id="bacnet-back-to-devices" class="btn" type="button" hidden>Geräteliste öffnen</button></div><div id="bacnet-scan-results" class="bacnet-device-scroll" tabindex="0" role="region" aria-labelledby="bacnet-device-heading"><div class="empty">Noch keine Suche gestartet.</div></div><section id="bacnet-object-panel" class="bacnet-object-panel" hidden></section></aside>`);
}
function renderOpcUaBrowser() {
document.querySelector('#opcua-browser').insertAdjacentHTML('beforeend', `<section class="grid two" style="margin-top:14px"><article class="card"><div class="card-head"><h2>OPC-UA-Browser</h2></div><form id="opcua-browse-form" class="form"><label>Endpunkt<input name="endpointUrl" placeholder="opc.tcp://192.168.10.10:4840" required></label><div class="row"><label>Sicherheit<select name="useSecurity"><option value="true">Gesicherter Kanal erforderlich</option><option value="false">Ohne Kanalsicherheit</option></select></label><label>Start-NodeId (optional)<input name="nodeId" placeholder="leer = ObjectsFolder"></label></div><div class="row three"><label>Anmeldung<select name="authenticationMode"><option value="Username">Benutzer / Passwort</option><option value="Anonymous">Anonym</option></select></label><label>Benutzer<input name="username" autocomplete="off"></label><label>Passwort<input name="password" type="password" autocomplete="off"></label></div><label class="switch"><input name="acceptUntrusted" type="checkbox"> Unbekanntes Serverzertifikat für diese Abfrage akzeptieren</label><p class="note">Gültigkeit und Zertifikatsangaben werden weiterhin geprüft. Gateway-Server: Web-Benutzer verwenden; Schreiben erfordert „Quellen verwalten“. Anonymer Zugriff ist nur lesend.</p><div class="buttons"><button class="btn primary">Durchsuchen</button><button class="btn" id="opcua-browse-root" type="button">Zur Wurzel</button></div><div id="opcua-browse-message"></div></form></article><article class="card"><div class="card-head"><h2>Gefundene Nodes</h2></div><div id="opcua-browse-results" class="empty">Noch keine Abfrage.</div></article></section>`);
document.querySelector('#opcua-browse-root').addEventListener('click', () => { const form = document.querySelector('#opcua-browse-form'); form.elements.nodeId.value = ''; form.requestSubmit(); });
const form = document.querySelector('#opcua-browse-form');
form.insertAdjacentHTML('afterbegin', `<label>Gespeicherte Verbindung<select name="clientId"><option value="">Neue Verbindung / einmalig browsen</option>${(state.opcuaClients?.clients || []).map(item => `<option value="${item.configuration.id}">${escapeHtml(item.configuration.name)}</option>`).join('')}</select></label><div class="row"><label>Verbindungsname<input name="connectionName" placeholder="GLT Hauptanlage"></label><label>Abonnement-Intervall (ms)<input name="publishingInterval" type="number" min="100" max="60000" value="1000"></label></div><label class="switch"><input name="enabled" type="checkbox" checked> Dauerhafte Verbindung aktiv</label><div id="opcua-client-status" class="note"></div>`);
form.querySelector('.buttons').insertAdjacentHTML('beforeend', '<button type="button" class="btn" id="opcua-client-save">Verbindung speichern</button>');
const select = form.elements.clientId;
select.addEventListener('change', () => {
const saved = state.opcuaClients.clients.find(item => item.configuration.id === select.value);
form.elements.password.value = ''; form.elements.nodeId.value = '';
document.querySelector('#opcua-browse-results').textContent = 'Noch keine Abfrage.';
if (!saved) { document.querySelector('#opcua-client-status').textContent = ''; return; }
const c = saved.configuration;
form.elements.connectionName.value = c.name; form.elements.endpointUrl.value = c.endpointUrl;
form.elements.useSecurity.value = String(c.useSecurity); form.elements.authenticationMode.value = c.authenticationMode;
form.elements.username.value = c.username || ''; form.elements.publishingInterval.value = c.publishingIntervalMilliseconds;
form.elements.acceptUntrusted.checked = c.acceptUntrustedServerCertificate; form.elements.enabled.checked = c.enabled;
form.elements.password.placeholder = saved.hasPassword ? 'Gespeichert – leer lassen zum Beibehalten' : '';
const status = state.opcuaClients.status.find(item => item.clientId === c.id);
document.querySelector('#opcua-client-status').textContent = status ? `${status.state} · ${status.subscribedPoints} abonnierte Punkte` : 'Deaktiviert / startet';
});
document.querySelector('#opcua-client-save').addEventListener('click', async () => {
try {
if (!form.reportValidity()) return;
const f = new FormData(form);
const configuration = { id: select.value || uuid(), name: String(f.get('connectionName')).trim(), endpointUrl: String(f.get('endpointUrl')).trim(), authenticationMode: f.get('authenticationMode'), username: String(f.get('username')).trim(), useSecurity: f.get('useSecurity') === 'true', acceptUntrustedServerCertificate: f.get('acceptUntrusted') === 'on', enabled: f.get('enabled') === 'on', publishingIntervalMilliseconds: Number(f.get('publishingInterval')) };
const saved = await api('/api/opcua/clients', { method: 'POST', body: JSON.stringify({ configuration, password: String(f.get('password')) || null }) });
await loadData();
if (![...select.options].some(option => option.value === saved.configuration.id)) select.add(new Option(saved.configuration.name, saved.configuration.id));
select.value = saved.configuration.id; select.dispatchEvent(new Event('change'));
errorTarget('opcua-browse-message', 'Gespeichert. Importierte Punkte werden automatisch abonniert.', true);
} catch (error) { errorTarget('opcua-browse-message', error.message); }
});
}
function bindPointEditor() {
const form = document.querySelector('#point-form');
if (!form) return;
function syncFields() {
const external = form.elements.scope.value === 'External';
const bacnet = form.elements.protocol.value === 'Bacnet' && form.elements.scope.value !== 'Internal';
form.querySelector('[data-point-external]').hidden = !external;
form.elements.externalIdentity.disabled = !external;
form.elements.externalIdentity.required = external;
form.querySelector('[data-point-bacnet]').hidden = !bacnet;
form.elements.bacnetObjectKind.disabled = form.elements.bacnetObjectInstance.disabled = !bacnet;
form.elements.bacnetObjectKind.required = bacnet && form.elements.scope.value === 'Gateway';
}
syncFields();
form.elements.protocol.addEventListener('change', syncFields);
form.elements.scope.addEventListener('change', syncFields);
form.addEventListener('submit', submitPoint);
document.querySelectorAll('[data-edit-point]').forEach(button => button.addEventListener('click', () => {
state.pointEditId = button.dataset.editPoint;
renderView();
document.querySelector('#point-form input[name="displayName"]')?.focus();
}));
document.querySelector('#cancel-point-edit')?.addEventListener('click', () => {
state.pointEditId = null;
renderView();
});
document.querySelectorAll('[data-delete-point]').forEach(button => button.addEventListener('click', () => deletePoint(button)));
}
async function submitPoint(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
event.preventDefault();
const form = new FormData(event.currentTarget);
const id = state.pointEditId;
const submit = event.currentTarget.querySelector('button[type="submit"]');
submit.disabled = true;
try {
const address = JSON.parse(form.get('address'));
const scope = form.get('scope');
const objectInstance = form.get('bacnetObjectInstance');
await api('/api/points', { method: 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: true, writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) });
await api(id ? `/api/points/${encodeURIComponent(id)}` : '/api/points', { method: id ? 'PUT' : 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: form.get('readable') === 'on', writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) });
state.pointEditId = null;
await loadData(); renderView();
} catch (error) { errorTarget('point-message', error.message); }
errorTarget('point-list-message', id ? 'Änderungen gespeichert.' : 'Datenpunkt angelegt.', true);
} catch (error) {
errorTarget('point-message', error instanceof SyntaxError ? 'Die Adresse enthält ungültiges JSON.' : error.message);
} finally { submit.disabled = false; }
}
async function deletePoint(button) {
const id = button.dataset.deletePoint;
const point = state.points.find(item => item.id === id);
if (!point) return;
button.disabled = true;
try {
const path = `/api/points/${encodeURIComponent(id)}`;
const usage = await api(path + '/dependencies');
const effects = [
usage.mappings && `${usage.mappings} Mapping(s) werden entfernt.`,
usage.mqttMappings && `${usage.mqttMappings} MQTT-Zuordnung(en) werden entfernt.`,
usage.alarms && `${usage.alarms} Alarmregel(n) werden entfernt.`,
usage.trendLogs && `${usage.trendLogs} Trendlog(s) werden gestoppt. Aufzeichnungen bleiben abrufbar.`
].filter(Boolean);
if (!window.confirm([`Datenpunkt „${point.displayName}“ löschen?`, ...effects].join('\n'))) return;
await api(path + '?confirmation=' + encodeURIComponent(usage.confirmation), { method: 'DELETE' });
if (state.pointEditId === id) state.pointEditId = null;
await loadData(); renderView();
errorTarget('point-list-message', 'Datenpunkt gelöscht.', true);
} catch (error) {
errorTarget('point-list-message', error.message);
} finally { button.disabled = false; }
}
function bindMappingEditor(kind, submit) {
const mqtt = kind === 'mqtt-mapping';
const editKey = mqtt ? 'mqttMappingEditId' : 'mappingEditId';
const endpoint = mqtt ? '/api/mqtt/mappings' : '/api/mappings';
const form = document.querySelector(`#${kind}-form`);
form?.addEventListener('submit', submit);
document.querySelectorAll(`[data-edit-${kind}]`).forEach(button => button.addEventListener('click', () => {
state[editKey] = button.getAttribute(`data-edit-${kind}`);
renderView();
document.querySelector(`#${kind}-form select`)?.focus();
}));
document.querySelector(`#cancel-${kind}-edit`)?.addEventListener('click', () => {
state[editKey] = null;
renderView();
});
document.querySelectorAll(`[data-delete-${kind}]`).forEach(button => button.addEventListener('click', async () => {
const id = button.getAttribute(`data-delete-${kind}`);
if (!window.confirm(mqtt ? 'MQTT-Verknüpfung löschen?' : 'Verknüpfung zwischen diesen Datenpunkten löschen?')) return;
button.disabled = true;
try {
await api(`${endpoint}/${encodeURIComponent(id)}`, { method: 'DELETE' });
if (state[editKey] === id) state[editKey] = null;
await loadData();
renderView();
errorTarget(`${kind}-list-message`, 'Verknüpfung gelöscht.', true);
} catch (error) {
errorTarget(`${kind}-list-message`, error.message);
} finally {
button.disabled = false;
}
}));
}
async function submitMapping(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
event.preventDefault();
const form = new FormData(event.currentTarget);
const id = state.mappingEditId;
const submit = event.currentTarget.querySelector('button[type="submit"], button:not([type])');
submit.disabled = true;
try {
const priority = form.get('bacnetPriority'); const transform = JSON.parse(form.get('transform'));
const response = await api('/api/mappings', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'), direction: form.get('direction'), enabled: true, bacnetPriority: priority ? Number(priority) : null, acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform }) });
const priority = form.get('bacnetPriority');
const transform = JSON.parse(form.get('transform'));
const response = await api(id ? `/api/mappings/${encodeURIComponent(id)}` : '/api/mappings', {
method: id ? 'PUT' : 'POST',
body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'),
direction: form.get('direction'), enabled: form.get('enabled') === 'on', bacnetPriority: priority ? Number(priority) : null,
acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform })
});
state.mappingEditId = null;
await loadData(); renderView();
if (response.warnings?.length) window.alert(response.warnings.join('\n'));
} catch (error) { errorTarget('mapping-message', error.message); }
errorTarget('mapping-list-message', response.warnings?.length ? response.warnings.join(' ') : 'Mapping gespeichert.', !response.warnings?.length);
} catch (error) {
errorTarget('mapping-message', error instanceof SyntaxError ? 'Die Transformation enthält ungültiges JSON.' : error.message);
} finally { submit.disabled = false; }
}
async function submitMqttConfiguration(event) {
@@ -179,46 +610,292 @@ async function submitMqttConfiguration(event) {
try {
const password = String(form.get('password') || '');
await api('/api/mqtt/configuration', { method: 'PUT', body: JSON.stringify({ configuration: { enabled: form.get('enabled') === 'on', host: String(form.get('host') || '').trim(), port: Number(form.get('port')), useTls: form.get('useTls') === 'on', ignoreCertificateErrors, clientId: String(form.get('clientId') || '').trim(), username: String(form.get('username') || '').trim() || null }, password: password || null, clearPassword: form.get('clearPassword') === 'on' }) });
state.mqttBrowser = null;
await loadData(); renderView(); errorTarget('mqtt-configuration-message', 'Gespeichert; die Verbindung wird neu aufgebaut.', true);
} catch (error) { errorTarget('mqtt-configuration-message', error.message); }
}
async function submitMqttMapping(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
event.preventDefault();
const form = new FormData(event.currentTarget);
const id = state.mqttMappingEditId;
const submit = event.currentTarget.querySelector('button[type="submit"]');
submit.disabled = true;
try {
const format = form.get('format');
await api('/api/mqtt/mappings', { method: 'POST', body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'), qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on', projectYear: format === 'SeMonitoring' ? Number(form.get('projectYear')) : null, projectNumber: format === 'SeMonitoring' ? form.get('projectNumber') : null, ispNumber: format === 'SeMonitoring' ? form.get('ispNumber') : null, seCategory: format === 'SeMonitoring' ? form.get('seCategory') : null, topicName: format === 'SeMonitoring' ? form.get('topicName') : null, jsonTopic: format === 'Json' ? form.get('jsonTopic') : null, jsonProperty: format === 'Json' ? form.get('jsonProperty') : null }) });
const format = form.has('seMonitoring') ? 'SeMonitoring' : form.get('freeFormat');
const monitoring = format === 'SeMonitoring';
await api(id ? `/api/mqtt/mappings/${encodeURIComponent(id)}` : '/api/mqtt/mappings', {
method: id ? 'PUT' : 'POST',
body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'),
qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on',
...(monitoring ? mqttSiteFromForm(form) : {}), seCategory: monitoring ? form.get('seCategory') : null,
topicName: monitoring ? form.get('topicName') : null, jsonTopic: monitoring ? null : form.get('jsonTopic'),
jsonProperty: format === 'Json' ? form.get('jsonProperty') : null })
});
state.mqttMappingEditId = null;
await loadData(); renderView();
errorTarget('mqtt-mapping-list-message', 'MQTT-Mapping gespeichert.', true);
} catch (error) { errorTarget('mqtt-mapping-message', error.message); }
finally { submit.disabled = false; }
}
async function submitTrendLog(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true }) });
await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true, isPublic: form.get('isPublic') === 'on' }) });
await loadData(); renderView();
} catch (error) { errorTarget('trend-message', error.message); }
}
async function submitTrendSelection(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
await api('/api/trend-selections', { method: 'POST', body: JSON.stringify({ name: form.get('name'), description: String(form.get('description') || '').trim() || null, shared: form.get('shared') === 'on', trendLogIds: form.getAll('trendLogIds') }) });
await loadData(); renderView();
} catch (error) { errorTarget('trend-selection-message', error.message); }
}
async function deleteTrendSelection(event) {
const id = event.currentTarget.dataset.deleteSelection;
if (!window.confirm('Diese gespeicherte Trend-Gruppe löschen?')) return;
try { await api(`/api/trend-selections/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); }
catch (error) { errorTarget('trend-selection-message', error.message); }
}
async function submitRunnerJob(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
await api('/api/runner/jobs', { method: 'POST', body: JSON.stringify({ name: form.get('name'), selectionId: form.get('selectionId'), time: form.get('time'), rangeHours: Number(form.get('rangeHours')), delimiter: form.get('delimiter'), enabled: form.get('enabled') === 'on', mailEnabled: form.get('mailEnabled') === 'on', mailTo: String(form.get('mailTo') || '').trim() || null, mailSubject: String(form.get('mailSubject') || '').trim() || null, mailMessage: String(form.get('mailMessage') || '').trim() || null }) });
await loadData(); renderView();
} catch (error) { errorTarget('runner-message', error.message); }
}
async function testRunnerJob(event) {
const button = event.currentTarget;
try {
const result = await api(`/api/runner/jobs/${encodeURIComponent(button.dataset.testRunner)}/test`, { method: 'POST' });
await loadData(); renderView();
window.alert(result.success ? `CSV erzeugt: ${result.filePath}${result.filePath && state.runnerJobs.find(job => job.id === button.dataset.testRunner)?.mailEnabled ? '\nMailversand abgeschlossen.' : ''}` : `CSV-Runner fehlgeschlagen: ${result.error}`);
} catch (error) { window.alert(`CSV-Runner fehlgeschlagen: ${error.message}`); }
}
async function deleteRunnerJob(event) {
const id = event.currentTarget.dataset.deleteRunner;
if (!window.confirm('Diesen CSV-Runner-Job löschen?')) return;
try { await api(`/api/runner/jobs/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); }
catch (error) { window.alert(error.message); }
}
async function submitMailIntegration(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
const apiKey = String(form.get('apiKey') || '').trim(); const clearApiKey = form.get('clearApiKey') === 'on';
if (!apiKey && !clearApiKey) throw new Error('Bitte einen neuen API-Key eintragen oder das Löschen auswählen.');
await api('/api/integrations/mail', { method: 'PUT', body: JSON.stringify({ apiKey: apiKey || null, clearApiKey }) });
await loadData(); renderView();
} catch (error) { errorTarget('mail-integration-message', error.message); }
}
async function submitBacnet(event) {
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
try {
c.deviceInstance = Number(form.get('deviceInstance')); c.deviceName = `SEIU-Gateway-${c.deviceInstance}`;
c.bacnet.interface = form.get('interface'); c.bacnet.ipPort = Number(form.get('ipPort')); c.bacnet.bbmdMode = form.get('bbmdMode'); c.bacnet.bbmdAddress = form.get('bbmdAddress') || null; c.bacnet.foreignDeviceTtlSeconds = form.get('ttl') ? Number(form.get('ttl')) : null;
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Aktivierung erfolgt beim nächsten Adapter-Start.', true);
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Der native Dienst übernimmt die Änderung automatisch; Netzwerkänderungen lösen einen kurzen Neustart aus. Abweichende Ports müssen auch in der NixOS-Firewall freigegeben sein.', true);
} catch (error) { errorTarget('bacnet-message', error.message); }
}
async function submitBacnetScan(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
const devices = await api('/api/bacnet/scan', { method: 'POST', body: JSON.stringify({ interface: String(form.get('interface') || '').trim() || null, targetAddress: String(form.get('targetAddress') || '').trim() || null, targetPort: Number(form.get('targetPort')), timeoutSeconds: Number(form.get('timeoutSeconds')) }) });
renderBacnetDevices(devices, form.get('interface'));
errorTarget('bacnet-scan-message', `${devices.length} Gerät(e) gefunden.`, true);
} catch (error) { errorTarget('bacnet-scan-message', error.message); }
}
async function saveGatewayConfiguration(messageTarget, message) {
try {
await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(state.configuration) });
await loadData(); renderView(); errorTarget(messageTarget, message, true);
} catch (error) { errorTarget(messageTarget, error.message); }
}
async function submitOpcUa(event) {
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
c.opcUa.port = Number(form.get('port')); c.opcUa.clientEnabled = form.get('clientEnabled') === 'on'; c.opcUa.serverEnabled = form.get('serverEnabled') === 'on'; c.opcUa.allowAnonymous = form.get('allowAnonymous') === 'on';
await saveGatewayConfiguration('opcua-message', 'Gespeichert. Der OPC-UA-Dienst übernimmt die Änderung automatisch.');
}
async function submitOpcUaBrowse(event) {
event.preventDefault(); const element = event.currentTarget; const form = new FormData(element);
const submit = element.querySelector('button[type="submit"], button:not([type])'); submit.disabled = true;
errorTarget('opcua-browse-message', 'Verbindung wird aufgebaut …', true);
try {
const clientId = form.get('clientId') || null;
if (clientId) {
const saved = state.opcuaClients.clients.find(item => item.configuration.id === clientId)?.configuration;
if (!saved || String(form.get('endpointUrl')).trim() !== saved.endpointUrl || form.get('authenticationMode') !== saved.authenticationMode || String(form.get('username')).trim() !== (saved.username || '') || (form.get('useSecurity') === 'true') !== saved.useSecurity || (form.get('acceptUntrusted') === 'on') !== saved.acceptUntrustedServerCertificate || form.get('password'))
throw new Error('Geänderte Verbindungsdaten bitte zuerst speichern. Browsen verwendet die gespeicherten Zugangsdaten.');
}
const items = await api('/api/opcua/browse', { method: 'POST', body: JSON.stringify({ clientId, endpointUrl: String(form.get('endpointUrl')).trim(), nodeId: String(form.get('nodeId') || '').trim() || null, useSecurity: form.get('useSecurity') === 'true', authenticationMode: form.get('authenticationMode'), username: String(form.get('username') || '').trim(), password: String(form.get('password') || ''), acceptUntrustedServerCertificate: form.get('acceptUntrusted') === 'on' }) });
const target = document.querySelector('#opcua-browse-results');
target.innerHTML = items.length ? `<table><thead><tr><th>Name</th><th>Klasse</th><th>NodeId</th><th>Wert</th><th></th></tr></thead><tbody>${items.map(item => `<tr><td>${escapeHtml(item.displayName)}</td><td>${escapeHtml(item.nodeClass)}</td><td><code>${escapeHtml(item.nodeId)}</code></td><td>${item.value === null || item.value === undefined ? '—' : escapeHtml(typeof item.value === 'string' ? item.value : JSON.stringify(item.value))}</td><td>${item.hasChildren ? `<button class="btn" type="button" data-opcua-node="${escapeHtml(item.nodeId)}">Öffnen</button>` : ''}</td></tr>`).join('')}</tbody></table>` : '<div class="empty">Keine untergeordneten Nodes.</div>';
target.querySelectorAll('[data-opcua-node]').forEach(button => button.addEventListener('click', () => { element.elements.nodeId.value = button.dataset.opcuaNode; element.requestSubmit(); }));
const importable = items.filter(item => item.stableNodeId && item.valueType && item.readable);
async function importPoints(selected, button) {
button.disabled = true;
try {
const imported = await api('/api/opcua/import', { method: 'POST', body: JSON.stringify({ clientId, points: selected.map(item => ({ nodeId: item.stableNodeId, displayName: item.displayName, valueType: item.valueType, readable: item.readable, writable: item.writable })) }) });
await loadData(); errorTarget('opcua-browse-message', `${imported.length} Punkte übernommen. Bereits vorhandene Punkte übersprungen.`, true);
} catch (error) { errorTarget('opcua-browse-message', error.message); }
finally { button.disabled = false; }
}
if (clientId && importable.length) {
const all = document.createElement('button'); all.type = 'button'; all.className = 'btn primary'; all.textContent = 'Alle lesbaren Skalare dieser Ebene hinzufügen';
target.prepend(all); all.addEventListener('click', () => importPoints(importable, all));
target.querySelectorAll('tbody tr').forEach((row, index) => {
const item = items[index]; if (!importable.includes(item)) return;
const add = document.createElement('button'); add.type = 'button'; add.className = 'btn'; add.textContent = 'Hinzufügen';
row.lastElementChild.append(add); add.addEventListener('click', () => importPoints([item], add));
});
}
errorTarget('opcua-browse-message', `${items.length} Nodes gelesen.${clientId ? '' : ' Verbindung speichern, um Punkte dauerhaft zu übernehmen.'}`, true);
} catch (error) { errorTarget('opcua-browse-message', error.message); }
finally { submit.disabled = false; }
}
async function submitModbusServer(event) {
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
c.modbusServers = c.modbusServers || [];
c.modbusServers.push({ id: uuid(), name: String(form.get('name')).trim(), bindAddress: String(form.get('bindAddress')).trim(), port: Number(form.get('port')), unitId: Number(form.get('unitId')), firstHoldingRegister: Number(form.get('firstHoldingRegister')), holdingRegisterCount: Number(form.get('holdingRegisterCount')), allowedClientIps: String(form.get('allowedClientIps') || '').split(/[\s,;]+/).map(value => value.trim()).filter(Boolean) });
await saveGatewayConfiguration('modbus-server-message', 'TCP-Server gespeichert und aktiviert.');
}
async function removeModbusServer(event) {
const id = event.currentTarget.dataset.removeModbusServer;
if (!window.confirm('Diese Modbus-TCP-Serverinstanz entfernen?')) return;
state.configuration.modbusServers = (state.configuration.modbusServers || []).filter(server => server.id !== id);
await saveGatewayConfiguration('modbus-server-message', 'TCP-Server entfernt.');
}
async function submitSerialPort(event) {
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
c.serialPorts = c.serialPorts || [];
c.serialPorts.push({ id: uuid(), alias: String(form.get('alias')).trim(), devicePath: String(form.get('devicePath')).trim(), baudRate: Number(form.get('baudRate')), parity: form.get('parity'), dataBits: Number(form.get('dataBits')), stopBits: Number(form.get('stopBits')) });
await saveGatewayConfiguration('serial-port-message', 'Serieller Port gespeichert.');
}
async function removeSerialPort(event) {
const id = event.currentTarget.dataset.removeSerialPort;
if (!window.confirm('Diesen COM-/USB-Alias entfernen?')) return;
state.configuration.serialPorts = (state.configuration.serialPorts || []).filter(port => port.id !== id);
await saveGatewayConfiguration('serial-port-message', 'Serieller Port entfernt.');
}
async function submitKnx(event) {
event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration;
c.knx.enabled = form.get('enabled') === 'on'; c.knx.secure = form.get('secure') === 'on'; c.knx.transport = form.get('transport'); c.knx.serialPortAlias = String(form.get('serialPortAlias') || '').trim() || null;
await saveGatewayConfiguration('knx-message', 'KNX-Konfiguration gespeichert.');
}
async function submitKnxEtsImport() {
const file = document.querySelector('#knx-ets-file')?.files?.[0];
try {
if (!file) throw new Error('Bitte zuerst eine ETS-Projektdatei oder XML-Export auswählen.');
const bytes = new Uint8Array(await file.arrayBuffer()); let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
const result = await api('/api/imports/knx-ets', { method: 'POST', body: JSON.stringify({ fileName: file.name, contentBase64: btoa(binary) }) });
await loadData(); errorTarget('knx-import-message', `${result.imported} Gruppenadresse(n) importiert${result.errors?.length ? `, ${result.errors.length} übersprungen.` : '.'}`, true);
} catch (error) { errorTarget('knx-import-message', error.message); }
}
async function downloadModbusExample() {
try {
const response = await fetch('/api/imports/modbus-example.csv', { headers: { Authorization: `Bearer ${state.token}` } });
if (!response.ok) throw new Error('Beispieldatei konnte nicht geladen werden.');
const href = URL.createObjectURL(await response.blob()); const link = document.createElement('a'); link.href = href; link.download = 'seiugw-modbus-beispiel.csv'; link.click(); URL.revokeObjectURL(href);
} catch (error) { errorTarget('modbus-import-message', error.message); }
}
async function submitModbusImport(event) {
event.preventDefault(); const file = new FormData(event.currentTarget).get('csvFile');
try {
if (!(file instanceof File) || !file.size) throw new Error('Bitte eine CSV-Datei auswählen.');
const result = await api('/api/imports/modbus-csv', { method: 'POST', body: JSON.stringify({ csv: await file.text() }) });
await loadData(); errorTarget('modbus-import-message', `${result.imported} Datenpunkte importiert${result.errors?.length ? `, ${result.errors.length} Zeile(n) übersprungen.` : '.'}`, true);
} catch (error) { errorTarget('modbus-import-message', error.message); }
}
async function submitPassword(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try { await api('/api/auth/password', { method: 'POST', body: JSON.stringify({ currentPassword: form.get('current'), newPassword: form.get('next') }) }); sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); }
const newPassword = form.get('next');
const newPasswordConfirmation = form.get('confirmation');
if (newPassword !== newPasswordConfirmation)
return errorTarget('password-message', 'Die neuen Passwörter müssen übereinstimmen.');
try { await api('/api/auth/password', { method: 'POST', body: JSON.stringify({ currentPassword: form.get('current'), newPassword, newPasswordConfirmation }) }); sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); }
catch (error) { errorTarget('password-message', error.message); }
}
async function submitUser(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
const payload = { username: form.get('username'), displayName: form.get('displayName'), email: String(form.get('email') || '').trim() || null, role: form.get('role'), active: form.get('active') === 'on' };
const password = String(form.get('password') || '');
if (state.userEditId) {
if (password) {
const confirmation = form.get('passwordConfirmation');
if (password !== confirmation) throw new Error('Die neuen Passwörter müssen übereinstimmen.');
payload.password = password;
payload.passwordConfirmation = confirmation;
}
await api(`/api/users/${encodeURIComponent(state.userEditId)}`, { method: 'PATCH', body: JSON.stringify(payload) });
state.userEditId = null;
} else {
await api('/api/users', { method: 'POST', body: JSON.stringify({ ...payload, password }) });
}
await loadData(); renderView(); errorTarget('user-message', 'Benutzer angelegt.', true);
} catch (error) { errorTarget('user-message', error.message); }
}
async function toggleUser(event) {
const button = event.currentTarget;
const active = button.dataset.active !== 'true';
if (!window.confirm(active ? 'Konto aktivieren?' : 'Konto deaktivieren?')) return;
try { await api(`/api/users/${encodeURIComponent(button.dataset.toggleUser)}`, { method: 'PATCH', body: JSON.stringify({ active }) }); await loadData(); renderView(); }
catch (error) { errorTarget('user-message', error.message); }
}
async function submitRole(event) {
event.preventDefault(); const form = new FormData(event.currentTarget);
try {
const permissions = String(form.get('permissions') || '').split(/[\s,;]+/).map(value => value.trim()).filter(Boolean);
await api('/api/roles', { method: 'POST', body: JSON.stringify({ name: form.get('name'), label: form.get('label'), permissions }) });
await loadData(); renderView(); errorTarget('role-message', 'Rolle gespeichert.', true);
} catch (error) { errorTarget('role-message', error.message); }
}
async function loadAudit() {
try { const entries = await api('/api/audit?limit=8'); const target = document.querySelector('#audit-content'); target.innerHTML = entries.length ? `<table><tbody>${entries.map(entry => `<tr><td>${escapeHtml(new Date(entry.occurredAtUtc).toLocaleString())}</td><td><span class="tag gray">${escapeHtml(entry.category)}</span></td><td>${escapeHtml(entry.message)}</td></tr>`).join('')}</tbody></table>` : 'Noch keine Ereignisse.'; }
catch (error) { errorTarget('audit-content', error.message); }
}
async function logout() { await api('/api/auth/logout', { method: 'POST' }); sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); }
boot().catch(error => { app.innerHTML = `<section class="auth"><div class="auth-card"><h1>Startfehler</h1><p>${escapeHtml(error.message)}</p></div></section>`; });
async function setTheme(theme) {
if (!['system', 'light', 'dark'].includes(theme)) return;
applyTheme(theme);
state.preferences = { ...(state.preferences || {}), theme };
try {
state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ theme }) });
errorTarget('theme-message', 'Darstellung gespeichert.', true);
errorTarget('system-message', 'Darstellung gespeichert.', true);
} catch (error) {
errorTarget('theme-message', `Nur lokal geändert: ${error.message}`);
errorTarget('system-message', `Farbschema wurde nur lokal gesetzt: ${error.message}`);
}
}
async function logout() { await api('/api/auth/logout', { method: 'POST' }); sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); }
boot().catch(error => {
if (!state.token && error.message === 'Sitzung abgelaufen.') return renderLogin();
app.innerHTML = `<section class="auth"><div class="auth-card"><h1>Startfehler</h1><p>${escapeHtml(error.message)}</p></div></section>`;
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

+119
View File
@@ -0,0 +1,119 @@
let activeBacnetDevice;
function showBacnetDevices() {
const heading = document.querySelector('#bacnet-device-heading');
if (!heading) return;
heading.textContent = 'Gefundene Geräte';
document.querySelector('#bacnet-back-to-devices').hidden = true;
document.querySelector('#bacnet-object-panel').hidden = true;
document.querySelector('#bacnet-scan-results').hidden = false;
}
function renderBacnetDevices(devices, networkInterface) {
activeBacnetDevice = null;
showBacnetDevices();
const list = document.querySelector('#bacnet-scan-results');
list.innerHTML = devices.length ? `<table><thead><tr><th>Gerät</th><th>Instanz</th><th>Adresse</th><th>Vendor</th><th></th></tr></thead>
<tbody>${devices.map(device => `<tr>
<td>${escapeHtml(device.deviceName || '—')}</td><td>${device.deviceInstance}</td>
<td><code>${escapeHtml(device.address)}:${device.port}</code>${device.network ? `<div class="note">BACnet-Netz ${device.network} · ${escapeHtml(device.mac || '—')}</div>` : ''}</td>
<td>${device.vendorId ?? '—'}</td>
<td><button type="button" class="btn" data-bacnet-device="${device.deviceInstance}">Objekte lesen</button></td>
</tr>`).join('')}</tbody></table>` : '<div class="empty">Keine BACnet-Geräte gefunden.</div>';
list.querySelectorAll('[data-bacnet-device]').forEach((button, index) => button.addEventListener('click', () =>
openBacnetObjects(button, { ...devices[index], interface: networkInterface })));
}
async function openBacnetObjects(button, device) {
if (!device) return;
const panel = document.querySelector('#bacnet-object-panel');
const selected = { device, rows: [], offset: 0, total: 0 };
activeBacnetDevice = selected;
button.disabled = true;
errorTarget('bacnet-scan-message', 'BACnet-Objekte werden gelesen …', true);
try {
const result = await requestBacnetObjectPage(selected);
if (!panel.isConnected || selected !== activeBacnetDevice) return;
document.querySelector('#bacnet-scan-results').hidden = true;
document.querySelector('#bacnet-device-heading').textContent = result.deviceName || device.deviceName || `BACnet-Gerät ${device.deviceInstance}`;
const back = document.querySelector('#bacnet-back-to-devices');
back.hidden = false;
back.onclick = () => { activeBacnetDevice = null; showBacnetDevices(); };
panel.hidden = false;
panel.innerHTML = `<div class="note">Device-Instanz ${device.deviceInstance} · ${escapeHtml(device.address)}</div>
<div class="buttons">
<button class="btn primary" type="button" id="bacnet-import-selected" disabled>Auswahl anlegen</button>
<button class="btn" type="button" id="bacnet-import-all">Alle importierbaren anlegen</button>
<button class="btn" type="button" id="bacnet-load-more" hidden>Weitere Objekte laden</button>
</div>
<div id="bacnet-object-message" role="status"></div>
<div id="bacnet-object-results" class="bacnet-device-scroll" tabindex="0" role="region" aria-label="BACnet-Objekte">
<table><thead><tr><th></th><th>Typ / Instanz</th><th>Objektname</th><th>Beschreibung</th><th>Aktueller Wert</th></tr></thead><tbody></tbody></table>
</div>`;
panel.querySelector('#bacnet-import-selected').onclick = () => importBacnetObjects(panel, selected, false);
panel.querySelector('#bacnet-import-all').onclick = () => importBacnetObjects(panel, selected, true);
panel.querySelector('#bacnet-load-more').onclick = async event => {
const more = event.currentTarget;
more.disabled = true;
try {
await requestBacnetObjectPage(selected);
if (selected === activeBacnetDevice) paintBacnetObjects(panel, selected);
} catch (error) { errorTarget('bacnet-object-message', error.message); }
finally { more.disabled = false; }
};
panel.addEventListener('change', syncBacnetImportSelection);
paintBacnetObjects(panel, selected);
errorTarget('bacnet-scan-message', `${selected.total} Objekt(e) gefunden.`, true);
} catch (error) {
errorTarget('bacnet-scan-message', error.message);
} finally { button.disabled = false; }
}
function syncBacnetImportSelection(event) {
const panel = event.currentTarget;
panel.querySelector('#bacnet-import-selected').disabled = !panel.querySelector('[data-bacnet-object]:checked');
}
async function requestBacnetObjectPage(selection) {
const result = await api('/api/bacnet/objects', { method:'POST',
body:JSON.stringify({device:selection.device, offset:selection.offset, limit:100}) });
selection.rows.push(...result.objects);
selection.total = result.total;
selection.offset = result.nextOffset;
return result;
}
function paintBacnetObjects(panel, selection) {
const selectedIds = new Set([...panel.querySelectorAll('[data-bacnet-object]:checked')].map(input => input.value));
panel.querySelector('tbody').innerHTML = selection.rows.map(object => {
const id = `${object.objectTypeCode}:${object.objectInstance}`;
const label = object.name || `${object.objectType} ${object.objectInstance}`;
const pick = object.pointId ? '<span class="tag">angelegt</span>' : object.valueType
? `<input type="checkbox" aria-label="${escapeHtml(label)} auswählen" data-bacnet-object value="${id}" ${selectedIds.has(id) ? 'checked' : ''}>` : '—';
return `<tr><td>${pick}</td><td>${escapeHtml(object.objectType)} · ${object.objectInstance}</td>
<td>${escapeHtml(object.name || '—')}</td><td>${escapeHtml(object.description || '—')}</td>
<td>${escapeHtml(object.value == null ? '—' : String(object.value))}</td></tr>`;
}).join('');
panel.querySelector('#bacnet-load-more').hidden = selection.offset >= Math.min(5000, selection.total);
panel.querySelector('#bacnet-import-all').disabled = selection.total === 0 || selection.total > 5000;
syncBacnetImportSelection({ currentTarget:panel });
}
async function importBacnetObjects(panel, selection, all) {
const objectIds = [...panel.querySelectorAll('[data-bacnet-object]:checked')].map(input => input.value);
const selected = new Set(objectIds);
const buttons = [...panel.querySelectorAll('button')];
buttons.forEach(button => { button.disabled = true; });
try {
const result = await api('/api/bacnet/import', { method:'POST', body:JSON.stringify({device:selection.device, objectIds, all}) });
for (const object of selection.rows) {
if (object.valueType && (all || selected.has(`${object.objectTypeCode}:${object.objectInstance}`))) object.pointId = 'imported';
}
await loadData();
errorTarget('bacnet-object-message', `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unsupported} ohne unterstützten Live-Wert`, true);
} catch (error) { errorTarget('bacnet-object-message', error.message); }
finally {
buttons.forEach(button => { button.disabled = false; });
if (activeBacnetDevice === selection) paintBacnetObjects(panel, selection);
}
}
+140
View File
@@ -0,0 +1,140 @@
function viewDocumentation() {
return `${header('Dokumentation')}<section id="documentation">
<nav class="tabs protocol-tabs" role="tablist" aria-label="Dokumente" hidden></nav>
<article class="card documentation-card" id="documentation-panel">
<p class="note" role="status">Dokumentation wird geladen …</p>
</article>
</section>`;
}
function bindDocumentation() {
const root = document.querySelector('#documentation');
const tabs = root.querySelector('[role=tablist]');
const panel = root.querySelector('#documentation-panel');
let documents = [];
let revision = 0;
function setMessage(message) {
const text = document.createElement('p');
text.className = 'note';
text.role = 'status';
text.textContent = message;
panel.replaceChildren(text);
}
function scrollToHeading(fragment) {
if (!fragment) return;
[...panel.querySelectorAll('[id]')].find(heading => heading.id === fragment)?.scrollIntoView({ block:'start' });
}
async function openDocument(index, fragment) {
const selected = documents[index];
if (!selected) return;
const current = ++revision;
state.documentationPath = selected.path;
[...tabs.children].forEach((tab, position) => {
const active = position === index;
tab.classList.toggle('active', active);
tab.setAttribute('aria-selected', String(active));
tab.tabIndex = active ? 0 : -1;
});
panel.setAttribute('aria-labelledby', `documentation-tab-${index}`);
setMessage('Dokument wird geladen …');
try {
const file = await api(`/api/docs/content?path=${encodeURIComponent(selected.path)}`);
if (!root.isConnected || current !== revision) return;
panel.replaceChildren(renderDocumentationMarkdown(file, documents));
scrollToHeading(fragment);
} catch (error) {
if (root.isConnected && current === revision) setMessage(error.message);
}
}
tabs.addEventListener('click', event => {
const tab = event.target.closest('[data-document-tab]');
if (tab) openDocument(Number(tab.dataset.documentTab));
});
tabs.addEventListener('keydown', event => {
const tab = event.target.closest('[data-document-tab]');
if (!tab) return;
const index = Number(tab.dataset.documentTab);
const next = { ArrowLeft:(index + documents.length - 1) % documents.length, ArrowRight:(index + 1) % documents.length,
Home:0, End:documents.length - 1 }[event.key];
if (next === undefined) return;
event.preventDefault();
tabs.children[next].focus();
openDocument(next);
});
panel.addEventListener('click', event => {
const link = event.target.closest('[data-document-link]');
if (!link) return;
const target = link.dataset.documentLink;
event.preventDefault();
if (target === state.documentationPath) scrollToHeading(link.dataset.documentFragment);
else openDocument(documents.findIndex(document => document.path === target), link.dataset.documentFragment);
});
api('/api/docs').then(catalog => {
if (!root.isConnected) return;
documents = catalog;
if (!documents.length) {
setMessage('Keine Dokumente vorhanden.');
return;
}
tabs.innerHTML = documents.map(({ title }, index) => `<button type="button" class="btn" id="documentation-tab-${index}"
role="tab" aria-controls="documentation-panel" data-document-tab="${index}">${escapeHtml(title)}</button>`).join('');
tabs.hidden = false;
panel.role = 'tabpanel';
panel.tabIndex = 0;
openDocument(Math.max(0, documents.findIndex(document => document.path === state.documentationPath)));
}).catch(error => { if (root.isConnected) setMessage(error.message); });
}
function renderDocumentationMarkdown(file, documents) {
const content = document.createElement('div');
content.className = 'documentation-markdown';
content.innerHTML = window.markdownit({ html:false }).render(file.markdown);
const slugs = new Set();
for (const heading of content.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
const base = heading.textContent.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').trim().replace(/\s+/g, '-') || 'abschnitt';
let slug = base;
for (let suffix = 1; slugs.has(slug); suffix++) slug = `${base}-${suffix}`;
slugs.add(slug);
heading.id = slug;
}
for (const table of content.querySelectorAll('table')) {
const container = document.createElement('div');
container.className = 'table-scroll';
table.replaceWith(container);
container.append(table);
}
const paths = new Set(documents.map(document => document.path));
const localOrigin = 'https://documentation.invalid';
const base = new URL(file.path.split('/').map(encodeURIComponent).join('/'), localOrigin);
for (const link of content.querySelectorAll('a[href]')) {
let url;
try { url = new URL(link.getAttribute('href'), base); }
catch {
link.removeAttribute('href');
continue;
}
if (url.origin === localOrigin) {
try {
const path = decodeURIComponent(url.pathname.slice(1));
if (paths.has(path)) {
link.dataset.documentLink = path;
link.dataset.documentFragment = decodeURIComponent(url.hash.slice(1));
link.href = url.hash || '#';
continue;
}
} catch (error) {
if (!(error instanceof URIError)) throw error;
}
link.removeAttribute('href');
} else if (url.protocol === 'https:' || url.protocol === 'http:') {
link.target = '_blank';
link.rel = 'noopener noreferrer';
} else if (url.protocol !== 'mailto:') link.removeAttribute('href');
}
return content;
}
+160
View File
@@ -0,0 +1,160 @@
function canViewGatewayStatus() {
return can('manage_sources') || can('manage_gateway') || can('manage_integrations');
}
function viewGatewayStatus() {
return `<div id="gateway-status">
<div class="card-head"><span class="note" data-status-time></span><button class="btn" type="button" data-status-refresh>Aktualisieren</button></div>
<div data-status-error role="status"></div>
<div data-status-content class="grid equal"></div>
</div>`;
}
function connectionStatusTag(text, tone = '') {
return `<span class="tag ${tone}">${escapeHtml(text)}</span>`;
}
function statusTime(date) {
if (!date) return '—';
return new Intl.DateTimeFormat('de-DE', { dateStyle:'short', timeStyle:'medium', timeZone:'Europe/Berlin' }).format(new Date(date));
}
function connectionStatusCard(name, tag, content) {
return `<article class="card connection-status-card"><div class="card-head"><h2>${name}</h2>${tag}</div>${content}</article>`;
}
function statusError(text) {
return text ? `<p class="notice red">${escapeHtml(text)}</p>` : '';
}
function renderGatewayStatus(snapshot) {
const cards = [];
const mqtt = snapshot.mqtt;
const bacnet = snapshot.bacnet;
const opc = snapshot.opcUa;
const modbus = snapshot.modbus;
if (mqtt) {
const stateTag = mqtt.connected ? connectionStatusTag('Verbunden') : mqtt.enabled
? connectionStatusTag('Nicht verbunden', 'warn') : connectionStatusTag('Deaktiviert', 'gray');
const lastFailure = mqtt.lastFailure || mqtt.lastError;
cards.push(connectionStatusCard('MQTT', stateTag, `<dl class="connection-facts">
<dt>Broker</dt><dd>${escapeHtml(mqtt.endpoint || '—')}</dd>
<dt>Verbunden seit</dt><dd>${statusTime(mqtt.connectedAtUtc)}</dd>
<dt>Letzter Empfang</dt><dd>${statusTime(mqtt.lastReceivedAtUtc)}</dd>
<dt>Zuletzt gesendet</dt><dd>${statusTime(mqtt.lastPublishedAtUtc)}</dd>
</dl>${lastFailure ? `<p class="note">Letzter Fehler · ${statusTime(mqtt.lastFailureAtUtc)}</p>${statusError(lastFailure)}` : ''}`));
}
if (bacnet) {
cards.push(connectionStatusCard('BACnet/IP', bacnet.connected ? connectionStatusTag('Dienst aktiv') : connectionStatusTag('Dienst nicht erreichbar', 'warn'),
`<dl class="connection-facts"><dt>Letztes Lebenszeichen</dt><dd>${statusTime(bacnet.heartbeatUtc)}</dd>
<dt>Offene Befehle</dt><dd>${bacnet.pendingCommands}</dd></dl>
${bacnet.failedCommands.length ? `<p class="note">Fehlgeschlagene Befehle</p><ul class="connection-issues">${bacnet.failedCommands.map(command => {
const name = state.points.find(point => point.id === command.pointId)?.displayName || command.pointId;
return `<li>${escapeHtml(name)} · ${escapeHtml(command.result)} · ${statusTime(command.occurredAtUtc)}</li>`;
}).join('')}</ul>` : ''}
${bacnet.unsupportedPoints.length ? statusError(`Native Objekte ohne Unterstützung · ${bacnet.unsupportedPoints.map(point => point.displayName).join(', ')}`) : ''}`));
}
if (opc) {
const server = opc.server;
const serverTag = server.listening ? connectionStatusTag(`Server aktiv · TCP ${server.port}`) : opc.serverEnabled
? connectionStatusTag('Server nicht bereit', 'warn') : connectionStatusTag('Server deaktiviert', 'gray');
cards.push(connectionStatusCard('OPC UA', serverTag, `${statusError(server.lastError)}
${opc.clients.length ? `<ul class="connection-issues">${opc.clients.map(client => {
const enabled = opc.clientsEnabled && client.enabled;
const clientState = enabled ? client.status?.state || 'Verbindungsaufbau' : 'Deaktiviert';
const detail = enabled && client.status?.connected ? ` · ${client.status.subscribedPoints} abonniert` : '';
return `<li>${escapeHtml(client.name)} · ${escapeHtml(clientState)}${detail}</li>`;
}).join('')}</ul>` : '<p class="note">Keine Client-Verbindung eingerichtet.</p>'}`));
}
if (modbus) {
cards.push(connectionStatusCard('Modbus TCP / RTU', '', `
${modbus.servers.length ? `<ul class="connection-issues">${modbus.servers.map(server => `<li>
${escapeHtml(server.name)} · TCP ${server.port} · ${server.listening ? 'Lauscht' : 'Nicht bereit'}
${statusError(server.error?.error)}</li>`).join('')}</ul>` : '<p class="note">Kein TCP-Server eingerichtet.</p>'}
${modbus.pointErrors.length ? `<p class="note">Lesefehler</p><ul class="connection-issues">${modbus.pointErrors.map(issue =>
`<li>${escapeHtml(issue.name)} · ${escapeHtml(issue.error)} · ${statusTime(issue.occurredAtUtc)}</li>`).join('')}</ul>` : ''}`));
}
if (snapshot.pointErrors) {
cards.push(connectionStatusCard('Datenpunktqualität', connectionStatusTag(`${snapshot.pointErrors.length} auffällig`, snapshot.pointErrors.length ? 'warn' : 'gray'),
snapshot.pointErrors.length ? `<div class="table-scroll connection-issues"><table><thead><tr><th>Datenpunkt</th><th>Treiber</th><th>Qualität</th><th>Zeit</th></tr></thead>
<tbody>${snapshot.pointErrors.map(point => `<tr><td>${escapeHtml(point.name)}</td><td>${escapeHtml(point.sourceProtocol)}</td><td>${escapeHtml(point.status)}</td><td>${statusTime(point.updatedAtUtc)}</td></tr>`).join('')}</tbody></table></div>`
: '<p class="note">Keine schlechte Qualität gemeldet.</p>'));
}
return cards.join('');
}
function refreshGatewayStatus(panel) {
if (!panel || panel.hidden || !panel.isConnected) return;
panel.dispatchEvent(new Event('refresh-gateway-status'));
}
function bindGatewayStatus() {
const panel = document.querySelector('#point-panel-status');
if (!panel) return;
const button = panel.querySelector('[data-status-refresh]');
const message = panel.querySelector('[data-status-error]');
let timer;
async function refresh() {
clearTimeout(timer);
if (panel.hidden || !panel.isConnected || button.disabled) return;
button.disabled = true;
try {
const snapshot = await api('/api/points/status');
panel.querySelector('[data-status-content]').innerHTML = renderGatewayStatus(snapshot);
panel.querySelector('[data-status-time]').textContent = `Stand ${statusTime(snapshot.checkedAtUtc)}`;
message.textContent = '';
} catch (error) {
message.textContent = error.message;
} finally {
button.disabled = false;
if (!panel.hidden && panel.isConnected) timer = setTimeout(refresh, 10000);
}
}
panel.addEventListener('refresh-gateway-status', refresh);
button.addEventListener('click', refresh);
refresh();
}
function viewInstallationSettings() {
const identity = state.configuration?.installation;
return `<article class="card"><div class="card-head"><h2>Projekt und ISP</h2></div>
<form id="installation-form" class="form">
<div class="row">
<label>Projektnummer<input name="projectNumber" value="${escapeHtml(identity?.projectNumber || 'P')}" maxlength="33" pattern="[Pp][A-Za-z0-9_\\-]{1,32}" required></label>
<label>ISP-Nummer<input name="ispNumber" type="number" min="1" max="99" value="${identity?.ispNumber ?? 1}" required></label>
</div>
<div>Rechnername <code data-installation-host></code></div>
<div class="buttons"><button type="submit" class="btn primary">Projekt und ISP speichern</button></div>
<div id="installation-message" role="status"></div>
</form>
</article>`;
}
function bindInstallationSettings() {
const form = document.querySelector('#installation-form');
if (!form) return;
const fields = form.elements;
const hostname = form.querySelector('[data-installation-host]');
const preview = () => {
hostname.textContent = `SE-UGW-${fields.projectNumber.value.trim().toUpperCase()}-ISP${String(fields.ispNumber.value || '1').padStart(2, '0')}`;
};
form.addEventListener('input', preview);
preview();
form.addEventListener('submit', async event => {
event.preventDefault();
const save = form.querySelector('button[type=submit]');
save.disabled = true;
try {
const installation = await api('/api/gateway/installation', { method:'PUT', body:JSON.stringify({
projectNumber: fields.projectNumber.value, ispNumber: Number(fields.ispNumber.value)
}) });
state.configuration.installation = installation;
fields.projectNumber.value = installation.projectNumber;
fields.ispNumber.value = installation.ispNumber;
preview();
if (can('manage_integrations')) state.mqttMappingDefaults = await api('/api/mqtt/mapping-defaults');
errorTarget('installation-message', 'Projekt und ISP gespeichert.', true);
} catch (error) { errorTarget('installation-message', error.message); }
finally { save.disabled = false; }
});
}
+21 -4
View File
@@ -1,13 +1,30 @@
<!doctype html>
<html lang="de">
<html lang="de" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SEIU Gateway</title>
<link rel="stylesheet" href="/styles.css">
<title>SE-Inno Universalgateway</title>
<script>
try {
const theme = localStorage.getItem('seiugw-theme') || 'dark';
document.documentElement.dataset.theme = theme === 'system' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme === 'light' ? 'light' : 'dark';
} catch { /* Dark is the default when browser storage is unavailable. */ }
</script>
<link rel="stylesheet" href="/styles.css?v=20261009-tabs-1">
<link rel="stylesheet" href="/ltd.css?v=20261124-point-scroll-1">
</head>
<body>
<main id="app" aria-live="polite"></main>
<script src="/app.js" defer></script>
<script src="/ltd.js?v=20261119-status-1" defer></script>
<script src="/network-settings.js?v=20261119-network-1" defer></script>
<script src="/bacnet-browser.js?v=20261119-batch-2" defer></script>
<script src="/mqtt-mapping-form.js?v=20261119-mqtt-template-1" defer></script>
<script src="/gateway-status.js?v=20261119-status-1" defer></script>
<script src="/mapping-batch.js?v=20261124-bulk-selection-1" defer></script>
<script src="/mqtt-topic-browser.js?v=20261119-mqtt-browser-1" defer></script>
<script src="/vendor/markdown-it-15.0.3.min.js" defer></script>
<script src="/documentation.js?v=20261119-docs-1" defer></script>
<script src="/system-update.js?v=20261124-update-availability-1" defer></script>
<script src="/app.js?v=20261124-update-1" defer></script>
</body>
</html>
+183
View File
@@ -0,0 +1,183 @@
/* Layout and palette from SE-LTD, with gateway screens sharing the same shell. */
/* Theme colors live in styles.css only; layout must not overwrite the palette. */
:root { font-family: "Segoe UI", Tahoma, sans-serif; font-size: 12px; }
body { min-width:360px; font-size:12px; }
[hidden] { display:none !important; }
.shell { grid-template-columns:184px minmax(0,1fr); }
.sidebar { position:sticky; top:0; height:100dvh; overflow-y:auto; padding:12px 9px 10px; display:flex; flex-direction:column; border-left:5px solid transparent; border-image:linear-gradient(#ef4444,#dc3b68 55%,#4f8df7) 1; border-right:1px solid var(--line); }
.shell.unpinned .sidebar { position:relative; }
.brand { padding:0 0 12px; gap:8px; font-size:12px; letter-spacing:0; line-height:1.15; border-bottom:1px solid var(--line); margin-bottom:10px; }
.brand-logo { width:32px; height:32px; }
.brand .pin { margin-left:auto; padding:5px 7px; }
.eyebrow { color:#ef4444; font-size:9px; font-weight:400; letter-spacing:.12em; }
.nav { gap:6px; }
.nav button { border:1px solid var(--line); color:var(--text); border-radius:12px; padding:9px 10px; }
.nav button.active { color:#ef4444; background:#ef444412; border-color:#ef444440; box-shadow:none; }
.sidebar-foot { position:static; margin-top:auto; padding:10px 0 0; border-top:1px solid var(--line); gap:8px; }
.sidebar-foot .btn { justify-self:start; }
.sidebar-foot small { font-size:9px; text-align:center; }
.documentation-card { padding:16px 20px; }
.documentation-markdown { max-width:112ch; font-size:13px; line-height:1.6; overflow-wrap:anywhere; }
.documentation-markdown :is(h1,h2,h3,h4,h5,h6) { margin:1.15em 0 .45em; scroll-margin-top:12px; }
.documentation-markdown h1 { font-size:23px; margin-top:0; }
.documentation-markdown h2 { font-size:17px; }
.documentation-markdown h3 { font-size:15px; }
.documentation-markdown p { margin:0 0 10px; }
.documentation-markdown :is(ul,ol) { margin:0 0 12px; padding-left:24px; }
.documentation-markdown li + li { margin-top:3px; }
.documentation-markdown a { color:var(--blue); text-decoration:underline; }
.documentation-markdown hr { border:0; border-top:1px solid var(--line); margin:18px 0; }
.documentation-markdown blockquote { border-left:3px solid var(--blue); margin:10px 0; padding:5px 12px; }
.documentation-markdown pre { overflow:auto; border:1px solid var(--line); border-radius:8px; background:var(--panel-2); padding:10px; }
.documentation-markdown :not(pre) > code { background:var(--panel-2); padding:1px 4px; border-radius:4px; }
.documentation-markdown table { margin:3px 0 10px; }
.documentation-markdown :is(td,th) { text-align:left; vertical-align:top; }
.documentation-markdown img { max-width:100%; }
.theme-control { display:grid; gap:6px; }
.theme-caption { color:var(--muted); font-size:10px; }
.sidebar-foot .theme-toggle { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; }
.sidebar-foot .theme-option { padding:7px 2px; font-size:10px; }
.theme-option.active { background:var(--blue-soft); color:var(--blue); border-color:var(--blue); }
#theme-message:empty { display:none; }
#theme-message { font-size:10px; margin:0; }
.user-caption { display:grid; gap:6px; }
.user-caption strong { color:var(--text); font-size:11px; overflow-wrap:anywhere; }
.content { max-width:none; min-width:0; padding:12px 12px 28px; }
.topline { margin-bottom:10px; min-height:27px; }
h1 { font-size:13px; font-weight:600; letter-spacing:0; }
h2 { font-size:14px; }
.status { font-size:10px; }
.grid { gap:10px; }
.grid.equal { grid-template-columns:repeat(2,minmax(0,1fr)); align-items:start; }
.grid.two { grid-template-columns:minmax(300px,1fr) minmax(0,1.4fr); }
.card { border-radius:14px; padding:12px; min-width:0; background:var(--panel); color:var(--text); box-shadow:0 12px 30px #0000000d; }
.card-head { margin-bottom:10px; }
.card-head .note { margin-top:3px; }
input,select,textarea { border-radius:10px; min-height:34px; padding:7px 10px; }
input[type="checkbox"] { min-height:0; accent-color:#93c5fd; }
input[type="color"] { padding:4px; width:36px; flex:0 0 36px; }
.btn,.theme-option { border-radius:18px; padding:7px 11px; background:transparent; font-size:11px; }
.btn.primary { border-color:transparent; background:linear-gradient(135deg,#ef4444,#b8275a 62%,#4f8df7); }
.btn:disabled { cursor:not-allowed; opacity:.5; }
.tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; }
.tabs .btn { border-radius:12px; min-height:33px; }
.tabs .active { color:#ef4444; border-color:#ef444440; background:#ef444412; }
.protocol-tabs { padding-bottom:10px; border-bottom:1px solid var(--line); }
.protocol-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); }
.protocol-panel { min-width:0; }
.bacnet-layout {
display:grid;
grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);
grid-template-areas:"settings devices" "search devices";
grid-template-rows:auto 1fr;
align-items:start;
gap:10px;
}
#bacnet-browser { display:contents; }
.bacnet-settings { grid-area:settings; }
.bacnet-search { grid-area:search; }
.bacnet-settings .note,.bacnet-search .note { margin:4px 0; }
.bacnet-devices {
grid-area:devices;
position:sticky;
top:12px;
display:flex;
flex-direction:column;
max-height:max(240px,calc(100dvh - 145px));
}
.bacnet-device-scroll {
min-height:0;
overflow:auto;
overscroll-behavior:contain;
scrollbar-color:var(--line-strong) transparent;
}
.bacnet-device-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); padding-top:8px; }
.bacnet-device-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; }
.bacnet-object-panel { min-height:0; display:flex; flex-direction:column; gap:8px; }
.bacnet-object-panel .buttons { flex-wrap:wrap; }
.bacnet-object-panel input[type="checkbox"] { width:auto; }
.mapping-batch { margin-bottom:10px; }
.mapping-batch .point-tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; }
.mapping-batch .point-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); }
.mapping-batch-grid { align-items:start; }
.mapping-batch [data-bulk-modbus]:not([hidden]) { display:grid; gap:8px; }
.bulk-point-list { max-height:36dvh; margin-top:8px; }
.bulk-point-list thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); }
.bulk-point-list td:first-child { width:5rem; }
.bulk-point-list input { width:auto; }
.bulk-point-list tr[data-bulk-point] { cursor:pointer; }
.bulk-point-list tr:has(input:checked) { background:var(--blue-soft); }
[data-bulk-assignments] ul { max-height:24dvh; overflow:auto; overflow-wrap:anywhere; }
.connection-status-card p { margin:6px 0; overflow-wrap:anywhere; }
.connection-facts { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:4px 12px; margin:6px 0; }
.connection-facts dt { color:var(--muted); }
.connection-facts dd { margin:0; overflow-wrap:anywhere; }
.connection-issues { max-height:35dvh; overflow:auto; overflow-wrap:anywhere; }
[data-mqtt-preview] { overflow-wrap:anywhere; }
.mqtt-topic-placeholders { display:flex; flex-wrap:wrap; gap:5px; }
.mqtt-topic-placeholders .btn { display:flex; flex-wrap:wrap; gap:5px; border-radius:8px; }
.mqtt-topic-browser { margin-bottom:10px; }
.mqtt-browser-start { align-self:end; }
.mqtt-browser-content { margin-top:12px; }
.mqtt-browser-selection { margin:8px 0; flex-wrap:wrap; }
.mqtt-topic-tree { max-height:50dvh; min-height:70px; overflow:auto; border:1px solid var(--line); border-radius:10px; margin-top:8px; padding:6px; }
.mqtt-topic-tree ul { padding:0 0 0 16px; margin:0; list-style:none; }
.mqtt-topic-tree > ul { padding-left:0; }
.mqtt-tree-row { display:flex; align-items:center; gap:7px; min-width:0; margin-bottom:3px; }
.mqtt-tree-row .btn { white-space:nowrap; border-radius:7px; text-align:left; padding:4px 7px; }
.mqtt-tree-row input { width:auto; flex:none; }
.mqtt-tree-row .mqtt-topic-value { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.mqtt-topic-item[aria-pressed="true"] { color:var(--blue); border-color:var(--blue); }
.mqtt-topic-detail { border:1px solid var(--line); border-radius:10px; padding:10px; min-width:0; }
.mqtt-topic-detail h3 { margin:0 0 8px; }
.mqtt-topic-preview,.mqtt-topic-path { white-space:pre-wrap; overflow-wrap:anywhere; }
.list { display:grid; gap:4px; }
.list-item { padding:7px 8px; border:1px solid var(--line); border-radius:12px; background:color-mix(in srgb,var(--panel-2) 50%,transparent); display:flex; align-items:center; justify-content:space-between; gap:10px; min-width:0; text-align:left; color:var(--text); }
.list-item strong,.list-item .note { display:block; overflow-wrap:anywhere; }
.list-item.active { border-color:var(--blue); }
.scroll { max-height:60vh; overflow:auto; scrollbar-width:thin; scrollbar-color:var(--line-strong) transparent; }
.alias-table { min-width:860px; }
.alias-table th { text-transform:none; font-size:11px; letter-spacing:0; }
.alias-table td { padding:3px 4px; border:0; vertical-align:middle; }
.alias-table th:first-child,.alias-table td:first-child { color:#ef4444; width:85px; }
.alias-table .color-field { display:flex; align-items:center; gap:6px; }
.alias-table input { min-width:70px; }
.alias-table input[type="color"] { min-width:36px; }
.alias-table td:nth-child(2) { width:32%; }
.alias-table td:nth-child(3) { width:18%; }
.alias-table td:nth-child(4) { width:12%; }
.alias-table td:nth-child(5) { width:12%; }
.alias-table td:nth-child(6) { width:18%; }
.full { grid-column:1/-1; }
.form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
.alarm-destination { border:1px solid var(--line); border-radius:10px; padding:8px; display:grid; gap:8px; }
.chart { display:block; width:100%; height:225px; }
.chart-legend { display:flex; flex-wrap:wrap; gap:10px; color:var(--muted); font-size:11px; }
.chart-legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; }
.widget-grid { margin-top:10px; }
.table-scroll { overflow:auto; }
.point-inventory {
display:flex;
flex-direction:column;
max-height:max(16rem,calc(100dvh - 12rem));
}
.point-inventory-scroll {
min-height:0;
overscroll-behavior:contain;
scrollbar-color:var(--line-strong) transparent;
}
.point-inventory-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); }
.point-inventory-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; }
.empty { text-align:center; padding:28px 10px; }
.runner-columns { min-height:230px; }
details > summary { cursor:pointer; color:var(--muted); padding:7px 0; }
button:focus-visible,a:focus-visible { outline:2px solid var(--blue); outline-offset:2px; }
@media(min-width:1800px) { .alias-table .scroll { max-height:65vh; } }
@media(max-width:1100px) {
.grid.two,.grid.equal { grid-template-columns:1fr; }
.point-inventory { max-height:max(16rem,60dvh); }
.status { max-width:45%; text-align:right; }
.bacnet-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"settings" "search" "devices"; grid-template-rows:auto; }
.bacnet-devices { position:static; max-height:60dvh; }
}
@media(max-width:650px) { .shell { grid-template-columns:145px minmax(0,1fr); } .brand .pin { display:none; } .content { padding:10px 8px; } .form-grid,.row,.row.three { grid-template-columns:1fr; } .topline .status { display:none; } .sidebar { padding:10px 6px; } .brand { font-size:10px; } .card-head { flex-wrap:wrap; } }
+208
View File
@@ -0,0 +1,208 @@
const emptyGuid = '00000000-0000-0000-0000-000000000000';
const trendColors = ['#c9dc1e', '#27e72e', '#12d0d3', '#2362d7', '#502ce2', '#cf177f', '#e61e14', '#ddad31'];
const adminDefinitions = [['aliases','Aliase','edit_aliases'],['units','Einheiten','edit_aliases'],['alarms','Alarme','manage_alarms'],['users','Benutzer','manage_users'],['roles','Rollen','manage_roles'],['api','API','manage_integrations'],['runner','Runner','manage_runner'],['debug','Debug','view_debug']];
function adminTabs() { return adminDefinitions.filter(tab => can(tab[2])); }
function tabBar(tabs, selected, attribute) { return `<nav class="tabs" aria-label="Reiter">${tabs.map(([id, title]) => `<button class="btn ${id === selected ? 'active' : ''}" ${attribute}="${id}" aria-current="${id === selected ? 'page' : 'false'}">${title}</button>`).join('')}</nav>`; }
function bodyOf(markup) { const template = document.createElement('template'); template.innerHTML = markup; template.content.querySelector('.topline')?.remove(); return template.innerHTML; }
function presentation(point, index = 0) { return state.presentation.points.find(item => item.pointId === point.id) || { pointId: point.id, alias: point.displayName, unit: '', factor: 1, kind: /bool|binary/i.test(point.valueType) ? 'digital' : 'analog', color: trendColors[index % trendColors.length] }; }
function pointTitle(point) { return presentation(point).alias; }
function sourceKey(point) { return `${point.protocol} · ${point.scope}`; }
function sourceOptions(selected) { return `<option value="">Alle Quellen</option>${[...new Set(state.points.map(sourceKey))].sort().map(key => `<option ${key === selected ? 'selected' : ''}>${escapeHtml(key)}</option>`).join('')}`; }
function unitOptions(selected) { return `<option value="">—</option>${state.presentation.units.map(unit => `<option value="${escapeHtml(unit.symbol)}" ${selected === unit.symbol ? 'selected' : ''}>${escapeHtml(unit.symbol)} · ${escapeHtml(unit.name)}</option>`).join('')}`; }
function uuid() { return typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)); }
function viewDataPoints() {
const tabs = [...(can('manage_sources') ? [['points','Datenpunkte']] : []), ...(can('manage_gateway') ? [['bacnet','BACnet/IP'], ['opcua','OPC UA'], ['modbus','Modbus TCP / RTU'], ['knx','KNX IP / TP']] : []), ...(can('manage_integrations') ? [['mqtt','MQTT']] : []), ...(can('manage_gateway') ? [['serial','USB / COM']] : [])];
if (canViewGatewayStatus()) tabs.push(['status', 'Status']);
if (!tabs.some(tab => tab[0] === state.pointsTab)) state.pointsTab = tabs[0]?.[0];
const navigation = `<nav class="tabs protocol-tabs" role="tablist" aria-label="Datenpunkte und Protokolle">${tabs.map(([id, title]) => `<button type="button" class="btn ${id === state.pointsTab ? 'active' : ''}" id="point-tab-${id}" role="tab" aria-controls="point-panel-${id}" aria-selected="${id === state.pointsTab}" tabindex="${id === state.pointsTab ? '0' : '-1'}" data-points-tab="${id}">${title}</button>`).join('')}</nav>`;
return `${header('Datenpunkte')}${navigation}${can('manage_sources') ? pointPanel('points',bodyOf(viewPoints())) : ''}${can('manage_gateway') ? bodyOf(viewProtocols()) : ''}${can('manage_integrations') ? pointPanel('mqtt',bodyOf(viewMqtt())) : ''}${canViewGatewayStatus() ? pointPanel('status',viewGatewayStatus()) : ''}`;
}
function pointPanel(id, markup) {
return `<section id="point-panel-${id}" class="protocol-panel" role="tabpanel" aria-labelledby="point-tab-${id}" data-points-panel="${id}" ${id === state.pointsTab ? '' : 'hidden'}>${markup}</section>`;
}
function bindPointTabs() {
const tabs = [...document.querySelectorAll('[data-points-tab]')];
const activate = button => {
state.pointsTab = button.dataset.pointsTab;
tabs.forEach(tab => {
const active = tab === button;
tab.classList.toggle('active',active);
tab.setAttribute('aria-selected',String(active));
tab.tabIndex = active ? 0 : -1;
});
document.querySelectorAll('[data-points-panel]').forEach(panel => { panel.hidden = panel.dataset.pointsPanel !== state.pointsTab; });
if (state.pointsTab === 'status') refreshGatewayStatus(document.querySelector('#point-panel-status'));
};
tabs.forEach((button, index) => {
button.addEventListener('click', () => activate(button));
button.addEventListener('keydown', event => {
const next = { ArrowRight: (index+1)%tabs.length, ArrowLeft: (index+tabs.length-1)%tabs.length, Home: 0, End: tabs.length-1 }[event.key];
if (next === undefined) return;
event.preventDefault();
activate(tabs[next]);
tabs[next].focus();
});
});
}
function viewAdmin() {
const tabs = adminTabs();
if (!tabs.some(tab => tab[0] === state.adminTab)) state.adminTab = tabs[0]?.[0];
const views = { aliases: viewAliases, units: viewUnits, alarms: viewAlarms, users: () => viewSystem('users'), roles: () => viewSystem('roles'), api: viewNotificationKeys, runner: viewLtdRunner, debug: () => viewSystem('debug') };
return `${header('Admin')}${tabBar(tabs,state.adminTab,'data-admin-tab')}${views[state.adminTab]?.() || ''}`;
}
function bindAdmin() {
document.querySelectorAll('[data-admin-tab]').forEach(button => button.addEventListener('click', () => { state.adminTab = button.dataset.adminTab; renderView(); }));
const bindings = { aliases: bindAliases, units: bindUnits, alarms: bindAlarms, api: bindNotificationKeys, runner: bindLtdRunner };
if (bindings[state.adminTab]) bindings[state.adminTab](); else bindView('system');
}
function viewAliases() {
const points = state.points.filter(point => !state.aliasSource || sourceKey(point) === state.aliasSource);
return `<article class="card"><div class="card-head"><div><h2>Aliase</h2><div class="note">Aliase, Einheiten und Farben direkt als CSV importieren oder exportieren. Faktoren gelten für die Anzeige, nicht für Protokollwerte.</div></div><div class="buttons"><button class="btn" id="alias-export">CSV Export</button><button class="btn" id="alias-import">CSV Import</button><input id="alias-file" type="file" accept=".csv,text/csv" hidden></div></div><label>Quelle<select id="alias-source">${sourceOptions(state.aliasSource)}</select></label><form id="aliases-form" class="form" style="margin-top:10px"><div class="scroll"><table class="alias-table"><thead><tr><th>Datenpunkt</th><th>Alias</th><th>Einheit</th><th>Faktor</th><th>Typ</th><th>Farbe</th></tr></thead><tbody>${points.map((point,index) => { const item = presentation(point,index); return `<tr data-alias-row="${point.id}"><td title="${escapeHtml(point.id)}">${escapeHtml(point.bacnetObjectInstance ?? `Wert ${state.points.indexOf(point)+1}`)}</td><td><input name="alias" aria-label="Alias" value="${escapeHtml(item.alias)}" required maxlength="160"></td><td><select name="unit" aria-label="Einheit">${unitOptions(item.unit)}</select></td><td><input name="factor" aria-label="Faktor" type="number" step="any" value="${item.factor}" required></td><td><select name="kind" aria-label="Typ"><option ${item.kind === 'analog' ? 'selected' : ''}>analog</option><option ${item.kind === 'digital' ? 'selected' : ''}>digital</option></select></td><td><div class="color-field"><input type="color" name="color" aria-label="Farbe" value="${item.color}"><input name="colorText" aria-label="Hex-Farbe" value="${item.color}" pattern="#[0-9a-fA-F]{6}" required></div></td></tr>`; }).join('')}</tbody></table>${points.length ? '' : '<div class="empty">Noch keine Datenpunkte in dieser Quelle.</div>'}</div><div class="buttons"><button class="btn primary" ${points.length ? '' : 'disabled'}>Aliase speichern</button></div><div id="aliases-message"></div></form></article>`;
}
function collectAliases() { return [...document.querySelectorAll('[data-alias-row]')].map(row => ({ pointId: row.dataset.aliasRow, alias: row.querySelector('[name=alias]').value, unit: row.querySelector('[name=unit]').value, factor: Number(row.querySelector('[name=factor]').value), kind: row.querySelector('[name=kind]').value, color: row.querySelector('[name=colorText]').value })); }
function bindAliases() {
document.querySelector('#alias-source').addEventListener('change', event => { state.aliasSource = event.target.value; renderView(); });
document.querySelectorAll('[data-alias-row]').forEach(row => {
row.querySelector('[name=color]').addEventListener('input', event => { row.querySelector('[name=colorText]').value = event.target.value; });
row.querySelector('[name=colorText]').addEventListener('input', event => { if (/^#[\da-f]{6}$/i.test(event.target.value)) row.querySelector('[name=color]').value = event.target.value; });
});
document.querySelector('#aliases-form').addEventListener('submit', async event => { event.preventDefault(); try { await api('/api/presentation/points', { method:'PUT', body:JSON.stringify(collectAliases()) }); await loadData(); errorTarget('aliases-message','Aliase gespeichert.',true); } catch(error) { errorTarget('aliases-message',error.message); } });
document.querySelector('#alias-export').addEventListener('click', () => { const lines = [['pointId','alias','unit','factor','kind','color'], ...collectAliases().map(item => [item.pointId,item.alias,item.unit,item.factor,item.kind,item.color])]; downloadText('\uFEFF'+lines.map(row => row.map(csvCell).join(';')).join('\r\n'),'gateway-aliase.csv','text/csv;charset=utf-8'); });
document.querySelector('#alias-import').addEventListener('click', () => document.querySelector('#alias-file').click());
document.querySelector('#alias-file').addEventListener('change', async event => {
try {
const file = event.target.files[0]; if (!file) return;
if (file.size > 4*1024*1024) throw new Error('CSV ist zu groß (max. 4 MB).');
const rows = parseAliasCsv(await file.text());
if (!rows.length) throw new Error('Keine Alias-Zeilen gefunden.');
if (!window.confirm(`${rows.length} Aliase aus der CSV übernehmen?`)) return;
await api('/api/presentation/points',{method:'PUT',body:JSON.stringify(rows)}); await loadData(); renderView(); errorTarget('aliases-message',`${rows.length} Aliase importiert.`,true);
} catch(error) { errorTarget('aliases-message',error.message); }
});
}
function csvCell(value) { const raw=String(value); return '"'+raw.replace(/"/g,'""')+'"'; }
function parseAliasCsv(text) {
const lines=[]; let row=[],cell='',quoted=false; text=text.replace(/^\uFEFF/,'');
for(let i=0;i<text.length;i++) { const c=text[i]; if(c==='"') { if(quoted && text[i+1]==='"') {cell+='"';i++;} else quoted=!quoted; } else if(c===';'&&!quoted) {row.push(cell);cell='';} else if((c==='\r'||c==='\n')&&!quoted) { if(c==='\r'&&text[i+1]==='\n')i++;row.push(cell);if(row.some(Boolean))lines.push(row);row=[];cell=''; } else cell+=c; }
if(quoted)throw new Error('Nicht geschlossenes Anführungszeichen in der CSV.');
row.push(cell);if(row.some(Boolean))lines.push(row);
const headings=lines.shift(); if(headings?.join(';')!=='pointId;alias;unit;factor;kind;color')throw new Error('Spalten: pointId;alias;unit;factor;kind;color. Bitte CSV Export als Vorlage verwenden.');
return lines.map((cells,index)=> { if(cells.length!==6)throw new Error(`CSV-Zeile ${index+2}: sechs Spalten erwartet.`); return {pointId:cells[0],alias:cells[1],unit:cells[2],factor:Number(cells[3].replace(',','.')),kind:cells[4],color:cells[5]}; });
}
function downloadText(text,name,type) { const url=URL.createObjectURL(new Blob([text],{type})); const link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); }
function viewUnits() { return `<article class="card"><div class="card-head"><div><h2>Einheiten</h2><div class="note">Einheiten zentral verwalten und bei Aliasen auswählen.</div></div><button class="btn" id="new-unit">Neue Einheit</button></div><form id="unit-form" class="form"><div class="row"><label>Symbol<input name="symbol" placeholder="z. B. bar" required maxlength="24"></label><label>Bezeichnung<input name="name" placeholder="z. B. Bar" required maxlength="100"></label></div><div class="buttons"><button class="btn" type="reset">Zurücksetzen</button><button class="btn primary">Einheit speichern</button></div><div id="unit-message"></div></form><div class="list">${state.presentation.units.map((unit,index)=>`<div class="list-item"><div><strong>${escapeHtml(unit.symbol)}</strong><span class="note">${escapeHtml(unit.name)}<br>${unit.isSystem?'Systemeinheit':'Eigene Einheit'}</span></div><button class="btn" data-edit-unit="${index}">Bearbeiten</button></div>`).join('')}</div></article>`; }
function bindUnits() {
const form=document.querySelector('#unit-form');
document.querySelector('#new-unit').addEventListener('click',()=>{form.reset();form.elements.symbol.focus();});
document.querySelectorAll('[data-edit-unit]').forEach(button=>button.addEventListener('click',()=>{const unit=state.presentation.units[Number(button.dataset.editUnit)];form.elements.symbol.value=unit.symbol;form.elements.name.value=unit.name;form.elements.name.focus();}));
form.addEventListener('submit',async event=>{event.preventDefault();try{await api('/api/presentation/units',{method:'PUT',body:JSON.stringify({symbol:form.elements.symbol.value,name:form.elements.name.value})});await loadData();renderView();}catch(error){errorTarget('unit-message',error.message);}});
}
function viewNotificationKeys() {
const labels={Mail:'Mail',WhatsApp:'WhatsApp · nur Alarme',Ntfy:'ntfy · nur Alarme'};
return `<section class="grid equal">${state.notifications.map(item=>`<article class="card"><div class="card-head"><h2>${labels[item.channel]}</h2><span class="tag ${item.hasApiKey?'':'gray'}">${item.hasApiKey?'Key gespeichert':'nicht freigeschaltet'}</span></div><form class="form" data-key-form="${item.channel}"><label>API-Key<input name="apiKey" type="password" autocomplete="new-password" placeholder="leer lassen = unverändert"></label><label class="switch"><input name="clearApiKey" type="checkbox"> Key löschen und Versand sperren</label><div class="note">${escapeHtml(item.endpoint)}</div><div class="buttons"><button class="btn primary">Speichern</button></div><div id="key-${item.channel}-message"></div></form></article>`).join('')}${can('manage_gateway')?`<article class="card"><div class="card-head"><h2>Komari</h2><span class="tag ${state.komari?.hasEnrollmentToken?'':'gray'}">${state.komari?.hasEnrollmentToken?'Key gespeichert':'kein Key'}</span></div><form id="komari-form" class="form"><label>Registrierungsschlüssel<input name="enrollmentToken" type="password" required minlength="8" maxlength="1024" autocomplete="new-password"></label><div class="note">Verschlüsselt in der Datenbank. Alternativ über die serverseitige Token-Datei importierbar.</div><div class="buttons"><button class="btn primary">Schlüssel ersetzen</button></div><div id="komari-message"></div></form></article>`:''}</section><p class="note">Gespeicherte Schlüssel werden nicht an den Browser zurückgegeben. Die API-Annahme einer Nachricht bestätigt noch keine Zustellung beim Empfänger.</p>`;
}
function bindNotificationKeys() {
document.querySelectorAll('[data-key-form]').forEach(form=>form.addEventListener('submit',async event=>{event.preventDefault();const channel=form.dataset.keyForm;try{const clearApiKey=form.elements.clearApiKey.checked;if(clearApiKey&&!window.confirm('Key löschen? Dieser Kanal sendet anschließend keine Nachrichten mehr.'))return;await api(`/api/integrations/notifications/${channel}`,{method:'PUT',body:JSON.stringify({apiKey:form.elements.apiKey.value||null,clearApiKey})});form.elements.apiKey.value='';await loadData();renderView();errorTarget(`key-${channel}-message`,'Gespeichert.',true);}catch(error){errorTarget(`key-${channel}-message`,error.message);}}));
document.querySelector('#komari-form')?.addEventListener('submit',async event=>{event.preventDefault();try{await api('/api/system/komari',{method:'PUT',body:JSON.stringify({enrollmentToken:event.currentTarget.elements.enrollmentToken.value})});await loadData();renderView();errorTarget('komari-message','Schlüssel verschlüsselt gespeichert.',true);}catch(error){errorTarget('komari-message',error.message);}});
}
function viewAlarms() {
const edit=state.alarms.find(rule=>rule.id===state.alarmEditId);
const point=state.points.find(item=>item.id===(edit?.pointId||state.alarmPointId));
const available=state.points.filter(item=>item.readable&&(!state.alarmSource||sourceKey(item)===state.alarmSource));
const rules=state.alarms.filter(rule=>!state.alarmSource||sourceKey(state.points.find(p=>p.id===rule.pointId)||{})===state.alarmSource);
return `<article class="card"><div class="card-head"><div><h2>Alarme</h2><div class="note">Datenpunkte unabhängig vom Trendlogging überwachen.</div></div><button class="btn" id="alarm-refresh">Aktualisieren</button></div><div class="grid equal"><div><h2>Quellen</h2><label>Aktive Quelle<select id="alarm-source">${sourceOptions(state.alarmSource)}</select></label></div><label>Suche<input id="alarm-search" placeholder="Alias, Datenpunkt oder Protokoll"></label><section><div class="card-head"><h2>Verfügbare Datenpunkte</h2><span class="tag gray">${available.length}</span></div><div class="list scroll">${available.map(item=>`<div class="list-item" data-alarm-search="${escapeHtml((pointTitle(item)+' '+item.displayName+' '+item.protocol).toLowerCase())}"><div><strong>${escapeHtml(pointTitle(item))}</strong><span class="note">${escapeHtml(item.protocol)} · ${escapeHtml(item.scope)}</span></div><button class="btn primary" data-add-alarm="${item.id}">Ins Alarming</button></div>`).join('')||'<div class="empty">Keine lesbaren Datenpunkte.</div>'}</div></section><section><div class="card-head"><h2>Wird alarmiert</h2><span class="tag gray">${rules.length}</span></div><div class="list scroll">${rules.map(rule=>`<div class="list-item"><div><strong>${escapeHtml(rule.name)}</strong><span class="note">${escapeHtml(state.points.find(p=>p.id===rule.pointId)?.displayName||rule.pointId)} · ${rule.enabled?'aktiv':'inaktiv'}<br>${rule.destinations.map(d=>escapeHtml(d.channel+' → '+d.recipient)).join(' · ')}</span></div><div class="buttons"><button class="btn" data-edit-alarm="${rule.id}">Bearbeiten</button><button class="btn danger" data-delete-alarm="${rule.id}">Löschen</button></div></div>`).join('')||'<div class="empty">Noch kein Datenpunkt im Alarming.</div>'}</div></section></div></article>${point?alarmEditor(point,edit):''}<article class="card" style="margin-top:10px"><div class="card-head"><h2>Versandstatus</h2></div><div class="table-scroll scroll"><table><thead><tr><th>Zeit</th><th>Meldung</th><th>Kanal</th><th>Status</th></tr></thead><tbody>${state.deliveries.map(item=>`<tr><td>${escapeHtml(new Date(item.createdAtUtc).toLocaleString('de-DE'))}</td><td>${escapeHtml(item.title)}</td><td>${escapeHtml(item.destination.channel)}</td><td>${escapeHtml(deliveryState(item.state))}${item.result?`<div class="note">${escapeHtml(item.result)}</div>`:''}</td></tr>`).join('')}</tbody></table>${state.deliveries.length?'':'<div class="empty">Noch keine Meldungen.</div>'}</div></article>`;
}
function deliveryState(value) { return ({Pending:'Wartend',Sending:'Wird gesendet',Accepted:'Von API angenommen',Failed:'Fehlgeschlagen',Unknown:'Unklar – kein automatischer Neuversand',Blocked:'Kanal gesperrt',Cancelled:'Abgebrochen'})[value]||value; }
function alarmEditor(point,rule) {
const destinations=rule?.destinations||[];
return `<article class="card" style="margin-top:10px" id="alarm-editor"><div class="card-head"><h2>${rule?'Alarm bearbeiten':'Alarm anlegen'} · ${escapeHtml(pointTitle(point))}</h2><button class="btn" id="alarm-cancel">Schließen</button></div><form id="alarm-form" class="form"><div class="row"><label>Name<input name="name" value="${escapeHtml(rule?.name||pointTitle(point))}" required maxlength="120"></label><label>Bedingung<select name="condition">${[['Active','Aktiv / ungleich 0'],['Inactive','Inaktiv / gleich 0'],['Above','Über Grenzwert'],['Below','Unter Grenzwert']].map(([value,label])=>`<option value="${value}" ${rule?.condition===value?'selected':''}>${label}</option>`).join('')}</select></label></div><div class="row"><label>Grenzwert<input name="threshold" type="number" step="any" value="${rule?.threshold??0}" required></label><label>Hysterese<input name="hysteresis" type="number" min="0" step="any" value="${rule?.hysteresis??0}" required></label></div><label>Meldung<textarea name="message" maxlength="8000">${escapeHtml(rule?.message||'')}</textarea></label><div class="row"><label class="switch"><input name="enabled" type="checkbox" ${!rule||rule.enabled?'checked':''}> aktiv</label><label class="switch"><input name="notifyRecovery" type="checkbox" ${rule?.notifyRecovery?'checked':''}> Entwarnung senden</label></div><div class="grid equal">${['Mail','WhatsApp','Ntfy'].map(channel=>{ const dest=destinations.find(item=>item.channel===channel),ready=state.notifications.find(item=>item.channel===channel)?.hasApiKey;return `<fieldset class="alarm-destination" data-destination="${channel}"><legend>${channel}</legend><label class="switch"><input name="use" type="checkbox" ${dest?'checked':''} ${ready?'':'disabled'}> ${ready?'Versand aktivieren':'Kein API-Key – unter Admin → API freischalten'}</label><label>${channel==='Mail'?'E-Mail-Adresse':channel==='WhatsApp'?'Rufnummer (+49…)':'Topic'}<input name="recipient" value="${escapeHtml(dest?.recipient||'')}" ${channel==='Mail'?'type="email"':''}></label>${channel==='WhatsApp'?`<div class="row"><label>Genehmigte Vorlage<select name="template">${['infomessagegroup','infoapp','meldung','stoerung','se_portal_admin','contact_form','se_portal_manage','se_portal'].map(template=>`<option ${template===(dest?.template||'stoerung')?'selected':''}>${template}</option>`).join('')}</select></label><label>pn<input name="pn" value="${escapeHtml(dest?.personName||'SE-Inno')}" maxlength="60"></label></div><div class="note">Vorlagenparameter: Zeilenumbrüche und Tabs werden zu Leerzeichen. Unicode bleibt erhalten. Max. 1024 Zeichen je Meldungsparameter.</div>`:channel==='Ntfy'?`<div class="row"><label>Priorität<select name="priority">${[0,1,2,3,4,5].map(n=>`<option ${n===(dest?.priority??0)?'selected':''}>${n}</option>`).join('')}</select></label><label>Tags<input name="tags" value="${escapeHtml(dest?.tags||'alarm')}" maxlength="200"></label></div>`:''}</fieldset>`;}).join('')}</div><div class="note">Versand nur bei Zustandswechsel. Grenzwerte beziehen sich auf den unveränderten Datenpunktwert. Keine automatische Wiederholung bei unklarem Versandstatus.</div><div class="buttons"><button class="btn primary">Alarm speichern</button></div><div id="alarm-message"></div></form></article>`;
}
function bindAlarms() {
document.querySelector('#alarm-source').addEventListener('change',event=>{state.alarmSource=event.target.value;renderView();});
document.querySelector('#alarm-search').addEventListener('input',event=>{const search=event.target.value.toLowerCase();document.querySelectorAll('[data-alarm-search]').forEach(row=>{row.hidden=!row.dataset.alarmSearch.includes(search);});});
document.querySelector('#alarm-refresh').addEventListener('click',async()=>{try{await loadData();renderView();}catch(error){window.alert(error.message);}});
document.querySelectorAll('[data-add-alarm]').forEach(button=>button.addEventListener('click',()=>{state.alarmPointId=button.dataset.addAlarm;state.alarmEditId=null;renderView();document.querySelector('#alarm-editor').scrollIntoView({block:'start',behavior:'smooth'});}));
document.querySelectorAll('[data-edit-alarm]').forEach(button=>button.addEventListener('click',()=>{state.alarmEditId=button.dataset.editAlarm;renderView();document.querySelector('#alarm-editor').scrollIntoView({block:'start',behavior:'smooth'});}));
document.querySelectorAll('[data-delete-alarm]').forEach(button=>button.addEventListener('click',async()=>{if(!window.confirm('Alarmregel löschen und noch wartende Meldungen verwerfen?'))return;try{await api(`/api/alarms/${button.dataset.deleteAlarm}`,{method:'DELETE'});state.alarmEditId=null;state.alarmPointId=null;await loadData();renderView();}catch(error){window.alert(error.message);}}));
document.querySelector('#alarm-cancel')?.addEventListener('click',()=>{state.alarmEditId=null;state.alarmPointId=null;renderView();});
document.querySelector('#alarm-form')?.addEventListener('submit',async event=>{
event.preventDefault();const form=new FormData(event.currentTarget),edit=state.alarms.find(rule=>rule.id===state.alarmEditId);
const destinations=[...document.querySelectorAll('[data-destination]')].filter(field=>field.querySelector('[name=use]').checked&&!field.querySelector('[name=use]').disabled).map(field=>({channel:field.dataset.destination,recipient:field.querySelector('[name=recipient]').value,template:field.querySelector('[name=template]')?.value||'stoerung',personName:field.querySelector('[name=pn]')?.value||'SE-Inno',priority:Number(field.querySelector('[name=priority]')?.value||0),tags:field.querySelector('[name=tags]')?.value||'alarm'}));
try{await api('/api/alarms',{method:'PUT',body:JSON.stringify({id:edit?.id||emptyGuid,name:form.get('name'),pointId:edit?.pointId||state.alarmPointId,condition:form.get('condition'),threshold:Number(form.get('threshold')),hysteresis:Number(form.get('hysteresis')),enabled:form.has('enabled'),notifyRecovery:form.has('notifyRecovery'),message:form.get('message'),destinations})});state.alarmPointId=null;state.alarmEditId=null;await loadData();renderView();}catch(error){errorTarget('alarm-message',error.message);}
});
}
function viewDashboard() {
return `${header('Dashboard')}<section class="grid equal"><article class="card"><div class="card-head"><div><h2>Widget</h2><div class="note">Aus einer gespeicherten Trend-Auswahl.</div></div></div><form id="widget-form" class="form"><div class="row"><label>Titel<input name="title" required maxlength="120"></label><label>Typ<select name="type"><option value="Graph">Graph</option><option value="Values">Werte</option></select></label></div><div class="row"><label>Quelle<select name="selectionId" required><option value="">Auswahl wählen</option>${state.trendSelections.map(item=>`<option value="${item.id}">${escapeHtml(item.name)}</option>`).join('')}</select></label><label>Zeitraum<select name="rangeHours"><option value="24">24 h</option><option value="48">48 h</option><option value="168">7 Tage</option><option value="720">30 Tage</option></select></label></div><div class="buttons"><button class="btn primary" ${state.trendSelections.length&&can('view_trends')?'':'disabled'}>Widget übernehmen</button></div><div id="widget-message"></div></form></article><article class="card"><div class="card-head"><div><h2>Auswahlen</h2><div class="note">Gespeicherte Punktgruppen für Trend und Dashboard.</div></div></div><div class="list">${state.trendSelections.map(selection=>`<div class="list-item"><button class="btn" data-select-widget="${selection.id}">${escapeHtml(selection.name)} <span class="note">${selection.trendLogIds.length} Punkte</span></button>${selection.ownerId===state.user?.user?.id||state.user?.user?.role==='admin'?`<button class="btn danger" title="Auswahl löschen" data-delete-selection="${selection.id}">×</button>`:''}</div>`).join('')||'<div class="empty">Noch keine Auswahl. Im Reiter Trend eine Gruppe speichern.</div>'}</div></article></section><section class="grid equal widget-grid">${state.dashboard.map(widget=>`<article class="card"><div class="card-head"><h2>${escapeHtml(widget.title)}</h2><div class="buttons"><span class="note">${widget.rangeHours} h</span><button class="btn danger" data-remove-widget="${widget.id}" title="Widget entfernen">×</button></div></div><div data-widget="${widget.id}" class="chart-container"><div class="empty">Daten werden geladen …</div></div></article>`).join('')}</section>`;
}
function bindDashboard() {
document.querySelector('#widget-form').addEventListener('submit',async event=>{event.preventDefault();const form=new FormData(event.currentTarget);try{const next=[...state.dashboard,{id:uuid(),title:form.get('title'),type:form.get('type'),selectionId:form.get('selectionId'),rangeHours:Number(form.get('rangeHours'))}];await api('/api/dashboard',{method:'PUT',body:JSON.stringify(next)});state.dashboard=next;renderView();}catch(error){errorTarget('widget-message',error.message);}});
document.querySelectorAll('[data-select-widget]').forEach(button=>button.addEventListener('click',()=>{const form=document.querySelector('#widget-form');form.elements.selectionId.value=button.dataset.selectWidget;form.elements.title.value=state.trendSelections.find(item=>item.id===button.dataset.selectWidget)?.name||'';}));
document.querySelectorAll('[data-delete-selection]').forEach(button=>button.addEventListener('click',deleteTrendSelection));
document.querySelectorAll('[data-remove-widget]').forEach(button=>button.addEventListener('click',async()=>{try{const next=state.dashboard.filter(item=>item.id!==button.dataset.removeWidget);await api('/api/dashboard',{method:'PUT',body:JSON.stringify(next)});state.dashboard=next;renderView();}catch(error){errorTarget('widget-message',error.message);}}));
state.dashboard.forEach(widget=>loadWidget(widget,document.querySelector(`[data-widget="${widget.id}"]`)));
}
async function loadWidget(widget,target) {
try {
if(!can('view_trends'))throw new Error('Keine Berechtigung für Trenddaten.');
const selection=widget.singleTrendLogId?{trendLogIds:[widget.singleTrendLogId]}:state.trendSelections.find(item=>item.id===widget.selectionId);if(!selection)throw new Error('Auswahl nicht mehr verfügbar.');
const start=Date.now()-widget.rangeHours*3600000;
const series=await Promise.all(selection.trendLogIds.map(async(id,index)=>{const log=state.trendLogs.find(item=>item.id===id); const point=state.points.find(item=>item.id===log?.sourcePointId);const style=point?presentation(point,index):state.presentation.points.find(item=>item.pointId===log?.sourcePointId);const records=await api(`/api/trend-logs/${id}/records?limit=2000`);return {name:style?.alias||log?.name||id,color:style?.color||trendColors[index%trendColors.length],unit:style?.unit||'',digital:style?.kind==='digital',values:records.filter(row=>Date.parse(row.timestampUtc)>=start&&(typeof row.value==='number'||typeof row.value==='boolean')&&(!row.status||['good','ok'].includes(row.status.toLowerCase()))).map(row=>({t:Date.parse(row.timestampUtc),y:Number(row.value)*(style?.factor??1)})).sort((a,b)=>a.t-b.t)};}));
if(!target?.isConnected)return;
if(!series.some(item=>item.values.length)){target.innerHTML='<div class="empty">Keine numerischen Trendwerte in diesem Zeitraum.</div>';return;}
if(widget.type==='Values') {target.innerHTML=`<div class="list">${series.map(item=>`<div class="list-item"><strong>${escapeHtml(item.name)}</strong><span>${item.values.length?escapeHtml(item.values.at(-1).y.toLocaleString('de-DE')):'—'} ${escapeHtml(item.unit)}</span></div>`).join('')}</div>`;return;}
target.innerHTML=`<canvas class="chart" role="img" aria-label="Trendverlauf"></canvas><div class="chart-legend">${series.map(item=>`<span><i style="background:${item.color}"></i>${escapeHtml(item.name)} ${escapeHtml(item.unit)}</span>`).join('')}</div><div class="note">Bis zu 2.000 letzte Werte je Trend. Unterschiedliche Einheiten teilen sich hier eine Achse.</div>`;
drawTrendChart(target.querySelector('canvas'),series,start,Date.now());
} catch(error) { if(target?.isConnected){target.innerHTML='<div class="empty"></div>';target.firstElementChild.textContent=error.message;} }
}
function drawTrendChart(canvas,series,start,end) {
const width=canvas.clientWidth||700,height=225,ratio=window.devicePixelRatio||1;canvas.width=width*ratio;canvas.height=height*ratio;const ctx=canvas.getContext('2d');ctx.scale(ratio,ratio);
let min=Infinity,max=-Infinity;for(const item of series)for(const point of item.values){min=Math.min(min,point.y);max=Math.max(max,point.y);}if(min===max){min-=1;max+=1;}
const x=t=>50+(t-start)/(end-start)*(width-66),y=value=>12+(max-value)/(max-min)*180;
ctx.font='10px Segoe UI';ctx.fillStyle=getComputedStyle(canvas).getPropertyValue('--muted');ctx.strokeStyle='#71809633';
for(let i=0;i<=4;i++){const value=min+(max-min)*i/4,pos=y(value);ctx.beginPath();ctx.moveTo(49,pos);ctx.lineTo(width-10,pos);ctx.stroke();ctx.fillText(value.toLocaleString('de-DE',{maximumFractionDigits:2}),1,pos+3);}
ctx.fillText(new Date(start).toLocaleString('de-DE',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}),50,215);ctx.textAlign='right';ctx.fillText(new Date(end).toLocaleTimeString('de-DE'),width-10,215);
for(const item of series){ctx.strokeStyle=item.color;ctx.fillStyle=item.color;ctx.lineWidth=Number(state.preferences?.trendLineWidth||1.8);ctx.beginPath();item.values.forEach((point,i)=>{if(!i)ctx.moveTo(x(point.t),y(point.y));else {if(item.digital)ctx.lineTo(x(point.t),y(item.values[i-1].y));ctx.lineTo(x(point.t),y(point.y));}});ctx.stroke();if(item.values.length===1){ctx.beginPath();ctx.arc(x(item.values[0].t),y(item.values[0].y),3,0,Math.PI*2);ctx.fill();}}
}
function bindTrendViewer() {
const target=document.createElement('article');target.className='card';target.style.marginBottom='10px';
target.innerHTML=`<div class="card-head"><h2>Trend</h2><a class="btn" href="/public-trends.html" target="_blank" rel="noopener">Öffentliche Trends</a></div><div class="row"><label>Datenreihe<select id="trend-view-log">${state.trendLogs.map(log=>`<option value="${log.id}">${escapeHtml(log.name)}</option>`).join('')}</select></label><label>Zeitraum<select id="trend-view-hours"><option value="24">24 h</option><option value="168">7 Tage</option><option value="720">30 Tage</option></select></label></div><div id="trend-view-chart"></div>`;
document.querySelector('#content .topline').after(target);
const update=()=>{const id=document.querySelector('#trend-view-log').value;if(id)loadWidget({singleTrendLogId:id,rangeHours:Number(document.querySelector('#trend-view-hours').value),type:'Graph'},document.querySelector('#trend-view-chart'));else document.querySelector('#trend-view-chart').innerHTML='<div class="empty">Noch keine Trenddaten.</div>';};
document.querySelector('#trend-view-log').addEventListener('change',update);document.querySelector('#trend-view-hours').addEventListener('change',update);update();
}
function viewLtdRunner() {
const job=state.runnerJobs.find(item=>item.id===state.runnerEditId);
const mailReady=state.notifications.find(item=>item.channel==='Mail')?.hasApiKey;
const fields=job||{name:'',selectionId:'',time:'06:00',rangeHours:24,delimiter:';',enabled:true,mailEnabled:false,mailTo:'',mailSubject:'Trenddaten',mailMessage:'Automatischer Export aus SE-Inno Universalgateway.'};
return `<article class="card"><div class="card-head"><div><h2>CSV-Runner</h2><div class="note">Gespeicherte Auswahlen automatisch als CSV ins Dateisystem exportieren und optional per Mail verschicken.</div></div><button class="btn" id="new-runner">Neuer Job</button></div><form id="runner-form" class="form-grid"><label>Name<input name="name" value="${escapeHtml(fields.name)}" placeholder="Tagesexport Lüftung" maxlength="120" required></label><label>Auswahl<select name="selectionId" required><option value="">Auswahl wählen</option>${state.trendSelections.map(item=>`<option value="${item.id}" ${item.id===fields.selectionId?'selected':''}>${escapeHtml(item.name)}</option>`).join('')}</select></label><label>Uhrzeit (deutsch)<input name="time" type="time" value="${fields.time}" required><span class="note">Format HH:MM Uhr, Zeitzone Europe/Berlin.</span></label><label>Zeitraum<select name="rangeHours">${[24,48,168,720].map(hours=>`<option value="${hours}" ${hours===fields.rangeHours?'selected':''}>letzte ${hours<168?hours+' h':hours/24+' Tage'}</option>`).join('')}</select></label><label>CSV-Trennzeichen<select name="delimiter">${[[';','Semikolon ;'],[',','Komma ,'],['\t','Tabulator']].map(([value,label])=>`<option value="${value}" ${value===fields.delimiter?'selected':''}>${label}</option>`).join('')}</select></label><label class="switch"><input name="enabled" type="checkbox" ${fields.enabled?'checked':''}> aktiv</label><label class="switch"><input name="mailEnabled" type="checkbox" ${fields.mailEnabled?'checked':''} ${mailReady?'':'disabled'}> CSV per Mail verschicken ${mailReady?'':'(API-Key fehlt)'}</label><label>Mail an<input name="mailTo" value="${escapeHtml(fields.mailTo||'')}" placeholder="kunde@example.com; service@example.com"><span class="note">Mehrere Empfänger mit Semikolon oder Komma trennen.</span></label><label>Betreff<input name="mailSubject" value="${escapeHtml(fields.mailSubject)}"></label><label class="full">Nachricht<input name="mailMessage" value="${escapeHtml(fields.mailMessage)}"></label><div class="buttons full"><button class="btn primary">${job?'Runner speichern':'Runner-Job anlegen'}</button></div><div id="runner-message" class="full"></div></form><section class="grid equal runner-columns" style="margin-top:10px"><article class="card"><div class="card-head"><h2>Vorhandene Runner</h2><span>${state.runnerJobs.length}</span></div><div class="list">${state.runnerJobs.map(item=>`<div class="list-item"><div><strong>${escapeHtml(item.name)}</strong><span class="note">${escapeHtml(state.trendSelections.find(selection=>selection.id===item.selectionId)?.name||'Auswahl fehlt')} · ${item.time} Uhr · ${item.enabled?'aktiv':'inaktiv'}<br>${item.lastResult?escapeHtml(item.lastResult.success?'Letzter Lauf: '+new Date(item.lastResult.ranAtUtc).toLocaleString('de-DE'):item.lastResult.error||'Fehler'):'Noch nicht gelaufen'}</span></div><div class="buttons"><button class="btn" data-test-runner="${item.id}">Test</button><button class="btn" data-edit-runner="${item.id}">Bearbeiten</button><button class="btn" data-delete-runner="${item.id}">Löschen</button></div></div>`).join('')||'<div class="empty">Keine Runner angelegt.</div>'}</div></article><article class="card"><div class="card-head"><h2>Ausführung</h2></div><div id="runner-execution" class="empty">Geplante Jobs werden zur eingestellten Uhrzeit ausgeführt. Der letzte Lauf steht beim jeweiligen Job.</div></article></section></article>`;
}
function bindLtdRunner() {
const status = document.querySelector('#runner-execution');
status.parentElement.querySelector('h2').textContent = 'Warteschlange';
const queue = document.createElement('div');
queue.id = 'runner-queue';
status.before(queue);
status.textContent = '';
const refreshQueue = async () => {
try {
const items = await api('/api/runner/queue');
if (!queue.isConnected) return;
queue.innerHTML = items.length ? `<div class="list">${items.map(item => `<div class="list-item"><div><strong>${escapeHtml(item.name)}</strong><span class="note">${item.state === 'Running' ? 'Wird ausgeführt' : 'Wartend'} · ${escapeHtml(new Date(item.enqueuedAtUtc).toLocaleTimeString('de-DE'))}</span></div></div>`).join('')}</div>` : '<div class="empty">Keine Aufträge warten auf die Ausführung.</div>';
} catch (error) { if (queue.isConnected) queue.textContent = error.message; }
};
refreshQueue();
const timer = setInterval(() => { if (!queue.isConnected) clearInterval(timer); else refreshQueue(); }, 2000);
document.querySelector('#new-runner').addEventListener('click',()=>{state.runnerEditId=null;renderView();});
document.querySelectorAll('[data-edit-runner]').forEach(button=>button.addEventListener('click',()=>{state.runnerEditId=button.dataset.editRunner;renderView();}));
document.querySelectorAll('[data-delete-runner]').forEach(button=>button.addEventListener('click',deleteRunnerJob));
document.querySelectorAll('[data-test-runner]').forEach(button=>button.addEventListener('click',async()=>{const job=state.runnerJobs.find(item=>item.id===button.dataset.testRunner);if(job.mailEnabled&&!window.confirm(`Test startet CSV-Export und Mailversand an ${job.mailTo}. Fortfahren?`))return;button.disabled=true;try{errorTarget('runner-execution','Job wird ausgeführt …',true);const result=await api(`/api/runner/jobs/${job.id}/test`,{method:'POST'});await loadData();renderView();errorTarget('runner-execution',result.success?'CSV erstellt'+(job.mailEnabled?' und von der Mail-API angenommen.':'.'):result.error,result.success);}catch(error){errorTarget('runner-execution',error.message);}finally{button.disabled=false;}}));
document.querySelector('#runner-form').addEventListener('submit',async event=>{event.preventDefault();const form=new FormData(event.currentTarget);try{await api('/api/runner/jobs'+(state.runnerEditId?'/'+state.runnerEditId:''),{method:state.runnerEditId?'PATCH':'POST',body:JSON.stringify({name:form.get('name'),selectionId:form.get('selectionId'),time:form.get('time'),rangeHours:Number(form.get('rangeHours')),delimiter:form.get('delimiter'),enabled:form.has('enabled'),mailEnabled:form.has('mailEnabled'),mailTo:form.get('mailTo')||null,mailSubject:form.get('mailSubject'),mailMessage:form.get('mailMessage')})});state.runnerEditId=null;await loadData();renderView();}catch(error){errorTarget('runner-message',error.message);}});
}
+242
View File
@@ -0,0 +1,242 @@
const bulkProtocolTabs = [['All', 'Alle'], ['Bacnet', 'BACnet'], ['OpcUa', 'OPC UA'],
['Modbus', 'Modbus'], ['Knx', 'KNX'], ['Mqtt', 'MQTT'], ['Internal', 'Intern']];
function viewMappingBatch() {
return `<article class="card mapping-batch">
<div class="card-head"><h2>Sammelmapping</h2></div>
<div class="point-tabs" role="group" aria-label="Quellprotokoll">
${bulkProtocolTabs.map(([key, label]) => `<button type="button" class="btn" data-bulk-protocol="${key}">${label}</button>`).join('')}
</div>
<div class="grid two mapping-batch-grid">
<div>
<div class="buttons">
<button type="button" class="btn" data-bulk-select-all>Alle sichtbaren auswählen</button>
<button type="button" class="btn" data-bulk-clear>Auswahl leeren</button>
<span data-bulk-count role="status"></span>
</div>
<div class="table-scroll bulk-point-list">
<table>
<thead><tr><th scope="col">Auswahl</th><th scope="col">Datenpunkt</th><th scope="col">Protokoll</th><th scope="col">Typ</th></tr></thead>
<tbody data-bulk-points></tbody>
</table>
</div>
<p class="note">Strg oder ⌘ wählt einzelne Zeilen zu oder ab. Umschalt wählt einen Bereich.</p>
</div>
<form id="bulk-mapping-form" class="form">
<label>Ziel<select name="target">
<option value="Bacnet">BACnet-Objekte auf dem Gateway</option>
<option value="OpcUa">OPC-UA-Variablen auf dem Gateway</option>
<option value="Modbus">Modbus-TCP-Server</option>
${can('manage_integrations') ? '<option value="Mqtt">MQTT</option>' : ''}
</select></label>
<div data-bulk-mqtt class="form" hidden>
<label class="switch"><input type="checkbox" name="seMonitoring" checked> SE-Monitoring verwenden</label>
<div data-bulk-mqtt-site class="form">
${mqttMonitoringSiteFields()}
<code class="note" data-mqtt-preview>${escapeHtml(mqttTopicTemplate() || '')}</code>
</div>
<div data-bulk-mqtt-free class="form" hidden>
<label>Format<select name="mqttFreeFormat">${mqttTopicFormatOptions('SingleTopic')}</select></label>
<label>MQTT-Topic-Präfix<input name="mqttTopicPrefix" placeholder="z. B. Heizung/ISP01" maxlength="850"></label>
</div>
</div>
<div data-bulk-modbus hidden>
<label>Serverinstanz<select name="modbusServerId"></select></label>
<label>Erste Modbus-Adresse (optional)<input name="firstRegister" type="number" min="0" max="65535"></label>
<p class="note">Zahlen nutzen Input Register. Binäre Werte nutzen Discrete Inputs. Belegte Adressen werden übersprungen.</p>
</div>
<div><button type="submit" class="btn primary">Auswahl mappen</button></div>
<div data-bulk-message role="status"></div>
<div data-bulk-assignments></div>
</form>
</div>
</article>`;
}
function bindMappingBatch() {
const card = document.querySelector('.mapping-batch');
if (!card) return;
const form = card.querySelector('form');
const body = card.querySelector('[data-bulk-points]');
const count = card.querySelector('[data-bulk-count]');
const tabs = [...card.querySelectorAll('[data-bulk-protocol]')];
const message = card.querySelector('[data-bulk-message]');
const assignments = card.querySelector('[data-bulk-assignments]');
const target = form.elements.target;
const serverSelect = form.elements.modbusServerId;
let serverRequest;
let anchor;
let visiblePoints = [];
let running = false;
const selected = new Set();
let protocol = state.bulkMappingProtocol || 'All';
function updateSelection() {
count.textContent = `${selected.size} ausgewählt`;
form.querySelector('button[type=submit]').disabled = running || !selected.size;
body.querySelectorAll('input[type=checkbox]').forEach(input => { input.checked = selected.has(input.value); });
}
function renderPoints() {
tabs.forEach(tab => {
const active = tab.dataset.bulkProtocol === protocol;
tab.classList.toggle('active', active);
tab.setAttribute('aria-pressed', String(active));
});
visiblePoints = state.points.filter(point => point.readable && (protocol === 'All' || point.protocol === protocol));
body.innerHTML = visiblePoints.map(point => `<tr data-bulk-point="${point.id}">
<td><input type="checkbox" value="${point.id}" aria-label="${escapeHtml(point.displayName)} auswählen"></td>
<td>${escapeHtml(point.displayName)}</td><td>${escapeHtml(point.protocol)}</td><td>${escapeHtml(point.valueType)}</td>
</tr>`).join('') || '<tr><td colspan="4">Keine lesbaren Datenpunkte.</td></tr>';
updateSelection();
}
tabs.forEach(tab => tab.addEventListener('click', () => {
protocol = state.bulkMappingProtocol = tab.dataset.bulkProtocol;
anchor = undefined;
renderPoints();
}));
body.addEventListener('click', event => {
const row = event.target.closest('[data-bulk-point]');
if (!row) return;
const id = row.dataset.bulkPoint;
const from = visiblePoints.findIndex(point => point.id === anchor);
if (event.shiftKey && from >= 0) {
const to = visiblePoints.findIndex(point => point.id === id);
for (const point of visiblePoints.slice(Math.min(from, to), Math.max(from, to) + 1)) selected.add(point.id);
} else {
if (event.target.type !== 'checkbox' && !event.ctrlKey && !event.metaKey) {
const onlySelected = selected.size === 1 && selected.has(id);
selected.clear();
if (!onlySelected) selected.add(id);
} else if (selected.has(id)) selected.delete(id);
else selected.add(id);
anchor = id;
}
updateSelection();
});
card.querySelector('[data-bulk-select-all]').addEventListener('click', () => {
visiblePoints.forEach(point => selected.add(point.id));
updateSelection();
});
card.querySelector('[data-bulk-clear]').addEventListener('click', () => {
selected.clear();
anchor = undefined;
updateSelection();
});
async function updateTarget() {
const modbus = target.value === 'Modbus';
const mqtt = target.value === 'Mqtt';
const prefix = form.elements.mqttTopicPrefix;
card.querySelector('[data-bulk-modbus]').hidden = !modbus;
card.querySelector('[data-bulk-mqtt]').hidden = !mqtt;
const monitoring = mqtt && form.elements.seMonitoring.checked;
card.querySelector('[data-bulk-mqtt-site]').hidden = !monitoring;
card.querySelector('[data-bulk-mqtt-free]').hidden = !mqtt || monitoring;
syncMqttMonitoringSiteFields(form, monitoring, mqttTopicTemplate() || '');
prefix.required = mqtt && !monitoring;
serverSelect.required = modbus;
if (!modbus || serverRequest) return;
serverSelect.innerHTML = '<option value="">Server werden geladen …</option>';
try {
serverRequest = api('/api/mappings/bulk/modbus-servers');
const servers = await serverRequest;
serverSelect.innerHTML = servers.map(server => `<option value="${server.id}">${escapeHtml(server.name)} · ${server.firstHoldingRegister}–${server.firstHoldingRegister + server.holdingRegisterCount - 1}</option>`).join('')
|| '<option value="">Keine Modbus-TCP-Instanz konfiguriert</option>';
} catch (error) {
serverRequest = null;
serverSelect.innerHTML = '<option value="">Serverliste nicht verfügbar</option>';
message.textContent = error.message;
}
}
target.addEventListener('change', updateTarget);
form.elements.seMonitoring.addEventListener('change', updateTarget);
form.addEventListener('submit', async event => {
event.preventDefault();
if (running || selected.size === 0) return;
const fields = new FormData(form);
const mqtt = target.value === 'Mqtt';
const monitoring = mqtt && fields.has('seMonitoring');
running = true;
updateSelection();
assignments.replaceChildren();
message.textContent = 'Mappings werden angelegt …';
try {
const result = await api('/api/mappings/bulk', { method: 'POST', body: JSON.stringify({
sourcePointIds: state.points.filter(point => selected.has(point.id)).map(point => point.id),
target: target.value,
modbusServerId: target.value === 'Modbus' ? fields.get('modbusServerId') || null : null,
firstRegister: target.value === 'Modbus' && fields.get('firstRegister') !== '' ? Number(fields.get('firstRegister')) : null,
mqttFormat: mqtt ? monitoring ? 'SeMonitoring' : fields.get('mqttFreeFormat') : null,
mqttSite: monitoring ? mqttSiteFromForm(fields) : null,
mqttTopicPrefix: mqtt && !monitoring ? fields.get('mqttTopicPrefix') : null
}) });
state.bulkMappingResult = result;
await loadData();
if (state.view === 'mappings') renderView();
} catch (error) {
message.textContent = error.message;
} finally { running = false; updateSelection(); }
});
renderPoints();
updateTarget();
if (state.bulkMappingResult) {
const { created, existing, assignments: entries } = state.bulkMappingResult;
state.bulkMappingResult = null;
message.textContent = `${created} angelegt, ${existing} bereits vorhanden.`;
if (entries.length) assignments.innerHTML = `<details><summary>Zugewiesene Ziele anzeigen</summary><ul>${entries.map(entry => `<li>${escapeHtml(entry)}</li>`).join('')}</ul></details>`;
}
}
const configurationCsvFiles = {
points: ['/api/points/csv', 'seiugw-datenpunkte.csv'],
mappings: ['/api/mappings/csv', 'seiugw-mappings.csv'],
mqtt: ['/api/mqtt/mappings/csv', 'seiugw-mqtt-mappings.csv']
};
function configurationCsvButtons(kind) {
return `<div class="buttons" data-configuration-csv="${kind}">
<button type="button" class="btn" data-csv-export>CSV exportieren</button>
<button type="button" class="btn" data-csv-import>CSV importieren</button>
<input type="file" accept=".csv,text/csv" aria-label="CSV-Datei auswählen" hidden>
</div>`;
}
function bindConfigurationCsv(kind, statusId) {
const buttons = document.querySelector(`[data-configuration-csv="${kind}"]`);
if (!buttons) return;
const fileInput = buttons.querySelector('input');
const [route, filename] = configurationCsvFiles[kind];
const status = () => document.getElementById(statusId);
buttons.querySelector('[data-csv-export]').addEventListener('click', async () => {
try {
const result = await fetch(route, { headers: { Authorization: `Bearer ${state.token}` } });
if (!result.ok) throw new Error(`CSV-Export fehlgeschlagen (${result.status}).`);
const link = document.createElement('a');
link.href = URL.createObjectURL(await result.blob());
link.download = filename;
link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
} catch (error) { if (status()) status().textContent = error.message; }
});
buttons.querySelector('[data-csv-import]').addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', async () => {
const file = fileInput.files[0];
fileInput.value = '';
if (!file || !status()) return;
const importButton = buttons.querySelector('[data-csv-import]');
importButton.disabled = true;
status().textContent = 'CSV wird eingelesen …';
try {
if (file.size > 4 * 1024 * 1024) throw new Error('Maximale CSV-Größe: 4 MB.');
const result = await api(route, { method: 'POST', body: JSON.stringify({ csv: await file.text() }) });
await loadData();
if (!buttons.isConnected) return;
renderView();
if (status()) status().textContent = `${result.created} angelegt, ${result.updated} aktualisiert.`;
} catch (error) { if (status()) status().textContent = error.message; }
finally { importButton.disabled = false; }
});
}
@@ -0,0 +1,210 @@
function mqttPointDefaults(id) {
return state.mqttMappingDefaults?.points.find(point => point.pointId === id);
}
function mqttTopicTemplate(editing) {
const settings = state.mqttMappingDefaults?.topicTemplate;
return editing?.format === 'SeMonitoring' ? editing.topicTemplate ?? settings?.defaultTemplate : settings?.template;
}
function expandMqttTopicTemplate(template, values) {
return template.replace(/\{[^{}]*\}/g, token => values[token] ?? token);
}
function mqttMonitoringSiteFields(site = state.mqttMappingDefaults?.site) {
return `<div class="row three">
<label>Projektjahr<input name="projectYear" type="number" min="2000" max="2100" value="${site?.projectYear ?? ''}" data-mqtt-site="{Jahr}"></label>
<label>Projektnummer<input name="projectNumber" maxlength="33" value="${escapeHtml(site?.projectNumber || '')}" data-mqtt-site="{Projekt}"></label>
<label>ISP<input name="ispNumber" maxlength="32" pattern="ISP[0-9]+" value="${escapeHtml(site?.ispNumber || '')}" data-mqtt-site="{ISP}"></label>
</div>`;
}
function syncMqttMonitoringSiteFields(form, monitoring, template) {
const needsHost = template.includes('{Rechnername}');
form.querySelectorAll('[data-mqtt-site]').forEach(input => {
const needed = template.includes(input.dataset.mqttSite) || needsHost && input.name !== 'projectYear';
input.required = monitoring && needed;
input.disabled = !monitoring || !needed;
input.closest('label').hidden = !needed;
});
}
function mqttTopicFormatOptions(selected) {
return `<option value="SingleTopic" ${selected === 'SingleTopic' ? 'selected' : ''}>Einzel-Topic (Zahl)</option>
<option value="Json" ${selected === 'Json' ? 'selected' : ''}>JSON</option>`;
}
function mqttMappingFormatLabel(format) {
return { SeMonitoring: 'SE-Monitoring', SingleTopic: 'Einzel-Topic', Json: 'JSON' }[format] || format;
}
function mqttSiteFromForm(form) {
return {
projectYear: form.get('projectYear') ? Number(form.get('projectYear')) : null,
projectNumber: form.get('projectNumber')?.trim() || null,
ispNumber: form.get('ispNumber')?.trim() || null
};
}
function mqttMappingForm(editing) {
const points = mappingPointOptions(editing?.pointId, 'valueType');
if (!points) return '<div class="notice">Zuerst einen Datenpunkt anlegen.</div>';
const suggested = mqttPointDefaults(editing?.pointId ?? state.points[0]?.id);
const monitoring = editing ? editing.format === 'SeMonitoring' : !!suggested?.category;
const option = (value, label, selected) => `<option value="${value}" ${value === selected ? 'selected' : ''}>${label}</option>`;
const categories = ['Analog', 'Notify', 'Alarms', 'Setpoints'];
if (editing?.seCategory === 'Alarm') categories.push('Alarm');
return `<form id="mqtt-mapping-form" class="form" data-topic-template="${escapeHtml(mqttTopicTemplate(editing) || '')}">
<label>Datenpunkt<select name="pointId" required>${points}</select></label>
<div class="row">
<label>Richtung<select name="direction">
${option('Publish', 'Nur senden', editing?.direction)}
${option('Subscribe', 'Nur empfangen', editing?.direction)}
${option('Bidirectional', 'Senden und empfangen', editing?.direction)}
</select></label>
<label>QoS<select name="qualityOfService">
${option('AtMostOnce', '0 · höchstens einmal', editing?.qualityOfService)}
${option('AtLeastOnce', '1 · mindestens einmal', editing?.qualityOfService ?? 'AtLeastOnce')}
${option('ExactlyOnce', '2 · genau einmal', editing?.qualityOfService)}
</select></label>
</div>
<label class="switch"><input type="checkbox" name="retain" ${editing?.retain ? 'checked' : ''}> Retained Message</label>
<label class="switch"><input name="seMonitoring" type="checkbox" ${monitoring ? 'checked' : ''}> SE-Monitoring verwenden</label>
<div data-mqtt-monitoring class="form" ${monitoring ? '' : 'hidden'}>
${mqttMonitoringSiteFields(editing?.format === 'SeMonitoring' ? editing : undefined)}
<div class="row">
<label>Kategorie<select name="seCategory">
${categories.map(category => option(category, category, editing?.seCategory ?? suggested?.category)).join('')}
</select></label>
<label>Punktname<input name="topicName" maxlength="200" value="${escapeHtml(editing?.topicName ?? suggested?.topicName ?? '')}" data-mqtt-required></label>
</div>
<code data-mqtt-preview class="note"></code>
</div>
<div data-mqtt-free class="form" ${monitoring ? 'hidden' : ''}>
<div class="row">
<label>Format<select name="freeFormat">${mqttTopicFormatOptions(editing?.format === 'Json' || !suggested?.category ? 'Json' : 'SingleTopic')}</select></label>
<label>Topic<input name="jsonTopic" maxlength="1024" value="${escapeHtml(editing?.jsonTopic ?? '')}" placeholder="anlage/temperatur"></label>
</div>
<label data-mqtt-json-property>JSON-Eigenschaft (optional)<input name="jsonProperty" value="${escapeHtml(editing?.jsonProperty ?? '')}" placeholder="temperatur"></label>
</div>
<div class="buttons"><button type="submit" class="btn primary">MQTT-Mapping speichern</button>
${editing ? '<button type="button" class="btn" id="cancel-mqtt-mapping-edit">Abbrechen</button>' : ''}</div>
<div id="mqtt-mapping-message" role="status"></div>
</form>`;
}
function bindMqttMappingOptions(form) {
if (!form) return;
const fields = form.elements;
const template = form.dataset.topicTemplate;
let preferMonitoring = !state.mqttMappingEditId || fields.seMonitoring.checked;
let preferFreeFormat = state.mqttMappingEditId ? fields.freeFormat.value : 'SingleTopic';
function update(reselect = false) {
const selected = mqttPointDefaults(fields.pointId.value);
const supportsNumbers = !!selected?.category;
fields.seMonitoring.disabled = !supportsNumbers;
fields.freeFormat.options[0].disabled = !supportsNumbers;
if (reselect) {
fields.seMonitoring.checked = supportsNumbers && preferMonitoring;
fields.seCategory.value = selected?.category || 'Analog';
fields.topicName.value = selected?.topicName || '';
fields.freeFormat.value = supportsNumbers ? preferFreeFormat : 'Json';
}
if (!supportsNumbers) {
fields.seMonitoring.checked = false;
fields.freeFormat.value = 'Json';
}
const monitoring = fields.seMonitoring.checked;
form.querySelector('[data-mqtt-monitoring]').hidden = !monitoring;
form.querySelector('[data-mqtt-free]').hidden = monitoring;
form.querySelector('[data-mqtt-json-property]').hidden = fields.freeFormat.value !== 'Json';
fields.jsonTopic.required = !monitoring;
syncMqttMonitoringSiteFields(form, monitoring, template);
form.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; });
fields.direction.options[0].disabled = monitoring && fields.seCategory.value === 'Setpoints';
fields.direction.options[1].disabled = fields.direction.options[0].disabled;
if (fields.direction.options[0].disabled) fields.direction.value = 'Bidirectional';
const project = fields.projectNumber.value.trim();
const isp = fields.ispNumber.value.trim();
form.querySelector('[data-mqtt-preview]').textContent = expandMqttTopicTemplate(template, {
'{Jahr}': fields.projectYear.value,
'{Projekt}': project,
'{ISP}': isp,
'{Kategorie}': fields.seCategory.value,
'{Datenpunkt}': fields.topicName.value.trim(),
'{Rechnername}': project && /^ISP\d+$/.test(isp) ? `SE-UGW-${project}-ISP${isp.slice(3).padStart(2, '0')}` : ''
});
}
fields.pointId.addEventListener('change', () => update(true));
fields.seMonitoring.addEventListener('change', () => {
preferMonitoring = fields.seMonitoring.checked;
update();
});
fields.freeFormat.addEventListener('change', () => {
preferFreeFormat = fields.freeFormat.value;
update();
});
fields.seCategory.addEventListener('change', () => update());
form.querySelector('[data-mqtt-monitoring]').addEventListener('input', () => update());
update();
}
function viewMqttTopicTemplateSettings() {
const settings = state.mqttMappingDefaults?.topicTemplate;
if (!settings) return '';
return `<article class="card"><div class="card-head"><h2>MQTT-Standardpfad</h2></div>
<form class="form" id="mqtt-topic-template-form">
<label>Topic-Vorlage<input name="template" type="text" value="${escapeHtml(settings.template)}" maxlength="1024" autocomplete="off" spellcheck="false" required></label>
<div class="mqtt-topic-placeholders" role="group" aria-label="Platzhalter">
${settings.placeholders.map(({token, description}) => `<button type="button" class="btn" data-template-insert="${escapeHtml(token)}">
<code>${escapeHtml(token)}</code><span class="note">${escapeHtml(description)}</span></button>`).join('')}
</div>
<div class="note">Vorschau mit Beispielpunkt</div>
<code data-mqtt-preview></code>
<div class="buttons">
<button type="submit" class="btn primary">Standardpfad speichern</button>
<button type="button" class="btn" data-template-default>Standardvorlage einsetzen</button>
</div>
<div id="mqtt-template-message" role="status"></div>
</form>
</article>`;
}
function bindMqttTopicTemplateSettings() {
const form = document.querySelector('#mqtt-topic-template-form');
if (!form) return;
let settings = state.mqttMappingDefaults.topicTemplate;
const input = form.elements.template;
const preview = form.querySelector('[data-mqtt-preview]');
const save = form.querySelector('[type=submit]');
const updatePreview = () => {
preview.textContent = expandMqttTopicTemplate(input.value, settings.previewValues) || '—';
};
form.querySelectorAll('[data-template-insert]').forEach(button => button.addEventListener('click', () => {
const start = input.selectionStart;
const end = input.selectionEnd;
input.focus({ preventScroll: true });
input.setRangeText(button.dataset.templateInsert, start, end, 'end');
updatePreview();
}));
form.querySelector('[data-template-default]').addEventListener('click', () => {
input.value = settings.defaultTemplate;
input.focus({ preventScroll: true });
updatePreview();
});
input.addEventListener('input', updatePreview);
form.addEventListener('submit', async event => {
event.preventDefault();
save.disabled = true;
const value = input.value;
try {
settings = await api('/api/mqtt/topic-template', { method:'PUT', body:JSON.stringify({ template:value }) });
state.mqttMappingDefaults.topicTemplate = settings;
if (input.value === value) input.value = settings.template;
updatePreview();
errorTarget('mqtt-template-message', 'MQTT-Standardpfad gespeichert.', true);
} catch (error) { errorTarget('mqtt-template-message', error.message); }
finally { save.disabled = false; }
});
updatePreview();
}
@@ -0,0 +1,273 @@
function viewMqttTopicBrowser() {
return `<article class="card mqtt-topic-browser" id="mqtt-topic-browser">
<div class="card-head"><h2>Topic-Browser</h2><span class="note" data-mqtt-browser-status></span></div>
<form class="form" data-broker-filter>
<div class="row">
<label>Filter am Broker<input name="filter" maxlength="1024" placeholder="z. B. Projekte2019/#" value="${escapeHtml(state.mqttBrowser?.filter || '#')}"></label>
<div class="buttons mqtt-browser-start"><button type="submit" class="btn primary">Topics beobachten</button></div>
</div>
</form>
<div data-mqtt-browser-message role="status"></div>
<div class="grid two mqtt-browser-content" hidden>
<div>
<label>Topic suchen<input type="search" data-topic-search placeholder="Teil des Topic-Pfads"></label>
${can('manage_sources') ? `<div class="buttons mqtt-browser-selection">
<button class="btn" type="button" data-topic-select-all>Alle Treffer auswählen</button>
<button class="btn" type="button" data-topic-clear>Auswahl leeren</button>
<button class="btn primary" type="button" data-topic-import>Auswahl übernehmen</button>
<span class="note" data-topic-selected></span>
</div>` : ''}
<div class="mqtt-topic-tree" data-topic-tree aria-label="Topic-Baum" role="region" tabindex="0"></div>
</div>
<section class="mqtt-topic-detail" data-topic-detail aria-label="Topic-Details"></section>
</div>
</article>`;
}
function mqttTopicNodes(topics) {
const root = new Map();
for (const topic of topics) {
let children = root;
const parts = topic.topic.split('/');
const levels = parts.length > 48 ? [...parts.slice(0, 47), parts.slice(47).join('/')] : parts;
for (let index = 0; index < levels.length; index++) {
const label = levels[index];
const path = levels.slice(0, index + 1).join('/');
if (!children.has(label)) children.set(label, { label, path, children: new Map(), selectable: [] });
const node = children.get(label);
if (topic.valueType && !topic.pointId) node.selectable.push(topic.topic);
if (index === levels.length - 1) node.topic = topic;
children = node.children;
}
}
return root;
}
function bindMqttTopicBrowser() {
const browser = document.querySelector('#mqtt-topic-browser');
if (!browser) return;
const model = state.mqttBrowser ??= {
filter: '#', snapshot: null, query: '', picked: new Set(), expanded: new Map(), focused: null, message: ''
};
const nodes = browser.querySelector('[data-topic-tree]');
const detail = browser.querySelector('[data-topic-detail]');
const form = browser.querySelector('[data-broker-filter]');
const search = browser.querySelector('[data-topic-search]');
const message = browser.querySelector('[data-mqtt-browser-message]');
const content = browser.querySelector('.mqtt-browser-content');
const status = browser.querySelector('[data-mqtt-browser-status]');
const importButton = browser.querySelector('[data-topic-import]');
const canImport = !!importButton;
let visibleTopics = [];
let visibleBranches = new Map();
let busy = false;
let timer;
let revision = 0;
search.value = model.query;
const token = value => escapeHtml(encodeURIComponent(value));
const importable = topic => topic.valueType && !topic.pointId;
const displayType = type => ({ Boolean: 'Binär', Double: 'Zahl', String: 'Text', Json: 'JSON' }[type] || '—');
function renderLeaf(topic, name) {
return `<div class="mqtt-tree-row mqtt-tree-leaf">
${canImport && importable(topic) ? `<input type="checkbox" data-topic-pick="${token(topic.topic)}" aria-label="${escapeHtml(topic.topic)} auswählen">` : ''}
<button type="button" class="btn mqtt-topic-item" data-topic-item="${token(topic.topic)}"
aria-pressed="${topic.topic === model.focused}">${escapeHtml(name || '(leere Ebene)')}</button>
<span class="note mqtt-topic-value" title="${escapeHtml(topic.preview)}">${escapeHtml(topic.preview)}</span>
${topic.pointId ? '<span class="tag gray">übernommen</span>' : ''}</div>`;
}
function renderBranch(branch) {
const opened = model.expanded.get(branch.path) ?? !!model.query;
visibleBranches.set(branch.path, branch.selectable);
return `<li><div class="mqtt-tree-row mqtt-tree-branch">
${canImport && branch.selectable.length ? `<input type="checkbox" data-topic-branch-pick="${token(branch.path)}" aria-label="Zweig ${escapeHtml(branch.path || '/')} auswählen">` : ''}
<button type="button" class="btn" data-topic-branch="${token(branch.path)}" aria-expanded="${opened}">
<span aria-hidden="true">${opened ? '▾' : '▸'}</span> ${escapeHtml(branch.label || '(leere Ebene)')}</button>
</div>${opened ? `<ul>${branch.topic ? `<li>${renderLeaf(branch.topic, branch.label)}</li>` : ''}
${renderNodes(branch.children)}</ul>` : ''}</li>`;
}
function renderNodes(branches) {
return [...branches.values()].map(branch => branch.children.size ? renderBranch(branch) :
`<li>${renderLeaf(branch.topic, branch.label)}</li>`).join('');
}
function renderDetail() {
const topic = model.snapshot?.topics.find(item => item.topic === model.focused);
detail.innerHTML = topic ? `<h3>Topic-Details</h3>
<code class="mqtt-topic-path">${escapeHtml(topic.topic)}</code>
<dl class="connection-facts">
<dt>Werttyp</dt><dd>${displayType(topic.valueType)}</dd>
<dt>Empfangen</dt><dd>${statusTime(topic.receivedAtUtc)}</dd>
<dt>Retained</dt><dd>${topic.retained ? 'Ja' : '—'}</dd>
</dl>
<pre class="mqtt-topic-preview">${escapeHtml(topic.preview)}</pre>
${topic.pointId ? '<p class="note">Als externer Datenpunkt angelegt.</p>' :
canImport && importable(topic) ? '<button type="button" class="btn primary" data-topic-import-one>Datenpunkt übernehmen</button>' :
!topic.valueType ? '<p class="note">Dieser Nachrichtenwert kann nicht als Datenpunkt übernommen werden.</p>' : ''}`
: '<p class="note">Ein Topic auswählen, um Wert und Details zu sehen.</p>';
}
function syncSelection() {
if (!canImport) return;
nodes.querySelectorAll('[data-topic-pick]').forEach(input => {
input.checked = model.picked.has(decodeURIComponent(input.dataset.topicPick));
});
nodes.querySelectorAll('[data-topic-branch-pick]').forEach(input => {
const topics = visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick));
const count = topics.filter(topic => model.picked.has(topic)).length;
input.checked = count === topics.length;
input.indeterminate = count > 0 && count < topics.length;
});
browser.querySelector('[data-topic-selected]').textContent = `${model.picked.size} ausgewählt`;
importButton.disabled = busy || !model.picked.size;
browser.querySelector('[data-topic-select-all]').disabled = !visibleTopics.some(importable);
browser.querySelector('[data-topic-clear]').disabled = !model.picked.size;
}
function render() {
const snapshot = model.snapshot;
const query = model.query.trim().toLowerCase();
visibleTopics = (snapshot?.topics || []).filter(topic => topic.topic.toLowerCase().includes(query));
content.hidden = !snapshot;
message.textContent = model.message;
status.textContent = snapshot ? `${snapshot.connected ? 'Verbunden' : 'Getrennt'} · ${visibleTopics.length} von ${snapshot.topics.length} Topics` : '';
if (!snapshot) return;
if (!model.message && snapshot.error) message.textContent = snapshot.error;
if (snapshot.limitReached && !message.textContent) message.textContent = '3.000 Topics erreicht. Mit einem Broker-Filter lässt sich der Bereich eingrenzen.';
const scroll = nodes.scrollTop;
const focused = nodes.contains(document.activeElement) ? document.activeElement : null;
const focusAttribute = ['data-topic-item', 'data-topic-branch', 'data-topic-pick', 'data-topic-branch-pick'].find(attribute => focused?.hasAttribute(attribute));
visibleBranches = new Map();
nodes.innerHTML = visibleTopics.length ? `<ul>${renderNodes(mqttTopicNodes(visibleTopics))}</ul>` :
`<div class="empty">${query ? 'Keine passenden Topics.' : 'Warte auf Retained- oder neue Nachrichten.'}</div>`;
if (focusAttribute) {
[...nodes.querySelectorAll(`[${focusAttribute}]`)].find(element =>
element.getAttribute(focusAttribute) === focused.getAttribute(focusAttribute))?.focus({ preventScroll: true });
}
nodes.scrollTop = scroll;
if (!detail.contains(document.activeElement)) renderDetail();
syncSelection();
}
function acceptSnapshot(snapshot) {
model.snapshot = snapshot;
const eligible = new Set(snapshot.topics.filter(importable).map(topic => topic.topic));
for (const topic of model.picked) if (!eligible.has(topic)) model.picked.delete(topic);
render();
}
async function refresh() {
clearTimeout(timer);
if (!browser.isConnected || !model.snapshot) return;
if (!busy && !browser.closest('[data-points-panel]')?.hidden) {
const currentRevision = revision;
try {
const snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected && currentRevision === revision) acceptSnapshot(snapshot);
} catch (error) {
if (currentRevision !== revision || !browser.isConnected) return;
model.message = error.message;
render();
return;
}
}
if (browser.isConnected) timer = setTimeout(refresh, 3000);
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (busy) return;
const button = form.querySelector('button');
button.disabled = busy = true;
const currentRevision = ++revision;
clearTimeout(timer);
model.message = 'Broker-Verbindung wird geöffnet …';
render();
try {
const filter = form.elements.filter.value || '#';
const snapshot = await api('/api/mqtt/browser', { method:'POST', body:JSON.stringify({ filter }) });
if (!browser.isConnected || currentRevision !== revision) return;
if (model.snapshot?.sessionId !== snapshot.sessionId) {
model.focused = null;
model.picked.clear();
model.expanded.clear();
}
model.filter = snapshot.filter;
model.message = '';
acceptSnapshot(snapshot);
} catch (error) {
model.snapshot = null;
model.message = error.message;
render();
} finally {
button.disabled = busy = false;
syncSelection();
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
});
search.addEventListener('input', () => { model.query = search.value; model.expanded.clear(); render(); });
nodes.addEventListener('click', event => {
const branch = event.target.closest('[data-topic-branch]');
const item = event.target.closest('[data-topic-item]');
if (branch) {
model.expanded.set(decodeURIComponent(branch.dataset.topicBranch), branch.getAttribute('aria-expanded') !== 'true');
render();
} else if (item) {
model.focused = decodeURIComponent(item.dataset.topicItem);
nodes.querySelectorAll('[data-topic-item]').forEach(button => button.setAttribute('aria-pressed', String(button === item)));
renderDetail();
}
});
nodes.addEventListener('change', event => {
const input = event.target;
const selected = input.dataset.topicPick != null ? [decodeURIComponent(input.dataset.topicPick)] :
input.dataset.topicBranchPick != null ? visibleBranches.get(decodeURIComponent(input.dataset.topicBranchPick)) : [];
for (const topic of selected) input.checked ? model.picked.add(topic) : model.picked.delete(topic);
syncSelection();
});
async function importTopics(topics) {
if (!topics.length || busy || !model.snapshot) return;
busy = true;
++revision;
detail.querySelector('[data-topic-import-one]')?.setAttribute('disabled', '');
syncSelection();
try {
const result = await api('/api/mqtt/browser/import', {
method:'POST', body:JSON.stringify({ sessionId: model.snapshot.sessionId, topics })
});
model.message = `${result.created} angelegt · ${result.existing} bereits vorhanden · ${result.unavailable} ohne importierbaren Wert`;
await loadData();
model.snapshot = await api(`/api/mqtt/browser/${model.snapshot.sessionId}`);
if (browser.isConnected) renderView();
} catch (error) {
model.message = error.message;
render();
} finally {
busy = false;
detail.querySelector('[data-topic-import-one]')?.removeAttribute('disabled');
syncSelection();
clearTimeout(timer);
if (browser.isConnected && model.snapshot) timer = setTimeout(refresh, 3000);
}
}
if (canImport) {
browser.querySelector('[data-topic-select-all]').addEventListener('click', () => {
visibleTopics.filter(importable).forEach(topic => model.picked.add(topic.topic));
syncSelection();
});
browser.querySelector('[data-topic-clear]').addEventListener('click', () => { model.picked.clear(); syncSelection(); });
importButton.addEventListener('click', () => importTopics([...model.picked]));
detail.addEventListener('click', event => {
if (event.target.closest('[data-topic-import-one]')) importTopics([model.focused]);
});
}
if (model.snapshot) {
acceptSnapshot(model.snapshot);
timer = setTimeout(refresh, 3000);
} else render();
}
+133
View File
@@ -0,0 +1,133 @@
function bindHostNetwork(panel) {
let selected;
let pendingLayout;
let timer;
const base = '/api/system/network';
const heading = '<h2>Netzwerk · IPv4</h2>';
const schedule = delay => { clearTimeout(timer); timer = setTimeout(load, delay); };
async function load() {
if (!panel.isConnected) return;
try {
const status = await api(base);
if (panel.isConnected) render(status);
} catch (error) {
if (!panel.isConnected) return;
if (panel.querySelector('#host-network-timer')) {
panel.querySelector('#host-network-timer').textContent = 'Verbindung unterbrochen. Öffne das Gateway unter seiner neuen Adresse.';
schedule(2500);
} else {
panel.innerHTML = `${heading}<p class="note">${escapeHtml(error.message)}</p><button type="button" class="btn">Erneut laden</button>`;
panel.querySelector('button').addEventListener('click', load);
}
}
}
function render(status) {
clearTimeout(timer);
if (status.pending) {
renderPending(status);
schedule(2000);
return;
}
pendingLayout = null;
if (status.busy) {
panel.innerHTML = `${heading}<p class="note">Netzwerkdienst übernimmt die Einstellungen …</p>`;
schedule(2000);
return;
}
const cards = status.interfaces;
const card = cards.find(item => item.name === selected) ?? cards[0];
if (!card) {
panel.innerHTML = `${heading}<p class="note">Keine verwaltbare Netzwerkkarte gefunden.</p>`;
return;
}
selected = card.name;
const routes = card.routes;
const ipv4 = card.addresses[0];
const saved = status.profiles[selected];
const mode = saved?.mode || 'dhcp';
panel.innerHTML = `${heading}
${status.notice ? `<p class="note" role="status">${escapeHtml(status.notice)}</p>` : ''}
<form class="form" style="margin-top:10px">
<label>Netzwerkkarte<select name="interface">${cards.map(item =>
`<option value="${escapeHtml(item.name)}" ${item.name === selected ? 'selected' : ''}>${escapeHtml(item.name)} · ${escapeHtml(item.macAddress)}</option>`
).join('')}</select></label>
<div class="note">Aktuell: ${escapeHtml(card.addresses.map(item => `${item.address}/${item.prefixLength}`).join(', ') || 'keine IPv4-Adresse')}
${routes[0]?.gateway ? ` · Gateway ${escapeHtml(routes[0].gateway)}` : ''}</div>
<div class="row">
<label>Adressvergabe<select name="mode"><option value="dhcp">DHCP</option><option value="static" ${mode === 'static' ? 'selected' : ''}>Statisch</option></select></label>
<label>Routenmetrik<input name="metric" type="number" min="1" max="65535" required value="${saved?.metric ?? routes[0]?.metric ?? (1000 + cards.indexOf(card))}"></label>
</div>
<fieldset class="form" data-static style="border:1px solid var(--line);border-radius:10px;min-width:0">
<legend>Statische IPv4-Einstellungen</legend>
<div class="row">
<label>IPv4-Adresse<input name="address" inputmode="decimal" value="${escapeHtml(saved?.address || ipv4?.address || '')}" required></label>
<label>Präfixlänge<input name="prefixLength" type="number" min="1" max="32" value="${saved?.prefixLength ?? ipv4?.prefixLength ?? 24}" required></label>
</div>
<div class="row">
<label>Standardgateway (optional)<input name="gateway" inputmode="decimal" value="${escapeHtml(saved ? saved.gateway || '' : routes[0]?.gateway || '')}"></label>
<label>DNS-Server (optional, durch Leerzeichen getrennt)<input name="dns" value="${escapeHtml(saved?.dns?.join(' ') || '')}"></label>
</div>
</fieldset>
<div class="note">Nach dem Anwenden bleiben zwei Minuten zum Bestätigen. Eine niedrigere Routenmetrik hat Vorrang.</div>
<div class="buttons"><button class="btn primary" type="submit">Netzwerkänderung anwenden</button></div>
<div id="host-network-message" role="status"></div>
</form>`;
const form = panel.querySelector('form');
const fields = form.querySelector('[data-static]');
function syncFields() { fields.hidden = fields.disabled = form.elements.mode.value !== 'static'; }
syncFields();
form.elements.mode.addEventListener('change', syncFields);
form.elements.interface.addEventListener('change', () => { selected = form.elements.interface.value; render(status); });
form.addEventListener('submit', async event => {
event.preventDefault();
const values = new FormData(form);
const profile = {
interface: values.get('interface'), mode: values.get('mode'), metric: Number(values.get('metric')),
address: values.get('address')?.trim(), prefixLength: Number(values.get('prefixLength')) || null,
gateway: values.get('gateway')?.trim(), dns: (values.get('dns') || '').split(/[\s,;]+/).filter(Boolean)
};
form.querySelector('button').disabled = true;
try {
render(await api(base + '/apply', { method: 'POST', body: JSON.stringify(profile) }));
} catch (error) {
errorTarget('host-network-message', error.message);
form.querySelector('button').disabled = false;
}
});
}
function renderPending(status) {
const { id, profile, ready, secondsLeft } = status.pending;
const card = status.interfaces.find(item => item.name === profile.interface);
const address = profile.address || card?.addresses.find(item => item.dynamic)?.address;
const layout = JSON.stringify([id, ready, address]);
if (pendingLayout !== layout) {
pendingLayout = layout;
const link = address ? new URL(location.href) : null;
if (link) { link.hostname = address; link.pathname = '/'; link.search = '?network-confirm=1'; link.hash = ''; }
panel.innerHTML = `${heading}<p>Änderung für <strong>${escapeHtml(profile.interface)}</strong> · ${profile.mode === 'static' ? 'Statisch' : 'DHCP'}</p>
<p id="host-network-timer" class="note"></p>
${link && link.hostname !== location.hostname ? `<p><a class="btn" href="${escapeHtml(link.href)}">Gateway unter ${escapeHtml(address)} öffnen</a></p>` : ''}
<div class="buttons">
<button type="button" class="btn primary" data-network-action="confirm" ${ready ? '' : 'disabled'}>Netzwerkänderung bestätigen</button>
<button type="button" class="btn" data-network-action="revert">Zurücksetzen</button>
</div><div id="host-network-message" role="status"></div>`;
panel.querySelectorAll('[data-network-action]').forEach(button => button.addEventListener('click', async () => {
clearTimeout(timer);
button.disabled = true;
try {
render(await api(base + '/' + button.dataset.networkAction, { method: 'POST', body: JSON.stringify({ id }) }));
} catch (error) {
errorTarget('host-network-message', error.message);
button.disabled = false;
schedule(2000);
}
}));
}
panel.querySelector('#host-network-timer').textContent = `${ready ? 'Neue Adresse aktiv.' : 'Warte auf die neue Adresse.'} Automatische Rückkehr in ${secondsLeft} s.`;
}
load();
}
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="de" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SE-Inno Universalgateway · Trend Logs</title>
<link rel="stylesheet" href="/styles.css?v=20261009-tabs-1">
<link rel="stylesheet" href="/ltd.css?v=20261009-tabs-1">
</head>
<body>
<main style="max-width:1440px;margin:0 auto;padding:20px">
<header class="topbar"><div class="brand"><img class="brand-logo" src="/assets/se-inno-logo.png" alt="SE-Inno"> SE-INNO UNIVERSALGATEWAY</div><span class="tag">öffentliche Trendansicht</span></header>
<section class="card" style="margin-top:18px"><div class="card-head"><h1>Trend Logs</h1><label>Trend Log <select id="trend-log"><option>Laden …</option></select></label></div><div id="trend-status" class="empty">Öffentliche Trenddaten werden geladen …</div><div id="trend-table"></div></section>
</main>
<script src="/public-trends.js"></script>
</body>
</html>
+31
View File
@@ -0,0 +1,31 @@
const trendSelect = document.querySelector('#trend-log');
const trendStatus = document.querySelector('#trend-status');
const trendTable = document.querySelector('#trend-table');
const escapeHtml = value => String(value ?? '').replace(/[&<>'"]/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' })[character]);
async function loadRecords(id) {
if (!id) return;
trendStatus.textContent = 'Werte werden geladen …';
trendTable.innerHTML = '';
const response = await fetch(`/api/public/trend-logs/${encodeURIComponent(id)}/records?limit=2000`);
if (!response.ok) throw new Error('Dieses Trend Log ist nicht öffentlich freigegeben oder nicht mehr verfügbar.');
const records = await response.json();
trendStatus.textContent = records.length ? `${records.length} aufgezeichnete Werte` : 'Noch keine Werte aufgezeichnet.';
trendTable.innerHTML = records.length ? `<table><thead><tr><th>Zeitpunkt</th><th>Wert</th><th>Quelle</th><th>Status</th></tr></thead><tbody>${records.map(record => `<tr><td>${escapeHtml(new Date(record.timestampUtc).toLocaleString('de-DE'))}</td><td>${escapeHtml(typeof record.value === 'string' ? record.value : JSON.stringify(record.value))}</td><td>${escapeHtml(record.sourceProtocol)}</td><td>${escapeHtml(record.status || '—')}</td></tr>`).join('')}</tbody></table>` : '';
}
async function bootPublicTrends() {
try {
const response = await fetch('/api/public/trend-logs');
if (!response.ok) throw new Error('Die öffentlichen Trend Logs konnten nicht geladen werden.');
const logs = await response.json();
if (!logs.length) { trendSelect.innerHTML = '<option>Keine öffentlichen Trend Logs</option>'; trendStatus.textContent = 'Der Administrator hat derzeit kein Trend Log veröffentlicht.'; return; }
const requested = new URLSearchParams(location.search).get('log');
const selected = logs.some(log => log.id === requested) ? requested : logs[0].id;
trendSelect.innerHTML = logs.map(log => `<option value="${escapeHtml(log.id)}" ${log.id === selected ? 'selected' : ''}>${escapeHtml(log.name)}</option>`).join('');
trendSelect.addEventListener('change', () => loadRecords(trendSelect.value).catch(error => { trendStatus.textContent = error.message; }));
await loadRecords(selected);
} catch (error) { trendStatus.textContent = error.message; }
}
bootPublicTrends();
+67 -28
View File
@@ -1,33 +1,72 @@
:root {
color-scheme: dark;
--page: #090c10;
--panel: #10161d;
--panel-2: #151c24;
--line: #28333e;
--muted: #8493a4;
--text: #dfe8f0;
--blue: #2f9deb;
--blue-strong: #1579c0;
--danger: #e26161;
--warn: #dba951;
color-scheme: light;
--page: #f4f6fb;
--page-overlay: linear-gradient(180deg, #f7f9fbe8, #f2f5f9f0);
--page-image: url("/assets/se-ltd-light.png");
--panel: #fffffff0;
--panel-2: #f6f8fb;
--sidebar: #f8fafcf2;
--line: #d7e0e9;
--line-strong: #bdcad6;
--muted: #5e7082;
--text: #172433;
--blue: #1677bd;
--blue-strong: #1267a7;
--blue-soft: #e7f2fa;
--row-hover: #eef5fa;
--notice: #fff9e9;
--notice-blue: #eaf4fc;
--danger: #b54848;
--danger-soft: #f8e9e9;
--tag-line: #9bb7ca;
--tag-text: #275d80;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 14px;
}
:root[data-theme="dark"] {
color-scheme: dark;
--page: #090c10;
--page-overlay: linear-gradient(180deg, #070c1480, #070c14b3);
--page-image: url("/assets/se-ltd-dark.png");
--panel: #0d1522f5;
--panel-2: #111c2b;
--sidebar: #090f19fa;
--line: #28333e;
--line-strong: #496071;
--muted: #a4b3c5;
--text: #edf2f7;
--blue: #2f9deb;
--blue-strong: #1579c0;
--blue-soft: #0e1b27;
--row-hover: #131b23;
--notice: #191713;
--notice-blue: #0e1b27;
--danger: #e26161;
--danger-soft: #2c1719;
--tag-line: #334657;
--tag-text: #b7d9f5;
}
* { box-sizing: border-box; }
body { margin: 0; min-width: 960px; min-height: 100vh; background: var(--page); color: var(--text); }
body { margin: 0; min-width: 960px; min-height: 100vh; background: var(--page-overlay), var(--page-image) center / cover fixed, var(--page); color: var(--text); }
button, input, select, textarea { font: inherit; }
button { cursor: pointer; }
.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
.sidebar { padding: 22px 14px; border-right: 1px solid var(--line); background: #0c1117; }
.brand { display: flex; gap: 10px; align-items: center; padding: 0 10px 24px; letter-spacing: .08em; font-weight: 700; font-size: 12px; }
.sidebar { padding: 22px 14px; border-right: 1px solid var(--line); background: var(--sidebar); }
.brand { display: flex; gap: 10px; align-items: center; padding: 0 10px 24px; letter-spacing: .06em; font-weight: 700; font-size: 11px; }
.brand-logo { width: 27px; height: 27px; object-fit: contain; }
.mark { width: 24px; height: 24px; display: grid; place-items: center; background: var(--blue); color: #06111b; font-size: 11px; border-radius: 3px; }
.nav { display: grid; gap: 3px; }
.nav button { border: 0; color: var(--muted); background: transparent; text-align: left; border-radius: 4px; padding: 9px 10px; font-size: 12px; }
.nav button:hover, .nav button.active { color: #eaf5ff; background: #172431; }
.nav button:hover, .nav button.active { color: var(--text); background: var(--blue-soft); }
.nav button.active { box-shadow: inset 2px 0 var(--blue); }
.sidebar-foot { color: var(--muted); font-size: 11px; position: fixed; bottom: 20px; padding: 0 10px; }
.sidebar-foot { color: var(--muted); font-size: 11px; position: fixed; bottom: 20px; padding: 0 10px; display: grid; gap: 12px; }
.user-caption { line-height: 1.45; }
.theme-toggle { display: flex; gap: 4px; }
.theme-option { border: 1px solid var(--line); color: var(--muted); background: transparent; border-radius: 3px; padding: 5px 6px; font-size: 10px; }
.theme-option:hover, .theme-option.active { border-color: var(--blue); color: var(--blue); background: var(--blue-soft); }
.content { padding: 24px 32px 42px; max-width: 1620px; width: 100%; }
.topline { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
@@ -45,30 +84,30 @@ h2 { margin: 0; font-size: 13px; font-weight: 600; }
.metric-sub { color: var(--muted); margin-top: 4px; font-size: 11px; }
.card-head { display: flex; justify-content: space-between; gap: 10px; align-items: center; margin-bottom: 14px; }
.note { font-size: 11px; color: var(--muted); line-height: 1.55; }
.notice { border-left: 2px solid var(--warn); padding: 9px 10px; background: #191713; color: #d9d4c8; font-size: 11px; line-height: 1.45; }
.notice.blue { border-color: var(--blue); background: #0e1b27; }
.notice { border-left: 2px solid #c39843; padding: 9px 10px; background: var(--notice); color: var(--text); font-size: 11px; line-height: 1.45; }
.notice.blue { border-color: var(--blue); background: var(--notice-blue); }
.form { display: grid; gap: 11px; }
.row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.row.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
label { display: grid; gap: 5px; color: var(--muted); font-size: 11px; }
input, select, textarea { width: 100%; border: 1px solid var(--line); background: #0c1218; border-radius: 3px; color: var(--text); padding: 8px 9px; outline: none; font-size: 12px; }
input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 2px #2f9deb20; }
input, select, textarea { width: 100%; border: 1px solid var(--line); background: var(--panel-2); border-radius: 3px; color: var(--text); padding: 8px 9px; outline: none; font-size: 12px; }
input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 2px color-mix(in srgb, var(--blue) 14%, transparent); }
textarea { min-height: 74px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
.switch { display: flex; align-items: center; gap: 7px; color: var(--text); font-size: 12px; }
.switch input { width: auto; }
.buttons { display: flex; align-items: center; gap: 8px; margin-top: 3px; }
.btn { padding: 8px 11px; border: 1px solid var(--line); background: var(--panel-2); color: var(--text); border-radius: 3px; font-size: 11px; }
.btn:hover { border-color: #496071; }
.btn:hover { border-color: var(--line-strong); }
.btn.primary { background: var(--blue-strong); border-color: var(--blue-strong); color: white; }
.btn.danger { color: #ffb3b3; }
.btn.danger { color: var(--danger); background: var(--danger-soft); }
table { width: 100%; border-collapse: collapse; font-size: 11px; }
th { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .06em; font-weight: 500; text-align: left; padding: 0 9px 8px; }
td { border-top: 1px solid #202b35; padding: 10px 9px; vertical-align: top; }
tr:hover td { background: #131b23; }
.tag { display: inline-block; border: 1px solid #334657; color: #b7d9f5; border-radius: 2px; padding: 2px 5px; font-size: 9px; text-transform: uppercase; letter-spacing: .04em; }
.tag.gray { border-color: #3a424b; color: #a5afb9; }
td { border-top: 1px solid var(--line); padding: 10px 9px; vertical-align: top; }
tr:hover td { background: var(--row-hover); }
.tag { display: inline-block; border: 1px solid var(--tag-line); color: var(--tag-text); border-radius: 2px; padding: 2px 5px; font-size: 9px; text-transform: uppercase; letter-spacing: .04em; }
.tag.gray { border-color: var(--line-strong); color: var(--muted); }
.tag.warn { border-color: #735c32; color: #e2bb72; }
.empty { color: var(--muted); font-size: 12px; padding: 16px 0; }
@@ -76,7 +115,7 @@ tr:hover td { background: #131b23; }
.auth-card { width: 360px; border: 1px solid var(--line); background: var(--panel); border-radius: 6px; padding: 24px; }
.auth-card h1 { margin-bottom: 8px; }
.auth-card p { margin: 0 0 21px; color: var(--muted); font-size: 12px; line-height: 1.5; }
.error { margin-top: 10px; color: #ffaaaa; font-size: 11px; line-height: 1.4; }
.success { margin-top: 10px; color: #8ad5ff; font-size: 11px; line-height: 1.4; }
.error { margin-top: 10px; color: var(--danger); font-size: 11px; line-height: 1.4; }
.success { margin-top: 10px; color: var(--blue); font-size: 11px; line-height: 1.4; }
.hidden { display: none; }
@media (max-width: 1180px) { .grid.overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+130
View File
@@ -0,0 +1,130 @@
const updateReturnKey = 'seiugw-update-return';
function bindSystemUpdate() {
const content = document.querySelector('#content');
content.querySelector('.grid').insertAdjacentHTML('beforeend', `
<article class="card" id="system-update-card">
<div class="card-head"><h2>Gateway-Update</h2><button class="btn" type="button" data-check-update hidden>Verfügbarkeit prüfen</button></div>
<p class="note">Laufender Commit <code data-running-commit>–</code></p>
<p class="note" data-update-availability role="status"></p>
<p class="note" data-update-status role="status">Status wird geladen …</p>
<form class="form" hidden>
<label>Administrator-Passwort<input name="password" type="password" autocomplete="current-password" maxlength="512" required></label>
<div class="buttons"><button class="btn primary">Update starten</button></div>
<div data-update-error class="error" role="alert"></div>
</form>
</article>`);
const card = content.querySelector('#system-update-card');
const form = card.querySelector('form');
const fields = form.querySelectorAll('input, button');
const checkButton = card.querySelector('[data-check-update]');
const message = card.querySelector('[data-update-status]');
const runningCommit = card.querySelector('[data-running-commit]');
const availability = card.querySelector('[data-update-availability]');
const error = card.querySelector('[data-update-error]');
const activePhases = new Set(['checking', 'fetching', 'building', 'activating', 'rollingBack']);
const informationalPhases = new Set(['ready', 'current', 'unpublished']);
let lastRun = '';
let queuedUntil = 0;
let busy = false;
let checking = false;
let checked = false;
let updateAvailable = false;
function updateControls() {
form.hidden = !updateAvailable;
fields.forEach(field => { field.disabled = busy; });
checkButton.disabled = busy || checking;
}
async function checkAvailability(force = false) {
if (busy || checking) return;
checking = true;
updateAvailable = false;
availability.textContent = 'Update-Verfügbarkeit wird geprüft …';
updateControls();
try {
const result = await api(force ? '/api/system/update/availability?refresh=true' : '/api/system/update/availability');
if (!card.isConnected) return;
const branch = result.branch;
const version = result.remoteCommit?.slice(0, 8);
const details = {
current: `Auf ${branch} ist kein Update verfügbar.`,
available: `Update auf ${branch} verfügbar · ${version}`,
incompatible: `Der Stand auf ${branch} ist älter oder hat einen abweichenden Verlauf · ${version}`,
unknown: 'Die Update-Verfügbarkeit kann ohne Build-Commit nicht ermittelt werden.',
disabled: 'Die Verfügbarkeitsprüfung ist nicht eingerichtet.'
};
availability.textContent = details[result.state] || `Der Stand auf ${branch} konnte nicht geprüft werden.`;
availability.title = result.remoteCommit || '';
updateAvailable = result.state === 'available';
} catch (failure) {
availability.textContent = failure.message;
availability.title = '';
} finally {
checking = false;
checked = true;
updateControls();
}
}
async function refresh() {
if (!card.isConnected) return;
try {
const status = await api('/api/system/update');
if (!card.isConnected) return;
if (Date.now() < queuedUntil && (status.runId || '') === lastRun && !activePhases.has(status.phase)) {
setTimeout(refresh, 1500);
return;
}
queuedUntil = 0;
const checkNeeded = !checked || busy || (status.runId || '') !== lastRun;
lastRun = status.runId || '';
runningCommit.textContent = status.runningCommit?.slice(0, 8) || 'Unbekannt';
runningCommit.title = status.runningCommit || '';
message.textContent = informationalPhases.has(status.phase) ? '' : status.message;
checkButton.hidden = status.phase === 'disabled';
busy = activePhases.has(status.phase);
updateControls();
if (busy) {
sessionStorage.setItem(updateReturnKey, '1');
setTimeout(refresh, 1500);
} else {
sessionStorage.removeItem(updateReturnKey);
if (!checkButton.hidden && checkNeeded) await checkAvailability();
}
} catch (failure) {
if (!card.isConnected) return;
if (sessionStorage.getItem(updateReturnKey)) {
message.textContent = 'Verbindung zum Gateway wird wieder aufgebaut …';
setTimeout(refresh, 2000);
} else {
message.textContent = failure.message;
}
}
}
checkButton.addEventListener('click', () => checkAvailability(true));
form.addEventListener('submit', async event => {
event.preventDefault();
if (!updateAvailable || busy) return;
const body = JSON.stringify({ password: form.elements.password.value });
form.reset();
error.textContent = '';
busy = true;
updateControls();
try {
const status = await api('/api/system/update', { method: 'POST', body });
sessionStorage.setItem(updateReturnKey, '1');
message.textContent = status.message;
queuedUntil = Date.now() + 10000;
setTimeout(refresh, 750);
} catch (failure) {
error.textContent = failure.message;
busy = false;
updateControls();
}
});
refresh();
}
@@ -0,0 +1,14 @@
(function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.markdownit=t())})(this,function(){var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n={};function r(e){let t=n[e];if(t)return t;t=n[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);t.push(n)}for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[r]=`%`+(`0`+r.toString(16).toUpperCase()).slice(-2)}return t}function i(e,t){typeof t!=`string`&&(t=i.defaultChars);let n=r(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t=``;for(let r=0,i=e.length;r<i;r+=3){let a=parseInt(e.slice(r+1,r+3),16);if(a<128)t+=n[a];else{if((a&224)==192&&r+3<i){let n=parseInt(e.slice(r+4,r+6),16);if((n&192)==128){let e=a<<6&1984|n&63;t+=e<128?`��`:String.fromCharCode(e),r+=3;continue}}if((a&240)==224&&r+6<i){let n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16);if((n&192)==128&&(i&192)==128){let e=a<<12&61440|n<<6&4032|i&63;t+=e<2048||e>=55296&&e<=57343?`���`:String.fromCharCode(e),r+=6;continue}}if((a&248)==240&&r+9<i){let n=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),o=parseInt(e.slice(r+10,r+12),16);if((n&192)==128&&(i&192)==128&&(o&192)==128){let e=a<<18&1835008|n<<12&258048|i<<6&4032|o&63;e<65536||e>1114111?t+=`����`:(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(e&1023))),r+=9;continue}}t+=`�`}}return t})}i.defaultChars=`;/?:@&=+$,#`,i.componentChars=``;var a={};function o(e){let t=a[e];if(t)return t;t=a[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);/^[0-9a-z]$/i.test(n)?t.push(n):t.push(`%`+(`0`+e.toString(16).toUpperCase()).slice(-2))}for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=e[n];return t}function s(e,t,n){typeof t!=`string`&&(n=t,t=s.defaultChars),n===void 0&&(n=!0);let r=o(t),i=``;for(let t=0,a=e.length;t<a;t++){let o=e.charCodeAt(t);if(n&&o===37&&t+2<a&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))i+=e.slice(t,t+3),t+=2;else if(o<128)i+=r[o];else if(o>=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1<a){let n=e.charCodeAt(t+1);if(n>=56320&&n<=57343){i+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}i+=`%EF%BF%BD`}else i+=encodeURIComponent(e[t])}return i}s.defaultChars=`;/?:@&=+$,-_.!~*'()#`,s.componentChars=`-_.!~*'()`;function c(e){let t=``;return t+=e.protocol||``,t+=e.slashes?`//`:``,t+=e.auth?e.auth+`@`:``,e.hostname&&e.hostname.indexOf(`:`)!==-1?t+=`[`+e.hostname+`]`:t+=e.hostname||``,t+=e.port?`:`+e.port:``,t+=e.pathname||``,t+=e.search||``,t+=e.hash||``,t}function l(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}var u=/^([a-z0-9.+-]+:)/i,d=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,p=[`%`,`/`,`?`,`;`,`#`,`'`,`{`,`}`,`|`,`\\`,`^`,"`",`<`,`>`,`"`,"`",` `,`\r`,`
`,` `],m=[`/`,`?`,`#`],h=255,g=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function b(e,t){if(e&&e instanceof l)return e;let n=new l;return n.parse(e,t),n}l.prototype.parse=function(e,t){let n,r,i,a=e;if(a=a.trim(),!t&&e.split(`#`).length===1){let e=f.exec(a);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=u.exec(a);if(o&&(o=o[0],n=o.toLowerCase(),this.protocol=o,a=a.substr(o.length)),(t||o||a.match(/^\/\/[^@\/]+@[^@\/]+/))&&(i=a.substr(0,2)===`//`,i&&!(o&&v[o])&&(a=a.substr(2),this.slashes=!0)),!v[o]&&(i||o&&!y[o])){let e=-1;for(let t=0;t<m.length;t++)r=a.indexOf(m[t]),r!==-1&&(e===-1||r<e)&&(e=r);let t,n;n=e===-1?a.lastIndexOf(`@`):a.lastIndexOf(`@`,e),n!==-1&&(t=a.slice(0,n),a=a.slice(n+1),this.auth=t),e=-1;for(let t=0;t<p.length;t++)r=a.indexOf(p[t]),r!==-1&&(e===-1||r<e)&&(e=r);e===-1&&(e=a.length),a[e-1]===`:`&&e--;let i=a.slice(0,e);a=a.slice(e),this.parseHost(i),this.hostname=this.hostname||``;let o=this.hostname[0]===`[`&&this.hostname[this.hostname.length-1]===`]`;if(!o){let e=this.hostname.split(/\./);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n&&!n.match(g)){let r=``;for(let e=0,t=n.length;e<t;e++)n.charCodeAt(e)>127?r+=`x`:r+=n[e];if(!r.match(g)){let r=e.slice(0,t),i=e.slice(t+1),o=n.match(_);o&&(r.push(o[1]),i.unshift(o[2])),i.length&&(a=i.join(`.`)+a),this.hostname=r.join(`.`);break}}}}this.hostname.length>h&&(this.hostname=``),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}let s=a.indexOf(`#`);s!==-1&&(this.hash=a.substr(s),a=a.slice(0,s));let c=a.indexOf(`?`);return c!==-1&&(this.search=a.substr(c),a=a.slice(0,c)),a&&(this.pathname=a),y[n]&&this.hostname&&!this.pathname&&(this.pathname=``),this},l.prototype.parseHost=function(e){let t=d.exec(e);t&&(t=t[0],t!==`:`&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var x=t({decode:()=>i,encode:()=>s,format:()=>c,parse:()=>b}),S=t({Any:()=>C,Cc:()=>ee,Cf:()=>te,P:()=>ne,S:()=>re,Z:()=>ie}),C=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,ee=/[\0-\x1F\x7F-\x9F]/,te=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,ne=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B4E\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDD6E\uDEAD\uDED0\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9\uDFD4\uDFD5\uDFD7\uDFD8]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09\uDFE1]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDD6D-\uDD6F\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD839\uDDFF|\uD83A[\uDD5E\uDD5F]/,re=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\ Line truncated
`;if(o){let e=a.attrIndex(`class`),t=a.attrs?a.attrs.slice():[];e<0?t.push([`class`,`${n.langPrefix}${s}`]):(t[e]=[t[e][0],t[e][1]],t[e][1]+=` ${n.langPrefix}${s}`);let r={attrs:t};return`<pre><code${i.renderAttrs(r)}>${l}</code></pre>\n`}return`<pre><code${i.renderAttrs(a)}>${l}</code></pre>\n`},V.image=function(e,t,n,r,i){let a=e[t];return a.attrs[a.attrIndex(`alt`)][1]=i.renderInlineAsText(a.children,n,r),i.renderToken(e,t,n)},V.hardbreak=function(e,t,n){return n.xhtmlOut?`<br />
`:`<br>
`},V.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?`<br />
`:`<br>
`:`
`},V.text=function(e,t){return M(e[t].content)},V.html_block=function(e,t){return e[t].content},V.html_inline=function(e,t){return e[t].content};var Ze=class{constructor(){D(this,`rules`,Object.assign({},V))}renderAttrs(e){let t,n,r;if(!e.attrs)return``;for(r=``,t=0,n=e.attrs.length;t<n;t++)r+=` ${M(e.attrs[t][0])}="${M(String(e.attrs[t][1]))}"`;return r}renderToken(e,t,n){let r=e[t],i=``;if(r.hidden)return``;let a=t-1;for(;a>=0&&e[a].hidden&&e[a].nesting===0;)a--;r.block&&r.nesting!==-1&&a>=0&&e[a].hidden&&e[a].nesting===-1&&(i+=`
`),i+=(r.nesting===-1?`</`:`<`)+r.tag,i+=this.renderAttrs(r),r.nesting===0&&n.xhtmlOut&&(i+=` /`);let o=!1;if(r.block&&(o=!0,r.nesting===1)){let n=t+1;for(;n<e.length&&e[n].hidden&&e[n].nesting===0;)n++;if(n<e.length){let t=e[n];(t.type===`inline`||t.hidden||t.nesting===-1&&t.tag===r.tag)&&(o=!1)}}return i+=o?`>
`:`>`,i}renderInline(e,t,n){let r=``,i=this.rules;for(let a=0,o=e.length;a<o;a++){let o=e[a].type;i[o]===void 0?r+=this.renderToken(e,a,t):r+=i[o](e,a,t,n,this)}return r}renderInlineAsText(e,t,n){let r=``;for(let i=0,a=e.length;i<a;i++)switch(e[i].type){case`text`:case`code_inline`:r+=e[i].content;break;case`image`:r+=this.renderInlineAsText(e[i].children,t,n);break;case`html_inline`:case`html_block`:r+=e[i].content;break;case`softbreak`:case`hardbreak`:r+=`
`}return r}render(e,t,n){let r=``,i=this.rules;for(let a=0,o=e.length;a<o;a++){let o=e[a].type;o===`inline`?r+=this.renderInline(e[a].children,t,n):i[o]===void 0?r+=this.renderToken(e,a,t):r+=i[o](e,a,t,n,this)}return r}},Qe=class{constructor(e,t,n){D(this,`tokens`,[]),D(this,`inlineMode`,!1),D(this,`Token`,z),this.src=e,this.env=n,this.md=t}},$e=/\r\n?/g,et=/\0/g;function tt(e){let t;t=e.src.replace($e,`
`),t=t.replace(et,`�`),e.src=t}function nt(e){let t;e.inlineMode?(t=new e.Token(`inline`,``,0),t.content=e.src,t.map=[0,1],t.children=[],e.tokens.push(t)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}function rt(e){let t=e.tokens,n=0;for(let e=0;e<t.length;e++)t[e].type!==`reference_definition`&&(e!==n&&(t[n]=t[e]),n++);t.length!==n&&(t.length=n)}function it(e){let t=e.tokens;for(let n=0,r=t.length;n<r;n++){let r=t[n];r.type===`inline`&&e.md.inline.parse(r.content,e.md,e.env,r.children)}}function at(e){return/^<a[>\s]/i.test(e)}function ot(e){return/^<\/a\s*>/i.test(e)}function st(e){let t=e.tokens;if(e.md.options.linkify)for(let n=0,r=t.length;n<r;n++){if(t[n].type!==`inline`||!e.md.linkify.test(t[n].content))continue;let r=t[n].children,i=[],a=0;for(let t=r.length-1;t>=0;t--){let n=r[t];if(n.type===`link_close`)for(t--;r[t].level!==n.level&&r[t].type!==`link_open`;)t--;else if(n.type===`html_inline`&&(at(n.content)&&a>0&&a--,ot(n.content)&&a++),!(a>0)&&n.type===`text`&&e.md.linkify.test(n.content)){let a=n.content,o=e.md.linkify.match(a),s=[],c=n.level,l=0;o.length>0&&o[0].index===0&&t>0&&r[t-1].type===`text_special`&&(o=o.slice(1));for(let t=0;t<o.length;t++){let n=o[t].url,r=e.md.normalizeLink(n);if(!e.md.validateLink(r))continue;let i=o[t].text;i=o[t].schema?o[t].schema===`mailto:`&&!/^mailto:/i.test(i)?e.md.normalizeLinkText(`mailto:${i}`).replace(/^mailto:/,``):e.md.normalizeLinkText(i):e.md.normalizeLinkText(`http://${i}`).replace(/^http:\/\//,``);let u=o[t].index;if(u>l){let t=new e.Token(`text`,``,0);t.content=a.slice(l,u),t.level=c,s.push(t)}let d=new e.Token(`link_open`,`a`,1);d.attrs=[[`href`,r]],d.level=c++,d.markup=`linkify`,d.info=`auto`,s.push(d);let f=new e.Token(`text`,``,0);f.content=i,f.level=c,s.push(f);let p=new e.Token(`link_close`,`a`,-1);p.level=--c,p.markup=`linkify`,p.info=`auto`,s.push(p),l=o[t].lastIndex}if(l<a.length){let t=new e.Token(`text`,``,0);t.content=a.slice(l),t.level=c,s.push(t)}i.push({index:t,nodes:s})}}if(i.length>0){let e=r.length;for(let t of i)e+=t.nodes.length-1;let a=Array(e),o=0,s=0;i.reverse();for(let e=0;e<r.length;e++){let t=i[o];if((t==null?void 0:t.index)===e){for(let e of t.nodes)a[s++]=e;o++}else a[s++]=r[e]}t[n].children=a}}}var ct=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,lt=/\((c|tm|r)\)/i,ut=/\((c|tm|r)\)/gi,dt={c:`©`,r:`®`,tm:`™`};function ft(e,t){return dt[t.toLowerCase()]}function pt(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];r.type===`text`&&!t&&(r.content=r.content.replace(ut,ft)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function mt(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];r.type===`text`&&!t&&ct.test(r.content)&&(r.content=r.content.replace(/\+-/g,`±`).replace(/\.{2,}/g,`…`).replace(/([?!])…/g,`$1..`).replace(/([?!]){4,}/g,`$1$1$1`).replace(/,{2,}/g,`,`).replace(/(^|[^-])---(?=[^-]|$)/gm,`$1—`).replace(/(^|\s)--(?=\s|$)/gm,`$1–`).replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,`$1–`)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function ht(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)e.tokens[t].type===`inline`&&(lt.test(e.tokens[t].content)&&pt(e.tokens[t].children),ct.test(e.tokens[t].content)&&mt(e.tokens[t].children))}var gt=/['"]/,_t=/['"]/g,vt=`’`,yt=1e3;function bt(e,t,n){for(;e.length>n;){let n=e.pop();n.isSingleQuote?t.single=n.prevSameQuoteIdx:t.double=n.prevSameQuoteIdx}}function H(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function xt(e,t){let n=``,r=0;t.sort((e,t)=>e.pos-t.pos);for(let i=0;i<t.length;i++){let a=t[i];n+=e.slice(r,a.pos)+a.ch,r=a.pos+1}return n+e.slice(r)}function St(e,t){let n,r=[],i={single:-1,double:-1},a={};for(let o=0;o<e.length;o++){let s=e[o],c=e[o].level;for(n=r.length-1;n>=0&&!(r[n].level<=c);n--);if(bt(r,i,n+1),s.type!==`text`)continue;let l=s.content,u=0,d=l.length;OUTER:for(;u<d;){_t.lastIndex=u;let s=_t.exec(l);if(!s)break;let f=!0,p=!0;u=s.index+1;let m=s[0]===`'`,h=32;if(s.index-1>=0)h=l.charCodeAt(s.index-1);else for(n=o-1;n>=0&&e[n].type!==`softbreak`&&e[n].type!==`hardbreak`;n--)if(e[n].content){h=e[n].content.charCodeAt(e[n].content.length-1);break}let g=32;if(u<d)g=l.charCodeAt(u);else for(n=o+1;n<e.length&&e[n].type!==`softbreak`&&e[n].type!==`hardbreak`;n++)if(e[n].content){g=e[n].content.charCodeAt(0);break}let _=I(h)||F(h),v=I(g)||F(g),y=P(h),b=P(g);if(b?f=!1:v&&(y||_||(f=!1)),y?p=!1:_&&(b||v||(p=!1)),g===34&&s[0]===`"`&&h>=48&&h<=57&&(p=f=!1),f&&p&&(f=_,p=v),!f&&!p)m&&H(a,o,s.index,vt);else{if(p&&(n=m?i.single:i.double,n>=0&&r[n].level===c)){let e=r[n],c,l;m?(c=t.md.options.quotes[2],l=t.md.options.quotes[3]):(c=t.md.options.quotes[0],l=t.md.options.quotes[1]),H(a,o,s.index,l),H(a,e.tokenIdx,e.contentPos,c),bt(r,i,n);continue OUTER}if(f){if(r.length>=yt)return;r.push({tokenIdx:o,contentPos:s.index,isSingleQuote:m,level:c,prevSameQuoteIdx:m?i.single:i.double}),m?i.single=r.length-1:i.double=r.length-1}else p&&m&&H(a,o,s.index,vt)}}}Object.keys(a).forEa Line truncated
`,a.map=[t,e.line],!0}function Pt(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4||i+3>a)return!1;let o=e.src.charCodeAt(i);if(o!==126&&o!==96)return!1;let s=i;i=e.skipChars(i,o);let c=i-s;if(c<3)return!1;let l=e.src.slice(s,i),u=e.src.slice(i,a);if(o===96&&u.indexOf(String.fromCharCode(o))>=0)return!1;if(r)return!0;let d=t,f=!1;for(;d++,!(d>=n||(i=s=e.bMarks[d]+e.tShift[d],a=e.eMarks[d],i<a&&e.sCount[d]<e.blkIndent));)if(e.src.charCodeAt(i)===o&&!(e.sCount[d]-e.blkIndent>=4)&&(i=e.skipChars(i,o),!(i-s<c)&&(i=e.skipSpaces(i),!(i<a)))){f=!0;break}c=e.sCount[t],e.line=d+ +!!f;let p=e.push(`fence`,`code`,0);return p.info=u,p.content=e.getLines(t+1,d,c,!0),p.markup=l,p.map=[t,e.line],!0}function Ft(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t],o=e.lineMax;if(e.sCount[t]-e.blkIndent>=4||e.src.charCodeAt(i)!==62)return!1;if(r)return!0;let s=[],c=[],l=[],u=[],d=e.md.block.ruler.getRules(`blockquote`),f=e.parentType;e.parentType=`blockquote`;let p=!1,m;for(m=t;m<n;m++){let t=e.sCount[m]<e.blkIndent;if(i=e.bMarks[m]+e.tShift[m],a=e.eMarks[m],i>=a)break;if(e.src.charCodeAt(i++)===62&&!t){let t=e.sCount[m]+1,n,r;e.src.charCodeAt(i)===32?(i++,t++,r=!1,n=!0):e.src.charCodeAt(i)===9?(n=!0,(e.bsCount[m]+t)%4==3?(i++,t++,r=!1):r=!0):n=!1;let o=t;for(s.push(e.bMarks[m]),e.bMarks[m]=i;i<a;){let t=e.src.charCodeAt(i);if(N(t))t===9?o+=4-(o+e.bsCount[m]+ +!!r)%4:o++;else break;i++}p=i>=a,c.push(e.bsCount[m]),e.bsCount[m]=e.sCount[m]+1+ +!!n,l.push(e.sCount[m]),e.sCount[m]=o-t,u.push(e.tShift[m]),e.tShift[m]=i-e.bMarks[m];continue}if(p)break;let r=!1;for(let t=0,i=d.length;t<i;t++)if(d[t](e,m,n,!0)){r=!0;break}if(r){e.lineMax=m,e.blkIndent!==0&&(s.push(e.bMarks[m]),c.push(e.bsCount[m]),u.push(e.tShift[m]),l.push(e.sCount[m]),e.sCount[m]-=e.blkIndent);break}s.push(e.bMarks[m]),c.push(e.bsCount[m]),u.push(e.tShift[m]),l.push(e.sCount[m]),e.sCount[m]=-1}let h=e.blkIndent;e.blkIndent=0;let g=e.push(`blockquote_open`,`blockquote`,1);g.markup=`>`;let _=[t,0];g.map=_,e.md.block.tokenize(e,t,m);let v=e.push(`blockquote_close`,`blockquote`,-1);v.markup=`>`,e.lineMax=o,e.parentType=f,_[1]=e.line;for(let n=0;n<u.length;n++)e.bMarks[n+t]=s[n],e.tShift[n+t]=u[n],e.sCount[n+t]=l[n],e.bsCount[n+t]=c[n];return e.blkIndent=h,!0}function It(e,t,n,r){let i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let a=e.bMarks[t]+e.tShift[t],o=e.src.charCodeAt(a++);if(o!==42&&o!==45&&o!==95)return!1;let s=1;for(;a<i;){let t=e.src.charCodeAt(a++);if(t!==o&&!N(t))return!1;t===o&&s++}if(s<3)return!1;if(r)return!0;e.line=t+1;let c=e.push(`hr`,`hr`,0);return c.map=[t,e.line],c.markup=Array(s+1).join(String.fromCharCode(o)),!0}function Lt(e,t){let n=e.eMarks[t],r=e.bMarks[t]+e.tShift[t],i=e.src.charCodeAt(r++);return i!==42&&i!==45&&i!==43||r<n&&!N(e.src.charCodeAt(r))?-1:r}function Rt(e,t){let n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t],i=n;if(i+1>=r)return-1;let a=e.src.charCodeAt(i++);if(a<48||a>57)return-1;for(;;){if(i>=r)return-1;if(a=e.src.charCodeAt(i++),a>=48&&a<=57){if(i-n>=10)return-1}else{if(a===41||a===46)break;return-1}}return i<r&&(a=e.src.charCodeAt(i),!N(a))?-1:i}function zt(e,t){let n=e.level+2;for(let r=t+2,i=e.tokens.length-2;r<i;r++)e.tokens[r].level===n&&e.tokens[r].type===`paragraph_open`&&(e.tokens[r+2].hidden=!0,e.tokens[r].hidden=!0,r+=2)}function Bt(e,t,n,r){let i,a,o,s,c=t,l=!0;if(e.sCount[c]-e.blkIndent>=4||e.listIndent>=0&&e.sCount[c]-e.listIndent>=4&&e.sCount[c]<e.blkIndent)return!1;let u=!1;r&&e.parentType===`paragraph`&&e.sCount[c]>=e.blkIndent&&(u=!0);let d,f,p;if((p=Rt(e,c))>=0){if(d=!0,o=e.bMarks[c]+e.tShift[c],f=Number(e.src.slice(o,p-1)),u&&f!==1)return!1}else if((p=Lt(e,c))>=0)d=!1;else return!1;if(u&&e.skipSpaces(p)>=e.eMarks[c])return!1;if(r)return!0;let m=e.src.charCodeAt(p-1),h=e.tokens.length;d?(s=e.push(`ordered_list_open`,`ol`,1),f!==1&&(s.attrs=[[`start`,f]])):s=e.push(`bullet_list_open`,`ul`,1);let g=[c,0];s.map=g,s.markup=String.fromCharCode(m);let _=!1,v=e.md.block.ruler.getRules(`list`),y=e.parentType;for(e.parentType=`list`;c<n;){a=p,i=e.eMarks[c];let t=e.sCount[c]+p-(e.bMarks[c]+e.tShift[c]),r=t;for(;a<i;){let t=e.src.charCodeAt(a);if(t===9)r+=4-(r+e.bsCount[c])%4;else if(t===32)r++;else break;a++}let u=a,f;f=u>=i?1:r-t,f>4&&(f=1);let h=t+f;s=e.push(`list_item_open`,`li`,1),s.markup=String.fromCharCode(m);let g=[c,0];s.map=g,d&&(s.info=e.src.slice(o,p-1));let y=e.tight,b=e.tShift[c],x=e.sCount[c],S=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=h,e.tight=!0,e.tShift[c]=u-e.bMarks[c],e.sCount[c]=r,u>=i&&e.isEmpty(c+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,c,n),(!e.tight||_)&&(l=!1),_=e.line-c>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=S,e.tShift[c]=b,e.sCount[c]=x,e.tight=y,s=e.push(`list_item_close`,`li`,-1),s.markup=String.fromCharCode(m),c=e.line,g[1]=c,c>=n||e.sCount[c]<e.blkIndent||e.sCount[c]-e.blkIndent>=4)break;let C=!1;for(let t=0,r=v.length;t<r;t++)if(v[t](e,c,n,!0)){C=!0;break}if(C)break;if(d){if(p=Rt(e,c),p<0)break;o=e.bMar Line truncated
//# sourceMappingURL=markdown-it.umd.min.js.map
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,37 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Services;
using Microsoft.Extensions.Logging.Abstractions;
internal static class BacnetBridgeTests
{
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
{
var point = store.CreatePoint(new CreatePointRequest("Native priority bridge AV", PointProtocol.Bacnet, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue));
var trend = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "Native observed trend", 902, 1, 100, true));
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(22), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good", bacnetPriority: 16);
Check(store.ListPointValues().All(value => value.PointId != point.Id), "A BACnet command must not become an effective value before native arbitration.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 0, "Commands must not be trended as actual values.");
using var connection = database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT priority FROM bacnet_commands WHERE point_id=$id";
command.Parameters.AddWithValue("$id", point.Id.ToString());
Check((long)command.ExecuteScalar()! == 16, "BACnet priority must reach the native queue.");
command.CommandText = "INSERT OR REPLACE INTO bacnet_runtime VALUES(1,$time,'Test'); INSERT INTO bacnet_observations(point_id,value_json,status,observed_ms) VALUES($id,'30','Good',$time)";
command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); command.ExecuteNonQuery();
using var bridge = new BacnetNativeBridgeService(database, store, NullLogger<BacnetNativeBridgeService>.Instance);
await bridge.StartAsync(CancellationToken.None);
try
{
var deadline = DateTime.UtcNow.AddSeconds(3);
while (store.ListPointValues().All(value => value.PointId != point.Id)) { if (DateTime.UtcNow > deadline) throw new InvalidOperationException("Native observation timed out."); await Task.Delay(25); }
Check(store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetInt32() == 30, "Native arbitration must determine the effective value.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 1, "Native observations must feed the trend once.");
command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE point_id=$id";
Check((long)command.ExecuteScalar()! == 1, "Native feedback must not enqueue another write.");
}
finally { await bridge.StopAsync(CancellationToken.None); }
Console.WriteLine("BACnet bridge tests passed: command/observation separation, priority transport, effective-value trend, no echo.");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
+137
View File
@@ -0,0 +1,137 @@
using System.Net;
using System.Text.Json;
using Gateway.Api.Contracts;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
internal static class LtdFeatureTests
{
private static readonly string[] WhatsAppFieldNames = ["api_key", "message", "number", "pn", "template"];
public static async Task RunAsync(GatewayStore store, GatewayDatabase database, IOptions<GatewayOptions> options, AuthenticatedGatewayUser admin)
{
var source = store.CreatePoint(new CreatePointRequest("Vorlauftemperatur", PointProtocol.Bacnet, PointScope.Gateway,
"Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue, 601));
var opc = store.CreatePoint(new CreatePointRequest("OPC-UA Betriebszustand", PointProtocol.OpcUa, PointScope.Gateway,
"Boolean", true, true, null, JsonSerializer.SerializeToElement(new { })));
var bacnetLog = store.CreateTrendLog(new CreateTrendLogRequest(source.Id, "Vorlauftemperatur", 601, 1, 1000, true));
var opcLog = store.CreateTrendLog(new CreateTrendLogRequest(opc.Id, "Betriebszustand", 602, 1, 1000, true));
var start = DateTimeOffset.UtcNow.AddHours(-2);
for (var index = 0; index < 120; index++)
{
store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(25 + Math.Sin(index / 15d) * 3), PointProtocol.Bacnet, start.AddMinutes(index));
store.SetPointValue(opc.Id, JsonSerializer.SerializeToElement(index % 20 < 10), PointProtocol.OpcUa, start.AddMinutes(index));
}
Check(store.ListTrendRecords(bacnetLog.Id, 200).Count == 120 && store.ListTrendRecords(opcLog.Id, 200).Count == 120,
"Gateway-owned BACnet and OPC UA point updates must feed their internal trends.");
store.SaveDisplayUnit(new DisplayUnit("bar", "Bar"));
store.SaveDisplayUnit(new DisplayUnit("°C", "Grad Celsius", false));
Check(store.ListDisplayUnits().Single(unit => unit.Symbol == "°C").IsSystem, "System units must retain their identity.");
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#12d0d3"), new(opc.Id, "Betrieb Anlage 1", "bool", 1, "digital", "#27e72e")]);
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#c9dc1e")]);
Check(store.ListPointPresentations().Count == 2, "Partial alias updates must not delete other aliases.");
var export = store.ListTrendExportRows([bacnetLog.Id], start);
Check(export.Count == 120 && export.All(row => row.PointName == "Vorlauf Anlage 1" && row.Unit == "°C"), "CSV exports must use the configured aliases and units.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "missing", 1, "analog", "#ffffff")]), "Unknown units must be rejected.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "°C", 1, "analog", "red;display:none")]), "CSS injection must be rejected.");
var selection = store.CreateTrendSelection(new CreateTrendSelectionRequest("Heizkreis", null, false, [bacnetLog.Id]), admin.User.Id);
store.SaveDashboard(admin.User.Id, true, [new(Guid.NewGuid(), "Heizkreis – Vorlauf", selection.Id, 24, "Graph")]);
Check(store.GetDashboard(admin.User.Id).Count == 1, "Widgets must persist per user.");
var viewer = store.CreateUser(new CreateUserRequest("ltd.viewer", "LTD Viewer", null, "safe testing password", "viewer"));
Reject(() => store.SaveDashboard(viewer.Id, false, [new(Guid.NewGuid(), "Private", selection.Id, 24, "Graph")]), "Other users' private selections must not be added to dashboards.");
store.UpdateKomariEnrollmentToken("test-komari-enrollment");
var tokenPath = Path.Combine(options.Value.DataDirectory, "token-test");
Check(store.MaterializeKomariEnrollmentToken(tokenPath) && File.ReadAllText(tokenPath) == "test-komari-enrollment", "Encrypted Komari token must materialize for the agent.");
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new("test-secret-" + channel));
using (var connection = database.OpenConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT value FROM settings WHERE key LIKE 'integration.%.api-key' OR key = 'komari.enrollment-token';";
using var reader = command.ExecuteReader();
while (reader.Read()) Check(!reader.GetString(0).Contains("test-", StringComparison.Ordinal), "Keys must not be stored in plaintext.");
}
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Saved keys must roundtrip.");
store.UpdateNotificationKey(NotificationChannel.Mail, new(null));
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Empty key edit must retain an existing key.");
Check(NotificationTransport.NormalizeTemplateText(" Störung\r\n\t Küche 21 °C 😀 ") == "Störung Küche 21 °C 😀", "WhatsApp must normalize whitespace and preserve Unicode.");
Reject(() => NotificationTransport.NormalizeTemplateText(new string('a', 1025)), "Overlong template parameters must not be truncated or sent.");
var destination = new AlarmDestination(NotificationChannel.WhatsApp, "+491234567890", "stoerung", "Prüfung");
var rule = store.SaveAlarmRule(new AlarmRule(Guid.Empty, "Vorlauf hoch", source.Id, AlarmCondition.Above, 30, 2, true, true, "Temperatur prüfen\nHeizkreis 1", [destination]));
var alarmTime = DateTimeOffset.UtcNow;
void Observe(double value, int seconds, string? status = null) => store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(value), PointProtocol.Bacnet, alarmTime.AddSeconds(seconds), status);
Observe(29, 1); Check(store.ListNotificationDeliveries().Count == 0, "Initial normal state must not send a recovery.");
Observe(31, 2); Observe(31, 3); Observe(29, 4);
Check(store.ListNotificationDeliveries().Count == 1, "Unchanged and hysteresis-band values must not repeat an alarm.");
var delivery = store.ClaimNotification()!;
Check(delivery.State == "Sending" && store.ClaimNotification() is null, "A notification can be claimed only once.");
using (var form = NotificationTransport.BuildAlarmForm("mock-key", delivery))
{
var fields = new Dictionary<string, string>();
foreach (var part in form) fields[part.Headers.ContentDisposition!.Name!.Trim('"')] = await part.ReadAsStringAsync();
Check(fields.Keys.Order().SequenceEqual(WhatsAppFieldNames.Order()), "WhatsApp form fields must match the supplied PHP API.");
Check(!fields["message"].Contains('\n') && fields["message"].Contains("prüfen", StringComparison.Ordinal), "Sent template variables must be normalized Unicode text.");
}
store.RecoverInterruptedNotifications();
Check(store.ListNotificationDeliveries().Single().State == "Unknown", "Uncertain sends must not be automatically duplicated after restart.");
Observe(27, 5); Observe(32, 4); Observe(33, 6, "bad");
Check(store.ListNotificationDeliveries().Count == 2, "Recovery should send once; stale or invalid-quality observations must not alarm.");
store.SaveAlarmRule(rule with { Message = "Neue Beschreibung" });
Observe(27, 7);
Check(store.ListNotificationDeliveries().Count == 2, "Editing descriptions must preserve alarm edge state.");
Observe(31, 8);
Check(store.ListNotificationDeliveries().Count == 3, "A new rising edge must send again.");
store.DeleteAlarmRule(rule.Id);
Check(store.ClaimNotification() is null, "Deleting a rule must cancel pending sends.");
store.UpdateNotificationKey(NotificationChannel.WhatsApp, new(null, true));
Reject(() => store.SaveAlarmRule(rule with { Id = Guid.Empty }), "A channel without a key must not activate an alarm.");
var handler = new FakeNotificationHandler();
var transport = new NotificationTransport(new FakeClientFactory(handler));
await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None);
Check(handler.Address == "https://whatsappapi.se-inno.de/" && handler.Multipart, "Notifications must use the fixed endpoint and multipart forms.");
handler.ResponseBody = "{\"success\":false,\"error\":\"secret raw response\"}";
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("API error should fail."); }
catch (DomainValidationException exception) { Check(!exception.Message.Contains("secret raw", StringComparison.Ordinal), "Remote response must not leak into logs or UI."); }
handler.ResponseBody = "{}"; handler.Status = HttpStatusCode.BadRequest;
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("HTTP error should fail."); }
catch (DomainValidationException) { }
var sessions = new SessionService(store);
var session = "Bearer " + sessions.Create(store.Authenticate(viewer.Username, "safe testing password")!);
Check(sessions.IsValid(session), "Viewer session must initially authenticate.");
store.UpdateUser(viewer.Id, new(null, null, null, null, null, false), admin.User.Id);
Check(!sessions.IsValid(session), "Disabling users must revoke existing sessions immediately.");
// Leave preview fixtures inert: no credentials or active alarm rules can send messages.
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new(null, true));
var configuration = store.GetGatewayConfiguration();
store.UpdateGatewayConfiguration(configuration with { OpcUa = configuration.OpcUa with { ServerEnabled = false }, Mqtt = (configuration.Mqtt ?? MqttConfiguration.CreateDefault()) with { Enabled = false }, ModbusServers = [] });
Console.WriteLine("LTD presentation, notifications, encryption and session tests passed (no real API messages).");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
private static void Reject(Action action, string message)
{
try { action(); } catch (DomainValidationException) { return; }
throw new InvalidOperationException(message);
}
private sealed class FakeClientFactory(FakeNotificationHandler handler) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private sealed class FakeNotificationHandler : HttpMessageHandler
{
public string? Address { get; private set; }
public bool Multipart { get; private set; }
public string ResponseBody { get; set; } = "{\"success\":true}";
public HttpStatusCode Status { get; set; } = HttpStatusCode.OK;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Address = request.RequestUri!.AbsoluteUri;
Multipart = request.Content is MultipartFormDataContent;
return Task.FromResult(new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) });
}
}
}
@@ -0,0 +1,89 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Opc.Ua;
#pragma warning disable CS0618
internal static class OpcUaClientTests
{
public static async Task RunAsync(GatewayStore remote, GatewayOpcUaServer server, string url, GatewayPoint remotePoint,
ApplicationConfiguration serverConfiguration)
{
var options = Options.Create(new GatewayOptions { DataDirectory = Path.Combine(Path.GetTempPath(), "seiugw-ua-client-" + Guid.NewGuid().ToString("N")),
Bacnet = new BacnetBootstrapOptions { Interface = "lo", DeviceInstance = 24, IpPort = 47829 } });
var database = new GatewayDatabase(options);
var store = new GatewayStore(database, new PasswordService(), new MappingValidator(), new SecretProtector(options), options);
store.Initialize();
var applications = new OpcUaApplicationFactory(database);
var config = await applications.CreateClientConfigurationAsync();
using (var trust = config.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(serverConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate);
using (var trust = serverConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(config.SecurityConfiguration.ApplicationCertificate.Certificate);
await serverConfiguration.CertificateValidator.UpdateAsync(serverConfiguration.SecurityConfiguration);
var client = store.SaveOpcUaClient(new SaveOpcUaClientRequest(new OpcUaClientConfiguration(Guid.NewGuid(), "Wire client", url,
OpcUaAuthenticationMode.Username, "admin", PublishingIntervalMilliseconds: 100), "correct horse battery staple")).Configuration;
store.SaveOpcUaClient(new SaveOpcUaClientRequest(client)); // Blank edit retains the encrypted password.
Check(store.GetOpcUaClientCredentials(client.Id).Password == "correct horse battery staple", "Saved password must survive edits.");
using (var connection = database.OpenConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT value FROM settings WHERE key LIKE 'opcua.password.%'";
Check(!((string)command.ExecuteScalar()!).Contains("correct horse", StringComparison.Ordinal), "OPC UA password must be encrypted at rest.");
}
var browser = new OpcUaBrowserService(applications, store);
var browsed = await browser.BrowseAsync(new OpcUaBrowseRequest("", "nsu=" + GatewayOpcUaServer.PointsNamespace + ";s=Gateway", ClientId: client.Id));
var item = browsed.Single(item => item.DisplayName == remotePoint.DisplayName);
Check(item.ValueType == "Float" && item.Writable && item.StableNodeId!.Contains("nsu=", StringComparison.Ordinal), "Import needs scalar type, access and a stable namespace URI.");
var imported = store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)]));
var point = imported.Single();
Check(store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)])).Count == 0, "Duplicate import must not create duplicate writers.");
var local = store.CreatePoint(new CreatePointRequest("Local setpoint", PointProtocol.Internal, PointScope.Internal, "Float", true, true, null, JsonSerializer.SerializeToElement(new { })));
store.CreateMapping(new CreateMappingRequest(local.Id, point.Id, MappingDirection.Bidirectional, true, null, false, JsonSerializer.SerializeToElement(new { })));
using var mappings = new MappingRuntimeService(store, new WriteJournal());
using var runtime = new OpcUaClientService(store, applications, NullLogger<OpcUaClientService>.Instance);
await mappings.StartAsync(CancellationToken.None);
await runtime.StartAsync(CancellationToken.None);
var writes = 0;
void Count(object? sender, PointValue update) { if (update.PointId == remotePoint.Id) Interlocked.Increment(ref writes); }
remote.PointValueUpdated += Count;
try
{
await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good"));
Check(writes == 0, "Initial synchronization must never write to the remote device.");
store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(37.25), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
await Until(() => remote.ListPointValues().Any(value => value.PointId == remotePoint.Id && value.Value.GetSingle() == 37.25f));
server.RefreshPoints(false);
await Task.Delay(700);
Check(writes == 1, "A mapped command and its subscription echo must produce exactly one remote write.");
remote.SetPointValue(remotePoint.Id, JsonSerializer.SerializeToElement(38.5), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
server.RefreshPoints(false);
await Until(() => store.ListPointValues().Any(value => value.PointId == local.Id && value.Value.ValueKind == JsonValueKind.Number && value.Value.GetDouble() == 38.5));
Check(writes == 2, "A remote update must reach the reverse mapping without being written back.");
store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(99), PointProtocol.Internal, DateTimeOffset.UtcNow, "BadNotConnected");
await Task.Delay(350);
Check(writes == 2, "Bad quality must never actuate an external point.");
var active = server.CurrentInstance.SessionManager.GetSessions().Single(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client");
server.CurrentInstance.CloseSession(null, active.Id, true);
await Until(() => server.CurrentInstance.SessionManager.GetSessions().Any(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client" && session.Id != active.Id), 25000);
await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good"));
Check(writes == 2, "Reconnect must rebuild subscriptions, read current values and never replay commands.");
Console.WriteLine("OPC UA client tests passed: encrypted credentials, typed import, subscription, bidirectional mapping, no echo, bad quality, reconnect.");
}
finally
{
remote.PointValueUpdated -= Count;
await runtime.StopAsync(CancellationToken.None);
await mappings.StopAsync(CancellationToken.None);
}
}
private static async Task Until(Func<bool> predicate, int timeout = 12000)
{
var limit = DateTime.UtcNow.AddMilliseconds(timeout);
while (!predicate()) { if (DateTime.UtcNow > limit) throw new InvalidOperationException("OPC UA client condition timed out."); await Task.Delay(50); }
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
#pragma warning restore CS0618
@@ -0,0 +1,132 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Contracts;
using Gateway.Api.Services;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
#pragma warning disable CS0618 // Exercise the same pinned SDK API as production.
internal static class OpcUaFeatureTests
{
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
{
var previous = store.GetGatewayConfiguration();
using var portReservation = new TcpListener(IPAddress.Loopback, 0);
portReservation.Start();
var port = ((IPEndPoint)portReservation.LocalEndpoint).Port;
portReservation.Stop();
store.UpdateGatewayConfiguration(previous with { OpcUa = previous.OpcUa with { Port = port, ServerEnabled = true, AllowAnonymous = true } });
var point = store.CreatePoint(new CreatePointRequest("UA Sollwert", PointProtocol.OpcUa, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { })));
var readOnly = store.CreatePoint(new CreatePointRequest("UA Eingang", PointProtocol.OpcUa, PointScope.Gateway, "Boolean", true, false, null, JsonSerializer.SerializeToElement(new { })));
var history = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "UA Drahttest", 901, 1, 100, true));
var applications = new OpcUaApplicationFactory(database);
var configuration = await applications.CreateServerConfigurationAsync(port, true);
configuration.ServerConfiguration.MaxBrowseContinuationPoints = 20;
var application = new ApplicationInstance(configuration);
var server = new GatewayOpcUaServer(store);
var updates = 0;
store.PointValueUpdated += Count;
void Count(object? sender, PointValue value) { if (value.PointId == point.Id) Interlocked.Increment(ref updates); }
try
{
await application.StartAsync(server);
var clientConfiguration = await applications.CreateClientConfigurationAsync();
// Explicitly trust this exact local test server; never bypass arbitrary certificate errors.
using (var trust = clientConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore())
{
var certificate = configuration.SecurityConfiguration.ApplicationCertificate.Certificate;
if ((await trust.FindByThumbprintAsync(certificate.Thumbprint)).Count == 0) await trust.AddAsync(certificate);
}
await clientConfiguration.CertificateValidator.UpdateAsync(clientConfiguration.SecurityConfiguration);
var url = $"opc.tcp://127.0.0.1:{port}";
using var discovery = DiscoveryClient.Create(clientConfiguration, new Uri(url), EndpointConfiguration.Create(clientConfiguration));
var discoveryResult = await discovery.GetEndpointsAsync(null, url, null, null, CancellationToken.None);
Check(discoveryResult.Endpoints.Count > 0 && discoveryResult.Endpoints.All(endpoint => new Uri(endpoint.EndpointUrl).Host == "127.0.0.1"),
"Discovery through a local IP must advertise that IP on every security policy.");
var selected = discoveryResult.Endpoints.Single(endpoint => endpoint.SecurityMode == MessageSecurityMode.SignAndEncrypt);
var endpoint = new ConfiguredEndpoint(null, selected, EndpointConfiguration.Create(clientConfiguration));
using var session = await Session.Create(clientConfiguration, endpoint, false, true, "Gateway wire test", 60_000,
new UserIdentity("admin", Encoding.UTF8.GetBytes("correct horse battery staple")), null);
var index = (ushort)session.NamespaceUris.GetIndex(GatewayOpcUaServer.PointsNamespace);
var node = new NodeId(point.Id, index);
session.Browse(null, null, new NodeId("Gateway", index), 100, BrowseDirection.Forward, ReferenceTypeIds.Organizes, true, (uint)NodeClass.Variable, out _, out var references);
Check(references.Any(reference => reference.NodeId == node), "Gateway variable must be browsable with a stable GUID node id.");
session.Read(null, 0, TimestampsToReturn.Both, [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], out var initial, out _);
Check(initial[0].StatusCode == StatusCodes.BadWaitingForInitialData, "Missing values must not appear as good zeroes.");
var notified = new TaskCompletionSource<float>(TaskCreationOptions.RunContinuationsAsynchronously);
using var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = node, AttributeId = Attributes.Value, SamplingInterval = 100, QueueSize = 10, DiscardOldest = true };
item.Notification += (_, _) =>
{
foreach (var data in item.DequeueValues())
if (data.StatusCode == StatusCodes.Good && data.Value is float number && number == 24.5f) notified.TrySetResult(number);
};
subscription.AddItem(item);
session.AddSubscription(subscription);
subscription.Create();
Check(Write(session, node, 21.5f) == StatusCodes.Good, "Authenticated scalar writes must be accepted.");
Check(updates == 1 && store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetSingle() == 21.5f, "UA write must enter the common store exactly once.");
Check(store.ListTrendRecords(history.Id, 10).Count == 1, "UA write must feed the configured trend.");
Check(Write(session, node, true) == StatusCodes.BadTypeMismatch, "Boolean must not overwrite a Real point.");
Check(Write(session, new NodeId(readOnly.Id, index), true) == StatusCodes.BadNotWritable, "Read-only input must reject writes.");
Check(updates == 1, "Rejected writes must not enter the point store.");
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(24.5), PointProtocol.Internal, DateTimeOffset.UtcNow.AddSeconds(2), "Good");
server.RefreshPoints(false);
await notified.Task.WaitAsync(TimeSpan.FromSeconds(10));
Check(updates == 2 && store.ListTrendRecords(history.Id, 10).Count == 2, "Subscription notifications must not echo into the store or trend.");
var late = store.CreatePoint(new CreatePointRequest("UA später angelegt", PointProtocol.OpcUa, PointScope.Gateway, "String", true, true, null, JsonSerializer.SerializeToElement(new { })));
server.RefreshPoints(true);
Check(Write(session, new NodeId(late.Id, index), "ÄÖÜ ✓") == StatusCodes.Good, "New nodes must appear without a server restart and support Unicode.");
var browsed = await new OpcUaBrowserService(applications).BrowseAsync(new OpcUaBrowseRequest(url, new NodeId("Gateway", index).ToString(), true, OpcUaAuthenticationMode.Username, "admin", "correct horse battery staple"));
Check(browsed.Any(value => value.NodeId == new NodeId(late.Id, index).ToString() && value.Value?.GetString() == "ÄÖÜ ✓"), "The web browser service must authenticate, browse and read real server variables.");
using var anonymous = await Session.Create(clientConfiguration, endpoint, false, "Anonymous read-only test", 60_000, new UserIdentity(), null);
Check(StatusCode.IsBad(Write(anonymous, node, 31f)), "Anonymous sessions must not write process values.");
using var viewer = await Session.Create(clientConfiguration, endpoint, false, "Viewer read-only test", 60_000, new UserIdentity("trend.viewer", Encoding.UTF8.GetBytes("another secure password")), null);
Check(StatusCode.IsBad(Write(viewer, node, 31f)), "Viewer accounts must not write process values.");
try
{
using var invalid = await Session.Create(clientConfiguration, endpoint, false, "Wrong password test", 60_000, new UserIdentity("admin", Encoding.UTF8.GetBytes("wrong password")), null);
throw new InvalidOperationException("Invalid password was accepted.");
}
catch (ServiceResultException exception) when (exception.StatusCode == StatusCodes.BadUserAccessDenied) { }
var viewerAccount = store.ListUsers().Single(user => user.Username == "trend.viewer");
var admin = store.ListUsers().Single(user => user.Username == "admin");
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, false), admin.Id);
server.RefreshPoints(true);
Check(server.CurrentInstance.SessionManager.GetSessions().All(active => active.Id != viewer.SessionId), "Revoking a user must close its existing OPC UA session and subscriptions.");
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, true), admin.Id);
await viewer.CloseAsync();
await anonymous.CloseAsync();
subscription.Delete(true);
await session.CloseAsync();
await OpcUaClientTests.RunAsync(store, server, url, point, configuration);
Console.WriteLine("OPC UA wire tests passed: browse, authentication, read/write, subscription, live nodes, trend, no echo.");
}
finally
{
store.PointValueUpdated -= Count;
await application.StopAsync();
server.Dispose();
store.UpdateGatewayConfiguration(previous);
}
}
private static StatusCode Write(Session session, NodeId node, object value)
{
session.Write(null, [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new DataValue(new Variant(value)) }], out var results, out _);
return results[0];
}
private static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
}
#pragma warning restore CS0618
+190 -1
View File
@@ -4,6 +4,8 @@ using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging.Abstractions;
using System.Net.Sockets;
var validator = new MappingValidator();
var sourceOne = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
@@ -45,9 +47,163 @@ store.Initialize();
Assert(!store.HasAdmin(), "A new database must not contain an admin password.");
store.CreateInitialAdmin(new SetInitialAdminRequest("correct horse battery staple", "P190726", 1));
Assert(store.HasAdmin() && store.VerifyAdminPassword("correct horse battery staple"), "The configured admin must authenticate.");
var authenticatedAdmin = store.Authenticate("admin", "correct horse battery staple");
Assert(authenticatedAdmin is not null && authenticatedAdmin.Permissions.Contains(GatewayPermissions.ManageUsers), "The migrated administrator must receive the complete admin role.");
var viewer = store.CreateUser(new CreateUserRequest("trend.viewer", "Trend Viewer", null, "another secure password", "viewer"));
Assert(store.Authenticate(viewer.Username, "another secure password")?.Permissions.SequenceEqual([GatewayPermissions.ViewDashboard, GatewayPermissions.ViewTrends]) == true, "Viewer accounts must receive only viewer permissions.");
Assert(store.GetGatewayConfiguration().VendorId == 815 && store.GetGatewayConfiguration().DeviceInstance == 23, "BACnet bootstrap defaults must be persisted.");
Assert(store.GetGatewayConfiguration().Installation?.HostName == "SE-UGW-P190726-ISP01", "First commissioning must create the requested Komari-visible hostname.");
Assert(File.Exists(Path.Combine(dataDirectory, "provisioning", "host.json")), "The NixOS hostname helper must receive an identity-only provisioning request.");
var oldConfiguration = store.GetGatewayConfiguration();
var installation = store.UpdateInstallationIdentity(new InstallationIdentity(" p260123 ", 3));
store.UpdateGatewayConfiguration(oldConfiguration);
Assert(installation.HostName == "SE-UGW-P260123-ISP03" && store.GetGatewayConfiguration().Installation == installation &&
File.ReadAllText(Path.Combine(dataDirectory, "provisioning", "host.json")).Contains("P260123", StringComparison.Ordinal),
"Changing installation identity must provision the new name and survive updates from an older protocol form.");
var etsXml = "<Project><GroupAddresses><GroupAddress Name=\"Room temperature\" Address=\"1/2/3\" DatapointType=\"DPT-9-001\" /></GroupAddresses></Project>";
var knxImport = KnxEtsImporter.Import(new KnxEtsImportRequest("sample.xml", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(etsXml))), store);
Assert(knxImport.Imported == 1 && store.ListPoints().Any(point => point.Protocol == PointProtocol.Knx && point.ExternalIdentity == "knx:1/2/3"), "ETS group addresses must be imported with their KNX identity.");
var mappingSource = store.CreatePoint(new CreatePointRequest(
"Mapped internal source", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappedTarget = store.CreatePoint(new CreatePointRequest(
"Mapped internal target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappingRuntime = new MappingRuntimeService(store, journal);
await mappingRuntime.StartAsync(CancellationToken.None);
var mappingRequest = new CreateMappingRequest(mappingSource.Id, mappedTarget.Id, MappingDirection.OneWay, true, null, false, JsonElementFor("{}"));
var editableMapping = store.CreateMapping(mappingRequest).Mapping;
store.SetPointValue(mappingSource.Id, JsonElementFor("42.5"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Any(value => value.PointId == mappedTarget.Id && value.Value.GetDouble() == 42.5), "The active mapping graph must forward a point value exactly once.");
var nextTarget = store.CreatePoint(new CreatePointRequest(
"New mapping target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var updatedMapping = store.UpdateMapping(editableMapping.Id, mappingRequest with { TargetPointId = nextTarget.Id })?.Mapping;
Assert(updatedMapping?.Id == editableMapping.Id && updatedMapping.CreatedAtUtc == editableMapping.CreatedAtUtc, "Editing must retain mapping identity.");
store.SetPointValue(mappingSource.Id, JsonElementFor("43"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == mappedTarget.Id).Value.GetDouble() == 42.5 &&
store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43, "Edited mappings must switch targets live.");
Assert(store.DeleteMapping(editableMapping.Id) && !store.DeleteMapping(editableMapping.Id), "Mapping deletion must distinguish missing mappings.");
store.SetPointValue(mappingSource.Id, JsonElementFor("44"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43 &&
store.GetPointDependencies(mappingSource.Id)?.Mappings == 0 && store.ListPoints().Any(point => point.Id == nextTarget.Id),
"Removing a mapping must stop forwarding and preserve both points.");
await mappingRuntime.StopAsync(CancellationToken.None);
var modbusServerId = Guid.NewGuid();
store.UpdateGatewayConfiguration(store.GetGatewayConfiguration() with
{
ModbusServers = [new ModbusServerConfiguration(modbusServerId, "Smoke", "127.0.0.1", 15022, 1, 0, 100, [])]
});
var modbusGatewayPoint = store.CreatePoint(new CreatePointRequest(
"Modbus server value", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, true, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"HoldingRegister\",\"address\":12,\"dataType\":\"UInt16\"}}")));
store.CreatePoint(new CreatePointRequest(
"Reserved input register", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, false, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"InputRegister\",\"address\":1,\"dataType\":\"UInt16\"}}")));
var csvSource = store.CreatePoint(new CreatePointRequest(
"=\"Zuluft; Vorlauf\"", PointProtocol.Internal, PointScope.Internal, "UInt16", true, false, null, JsonElementFor("{}")));
store.SetPointValue(csvSource.Id, JsonElementFor("73"), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
var batch = new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Modbus, modbusServerId);
Assert(store.CreateBulkMappings(batch) is { Created: 2, Existing: 0 }, "Bulk Modbus mapping must create both routes.");
var targets = store.ListMappings().Where(mapping => batch.SourcePointIds.Contains(mapping.SourcePointId)).ToDictionary(
mapping => mapping.SourcePointId, mapping => store.ListPoints().Single(point => point.Id == mapping.TargetPointId));
Assert(targets[mappingSource.Id].Address.GetProperty("address").GetInt32() == 2 &&
targets[csvSource.Id].Address.GetProperty("address").GetInt32() == 4 &&
store.ListPointValues().Single(value => value.PointId == targets[csvSource.Id].Id).Value.GetInt32() == 73 &&
store.CreateBulkMappings(batch) is { Created: 0, Existing: 2 }, "Register allocation must skip conflicts, preserve widths and seed current values.");
var batchMqtt = store.CreateBulkMappings(new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Mqtt, MqttTopicPrefix: "test/batch"));
Assert(batchMqtt.Created == 2 && batchMqtt.Assignments.Distinct().Count() == 2, "Bulk MQTT requires a unique topic for each point.");
var statePoint = store.CreatePoint(new("Pumpe läuft", PointProtocol.Internal, PointScope.Internal, "Bool", true, false, null, JsonElementFor("{}")));
var alarmPoint = store.CreatePoint(new("Pumpe Störung", PointProtocol.Internal, PointScope.Internal, "Boolean", true, false, null, JsonElementFor("{}")));
store.UpdateNotificationKey(NotificationChannel.Mail, new("local-smoke-key"));
var rule = store.SaveAlarmRule(new(Guid.NewGuid(), "Smoke alarm", alarmPoint.Id, AlarmCondition.Active, 0, 0, true, false, "",
[new(NotificationChannel.Mail, "alarm@example.invalid")]));
var mqttDefaults = store.GetMqttMappingDefaults();
Assert(mqttDefaults.Site == new MqttMonitoringSite(2026, "P260123", "ISP3") &&
mqttDefaults.Points.Single(point => point.PointId == csvSource.Id).Category == SeMonitoringCategory.Analog &&
mqttDefaults.Points.Single(point => point.PointId == statePoint.Id).Category == SeMonitoringCategory.Notify &&
mqttDefaults.Points.Single(point => point.PointId == alarmPoint.Id).Category == SeMonitoringCategory.Alarms,
"The MQTT default must use commissioning data and distinguish numerics, digital states and active alarm points.");
var monitoringBatch = store.CreateBulkMappings(new([csvSource.Id, statePoint.Id, alarmPoint.Id], BulkMappingTarget.Mqtt));
Assert(monitoringBatch.Created == 3 && monitoringBatch.Assignments.Any(item => item.Contains("/Alarms/", StringComparison.Ordinal)) &&
monitoringBatch.Assignments.Any(item => item.Contains("/Notify/", StringComparison.Ordinal)), "Bulk MQTT should use SE-Monitoring by default.");
var oldTopics = store.ListMqttMappings().ToDictionary(mapping => mapping.Id, GatewayStore.GetMqttTopic);
var templateView = store.UpdateMqttTopicTemplate("Anlagen/{Rechnername}/{Kategorie}/{Datenpunkt}");
Assert(templateView.PreviewValues["{Rechnername}"] == "SE-UGW-P260123-ISP03", "The preview must show the configured installation identity.");
var templatedRequest = new CreateMqttMappingRequest(csvSource.Id, MqttMappingFormat.SeMonitoring, MqttDirection.Publish,
MqttQualityOfService.AtLeastOnce, false, null, "P260123", "ISP3", SeMonitoringCategory.Analog, "Vorlauf", null, null);
var customMapping = store.CreateMqttMapping(templatedRequest);
const string customTopic = "Anlagen/SE-UGW-P260123-ISP03/Analog/Vorlauf";
Assert(GatewayStore.GetMqttTopic(customMapping) == customTopic &&
store.ListMqttMappings().Where(mapping => oldTopics.ContainsKey(mapping.Id)).All(mapping => GatewayStore.GetMqttTopic(mapping) == oldTopics[mapping.Id]),
"A new template must affect new mappings and preserve every previously resolved topic.");
var bulkTemplate = store.UpdateMqttTopicTemplate("Messwerte/{Projekt}/{Datenpunkt}");
var batchWithTemplate = store.CreateBulkMappings(new([statePoint.Id], BulkMappingTarget.Mqtt));
Assert(batchWithTemplate.Created == 1 && batchWithTemplate.Assignments.Single().EndsWith("Messwerte/P260123/Pumpe_läuft", StringComparison.Ordinal) &&
GatewayStore.GetMqttTopic(store.UpdateMqttMapping(customMapping.Id, templatedRequest with { Retain = true })!) == customTopic,
"Bulk mappings must use the active template while an existing mapping edit keeps its saved path.");
try
{
store.UpdateMqttTopicTemplate("Messwerte/{Unbekannt}/{Datenpunkt}");
throw new InvalidOperationException("An unknown MQTT placeholder must be rejected.");
}
catch (DomainValidationException)
{
Assert(store.GetMqttMappingDefaults().TopicTemplate.Template == bulkTemplate.Template, "Rejected templates must not overwrite the saved template.");
}
var legacyMqttCsv = "Id;PointId;Format;Direction;QualityOfService;Retain;ProjectYear;ProjectNumber;IspNumber;SeCategory;TopicName;JsonTopic;JsonProperty\r\n" +
$";{csvSource.Id};SeMonitoring;Publish;AtLeastOnce;False;2026;P260123;ISP3;Analog;CsvLegacy;;\r\n";
Assert(store.ImportConfigurationCsv(ConfigurationCsvKind.MqttMappings, legacyMqttCsv).Created == 1 &&
store.ListMqttMappings().Any(mapping => GatewayStore.GetMqttTopic(mapping) == "Projekte2026/P260123/ISP3/Analog/CsvLegacy_Wert"),
"MQTT CSVs exported before the template field must continue to resolve legacy paths.");
store.UpdateMqttTopicTemplate(templateView.DefaultTemplate);
var rawMqtt = store.CreateMqttMapping(new(csvSource.Id, MqttMappingFormat.SingleTopic, MqttDirection.Publish, MqttQualityOfService.AtLeastOnce,
false, null, null, null, null, null, "plant/temperature", null));
Assert(GatewayStore.GetMqttTopic(rawMqtt) == "plant/temperature", "A numeric single-topic mapping must use the specified topic exactly.");
store.DeleteAlarmRule(rule.Id);
store.UpdateNotificationKey(NotificationChannel.Mail, new(null, true));
foreach (var kind in Enum.GetValues<ConfigurationCsvKind>())
{
var csv = store.ExportConfigurationCsv(kind);
Assert(store.ImportConfigurationCsv(kind, csv) is { Created: 0, Updated: > 0 } &&
store.ExportConfigurationCsv(kind) == csv, $"CSV round-trip must preserve IDs and escaping for {kind}.");
}
var exportedPoints = store.ExportConfigurationCsv(ConfigurationCsvKind.Points);
var editedPoints = exportedPoints.Replace("Modbus server value", "Modbus renamed", StringComparison.Ordinal);
try
{
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints + "invalid\r\n");
throw new InvalidOperationException("A malformed row should fail the whole CSV import.");
}
catch (DomainValidationException exception)
{
Assert(exception.Message.Contains("CSV-Zeile", StringComparison.Ordinal) &&
store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus server value",
"A failed CSV import must report the row and roll back earlier changes.");
}
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints);
Assert(store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus renamed", "A CSV edit must update the existing point.");
var modbusService = new ModbusProtocolService(store, journal, NullLogger<ModbusProtocolService>.Instance);
await modbusService.StartAsync(CancellationToken.None);
await Task.Delay(350);
store.SetPointValue(modbusGatewayPoint.Id, JsonElementFor("42"), PointProtocol.Internal, DateTimeOffset.UtcNow);
using (var modbusClient = new TcpClient())
{
await modbusClient.ConnectAsync("127.0.0.1", 15022);
var request = new byte[] { 0, 1, 0, 0, 0, 6, 1, 3, 0, 12, 0, 1 };
await modbusClient.GetStream().WriteAsync(request);
var response = new byte[11];
await modbusClient.GetStream().ReadExactlyAsync(response);
Assert(response.SequenceEqual(new byte[] { 0, 1, 0, 0, 0, 5, 1, 3, 2, 0, 42 }), "The Modbus TCP server must expose mapped holding registers.");
}
await modbusService.StopAsync(CancellationToken.None);
modbusService.Dispose();
var opcFactory = new OpcUaApplicationFactory(database);
var opcClientConfiguration = await opcFactory.CreateClientConfigurationAsync();
Assert(opcClientConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate is not null, "The OPC UA browser must create a persistent application certificate.");
try { await OpcUaFeatureTests.RunAsync(store, database); }
catch (Exception exception) { Console.Error.WriteLine(exception); Environment.ExitCode = 1; return; }
await BacnetBridgeTests.RunAsync(store, database);
var sourcePoint = store.CreatePoint(new CreatePointRequest(
"Internal temperature",
@@ -82,6 +238,12 @@ var analogMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
Assert(
GatewayStore.GetMqttTopic(analogMqttMapping) == "Projekte2019/P1909015/ISP1/Analog/iVlTempFuehler4Speicher_Wert",
"SE Monitoring topics must match the requested hierarchy.");
var editedMqtt = store.UpdateMqttMapping(analogMqttMapping.Id, new CreateMqttMappingRequest(
sourcePoint.Id, MqttMappingFormat.Json, MqttDirection.Publish, MqttQualityOfService.AtMostOnce, false,
null, null, null, null, null, "test/updated-topic", "value"));
Assert(editedMqtt?.Id == analogMqttMapping.Id && GatewayStore.GetMqttTopic(editedMqtt) == "test/updated-topic", "MQTT edits must replace the mapped topic.");
Assert(store.DeleteMqttMapping(analogMqttMapping.Id) && store.GetPointDependencies(sourcePoint.Id)?.MqttMappings == 0,
"Deleting an MQTT mapping must unlink its source point.");
var invalidNotifyMappingRejected = false;
try
@@ -156,7 +318,8 @@ var scheduleJsonMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
"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 trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true, true));
Assert(store.IsPublicTrendLog(trendLog.Id) && store.ListPublicTrendLogs().Single().Id == trendLog.Id, "Only explicitly marked trend logs may be exposed publicly.");
var historyStart = new DateTimeOffset(2026, 10, 7, 8, 0, 0, TimeSpan.Zero);
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("21.5"), PointProtocol.Internal, null, historyStart));
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.0"), PointProtocol.Internal, null, historyStart.AddMinutes(1)));
@@ -180,7 +343,33 @@ Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.1"
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.2"), PointProtocol.Internal, null, sampleTime.AddSeconds(60)).Count == 1, "Observations at the configured interval must be recorded.");
Assert(store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "The sampled trend log must contain two records.");
var renamedPoint = store.UpdatePoint(sampledSourcePoint.Id, new CreatePointRequest(
"Humidity renamed", sampledSourcePoint.Protocol, sampledSourcePoint.Scope, sampledSourcePoint.ValueType,
sampledSourcePoint.Readable, sampledSourcePoint.Writable, null, JsonElementFor("{}")));
Assert(renamedPoint?.Id == sampledSourcePoint.Id && renamedPoint.DisplayName == "Humidity renamed", "Point editing must keep the point identity.");
var usage = store.GetPointDependencies(sampledSourcePoint.Id);
Assert(usage?.TrendLogs == 1, "The delete preview must include linked trend logs.");
try
{
store.DeletePoint(sampledSourcePoint.Id, null);
throw new InvalidOperationException("Deleting a linked point must require confirmation.");
}
catch (DomainValidationException) { }
Assert(store.DeletePoint(sampledSourcePoint.Id, usage!.Confirmation), "A confirmed point must be removable.");
Assert(store.ListPoints().All(point => point.Id != sampledSourcePoint.Id) &&
!store.ListTrendLogs().Single(log => log.Id == sampledLog.Id).Enabled &&
store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "Removing a point must stop logging and preserve the history.");
await LtdFeatureTests.RunAsync(store, database, options, authenticatedAdmin!);
var bulkSources = Enumerable.Range(1, 501).Select(index => store.CreatePoint(new(
$"Bulk source {index}", PointProtocol.Internal, PointScope.Internal, "Boolean", true, false, null, JsonElementFor("{}"))).Id).ToArray();
var largeMapping = store.CreateBulkMappings(new(bulkSources, BulkMappingTarget.OpcUa));
Assert(largeMapping is { Created: 501, Existing: 0 } && largeMapping.Assignments.Count == 501,
"A single bulk mapping must accept a selection beyond the former 500-point limit.");
Console.WriteLine("Gateway smoke tests passed.");
if (args.Contains("--preview", StringComparer.Ordinal)) Console.WriteLine($"Preview data: {dataDirectory}");
static GatewayPoint CreatePoint(PointProtocol protocol, PointScope scope, string? externalIdentity)
{
+149
View File
@@ -0,0 +1,149 @@
"""Isolated wire test: only loopback, a temporary DB, no building-network writes."""
import json
import os
import socket
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import time
runtime = Path(sys.argv[1]) / "bin"
work = Path(tempfile.mkdtemp(prefix="seiugw-bacnet-wire-"))
db = sqlite3.connect(work / "seiugw.db")
# Share the exact schema with the application rather than maintaining a fixture copy.
source = Path(__file__).resolve().parents[1] / "src/Gateway.Api/Services/GatewayDatabase.cs"
schema = source.read_text().split('command.CommandText = """', 1)[1].split('""";', 1)[0]
db.executescript(schema)
config = {"deviceInstance": 900023, "deviceName": "SE-UGW-Wire-Test", "bacnet": {"interface": "lo", "ipPort": 47828, "bbmdMode": "Disabled"}}
db.execute("INSERT INTO settings VALUES(?,?)", ("gateway.configuration", json.dumps(config)))
types = [("AnalogInput", 0), ("AnalogOutput", 1), ("AnalogValue", 2), ("BinaryInput", 3), ("BinaryOutput", 4), ("BinaryValue", 5),
("MultiStateInput", 13), ("MultiStateOutput", 14), ("MultiStateValue", 19), ("Schedule", 17), ("Calendar", 6)]
for i, (kind, number) in enumerate(types, 1):
db.execute("INSERT INTO points VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NULL)", (f"00000000-0000-0000-0000-{i:012}", kind, "Bacnet", "Gateway", "Real", 1, 1,
None, '{"units":62,"numberOfStates":16}', "2026-10-09T00:00:00Z", kind, 77))
db.commit()
environment = {**os.environ, "LC_ALL": "C", "BACNET_DATALINK": "bip", "BACNET_IFACE": "lo", "BACNET_IP_PORT": "47829", "BACNET_IP_BROADCAST_PORT": "47828", "BACNET_APDU_TIMEOUT": "1000"}
log = open(work / "server.log", "w")
server = None
cov = None
def start():
global server
server = subprocess.Popen([runtime / "bacserv", "900023"], cwd=work, env={**environment, "SEIUGW_DATABASE": str(work / "seiugw.db")}, stdout=log, stderr=log)
time.sleep(1.5)
assert server.poll() is None, (work / "server.log").read_text()
def call(tool, args, success=True):
result = subprocess.run([runtime / tool, "900023", *map(str, args), "--mac", "127.0.0.1:47828", "--dnet", "0"], env=environment, cwd=work, text=True, capture_output=True, timeout=10)
assert (result.returncode == 0) == success, (args, result.stdout, result.stderr)
return result.stdout.strip()
def read(obj, prop=85, index=None):
return call("bacrp", [obj, 77 if obj != 8 else 900023, prop, *([] if index is None else [index])])
def write(obj, tag, value, priority=16, prop=85, success=True):
return call("bacwp", [obj, 77, prop, priority, -1, tag, value], success)
def command(i, value, priority=16):
cursor = db.execute("INSERT INTO bacnet_commands(point_id,value_json,priority,created_ms) VALUES(?,?,?,?)",
(f"00000000-0000-0000-0000-{i:012}", json.dumps(value), priority, int(time.time()*1000)))
db.commit()
limit = time.monotonic()+5
while time.monotonic() < limit:
row = db.execute("SELECT state,result FROM bacnet_commands WHERE id=?", (cursor.lastrowid,)).fetchone()
if row[0] != "pending" and row[0] != "claimed":
assert row[0] == "done", row
return
time.sleep(.05)
raise AssertionError("Command was not processed")
try:
start()
# Field devices may send I-Am to the BACnet port, as a broadcast or unicast.
# The native socket must receive these while its normal ReadProperty service stays available.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as broadcast, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as peer:
broadcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
broadcast.bind(("127.255.255.255", 47828))
broadcast.settimeout(5)
peer.bind(("127.0.0.2", 47828))
peer.settimeout(5)
peer.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
for target in (None, "127.0.0.2"):
scan_id = "wire-broadcast" if target is None else "wire-direct"
db.execute("INSERT OR REPLACE INTO bacnet_discovery VALUES(1,?,?,?,?,0)",
(scan_id, target, 47828, int((time.time()+7)*1000)))
db.commit()
request, origin = (broadcast if target is None else peer).recvfrom(512)
assert origin == ("127.0.0.1", 47828) and request.endswith(b"\x10\x08"), (request.hex(), origin)
payload = bytes.fromhex("01001000c4") + ((8 << 22) | 1975).to_bytes(4, "big") + bytes.fromhex("2205c4910022032f")
function = 0x0b if target is None else 0x0a
peer.sendto(bytes([0x81, function, 0, len(payload)+4]) + payload,
("127.255.255.255" if target is None else "127.0.0.1", 47828))
if target is None:
routed = bytes.fromhex("01080014012a")
routed += payload[2:5] + ((8 << 22) | 1976).to_bytes(4, "big") + payload[9:]
peer.sendto(bytes([0x81, 0x0b, 0, len(routed)+4]) + routed, ("127.255.255.255", 47828))
for _ in range(30):
results = db.execute("SELECT device_instance,address,port,vendor,max_apdu,network,mac FROM bacnet_discovered_devices WHERE scan_id=? ORDER BY device_instance", (scan_id,)).fetchall()
if len(results) == (2 if target is None else 1):
break
time.sleep(.1)
assert results[0] == (1975, "127.0.0.2", 47828, 815, 1476, 0, None), results
if target is None:
assert results[1] == (1976, "127.0.0.2", 47828, 815, 1476, 20, "2A"), results
print("Native BACnet discovery passed: source port, broadcast and direct I-Am")
assert read(8, 120) == "815", read(8, 120)
object_list = read(8, 76)
for _, number in types: assert read(number, 75), number
assert "analog-value" in object_list.lower(), object_list
write(0, 4, 10, success=False) # AI Present_Value is not externally writable while in service.
write(2, 4, 21.5)
assert float(read(2)) == 21.5
write(2, 4, 30, 14)
command(3, 22, 16)
assert float(read(2)) == 30 and float(read(2, 87, 16)) == 22
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 31, 14)
server.terminate(); server.wait(timeout=5); start()
assert float(read(2)) == 31 and float(read(2, 87, 16)) == 22, "Priority slots must survive a native service restart"
write(2, 0, 0, 14)
assert float(read(2)) == 22
write(2, 4, 99, 6, success=False)
command(1, 18.75)
assert float(read(0)) == 18.75
command(6, True)
assert "active" in read(5).lower() or read(5) == "1", read(5)
command(9, 3)
assert int(read(19)) == 3
# Use the upstream COV client with an explicit loopback-only address cache.
(work / "address_cache").write_text("900023 7F:00:00:01:BA:D4 0 0 1476\n")
cov_log = open(work / "cov.log", "w")
cov = subprocess.Popen(["stdbuf", "-oL", str(runtime / "bacscov"), "900023", "2", "77", "17", "unconfirmed", "30"],
cwd=work, env={**environment, "BACNET_IP_PORT": "47830"}, stdout=cov_log, stderr=cov_log)
time.sleep(1)
write(2, 4, 42.5)
time.sleep(2)
cov_log.flush()
cov_text = (work / "cov.log").read_text()
assert "Acknowledged" in cov_text and cov_text.count("Received Notification!") >= 2 and float(read(2)) == 42.5, cov_text
latest = db.execute("SELECT value_json,status FROM bacnet_observations WHERE point_id LIKE '%000000000003' ORDER BY id DESC LIMIT 1").fetchone()
assert float(latest[0]) == 42.5 and latest[1] == "Good", latest
# A new object appears without restarting the server.
db.execute("INSERT INTO points SELECT '00000000-0000-0000-0000-000000000099','Late AV',protocol,scope,value_type,readable,writable,NULL,address_json,created_at_utc,bacnet_object_kind,99,NULL FROM points WHERE bacnet_object_kind='AnalogValue'")
db.commit(); time.sleep(1.3)
assert "99" in read(8, 76)
db.execute("UPDATE points SET display_name='Renamed AV' WHERE bacnet_object_kind='AnalogValue' AND bacnet_object_instance=77")
db.commit(); time.sleep(1.3)
assert "Renamed AV" in read(2, 77) and float(read(2)) == 42.5
db.execute("UPDATE points SET deleted_at_utc='2026-11-19T00:00:00Z' WHERE id LIKE '%000000000099'")
db.commit(); time.sleep(1.3)
assert "99" not in read(8, 76)
print("BACnet wire tests passed: native Object_List, AI/AO/AV/BI/BO/BV/MSI/MSO/MSV/Schedule/Calendar, priority 16/14/NULL, persistence, COV, live creation, command/observation bridge.")
finally:
if cov is not None: cov.terminate(); cov.wait(timeout=5)
if server is not None and server.poll() is None: server.terminate(); server.wait(timeout=5)
db.close(); log.close()
print(f"Isolated test evidence: {work}")
+86
View File
@@ -0,0 +1,86 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { test } = require('node:test');
// No browser dependencies; exercise the same theme/tab functions as the shipped UI.
function element(dataset = {}) {
const classes = new Set();
return { dataset, handlers: {}, attributes: {}, hidden: false,
classList: { toggle(name, on) { on ? classes.add(name) : classes.delete(name); } },
addEventListener(name, handler) { this.handlers[name] = handler; },
setAttribute(name, value) { this.attributes[name] = value; },
focus() { this.focused = true; }
};
}
function harness() {
const themes = ['light','dark','system'].map(theme => element({ theme }));
const tabs = ['points','bacnet','opcua','modbus','knx','mqtt','serial','status'].map(pointsTab => element({ pointsTab }));
const panels = tabs.map(tab => element({ pointsPanel: tab.dataset.pointsTab }));
const storage = new Map();
const document = { documentElement: element(), querySelector: () => null,
querySelectorAll(selector) { return selector === 'button[data-theme]' ? themes : selector === '[data-points-tab]' ? tabs : selector === '[data-points-panel]' ? panels : []; }
};
const context = vm.createContext({ document, window: { matchMedia: () => ({ matches: true, addEventListener() {} }) },
sessionStorage: { getItem() { return null; } }, localStorage: { getItem: key => storage.get(key), setItem: (key,value) => storage.set(key,value) }
});
const root = path.join(__dirname, '../src/Gateway.Api/wwwroot');
const app = fs.readFileSync(path.join(root,'app.js'),'utf8');
vm.runInContext(fs.readFileSync(path.join(root,'ltd.js'),'utf8'),context);
vm.runInContext(fs.readFileSync(path.join(root,'gateway-status.js'),'utf8'),context);
vm.runInContext(app.slice(0,app.lastIndexOf('boot().catch(')),context);
return { context, document, themes, tabs, panels, storage, run: code => vm.runInContext(code,context) };
}
test('theme updates every switch in place, persists preference, and does not rebuild forms', async () => {
const h = harness();
h.run("renderShell = () => { throw new Error('Theme must preserve forms'); }; api = async () => ({ theme: 'light', sidebarPinned: true });");
await h.run("setTheme('light')");
assert.equal(h.document.documentElement.dataset.theme,'light');
assert.equal(h.storage.get('seiugw-theme'),'light');
assert.equal(h.themes[0].attributes['aria-pressed'],'true');
assert.equal(h.themes[1].attributes['aria-pressed'],'false');
h.run("applyTheme('system')");
assert.equal(h.document.documentElement.dataset.theme,'dark');
assert.equal(h.themes[2].attributes['aria-pressed'],'true');
});
test('tab clicks and arrow keys select exactly one retained panel', () => {
const h = harness();
h.run("renderView = () => { throw new Error('Tabs must preserve mounted forms'); }; bindPointTabs();");
h.panels[3].draft = 'unsaved';
h.tabs[3].handlers.click();
assert.deepEqual(h.panels.filter(p => !p.hidden).map(p => p.dataset.pointsPanel),['modbus']);
h.tabs[3].handlers.keydown({ key: 'ArrowRight', preventDefault() {} });
assert.deepEqual(h.panels.filter(p => !p.hidden).map(p => p.dataset.pointsPanel),['knx']);
assert.equal(h.tabs[4].focused,true);
h.tabs[3].handlers.click();
assert.equal(h.panels[3].draft,'unsaved');
assert.equal(h.tabs.filter(tab => tab.tabIndex === 0).length,1);
});
test('protocol forms and browser hosts belong to separate accessible panels', () => {
const h = harness();
h.run("state.configuration = { bacnet: {}, opcUa: {}, knx: {} }; state.pointsTab = 'bacnet';");
const markup = h.run('viewProtocols()');
const expected = { bacnet: ['bacnet-form','bacnet-browser'], opcua: ['opcua-form','opcua-browser'], modbus: ['modbus-server-form','modbus-import-form'], knx: ['knx-form'], serial: ['serial-port-form'] };
const sections = [...markup.matchAll(/<section id="point-panel-([^"]+)"[\s\S]*?(?=<section id="point-panel-|$)/g)];
assert.equal(sections.length,5);
for (const [markup,id] of sections) {
for (const form of expected[id]) assert.ok(markup.includes(`id="${form}"`),`${form} must be in ${id}`);
assert.ok(markup.includes(`aria-labelledby="point-tab-${id}"`));
assert.equal(/data-points-panel="[^"]+" hidden/.test(markup),id !== 'bacnet');
}
});
test('protocol tabs respect permissions, including MQTT-only accounts', () => {
const h = harness();
h.run("bodyOf = markup => markup; viewMqtt = () => '<div>MQTT test</div>'; state.user = { permissions: ['manage_integrations'] };");
const markup = h.run('viewDataPoints()');
assert.ok(markup.includes('point-tab-mqtt'));
assert.ok(markup.includes('point-tab-status'));
assert.ok(!markup.includes('point-tab-bacnet'));
assert.ok(!markup.includes('point-tab-points'));
assert.equal(h.run('state.pointsTab'),'mqtt');
});