diff --git a/README.md b/README.md index a7b80e5..5f7b164 100644 --- a/README.md +++ b/README.md @@ -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 @@ -53,14 +53,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=`. 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. 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 `. Der Drahttest verwendet ausschließlich Loopback, Ports 47828–47830 und eine eigene temporäre Datenbank; keine Feldgeräte werden beschrieben. ## MQTT-Mapping diff --git a/flake.nix b/flake.nix index d8a38f1..40b2809 100644 --- a/flake.nix +++ b/flake.nix @@ -16,6 +16,7 @@ { default = pkgs.callPackage ./nix/package.nix { }; seiugw = self.packages.${system}.default; + bacnet = pkgs.callPackage ./nix/bacnet.nix { }; }); devShells = forAllSystems (system: diff --git a/native/bacnet/gateway_bridge.c b/native/bacnet/gateway_bridge.c new file mode 100644 index 0000000..c944ad6 --- /dev/null +++ b/native/bacnet/gateway_bridge.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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_msnext) observe(p); +} diff --git a/native/bacnet/gateway_bridge.h b/native/bacnet/gateway_bridge.h new file mode 100644 index 0000000..a2acc1f --- /dev/null +++ b/native/bacnet/gateway_bridge.h @@ -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 diff --git a/nix/bacnet.nix b/nix/bacnet.nix new file mode 100644 index 0000000..d02ae62 --- /dev/null +++ b/nix/bacnet.nix @@ -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 ' '#include + #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 ' '#include + #include ' \ + --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 + ''; +} diff --git a/nix/bootstrap-configuration.nix b/nix/bootstrap-configuration.nix new file mode 100644 index 0000000..ad2dd2e --- /dev/null +++ b/nix/bootstrap-configuration.nix @@ -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"; +} diff --git a/nix/bootstrap-hardware-configuration.nix b/nix/bootstrap-hardware-configuration.nix new file mode 100644 index 0000000..47dac01 --- /dev/null +++ b/nix/bootstrap-hardware-configuration.nix @@ -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; +} diff --git a/nix/deps.json b/nix/deps.json index 7edb5ab..2cccc56 100644 --- a/nix/deps.json +++ b/nix/deps.json @@ -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=" } ] diff --git a/nix/host-hyperv.nix b/nix/host-hyperv.nix new file mode 100644 index 0000000..5c0323b --- /dev/null +++ b/nix/host-hyperv.nix @@ -0,0 +1,24 @@ +{ ... }: + +{ + imports = [ + (builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default + ]; + + services.seiugw = { + enable = true; + bacnet.interface = "eth0"; + bacnet.deviceInstance = 23; + bacnet.ipPort = 47808; + webPort = 8088; + openFirewall = true; + trends = { + enable = true; + databaseName = "wago"; + }; + komari = { + enable = true; + endpoint = "https://komari.cloud.se-inno.de"; + }; + }; +} diff --git a/nix/host-network.py b/nix/host-network.py new file mode 100644 index 0000000..77b1b59 --- /dev/null +++ b/nix/host-network.py @@ -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() diff --git a/nix/installed-hyperv-configuration.nix b/nix/installed-hyperv-configuration.nix new file mode 100644 index 0000000..96dd7ab --- /dev/null +++ b/nix/installed-hyperv-configuration.nix @@ -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"; +} diff --git a/nix/module.nix b/nix/module.nix index 25efde5..a422241 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -6,6 +6,12 @@ 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}"; in { options.services.seiugw = { @@ -67,6 +73,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 +109,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 { @@ -122,9 +134,11 @@ in config = mkIf cfg.enable { users.groups.seiugw = { }; + users.groups.dialout = { }; users.users.seiugw = { isSystemUser = true; group = "seiugw"; + extraGroups = [ "dialout" ]; home = cfg.dataDir; createHome = true; }; @@ -132,15 +146,62 @@ 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 -" ]; 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,6 +235,7 @@ 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; @@ -188,6 +250,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 +314,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 +340,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 +348,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 +406,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 +435,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 +454,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"} ''; diff --git a/src/Gateway.Api/Contracts/AuthenticationContracts.cs b/src/Gateway.Api/Contracts/AuthenticationContracts.cs index 6e69355..56cab22 100644 --- a/src/Gateway.Api/Contracts/AuthenticationContracts.cs +++ b/src/Gateway.Api/Contracts/AuthenticationContracts.cs @@ -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 Permissions); + +public sealed record UpdateKomariEnrollmentTokenRequest(string EnrollmentToken); + +public sealed record UpdateUserPreferencesRequest(string? Theme, string? CsvDelimiter, bool? SidebarPinned, decimal? TrendLineWidth); diff --git a/src/Gateway.Api/Domain/Alarms.cs b/src/Gateway.Api/Domain/Alarms.cs new file mode 100644 index 0000000..ff90933 --- /dev/null +++ b/src/Gateway.Api/Domain/Alarms.cs @@ -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 Destinations); +public sealed record NotificationDelivery(long Id, Guid RuleId, string Title, string Message, + AlarmDestination Destination, string State, DateTimeOffset CreatedAtUtc, string? Result); diff --git a/src/Gateway.Api/Domain/CsvRunner.cs b/src/Gateway.Api/Domain/CsvRunner.cs new file mode 100644 index 0000000..0f08a17 --- /dev/null +++ b/src/Gateway.Api/Domain/CsvRunner.cs @@ -0,0 +1,73 @@ +namespace Gateway.Api.Domain; + +/// A reusable group of trend logs, equivalent to an LTD saved selection. +public sealed record GatewayTrendSelection( + Guid Id, + string Name, + string? Description, + Guid OwnerId, + bool Shared, + IReadOnlyList TrendLogIds, + DateTimeOffset CreatedAtUtc, + DateTimeOffset UpdatedAtUtc); + +public sealed record CreateTrendSelectionRequest(string Name, string? Description, bool Shared, IReadOnlyList TrendLogIds); +public sealed record UpdateTrendSelectionRequest(string? Name, string? Description, bool? Shared, IReadOnlyList? TrendLogIds); + +/// Scheduled CSV export and optional mail dispatch for one saved selection. +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 = ""); diff --git a/src/Gateway.Api/Domain/GatewayConfiguration.cs b/src/Gateway.Api/Domain/GatewayConfiguration.cs index f40ed14..8700bb1 100644 --- a/src/Gateway.Api/Domain/GatewayConfiguration.cs +++ b/src/Gateway.Api/Domain/GatewayConfiguration.cs @@ -9,7 +9,9 @@ public sealed record GatewayConfiguration( IReadOnlyList ModbusServers, KnxConfiguration Knx, MqttConfiguration? Mqtt = null, - InstallationIdentity? Installation = null) + InstallationIdentity? Installation = null, + IReadOnlyList? SerialPorts = null, + IReadOnlyList? 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: []); } /// @@ -52,7 +56,26 @@ public sealed record OpcUaConfiguration( int Port, bool ClientEnabled, bool ServerEnabled, - bool AllowAnonymous); + bool AllowAnonymous, + IReadOnlyList? 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 AllowedClientIps); -public sealed record KnxConfiguration(bool Enabled, bool Secure); +/// Named serial interface. The device path remains a Linux path such as /dev/ttyUSB0. +public sealed record SerialPortConfiguration( + Guid Id, + string Alias, + string DevicePath, + int BaudRate, + string Parity, + int DataBits, + int StopBits); + +/// Modbus RTU slave configuration addressed through a configured serial alias. +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, diff --git a/src/Gateway.Api/Domain/Identity.cs b/src/Gateway.Api/Domain/Identity.cs new file mode 100644 index 0000000..a09b607 --- /dev/null +++ b/src/Gateway.Api/Domain/Identity.cs @@ -0,0 +1,53 @@ +namespace Gateway.Api.Domain; + +/// Locally managed account. Password material never leaves the store. +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 Permissions, + bool IsSystem, + DateTimeOffset UpdatedAtUtc); + +public sealed record AuthenticatedGatewayUser( + GatewayUser User, + IReadOnlyList Permissions); + +/// Personal presentation settings, kept server-side like the former LTD UI. +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 Catalog = + [ + ViewDashboard, ViewTrends, EditAliases, ManageSources, ViewDebug, + ManageAlarms, ManageUsers, ManageRoles, ManageIntegrations, + ManageRunner, ManageGateway + ]; +} diff --git a/src/Gateway.Api/Domain/Mqtt.cs b/src/Gateway.Api/Domain/Mqtt.cs index 39c5073..bb098e8 100644 --- a/src/Gateway.Api/Domain/Mqtt.cs +++ b/src/Gateway.Api/Domain/Mqtt.cs @@ -5,7 +5,8 @@ namespace Gateway.Api.Domain; public enum MqttMappingFormat { SeMonitoring, - Json + Json, + SingleTopic } public enum MqttDirection @@ -20,7 +21,8 @@ public enum SeMonitoringCategory Analog, Notify, Alarm, - Setpoints + Setpoints, + Alarms } public enum MqttQualityOfService @@ -67,6 +69,10 @@ public sealed record UpdateMqttConfigurationRequest( public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool HasPassword); +public sealed record MqttMonitoringSite(int? ProjectYear, string? ProjectNumber, string? IspNumber); +public sealed record MqttPointDefaults(Guid PointId, SeMonitoringCategory? Category, string TopicName); +public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList Points); + public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc); public sealed record MqttClientStatus( @@ -76,4 +82,6 @@ public sealed record MqttClientStatus( string? LastError, DateTimeOffset? ConnectedAtUtc, DateTimeOffset? LastReceivedAtUtc, - DateTimeOffset? LastPublishedAtUtc); + DateTimeOffset? LastPublishedAtUtc, + string? LastFailure = null, + DateTimeOffset? LastFailureAtUtc = null); diff --git a/src/Gateway.Api/Domain/Points.cs b/src/Gateway.Api/Domain/Points.cs index 4676bd4..aa565e6 100644 --- a/src/Gateway.Api/Domain/Points.cs +++ b/src/Gateway.Api/Domain/Points.cs @@ -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 { diff --git a/src/Gateway.Api/Domain/Presentation.cs b/src/Gateway.Api/Domain/Presentation.cs new file mode 100644 index 0000000..ab03398 --- /dev/null +++ b/src/Gateway.Api/Domain/Presentation.cs @@ -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); diff --git a/src/Gateway.Api/Domain/TrendLogs.cs b/src/Gateway.Api/Domain/TrendLogs.cs index 89a811b..f576a32 100644 --- a/src/Gateway.Api/Domain/TrendLogs.cs +++ b/src/Gateway.Api/Domain/TrendLogs.cs @@ -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, diff --git a/src/Gateway.Api/Gateway.Api.csproj b/src/Gateway.Api/Gateway.Api.csproj index 1fb80aa..180a2ea 100644 --- a/src/Gateway.Api/Gateway.Api.csproj +++ b/src/Gateway.Api/Gateway.Api.csproj @@ -2,5 +2,10 @@ + + + + + diff --git a/src/Gateway.Api/Program.cs b/src/Gateway.Api/Program.cs index 178ebe7..6cf6074 100644 --- a/src/Gateway.Api/Program.cs +++ b/src/Gateway.Api/Program.cs @@ -1,3 +1,4 @@ +using System.Text; using System.Text.Json.Serialization; using Gateway.Api.Contracts; using Gateway.Api.Domain; @@ -9,9 +10,12 @@ using Gateway.Api.Services; // store. Explicitly use the executable directory as the content/web root so // the web UI is available no matter which working directory systemd uses. var applicationRoot = AppContext.BaseDirectory; -var builder = WebApplication.CreateBuilder(args); -builder.WebHost.UseContentRoot(applicationRoot); -builder.WebHost.UseWebRoot(Path.Combine(applicationRoot, "wwwroot")); +var builder = WebApplication.CreateBuilder(new WebApplicationOptions +{ + Args = args, + ContentRootPath = applicationRoot, + WebRootPath = Path.Combine(applicationRoot, "wwwroot") +}); builder.Services.Configure(builder.Configuration.GetSection("Gateway")); builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter())); builder.Services.AddSingleton(); @@ -21,11 +25,45 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddHttpClient("seiugw-notifications", client => { client.Timeout = TimeSpan.FromSeconds(10); client.MaxResponseContentBufferSize = 64 * 1024; }) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); +builder.Services.AddHostedService(); var app = builder.Build(); -app.Services.GetRequiredService().Initialize(); +var commandStore = app.Services.GetRequiredService(); +if (args.Length == 2 && args[0] == "--materialize-komari-token") +{ + Environment.ExitCode = commandStore.MaterializeKomariEnrollmentToken(args[1]) ? 0 : 1; + return; +} +if (args.Length == 2 && args[0] == "--import-komari-token") +{ + commandStore.ImportKomariEnrollmentTokenFile(args[1]); + return; +} +commandStore.Initialize(); app.Use(async (context, next) => { @@ -43,11 +81,95 @@ app.Use(async (context, next) => app.UseDefaultFiles(); app.UseStaticFiles(); +app.MapGet("/api/presentation", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.IsValid(request.Headers.Authorization) + ? Results.Ok(new { units = store.ListDisplayUnits(), points = store.ListPointPresentations() }) : Results.Unauthorized()); +app.MapPut("/api/presentation/units", (DisplayUnit unit, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases) + ? Results.Ok(store.SaveDisplayUnit(unit)) : Results.StatusCode(403)); +app.MapPut("/api/presentation/points", (PointPresentation[] points, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.EditAliases)) return Results.StatusCode(403); + store.SavePointPresentations(points); + return Results.NoContent(); +}); +app.MapGet("/api/dashboard", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Contains(GatewayPermissions.ViewDashboard) + ? Results.Ok(store.GetDashboard(user.User.Id)) : Results.StatusCode(403)); +app.MapPut("/api/dashboard", (DashboardWidget[] widgets, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (sessions.GetUser(request.Headers.Authorization) is not { } user || !user.Permissions.Contains(GatewayPermissions.ViewDashboard)) return Results.StatusCode(403); + store.SaveDashboard(user.User.Id, user.User.Role == "admin", widgets); + return Results.NoContent(); +}); + +app.MapGet("/api/points/catalog", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.GetUser(request.Headers.Authorization) is { } user && user.Permissions.Any(permission => permission is GatewayPermissions.ManageSources or GatewayPermissions.EditAliases or GatewayPermissions.ManageAlarms or GatewayPermissions.ManageIntegrations) + ? Results.Ok(store.ListPoints().Select(point => new { point.Id, point.DisplayName, point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable })) : Results.StatusCode(403)); + +app.MapGet("/api/points/status", (HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt, + OpcUaClientService opcUaClient, OpcUaServerService opcUaServer, ModbusProtocolService modbus) => +{ + var auth = request.Headers.Authorization; + var gateway = sessions.HasPermission(auth, GatewayPermissions.ManageGateway); + var sources = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageSources); + var integrations = gateway || sessions.HasPermission(auth, GatewayPermissions.ManageIntegrations); + if (!sources && !integrations) return Results.StatusCode(403); + var configuration = store.GetGatewayConfiguration(); + var clientStatus = opcUaClient.GetStatus().ToDictionary(client => client.ClientId); + var pointNames = sources ? store.ListPoints().ToDictionary(point => point.Id, point => point.DisplayName) : []; + return Results.Ok(new + { + checkedAtUtc = DateTimeOffset.UtcNow, + mqtt = integrations ? mqtt.GetStatus() : null, + bacnet = sources ? store.GetBacnetNativeStatus() : null, + opcUa = sources ? new + { + serverEnabled = configuration.OpcUa.ServerEnabled, + server = opcUaServer.GetStatus(), + clientsEnabled = configuration.OpcUa.ClientEnabled, + clients = (configuration.OpcUa.Clients ?? []).Select(client => new { client.Id, client.Name, client.Enabled, status = clientStatus.GetValueOrDefault(client.Id) }) + } : null, + modbus = sources ? new + { + servers = configuration.ModbusServers.Select(server => new { server.Name, server.Port, listening = modbus.IsTcpListening(server), error = modbus.GetTcpError(server.Id) }), + pointErrors = modbus.GetPointErrors().Where(issue => pointNames.ContainsKey(issue.Id)).OrderByDescending(issue => issue.OccurredAtUtc) + .Select(issue => new { pointId = issue.Id, name = pointNames[issue.Id], issue.Error, issue.OccurredAtUtc }).ToArray() + } : null, + pointErrors = sources ? store.ListPointValues() + .Where(value => pointNames.ContainsKey(value.PointId) && value.Status is { Length: > 0 } quality && + !quality.Equals("Good", StringComparison.OrdinalIgnoreCase) && !quality.Equals("ok", StringComparison.OrdinalIgnoreCase)) + .Select(value => new { value.PointId, name = pointNames[value.PointId], value.SourceProtocol, value.Status, value.UpdatedAtUtc }).ToArray() : null + }); +}); + +app.MapGet("/api/integrations/notifications", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) + ? Results.Ok(store.ListNotificationIntegrations()) : Results.StatusCode(403)); +app.MapPut("/api/integrations/notifications/{channel}", (NotificationChannel channel, UpdateNotificationKeyRequest update, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403); + store.UpdateNotificationKey(channel, update); + return Results.NoContent(); +}); +app.MapGet("/api/alarms", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListAlarmRules()) : Results.StatusCode(403)); +app.MapPut("/api/alarms", (AlarmRule rule, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.SaveAlarmRule(rule)) : Results.StatusCode(403)); +app.MapDelete("/api/alarms/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms)) return Results.StatusCode(403); + store.DeleteAlarmRule(id); + return Results.NoContent(); +}); +app.MapGet("/api/alarms/deliveries", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageAlarms) ? Results.Ok(store.ListNotificationDeliveries()) : Results.StatusCode(403)); + app.MapGet("/api/health", (GatewayStore store) => Results.Ok(new { status = "ok", adminConfigured = store.HasAdmin(), - protocolDataPlane = "not-started" + protocolDataPlane = builder.Configuration["Gateway:ProtocolDataPlane"] ?? "not-started" })); app.MapGet("/api/setup", (GatewayStore store) => Results.Ok(new { adminConfigured = store.HasAdmin() })); @@ -60,15 +182,21 @@ app.MapPost("/api/setup", (SetInitialAdminRequest request, GatewayStore store) = app.MapPost("/api/auth/login", (LoginRequest request, GatewayStore store, SessionService sessions) => { - if (request.Username != "admin" || !store.VerifyAdminPassword(request.Password)) + var user = store.Authenticate(request.Username, request.Password); + if (user is null) { return Results.Unauthorized(); } - var token = sessions.Create(); - return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12))); + var token = sessions.Create(user); + return Results.Ok(new LoginResponse(token, DateTimeOffset.UtcNow.AddHours(12), user)); }); +app.MapGet("/api/auth/me", (HttpRequest request, SessionService sessions) => + sessions.GetUser(request.Headers.Authorization) is { } user + ? Results.Ok(new { user }) + : Results.Unauthorized()); + app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) => { sessions.Remove(request.Headers.Authorization); @@ -77,24 +205,99 @@ app.MapPost("/api/auth/logout", (HttpRequest request, SessionService sessions) = app.MapPost("/api/auth/password", (ChangePasswordRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(httpRequest.Headers.Authorization)) + if (sessions.GetUser(httpRequest.Headers.Authorization) is not { } user) { return Results.Unauthorized(); } - store.ChangeAdminPassword(request.CurrentPassword, request.NewPassword); + if (string.IsNullOrEmpty(request.NewPasswordConfirmation) || + !string.Equals(request.NewPassword, request.NewPasswordConfirmation, StringComparison.Ordinal)) + { + return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." }); + } + store.ChangeUserPassword(user.User.Id, request.CurrentPassword, request.NewPassword); sessions.Remove(httpRequest.Headers.Authorization); return Results.NoContent(); }); +app.MapGet("/api/auth/preferences", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.GetUser(request.Headers.Authorization) is { } user + ? Results.Ok(store.GetUserPreferences(user.User.Id)) + : Results.Unauthorized()); + +app.MapPut("/api/auth/preferences", (UpdateUserPreferencesRequest update, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.GetUser(request.Headers.Authorization) is { } user + ? Results.Ok(store.UpdateUserPreferences(user.User.Id, update)) + : Results.Unauthorized()); + +app.MapGet("/api/system/komari", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway) + ? Results.Ok(new { hasEnrollmentToken = store.HasKomariEnrollmentToken() }) + : Results.Unauthorized()); + +app.MapPut("/api/system/komari", (UpdateKomariEnrollmentTokenRequest request, HttpRequest httpRequest, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(httpRequest.Headers.Authorization, GatewayPermissions.ManageGateway)) + { + return Results.Unauthorized(); + } + store.UpdateKomariEnrollmentToken(request.EnrollmentToken); + return Results.NoContent(); +}); + +app.MapGet("/api/users", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers) + ? Results.Ok(store.ListUsers()) + : Results.Unauthorized()); + +app.MapPost("/api/users", (CreateUserRequest user, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers)) + { + return Results.Unauthorized(); + } + var created = store.CreateUser(user); + return Results.Created($"/api/users/{created.Id}", created); +}); + +app.MapPatch("/api/users/{userId:guid}", (Guid userId, UpdateUserRequest update, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + var actingUser = sessions.GetUser(request.Headers.Authorization); + if (actingUser is null || !actingUser.Permissions.Contains(GatewayPermissions.ManageUsers, StringComparer.Ordinal)) + { + return Results.Unauthorized(); + } + if (update.Password is not null && + !string.Equals(update.Password, update.PasswordConfirmation, StringComparison.Ordinal)) + { + return Results.BadRequest(new { error = "Die neuen Passwörter müssen übereinstimmen." }); + } + return Results.Ok(store.UpdateUser(userId, update, actingUser.User.Id)); +}); + +app.MapGet("/api/roles", (HttpRequest request, GatewayStore store, SessionService sessions) => + (sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles) || sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageUsers)) + ? Results.Ok(new { roles = store.ListRoles(), permissions = GatewayPermissions.Catalog }) + : Results.Unauthorized()); + +app.MapPost("/api/roles", (SaveRoleRequest role, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRoles)) + { + return Results.Unauthorized(); + } + var saved = store.SaveRole(role); + return Results.Created($"/api/roles/{saved.Name}", saved); +}); + app.MapGet("/api/gateway/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway) ? Results.Ok(store.GetGatewayConfiguration()) : Results.Unauthorized()); app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, HttpRequest request, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway)) { return Results.Unauthorized(); } @@ -103,14 +306,60 @@ app.MapPut("/api/gateway/configuration", (GatewayConfiguration configuration, Ht return Results.NoContent(); }); +app.MapGet("/api/gateway/hardware", (HttpRequest request, HardwareDiscoveryService hardware, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway) + ? Results.Ok(hardware.GetInventory()) + : Results.Unauthorized()); +app.MapPut("/api/gateway/installation", (InstallationIdentity identity, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageGateway) + ? Results.Ok(store.UpdateInstallationIdentity(identity)) : Results.StatusCode(403)); + +var network = app.MapGroup("/api/system/network"); +network.AddEndpointFilter(async (context, next) => +{ + var http = context.HttpContext; + return http.RequestServices.GetRequiredService() + .HasPermission(http.Request.Headers.Authorization, GatewayPermissions.ManageGateway) + ? await next(context) : Results.StatusCode(403); +}); +network.MapGet("", (HostNetworkService service, CancellationToken ct) => service.SendAsync(new { action = "status" }, ct)); +network.MapPost("/apply", (HostNetworkProfile profile, HostNetworkService service, CancellationToken ct) => + service.SendAsync(new { action = "apply", profile }, ct)); +network.MapPost("/confirm", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) => + service.SendAsync(new { action = "confirm", change.Id }, ct)); +network.MapPost("/revert", (HostNetworkConfirmation change, HostNetworkService service, CancellationToken ct) => + service.SendAsync(new { action = "revert", change.Id }, ct)); + +app.MapPost("/api/bacnet/scan", async (BacnetScanRequest scan, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized(); + return Results.Ok(await browser.ScanAsync(scan, cancellationToken)); +}); + +app.MapPost("/api/bacnet/browse", async (BacnetBrowseRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.Unauthorized(); + return Results.Ok(await browser.BrowseObjectListAsync(browse, cancellationToken)); +}); +app.MapPost("/api/bacnet/objects", async (BacnetObjectsRequest browse, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return Results.Ok(await browser.BrowseDetailsAsync(browse, cancellationToken)); +}); +app.MapPost("/api/bacnet/import", async (BacnetImportRequest import, HttpRequest request, BacnetBrowserService browser, SessionService sessions, CancellationToken cancellationToken) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return Results.Ok(await browser.ImportAsync(import, cancellationToken)); +}); + app.MapGet("/api/points", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) ? Results.Ok(store.ListPoints()) : Results.Unauthorized()); app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) { return Results.Unauthorized(); } @@ -118,54 +367,150 @@ app.MapPost("/api/points", (CreatePointRequest point, HttpRequest request, Gatew var createdPoint = store.CreatePoint(point); return Results.Created($"/api/points/{createdPoint.Id}", createdPoint); }); +app.MapGet("/api/points/{id:guid}/dependencies", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return store.GetPointDependencies(id) is { } dependencies ? Results.Ok(dependencies) : Results.NotFound(); +}); +app.MapPut("/api/points/{id:guid}", (Guid id, CreatePointRequest point, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return store.UpdatePoint(id, point) is { } updated ? Results.Ok(updated) : Results.NotFound(); +}); +app.MapDelete("/api/points/{id:guid}", (Guid id, string? confirmation, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return store.DeletePoint(id, confirmation) ? Results.NoContent() : Results.NotFound(); +}); + +app.MapGet("/api/imports/modbus-example.csv", (HttpRequest request, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.File(System.Text.Encoding.UTF8.GetBytes(ModbusCsvImporter.Example), "text/csv; charset=utf-8", "seiugw-modbus-beispiel.csv") + : Results.Unauthorized()); + +app.MapPost("/api/imports/modbus-csv", (ModbusCsvImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) + { + return Results.Unauthorized(); + } + + return Results.Ok(ModbusCsvImporter.Import(import.Csv, store)); +}); + +app.MapPost("/api/imports/knx-ets", (KnxEtsImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) + { + return Results.Unauthorized(); + } + return Results.Ok(KnxEtsImporter.Import(import, store)); +}); + +app.MapPost("/api/opcua/browse", async (OpcUaBrowseRequest browse, HttpRequest request, OpcUaBrowserService browser, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) + { + return Results.Unauthorized(); + } + + return Results.Ok(await browser.BrowseAsync(browse)); +}); + +app.MapGet("/api/opcua/clients", (HttpRequest request, GatewayStore store, OpcUaClientService clients, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(new { clients = store.ListOpcUaClients(), status = clients.GetStatus() }) : Results.Unauthorized()); +app.MapGet("/api/bacnet/status", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(store.GetBacnetNativeStatus()) : Results.Unauthorized()); +app.MapPost("/api/opcua/clients", (SaveOpcUaClientRequest configuration, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(store.SaveOpcUaClient(configuration)) : Results.Unauthorized()); +app.MapPost("/api/opcua/import", (OpcUaImportRequest import, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(store.ImportOpcUaPoints(import)) : Results.Unauthorized()); app.MapGet("/api/mqtt/configuration", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.GetMqttConfiguration()) : Results.Unauthorized()); -app.MapPut("/api/mqtt/configuration", (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) => +app.MapPut("/api/mqtt/configuration", async (UpdateMqttConfigurationRequest mqtt, HttpRequest request, GatewayStore store, + SessionService sessions, MqttClientService mqttClient, MqttTopicBrowserService browser) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) { return Results.Unauthorized(); } store.UpdateMqttConfiguration(mqtt); mqttClient.RequestReconfigure(); + await browser.ResetAsync(CancellationToken.None); return Results.NoContent(); }); +app.MapPost("/api/mqtt/browser", async (MqttTopicBrowseRequest browse, HttpRequest request, SessionService sessions, + MqttTopicBrowserService browser, CancellationToken cancellationToken) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) + ? Results.Ok(await browser.StartBrowseAsync(browse, cancellationToken)) : Results.StatusCode(403)); +app.MapGet("/api/mqtt/browser/{id:guid}", (Guid id, HttpRequest request, SessionService sessions, MqttTopicBrowserService browser) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) + ? Results.Ok(browser.GetBrowse(id)) : Results.StatusCode(403)); +app.MapPost("/api/mqtt/browser/import", async (MqttTopicImportRequest import, HttpRequest request, SessionService sessions, + MqttTopicBrowserService browser, CancellationToken cancellationToken) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) && + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(await browser.ImportAsync(import, cancellationToken)) : Results.StatusCode(403)); + app.MapGet("/api/mqtt/status", (HttpRequest request, SessionService sessions, MqttClientService mqttClient) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(mqttClient.GetStatus()) : Results.Unauthorized()); app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.ListMqttMappings().Select(mapping => new { Mapping = mapping, Topic = GatewayStore.GetMqttTopic(mapping) })) : Results.Unauthorized()); +app.MapGet("/api/mqtt/mapping-defaults", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) + ? Results.Ok(store.GetMqttMappingDefaults()) : Results.StatusCode(403)); app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) { return Results.Unauthorized(); } var createdMapping = store.CreateMqttMapping(mapping); + if (createdMapping.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([createdMapping.Id]); mqttClient.RequestReconfigure(); return Results.Created($"/api/mqtt/mappings/{createdMapping.Id}", new { Mapping = createdMapping, Topic = GatewayStore.GetMqttTopic(createdMapping) }); }); +app.MapPut("/api/mqtt/mappings/{id:guid}", (Guid id, CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403); + if (store.UpdateMqttMapping(id, mapping) is not { } updated) return Results.NotFound(); + if (updated.Direction == MqttDirection.Publish) mqttClient.QueueInitialPublications([updated.Id]); + mqttClient.RequestReconfigure(); + return Results.Ok(new { Mapping = updated, Topic = GatewayStore.GetMqttTopic(updated) }); +}); +app.MapDelete("/api/mqtt/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.StatusCode(403); + if (!store.DeleteMqttMapping(id)) return Results.NotFound(); + mqttClient.RequestReconfigure(); + return Results.NoContent(); +}); app.MapGet("/api/mappings", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) ? Results.Ok(store.ListMappings()) : Results.Unauthorized()); app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) { return Results.Unauthorized(); } @@ -173,15 +518,59 @@ app.MapPost("/api/mappings", (CreateMappingRequest mapping, HttpRequest request, var response = store.CreateMapping(mapping); return Results.Created($"/api/mappings/{response.Mapping.Id}", response); }); +app.MapPut("/api/mappings/{id:guid}", (Guid id, CreateMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return store.UpdateMapping(id, mapping) is { } updated ? Results.Ok(updated) : Results.NotFound(); +}); +app.MapDelete("/api/mappings/{id:guid}", (Guid id, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) return Results.StatusCode(403); + return store.DeleteMapping(id) ? Results.NoContent() : Results.NotFound(); +}); +app.MapGet("/api/mappings/bulk/modbus-servers", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources) + ? Results.Ok(store.GetGatewayConfiguration().ModbusServers.Select(server => + new { server.Id, server.Name, server.FirstHoldingRegister, server.HoldingRegisterCount })) + : Results.StatusCode(403)); +app.MapPost("/api/mappings/bulk", (BulkMappingRequest bulk, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) => +{ + var authorization = request.Headers.Authorization; + if (!sessions.HasPermission(authorization, GatewayPermissions.ManageSources) || + bulk.Target == BulkMappingTarget.Mqtt && !sessions.HasPermission(authorization, GatewayPermissions.ManageIntegrations)) + return Results.StatusCode(403); + var result = store.CreateBulkMappings(bulk); + mqtt.QueueInitialPublications(result.NewMqttMappings); + return Results.Ok(result); +}); + +MapConfigurationCsv("/api/points/csv", "seiugw-datenpunkte.csv", ConfigurationCsvKind.Points, GatewayPermissions.ManageSources); +MapConfigurationCsv("/api/mappings/csv", "seiugw-mappings.csv", ConfigurationCsvKind.Mappings, GatewayPermissions.ManageSources); +MapConfigurationCsv("/api/mqtt/mappings/csv", "seiugw-mqtt-mappings.csv", ConfigurationCsvKind.MqttMappings, GatewayPermissions.ManageIntegrations); + +void MapConfigurationCsv(string route, string file, ConfigurationCsvKind kind, string permission) +{ + app.MapGet(route, (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, permission) + ? Results.File(Encoding.UTF8.GetBytes(store.ExportConfigurationCsv(kind)), "text/csv; charset=utf-8", file) + : Results.StatusCode(403)); + app.MapPost(route, (ConfigurationCsvRequest input, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqtt) => + { + if (!sessions.HasPermission(request.Headers.Authorization, permission)) return Results.StatusCode(403); + var result = store.ImportConfigurationCsv(kind, input.Csv); + if (kind == ConfigurationCsvKind.MqttMappings && result.Created + result.Updated > 0) mqtt.RequestReconfigure(); + return Results.Ok(result); + }); +} app.MapGet("/api/trend-logs", (HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends) ? Results.Ok(store.ListTrendLogs()) : Results.Unauthorized()); app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest request, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) { return Results.Unauthorized(); } @@ -191,13 +580,22 @@ app.MapPost("/api/trend-logs", (CreateTrendLogRequest trendLog, HttpRequest requ }); app.MapGet("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewTrends) ? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500)) : Results.Unauthorized()); +// Public trend access is deliberately opt-in per trend log. It exposes only sampled values, +// never gateway configuration, credentials, points, mappings, or write functions. +app.MapGet("/api/public/trend-logs", (GatewayStore store) => Results.Ok(store.ListPublicTrendLogs())); + +app.MapGet("/api/public/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, int? limit, GatewayStore store) => + store.IsPublicTrendLog(trendLogId) + ? Results.Ok(store.ListTrendRecords(trendLogId, limit ?? 500)) + : Results.NotFound()); + app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, AppendTrendRecordRequest trendRecord, HttpRequest request, GatewayStore store, SessionService sessions) => { - if (!sessions.IsValid(request.Headers.Authorization)) + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageSources)) { return Results.Unauthorized(); } @@ -206,8 +604,81 @@ app.MapPost("/api/trend-logs/{trendLogId:guid}/records", (Guid trendLogId, Appen return createdRecord is null ? Results.NoContent() : Results.Created($"/api/trend-logs/{trendLogId}/records/{createdRecord.SequenceNumber}", createdRecord); }); +app.MapGet("/api/trend-selections", (HttpRequest request, GatewayStore store, SessionService sessions) => +{ + var user = sessions.GetUser(request.Headers.Authorization); + return user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal) + ? Results.Unauthorized() + : Results.Ok(store.ListTrendSelections(user.User.Id, user.User.Role == "admin")); +}); + +app.MapPost("/api/trend-selections", (CreateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + var user = sessions.GetUser(request.Headers.Authorization); + if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized(); + var created = store.CreateTrendSelection(selection, user.User.Id); + return Results.Created($"/api/trend-selections/{created.Id}", created); +}); + +app.MapPatch("/api/trend-selections/{selectionId:guid}", (Guid selectionId, UpdateTrendSelectionRequest selection, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + var user = sessions.GetUser(request.Headers.Authorization); + if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized(); + return Results.Ok(store.UpdateTrendSelection(selectionId, selection, user.User.Id, user.User.Role == "admin")); +}); + +app.MapDelete("/api/trend-selections/{selectionId:guid}", (Guid selectionId, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + var user = sessions.GetUser(request.Headers.Authorization); + if (user is null || !user.Permissions.Contains(GatewayPermissions.ViewTrends, StringComparer.Ordinal)) return Results.Unauthorized(); + store.DeleteTrendSelection(selectionId, user.User.Id, user.User.Role == "admin"); + return Results.NoContent(); +}); + +app.MapGet("/api/integrations/mail", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.GetMailIntegration()) : Results.Unauthorized()); + +app.MapPut("/api/integrations/mail", (UpdateMailIntegrationRequest integration, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations)) return Results.Unauthorized(); + store.UpdateMailIntegration(integration); + return Results.NoContent(); +}); + +app.MapGet("/api/runner/jobs", (HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(store.ListCsvRunnerJobs()) : Results.Unauthorized()); + +app.MapGet("/api/runner/queue", (HttpRequest request, CsvRunnerService runner, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner) ? Results.Ok(runner.ListExecutions()) : Results.StatusCode(403)); + +app.MapPost("/api/runner/jobs", (CreateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized(); + var created = store.CreateCsvRunnerJob(job); + return Results.Created($"/api/runner/jobs/{created.Id}", created); +}); + +app.MapPatch("/api/runner/jobs/{jobId:guid}", (Guid jobId, UpdateCsvRunnerJobRequest job, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized(); + return Results.Ok(store.UpdateCsvRunnerJob(jobId, job)); +}); + +app.MapPost("/api/runner/jobs/{jobId:guid}/test", async (Guid jobId, HttpRequest request, CsvRunnerService runner, SessionService sessions, CancellationToken cancellationToken) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized(); + return Results.Ok(await runner.RunNowAsync(jobId, cancellationToken)); +}); + +app.MapDelete("/api/runner/jobs/{jobId:guid}", (Guid jobId, HttpRequest request, GatewayStore store, SessionService sessions) => +{ + if (!sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageRunner)) return Results.Unauthorized(); + store.DeleteCsvRunnerJob(jobId); + return Results.NoContent(); +}); + app.MapGet("/api/audit", (int? limit, HttpRequest request, GatewayStore store, SessionService sessions) => - sessions.IsValid(request.Headers.Authorization) + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ViewDebug) ? Results.Ok(store.ListAudit(limit ?? 100)) : Results.Unauthorized()); diff --git a/src/Gateway.Api/Services/BacnetBrowserService.cs b/src/Gateway.Api/Services/BacnetBrowserService.cs new file mode 100644 index 0000000..779d1e9 --- /dev/null +++ b/src/Gateway.Api/Services/BacnetBrowserService.cs @@ -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); + +/// +/// 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. +/// +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> 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(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> 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(); + 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> 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(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 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 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 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 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 { 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 { 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 { 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 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 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 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 value, uint number) + { + value.Add((byte)(number >> 24)); value.Add((byte)(number >> 16)); value.Add((byte)(number >> 8)); value.Add((byte)number); + } +} diff --git a/src/Gateway.Api/Services/BacnetExternalPointService.cs b/src/Gateway.Api/Services/BacnetExternalPointService.cs new file mode 100644 index 0000000..b25c319 --- /dev/null +++ b/src/Gateway.Api/Services/BacnetExternalPointService.cs @@ -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 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 logger) : BackgroundService +{ + private readonly Dictionary _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(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; +} diff --git a/src/Gateway.Api/Services/BacnetNativeBridgeService.cs b/src/Gateway.Api/Services/BacnetNativeBridgeService.cs new file mode 100644 index 0000000..3e0f858 --- /dev/null +++ b/src/Gateway.Api/Services/BacnetNativeBridgeService.cs @@ -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(); + 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(); + } +} + +/// Only native effective values feed the shared mapping/trend store, never unarbitrated commands. +public sealed class BacnetNativeBridgeService(GatewayDatabase database, GatewayStore store, ILogger 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(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(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; } + } + } +} diff --git a/src/Gateway.Api/Services/BacnetObjectDetails.cs b/src/Gateway.Api/Services/BacnetObjectDetails.cs new file mode 100644 index 0000000..7f1fbfb --- /dev/null +++ b/src/Gateway.Api/Services/BacnetObjectDetails.cs @@ -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 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 ReadDeviceNamesAsync(IReadOnlyList 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 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 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(); + 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(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 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> ReadInventoryAsync(UdpClient socket, IPEndPoint endpoint, int device, + BacnetRoute? route, int offset, int end, CancellationToken token) + { + var objects = new List(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 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 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 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; + } +} diff --git a/src/Gateway.Api/Services/CsvRunnerService.cs b/src/Gateway.Api/Services/CsvRunnerService.cs new file mode 100644 index 0000000..47b489c --- /dev/null +++ b/src/Gateway.Api/Services/CsvRunnerService.cs @@ -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; + +/// 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. +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 _executions = new(); + + public IReadOnlyList ListExecutions() => _executions.Values.OrderBy(item => item.EnqueuedAtUtc).ToArray(); + + public CsvRunnerService(GatewayStore store, NotificationTransport transport, IOptions options) + { + _store = store; + _transport = transport; + _exportDirectory = Path.Combine(Path.GetFullPath(options.Value.DataDirectory), "exports"); + } + + public async Task 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 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 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"); } + } +} diff --git a/src/Gateway.Api/Services/GatewayDatabase.cs b/src/Gateway.Api/Services/GatewayDatabase.cs index 27c09d2..dcf09da 100644 --- a/src/Gateway.Api/Services/GatewayDatabase.cs +++ b/src/Gateway.Api/Services/GatewayDatabase.cs @@ -38,10 +38,45 @@ public sealed class GatewayDatabase using var command = connection.CreateCommand(); command.CommandText = """ PRAGMA journal_mode = WAL; + CREATE TABLE IF NOT EXISTS bacnet_commands ( + id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL, + priority INTEGER NOT NULL, created_ms INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'pending', result TEXT NULL + ); + CREATE TABLE IF NOT EXISTS bacnet_properties ( + id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, property INTEGER NOT NULL, + array_index INTEGER NOT NULL, priority INTEGER NOT NULL, payload BLOB NOT NULL, + UNIQUE(point_id, property, array_index, priority) + ); + CREATE TABLE IF NOT EXISTS bacnet_observations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL, + status TEXT NOT NULL, observed_ms INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS bacnet_runtime ( + id INTEGER PRIMARY KEY CHECK(id=1), heartbeat_ms INTEGER NOT NULL, state TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS bacnet_discovery ( + id INTEGER PRIMARY KEY CHECK(id=1), scan_id TEXT NOT NULL, target TEXT, + port INTEGER NOT NULL, expires_ms INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE IF NOT EXISTS bacnet_discovered_devices ( + scan_id TEXT NOT NULL, device_instance INTEGER NOT NULL, address TEXT NOT NULL, + port INTEGER NOT NULL, vendor INTEGER NOT NULL, max_apdu INTEGER NOT NULL, + network INTEGER NOT NULL DEFAULT 0, mac TEXT, + PRIMARY KEY(scan_id, device_instance, address, port) + ); CREATE TABLE IF NOT EXISTS settings ( key TEXT NOT NULL PRIMARY KEY, value TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS alarm_rules ( + id TEXT PRIMARY KEY, point_id TEXT NOT NULL REFERENCES points(id), enabled INTEGER NOT NULL, + configuration_json TEXT NOT NULL, active INTEGER NULL, observed_at_utc TEXT NULL + ); + CREATE TABLE IF NOT EXISTS notification_outbox ( + id INTEGER PRIMARY KEY AUTOINCREMENT, rule_id TEXT NOT NULL, title TEXT NOT NULL, message TEXT NOT NULL, + destination_json TEXT NOT NULL, state TEXT NOT NULL, created_at_utc TEXT NOT NULL, result TEXT NULL + ); + CREATE INDEX IF NOT EXISTS idx_notification_pending ON notification_outbox(state, id); CREATE TABLE IF NOT EXISTS admin_account ( id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1), username TEXT NOT NULL UNIQUE CHECK(username = 'admin'), @@ -50,6 +85,34 @@ public sealed class GatewayDatabase password_iterations INTEGER NOT NULL, changed_at_utc TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS app_roles ( + name TEXT NOT NULL PRIMARY KEY, + label TEXT NOT NULL, + permissions_json TEXT NOT NULL, + is_system INTEGER NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS app_users ( + id TEXT NOT NULL PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + email TEXT NULL UNIQUE, + password_hash BLOB NOT NULL, + password_salt BLOB NOT NULL, + password_iterations INTEGER NOT NULL, + role_name TEXT NOT NULL REFERENCES app_roles(name) ON UPDATE CASCADE ON DELETE RESTRICT, + active INTEGER NOT NULL, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS app_user_preferences ( + user_id TEXT NOT NULL PRIMARY KEY REFERENCES app_users(id) ON DELETE CASCADE, + theme TEXT NOT NULL DEFAULT 'system', + csv_delimiter TEXT NOT NULL DEFAULT ';', + sidebar_pinned INTEGER NOT NULL DEFAULT 1, + trend_line_width REAL NOT NULL DEFAULT 1.8, + updated_at_utc TEXT NOT NULL + ); CREATE TABLE IF NOT EXISTS points ( id TEXT NOT NULL PRIMARY KEY, display_name TEXT NOT NULL, @@ -62,7 +125,8 @@ public sealed class GatewayDatabase address_json TEXT NOT NULL, created_at_utc TEXT NOT NULL, bacnet_object_kind TEXT NULL, - bacnet_object_instance INTEGER NULL + bacnet_object_instance INTEGER NULL, + deleted_at_utc TEXT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS idx_points_external_identity ON points(protocol, external_identity) @@ -117,6 +181,7 @@ public sealed class GatewayDatabase interval_seconds INTEGER NOT NULL, max_records INTEGER NOT NULL, enabled INTEGER NOT NULL, + public_access INTEGER NOT NULL DEFAULT 0, created_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS trend_records ( @@ -130,18 +195,55 @@ public sealed class GatewayDatabase ); CREATE INDEX IF NOT EXISTS idx_trend_records_query ON trend_records(trend_log_id, sequence_number DESC); + CREATE TABLE IF NOT EXISTS trend_selections ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + description TEXT NULL, + owner_id TEXT NOT NULL REFERENCES app_users(id) ON DELETE CASCADE, + shared INTEGER NOT NULL, + trend_log_ids_json TEXT NOT NULL, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS csv_runner_jobs ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + selection_id TEXT NOT NULL REFERENCES trend_selections(id) ON DELETE RESTRICT, + time TEXT NOT NULL, + range_hours INTEGER NOT NULL, + delimiter TEXT NOT NULL, + enabled INTEGER NOT NULL, + mail_enabled INTEGER NOT NULL, + mail_to TEXT NULL, + mail_subject TEXT NOT NULL, + mail_message TEXT NOT NULL, + last_run_local_date TEXT NULL, + last_result_json TEXT NULL, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); """; command.ExecuteNonQuery(); EnsureColumn(connection, "points", "bacnet_object_kind", "TEXT NULL"); EnsureColumn(connection, "points", "bacnet_object_instance", "INTEGER NULL"); - using var bacnetObjectIndex = connection.CreateCommand(); - bacnetObjectIndex.CommandText = """ + EnsureColumn(connection, "points", "deleted_at_utc", "TEXT NULL"); + EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0"); + EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0"); + EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL"); + using var indexMigration = connection.BeginTransaction(); + using var pointIndexes = connection.CreateCommand(); + pointIndexes.Transaction = indexMigration; + pointIndexes.CommandText = """ + DROP INDEX IF EXISTS idx_points_external_identity; + CREATE UNIQUE INDEX idx_points_external_identity ON points(protocol, external_identity) + WHERE external_identity IS NOT NULL AND deleted_at_utc IS NULL; DROP INDEX IF EXISTS idx_points_bacnet_object; CREATE UNIQUE INDEX idx_points_bacnet_object ON points(bacnet_object_kind, bacnet_object_instance) - WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL; + WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL AND deleted_at_utc IS NULL; """; - bacnetObjectIndex.ExecuteNonQuery(); + pointIndexes.ExecuteNonQuery(); + indexMigration.Commit(); } private static void EnsureColumn(SqliteConnection connection, string tableName, string columnName, string definition) diff --git a/src/Gateway.Api/Services/GatewayOpcUaServer.cs b/src/Gateway.Api/Services/GatewayOpcUaServer.cs new file mode 100644 index 0000000..ca9b091 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayOpcUaServer.cs @@ -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. + +/// A real UA address space backed by the common point store, not a second writer. +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 _pending = new(); + private readonly Dictionary _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> 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(); + 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 diff --git a/src/Gateway.Api/Services/GatewayStore.Alarms.cs b/src/Gateway.Api/Services/GatewayStore.Alarms.cs new file mode 100644 index 0000000..8b92e35 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.Alarms.cs @@ -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 ListNotificationIntegrations() + { + using var connection = _database.OpenConnection(); + return Enum.GetValues().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 ListAlarmRules() + { + using var connection = _database.OpenConnection(); + return ReadAlarmRules(connection); + } + + private static List 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(); + while (reader.Read()) rules.Add(JsonSerializer.Deserialize(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(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 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(); + 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(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(); + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs b/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs new file mode 100644 index 0000000..6e3fce0 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs @@ -0,0 +1,192 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using Gateway.Api.Domain; +using Microsoft.Data.Sqlite; + +namespace Gateway.Api.Services; + +public enum BulkMappingTarget { Mqtt, Modbus, Bacnet, OpcUa } +public sealed record BulkMappingRequest(Guid[] SourcePointIds, BulkMappingTarget Target, + Guid? ModbusServerId = null, int? FirstRegister = null, string? MqttTopicPrefix = null, + MqttMappingFormat? MqttFormat = null, MqttMonitoringSite? MqttSite = null); +public sealed record BulkMappingResult(int Created, int Existing, IReadOnlyList Assignments) +{ + [JsonIgnore] + public IReadOnlyList NewMqttMappings { get; init; } = []; +} + +public sealed partial class GatewayStore +{ + public BulkMappingResult CreateBulkMappings(BulkMappingRequest request) + { + if (request.SourcePointIds is not { Length: >= 1 and <= 500 } || request.SourcePointIds.Distinct().Count() != request.SourcePointIds.Length || + !Enum.IsDefined(request.Target)) + throw new DomainValidationException("Bitte 1 bis 500 verschiedene Datenpunkte und ein gültiges Ziel auswählen."); + + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var points = ReadPoints(connection, transaction).ToDictionary(point => point.Id); + var links = ReadMappings(connection, transaction); + var mqtt = ReadMqttMappings(connection, transaction); + var configuration = ReadGatewayConfiguration(connection, transaction); + var server = request.Target == BulkMappingTarget.Modbus + ? configuration.ModbusServers.SingleOrDefault(item => item.Id == request.ModbusServerId) ?? + throw new DomainValidationException("Bitte zuerst eine Modbus-TCP-Serverinstanz auswählen.") + : null; + var prefix = request.MqttTopicPrefix?.Trim().TrimEnd('/'); + var mqttFormat = request.MqttFormat ?? (prefix is null ? MqttMappingFormat.SeMonitoring : MqttMappingFormat.Json); + var site = request.MqttSite ?? DefaultMonitoringSite(configuration.Installation); + var alarms = request.Target == BulkMappingTarget.Mqtt && mqttFormat == MqttMappingFormat.SeMonitoring + ? ReadMqttAlarmPoints(connection, transaction) : []; + if (request.Target == BulkMappingTarget.Mqtt && mqttFormat != MqttMappingFormat.SeMonitoring && + (string.IsNullOrWhiteSpace(prefix) || !IsValidMqttTopic(prefix) || prefix.Length > 850)) + throw new DomainValidationException("Für MQTT ein gültiges Topic-Präfix ohne Wildcards eingeben."); + + var usedRegisters = new HashSet<(ModbusArea Area, int Index)>(); + if (server is not null) + { + foreach (var point in points.Values) + { + if (!ModbusAddressing.TryParse(point, out var address) || address.ServerId != server.Id) continue; + for (var offset = 0; offset < address.RegisterCount; offset++) usedRegisters.Add((address.Area, address.Address + offset)); + } + } + var nextRegister = request.FirstRegister ?? server?.FirstHoldingRegister ?? 0; + var nextDiscrete = nextRegister; + if (server is not null && (nextRegister < server.FirstHoldingRegister || nextRegister >= server.FirstHoldingRegister + server.HoldingRegisterCount)) + throw new DomainValidationException("Die Startadresse liegt außerhalb des Registerbereichs der Modbus-Instanz."); + + var saved = new List(); + var seed = new List(); + var mqttCreated = new List(); + var skipped = 0; + foreach (var id in request.SourcePointIds) + { + if (!points.TryGetValue(id, out var source) || !source.Readable) + throw new DomainValidationException("Die Auswahl enthält einen fehlenden oder nicht lesbaren Datenpunkt."); + if (request.Target == BulkMappingTarget.Mqtt) + { + var slug = Regex.Replace(source.DisplayName.ToLowerInvariant(), "[^a-z0-9_-]+", "-").Trim('-'); + if (slug.Length > 80) slug = slug[..80]; + var pointDefaults = GetMqttPointDefaults(source, alarms); + var monitoring = mqttFormat == MqttMappingFormat.SeMonitoring; + if (monitoring && pointDefaults.Category is null) + throw new DomainValidationException($"'{source.DisplayName}' benötigt das MQTT-Format JSON."); + var topicName = pointDefaults.TopicName; + var topic = monitoring ? BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName) : + $"{prefix}/{(slug.Length == 0 ? "punkt" : slug)}-{source.Id:N}"; + var occupied = mqtt.Where(mapping => GetMqttTopic(mapping) == topic).ToArray(); + if (occupied.Any(mapping => mapping.PointId == source.Id && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)) + { + skipped++; + continue; + } + if (monitoring && occupied.Length > 0) + { + topicName = $"{topicName}-{source.Id:N}"; + topic = BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName); + if (mqtt.Any(mapping => mapping.PointId == source.Id && GetMqttTopic(mapping) == topic && + mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)) + { + skipped++; + continue; + } + if (mqtt.Any(mapping => GetMqttTopic(mapping) == topic)) + throw new DomainValidationException($"Das erzeugte MQTT-Topic für '{source.DisplayName}' ist bereits belegt."); + } + var mqttMapping = SaveMqttMapping(connection, transaction, null, new CreateMqttMappingRequest(source.Id, mqttFormat, + MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false, + monitoring ? site.ProjectYear : null, monitoring ? site.ProjectNumber : null, monitoring ? site.IspNumber : null, + monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null))!; + mqtt.Add(mqttMapping); + mqttCreated.Add(mqttMapping.Id); + saved.Add($"{source.DisplayName} → {topic}"); + continue; + } + + var protocol = request.Target switch + { + BulkMappingTarget.Modbus => PointProtocol.Modbus, + BulkMappingTarget.Bacnet => PointProtocol.Bacnet, + _ => PointProtocol.OpcUa + }; + if (links.Any(link => link.Enabled && link.SourcePointId == source.Id && + points.TryGetValue(link.TargetPointId, out var target) && target.Protocol == protocol && target.Scope == PointScope.Gateway && + (server is null || ModbusAddressing.TryParse(target, out var bound) && bound.ServerId == server.Id))) + { + skipped++; + continue; + } + + var name = $"{source.DisplayName[..Math.Min(114, source.DisplayName.Length)]} [{source.Id:N}]"; + var type = OpcUaPointTypes.Resolve(source.ValueType); + var binary = type == Opc.Ua.BuiltInType.Boolean; + CreatePointRequest targetRequest; + string? assignment = null; + if (server is not null) + { + var dataType = type switch + { + Opc.Ua.BuiltInType.Boolean => ModbusDataType.Boolean, + Opc.Ua.BuiltInType.Byte or Opc.Ua.BuiltInType.UInt16 => ModbusDataType.UInt16, + Opc.Ua.BuiltInType.SByte or Opc.Ua.BuiltInType.Int16 => ModbusDataType.Int16, + Opc.Ua.BuiltInType.Int32 => ModbusDataType.Int32, + Opc.Ua.BuiltInType.UInt32 => ModbusDataType.UInt32, + Opc.Ua.BuiltInType.Float or Opc.Ua.BuiltInType.Double => ModbusDataType.Float32, + _ => throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten Modbus-Werttyp.") + }; + var area = binary ? ModbusArea.DiscreteInput : ModbusArea.InputRegister; + var width = dataType is ModbusDataType.UInt32 or ModbusDataType.Int32 or ModbusDataType.Float32 ? 2 : 1; + ref var cursor = ref (binary ? ref nextDiscrete : ref nextRegister); + var limit = server.FirstHoldingRegister + server.HoldingRegisterCount; + while (cursor + width <= limit && Enumerable.Range(cursor, width).Any(index => usedRegisters.Contains((area, index)))) cursor++; + if (cursor + width > limit) + throw new DomainValidationException($"Für '{source.DisplayName}' ist im Modbus-Server kein freier Adressbereich mehr verfügbar."); + var register = cursor; + cursor += width; + for (var offset = 0; offset < width; offset++) usedRegisters.Add((area, register + offset)); + targetRequest = new(name, protocol, PointScope.Gateway, dataType.ToString(), true, false, null, + JsonSerializer.SerializeToElement(new { serverId = server.Id, unitId = server.UnitId, area = area.ToString(), address = register, dataType = dataType.ToString() })); + assignment = $"{area} {register}" + (width > 1 ? $"–{register + width - 1}" : ""); + } + else if (protocol == PointProtocol.Bacnet) + { + if (type is Opc.Ua.BuiltInType.Null or Opc.Ua.BuiltInType.String) + throw new DomainValidationException($"'{source.DisplayName}' hat keinen unterstützten BACnet-Werttyp."); + targetRequest = new(name, protocol, PointScope.Gateway, binary ? "Boolean" : "Real", true, false, null, + EmptyObject(), binary ? BacnetObjectKind.BinaryValue : BacnetObjectKind.AnalogValue); + } + else + { + targetRequest = new(name, protocol, PointScope.Gateway, source.ValueType, true, false, null, EmptyObject()); + } + + var targetPoint = InsertPoint(connection, transaction, targetRequest); + var mapping = SaveMapping(connection, transaction, null, + new CreateMappingRequest(source.Id, targetPoint.Id, MappingDirection.OneWay, true, null, false, EmptyObject()))!.Mapping; + seed.Add(mapping); + saved.Add($"{source.DisplayName} → {assignment ?? (protocol == PointProtocol.Bacnet ? $"{targetPoint.BacnetObjectKind} {targetPoint.BacnetObjectInstance}" : targetPoint.DisplayName)}"); + } + transaction.Commit(); + SeedNewMappings(seed); + return new(saved.Count, skipped, saved) { NewMqttMappings = mqttCreated }; + } + + private void SeedNewMappings(List 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. */ } + } + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs b/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs new file mode 100644 index 0000000..5671b4f --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs @@ -0,0 +1,169 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Gateway.Api.Domain; +using Microsoft.Data.Sqlite; +using Microsoft.VisualBasic.FileIO; + +namespace Gateway.Api.Services; + +public enum ConfigurationCsvKind { Points, Mappings, MqttMappings } +public sealed record ConfigurationCsvRequest(string Csv); +public sealed record ConfigurationCsvResult(int Created, int Updated); + +public sealed partial class GatewayStore +{ + private static readonly string[] PointColumns = + ["Id", "Name", "Protocol", "Scope", "ValueType", "Readable", "Writable", "ExternalIdentity", "Address", "BacnetObjectKind", "BacnetObjectInstance"]; + private static readonly string[] MappingColumns = + ["Id", "SourcePointId", "TargetPointId", "Direction", "Enabled", "BacnetPriority", "AcknowledgeMultipleExternalWriters", "Transform"]; + private static readonly string[] MqttMappingColumns = + ["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty"]; + + public string ExportConfigurationCsv(ConfigurationCsvKind kind) + { + IEnumerable records = kind switch + { + ConfigurationCsvKind.Points => ListPoints().Select(point => new object?[] { point.Id, point.DisplayName, + point.Protocol, point.Scope, point.ValueType, point.Readable, point.Writable, point.ExternalIdentity, + point.Address.GetRawText(), point.BacnetObjectKind, point.BacnetObjectInstance }), + ConfigurationCsvKind.Mappings => ListMappings().Select(mapping => new object?[] { mapping.Id, mapping.SourcePointId, + mapping.TargetPointId, mapping.Direction, mapping.Enabled, mapping.BacnetPriority, + mapping.AcknowledgeMultipleExternalWriters, mapping.Transform.GetRawText() }), + _ => ListMqttMappings().Select(mapping => new object?[] { mapping.Id, mapping.PointId, mapping.Format, + mapping.Direction, mapping.QualityOfService, mapping.Retain, mapping.ProjectYear, mapping.ProjectNumber, + mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty }) + }; + var output = new StringBuilder("\uFEFF"); + output.AppendJoin(';', CsvColumns(kind)).Append("\r\n"); + foreach (var record in records) + { + output.AppendJoin(';', record.Select(field => + { + var value = Convert.ToString(field, CultureInfo.InvariantCulture) ?? ""; + if (NeedsCsvEscape(value)) value = "'" + value; + return "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""; + })).Append("\r\n"); + } + return output.ToString(); + } + + public ConfigurationCsvResult ImportConfigurationCsv(ConfigurationCsvKind kind, string csv) + { + if (string.IsNullOrWhiteSpace(csv) || Encoding.UTF8.GetByteCount(csv) > 4 * 1024 * 1024) + throw new DomainValidationException("CSV fehlt oder überschreitet 4 MB."); + + var content = csv.TrimStart('\uFEFF'); + var endOfHeader = content.IndexOfAny(['\r', '\n']); + var header = endOfHeader < 0 ? content : content[..endOfHeader]; + using var parser = new TextFieldParser(new StringReader(content)) + { + HasFieldsEnclosedInQuotes = true, + TrimWhiteSpace = false + }; + parser.SetDelimiters(header.Contains(';') ? ";" : ","); + var columns = CsvColumns(kind); + try + { + if (!(parser.ReadFields() ?? []).Select(value => value.Trim()).SequenceEqual(columns, StringComparer.OrdinalIgnoreCase)) + throw new DomainValidationException("Die CSV-Spalten stimmen mit der exportierten Vorlage nicht überein."); + } + catch (MalformedLineException) { throw new DomainValidationException("Ungültiger CSV-Kopf."); } + + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var existing = kind switch + { + ConfigurationCsvKind.Points => ReadPoints(connection, transaction).Select(point => point.Id).ToHashSet(), + ConfigurationCsvKind.Mappings => ReadMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet(), + _ => ReadMqttMappings(connection, transaction).Select(mapping => mapping.Id).ToHashSet() + }; + var seen = new HashSet(); + 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(fields[2], "Protocol"), + CsvEnum(fields[3], "Scope"), fields[4], CsvBool(fields[5], "Readable"), CsvBool(fields[6], "Writable"), + CsvOptional(fields[7]), JsonSerializer.Deserialize(fields[8]), + CsvOptional(fields[9]) is { } objectKind ? CsvEnum(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(fields[3], "Direction"), CsvBool(fields[4], "Enabled"), + CsvInteger(fields[5], "BacnetPriority"), CsvBool(fields[6], "AcknowledgeMultipleExternalWriters"), + JsonSerializer.Deserialize(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(fields[2], "Format"), + CsvEnum(fields[3], "Direction"), CsvEnum(fields[4], "QualityOfService"), + CsvBool(fields[5], "Retain"), CsvInteger(fields[6], "ProjectYear"), CsvOptional(fields[7]), CsvOptional(fields[8]), + CsvOptional(fields[9]) is { } category ? CsvEnum(category, "SeCategory") : null, + CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12])); + SaveMqttMapping(connection, transaction, update ? id : null, mqtt, update ? null : id); + break; + } + } + + private static string[] CsvColumns(ConfigurationCsvKind kind) => kind switch + { + ConfigurationCsvKind.Points => PointColumns, + ConfigurationCsvKind.Mappings => MappingColumns, + _ => MqttMappingColumns + }; + + private static string? CsvOptional(string text) => string.IsNullOrWhiteSpace(text) ? null : text; + private static Guid CsvGuid(string text, string field) => Guid.TryParse(text, out var value) && value != Guid.Empty + ? value : throw new DomainValidationException($"{field} erwartet eine gültige ID."); + private static int? CsvInteger(string text, string field) => string.IsNullOrWhiteSpace(text) ? null : + int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) + ? value : throw new DomainValidationException($"{field} erwartet eine Ganzzahl."); + private static bool CsvBool(string text, string field) => text.Trim().ToLowerInvariant() switch + { + "true" or "1" => true, + "false" or "0" => false, + _ => throw new DomainValidationException($"{field} erwartet True oder False.") + }; + private static T CsvEnum(string text, string field) where T : struct, Enum => + Enum.TryParse(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 '\'', ..]; +} diff --git a/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs b/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs new file mode 100644 index 0000000..929c7dc --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs @@ -0,0 +1,54 @@ +using System.Globalization; +using Gateway.Api.Domain; +using Microsoft.Data.Sqlite; + +namespace Gateway.Api.Services; + +public sealed partial class GatewayStore +{ + public MqttMappingDefaults GetMqttMappingDefaults() + { + using var connection = _database.OpenConnection(); + var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection).Installation); + var alarms = ReadMqttAlarmPoints(connection); + return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray()); + } + + internal GatewayPoint? GetMqttPoint(Guid id) + { + using var connection = _database.OpenConnection(); + return FindActivePoint(connection, null, id); + } + + internal static bool IsBooleanMqttPoint(GatewayPoint point) => + point.BacnetObjectKind is BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue || + OpcUaPointTypes.Resolve(point.ValueType) == Opc.Ua.BuiltInType.Boolean; + + private static MqttMonitoringSite DefaultMonitoringSite(InstallationIdentity? installation) + { + var project = installation?.ProjectNumber; + var year = project is { Length: >= 7 } && IsProjectNumber(project) && + int.TryParse(project.AsSpan(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out var projectYear) + ? 2000 + projectYear : (int?)null; + return new(year, project, installation is null ? null : $"ISP{installation.IspNumber}"); + } + + private static HashSet 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 alarms) + { + var category = GetMqttPointClassification(point) switch + { + MqttPointClassification.Analog => SeMonitoringCategory.Analog, + MqttPointClassification.Digital => alarms.Contains(point.Id) ? SeMonitoringCategory.Alarms : SeMonitoringCategory.Notify, + _ => (SeMonitoringCategory?)null + }; + var name = new string(point.DisplayName.Select(character => char.IsLetterOrDigit(character) || character is '_' or '-' ? character : '_').ToArray()).Trim('_'); + if (name.EndsWith("_Wert", StringComparison.OrdinalIgnoreCase)) name = name[..^5]; + return new(point.Id, category, name.Length == 0 ? "Punkt" : name); + } + + private static string BuildMonitoringTopic(MqttMonitoringSite site, SeMonitoringCategory category, string name) => + $"Projekte{site.ProjectYear}/{site.ProjectNumber}/{site.IspNumber}/{GetCategorySegment(category)}/{name}_Wert"; +} diff --git a/src/Gateway.Api/Services/GatewayStore.MqttExternalPoints.cs b/src/Gateway.Api/Services/GatewayStore.MqttExternalPoints.cs new file mode 100644 index 0000000..c53697d --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.MqttExternalPoints.cs @@ -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 ListMqttExternalPoints() + { + using var connection = _database.OpenConnection(); + return ReadMqttExternalPoints(connection); + } + + private static List 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(); + 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); + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.OpcUa.cs b/src/Gateway.Api/Services/GatewayStore.OpcUa.cs new file mode 100644 index 0000000..aa139b9 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.OpcUa.cs @@ -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 Points); + +public sealed partial class GatewayStore +{ + public IReadOnlyList 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(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 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(); + 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; + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.PointLifecycle.cs b/src/Gateway.Api/Services/GatewayStore.PointLifecycle.cs new file mode 100644 index 0000000..08ca2de --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.PointLifecycle.cs @@ -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(); + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.Presentation.cs b/src/Gateway.Api/Services/GatewayStore.Presentation.cs new file mode 100644 index 0000000..4a0067d --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.Presentation.cs @@ -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 ListDisplayUnits() + { + using var connection = _database.OpenConnection(); + var json = GetSetting(connection, "presentation.units"); + return json is null ? DefaultUnits : JsonSerializer.Deserialize(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(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 ListPointPresentations() + { + using var connection = _database.OpenConnection(); + var json = GetSetting(connection, "presentation.points"); + return json is null ? [] : JsonSerializer.Deserialize(json, JsonOptions)!; + } + + public void SavePointPresentations(IReadOnlyList 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(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 GetDashboard(Guid userId) + { + using var connection = _database.OpenConnection(); + var json = GetSetting(connection, $"dashboard.{userId}"); + return json is null ? [] : JsonSerializer.Deserialize(json, JsonOptions)!; + } + + public void SaveDashboard(Guid userId, bool isAdministrator, IReadOnlyList 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)); + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.cs b/src/Gateway.Api/Services/GatewayStore.cs index 9638dfb..2f3d019 100644 --- a/src/Gateway.Api/Services/GatewayStore.cs +++ b/src/Gateway.Api/Services/GatewayStore.cs @@ -11,10 +11,20 @@ using Microsoft.Extensions.Options; namespace Gateway.Api.Services; -public sealed class GatewayStore +public sealed partial class GatewayStore { private const string GatewayConfigurationKey = "gateway.configuration"; private const string MqttPasswordKey = "mqtt.password"; + private const string KomariEnrollmentTokenKey = "komari.enrollment-token"; + private const string MailApiKey = "integration.mail.api-key"; + private static readonly char[] MailRecipientSeparators = [';', ',']; + private static readonly Guid BuiltInAdminId = Guid.Empty; + private static readonly IReadOnlyList<(string Name, string Label, IReadOnlyList Permissions, bool IsSystem)> DefaultRoles = + [ + ("viewer", "Betrachter", [GatewayPermissions.ViewDashboard, GatewayPermissions.ViewTrends], true), + ("technician", "Techniker", [GatewayPermissions.ViewDashboard, GatewayPermissions.ViewTrends, GatewayPermissions.EditAliases, GatewayPermissions.ManageSources, GatewayPermissions.ViewDebug, GatewayPermissions.ManageAlarms], true), + ("admin", "Administrator", GatewayPermissions.Catalog, true) + ]; private static readonly JsonSerializerOptions JsonOptions = CreateJsonOptions(); private readonly GatewayDatabase _database; private readonly PasswordService _passwordService; @@ -43,6 +53,7 @@ public sealed class GatewayStore { _database.Initialize(); using var connection = _database.OpenConnection(); + EnsureIdentityStore(connection); var savedConfiguration = GetSetting(connection, GatewayConfigurationKey); if (savedConfiguration is not null) { @@ -78,8 +89,7 @@ public sealed class GatewayStore throw new DomainValidationException("Der Admin-Zugang wurde bereits eingerichtet."); } - var installation = new InstallationIdentity(request.ProjectNumber.Trim().ToUpperInvariant(), request.IspNumber); - ValidateInstallationIdentity(installation); + var installation = NormalizeInstallationIdentity(new InstallationIdentity(request.ProjectNumber, request.IspNumber)); var passwordHash = _passwordService.Create(request.Password); using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); @@ -94,7 +104,8 @@ public sealed class GatewayStore command.Parameters.AddWithValue("$iterations", passwordHash.Iterations); command.Parameters.AddWithValue("$changedAt", DateTimeOffset.UtcNow.ToString("O")); command.ExecuteNonQuery(); - var configuration = ReadGatewayConfiguration(connection) with { Installation = installation }; + UpsertBuiltInAdmin(connection, transaction, passwordHash, DateTimeOffset.UtcNow); + var configuration = ReadGatewayConfiguration(connection, transaction) with { Installation = installation }; SetSetting(connection, GatewayConfigurationKey, JsonSerializer.Serialize(configuration, JsonOptions), transaction); WriteAudit(connection, "auth", "Admin account created and installation identity assigned.", transaction); transaction.Commit(); @@ -119,30 +130,443 @@ public sealed class GatewayStore reader.GetInt32(2)); } - public void ChangeAdminPassword(string currentPassword, string newPassword) + public AuthenticatedGatewayUser? Authenticate(string username, string password) { - if (!VerifyAdminPassword(currentPassword)) + if (string.IsNullOrWhiteSpace(username) || string.IsNullOrEmpty(password)) { - throw new DomainValidationException("Das aktuelle Passwort ist nicht korrekt."); + return null; } - var passwordHash = _passwordService.Create(newPassword); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = """ + SELECT id, username, display_name, email, role_name, active, created_at_utc, updated_at_utc, + password_hash, password_salt, password_iterations + FROM app_users WHERE username = $username COLLATE NOCASE AND active = 1 LIMIT 1; + """; + command.Parameters.AddWithValue("$username", username.Trim()); + using var reader = command.ExecuteReader(); + if (!reader.Read() || !_passwordService.Verify(password, (byte[])reader.GetValue(8), (byte[])reader.GetValue(9), reader.GetInt32(10))) + { + return null; + } + + var user = ReadUser(reader); + reader.Close(); + var role = GetRole(connection, user.Role); + return new AuthenticatedGatewayUser(user, role?.Permissions ?? []); + } + + public AuthenticatedGatewayUser? GetAuthenticatedUser(Guid userId) + { + using var connection = _database.OpenConnection(); + var user = GetUser(connection, userId); + if (user is null || !user.Active) + { + return null; + } + + return new AuthenticatedGatewayUser(user, GetRole(connection, user.Role)?.Permissions ?? []); + } + + public IReadOnlyList ListUsers() + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT id, username, display_name, email, role_name, active, created_at_utc, updated_at_utc FROM app_users ORDER BY username COLLATE NOCASE;"; + using var reader = command.ExecuteReader(); + var users = new List(); + while (reader.Read()) + { + users.Add(ReadUser(reader)); + } + return users; + } + + public GatewayUser CreateUser(CreateUserRequest request) + { + var username = NormalizeUsername(request.Username); + var displayName = NormalizeDisplayName(request.DisplayName); + var email = NormalizeEmail(request.Email); + var role = NormalizeRoleName(request.Role); + var passwordHash = _passwordService.Create(request.Password); + using var connection = _database.OpenConnection(); + if (GetRole(connection, role) is null) + { + throw new DomainValidationException("Die ausgewählte Rolle existiert nicht."); + } + + var now = DateTimeOffset.UtcNow; + var user = new GatewayUser(Guid.NewGuid(), username, displayName, email, role, request.Active, now, now); + try + { + using var command = connection.CreateCommand(); + command.CommandText = """ + INSERT INTO app_users(id, username, display_name, email, password_hash, password_salt, password_iterations, role_name, active, created_at_utc, updated_at_utc) + VALUES($id, $username, $displayName, $email, $hash, $salt, $iterations, $role, $active, $createdAt, $updatedAt); + """; + BindUser(command, user, passwordHash); + command.ExecuteNonQuery(); + WriteAudit(connection, "auth", $"User '{user.Username}' created with role '{user.Role}'."); + return user; + } + catch (SqliteException exception) when (exception.SqliteErrorCode == 19) + { + throw new DomainValidationException("Benutzername oder E-Mail-Adresse wird bereits verwendet."); + } + } + + public GatewayUser UpdateUser(Guid userId, UpdateUserRequest request, Guid actingUserId) + { + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var current = GetUser(connection, userId, transaction) ?? throw new DomainValidationException("Benutzer wurde nicht gefunden."); + var username = request.Username is null ? current.Username : NormalizeUsername(request.Username); + var displayName = request.DisplayName is null ? current.DisplayName : NormalizeDisplayName(request.DisplayName); + var email = request.Email is null ? current.Email : NormalizeEmail(request.Email); + var role = request.Role is null ? current.Role : NormalizeRoleName(request.Role); + var active = request.Active ?? current.Active; + if (GetRole(connection, role, transaction) is null) + { + throw new DomainValidationException("Die ausgewählte Rolle existiert nicht."); + } + if (userId == actingUserId && (!active || !string.Equals(role, current.Role, StringComparison.Ordinal))) + { + throw new DomainValidationException("Das eigene Konto kann nicht deaktiviert oder in eine andere Rolle verschoben werden."); + } + if ((current.Active && current.Role == "admin") && (!active || role != "admin") && CountActiveAdministrators(connection, transaction) <= 1) + { + throw new DomainValidationException("Mindestens ein aktiver Administrator muss erhalten bleiben."); + } + + var nextPassword = request.Password is null ? null : _passwordService.Create(request.Password); + var updated = current with { Username = username, DisplayName = displayName, Email = email, Role = role, Active = active, UpdatedAtUtc = DateTimeOffset.UtcNow }; + try + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = """ + UPDATE app_users SET username = $username, display_name = $displayName, email = $email, + password_hash = COALESCE($hash, password_hash), password_salt = COALESCE($salt, password_salt), + password_iterations = COALESCE($iterations, password_iterations), role_name = $role, active = $active, updated_at_utc = $updatedAt + WHERE id = $id; + """; + command.Parameters.AddWithValue("$id", updated.Id.ToString()); + command.Parameters.AddWithValue("$username", updated.Username); + command.Parameters.AddWithValue("$displayName", updated.DisplayName); + command.Parameters.AddWithValue("$email", (object?)updated.Email ?? DBNull.Value); + command.Parameters.AddWithValue("$hash", (object?)nextPassword?.Hash ?? DBNull.Value); + command.Parameters.AddWithValue("$salt", (object?)nextPassword?.Salt ?? DBNull.Value); + command.Parameters.AddWithValue("$iterations", (object?)nextPassword?.Iterations ?? DBNull.Value); + command.Parameters.AddWithValue("$role", updated.Role); + command.Parameters.AddWithValue("$active", updated.Active ? 1 : 0); + command.Parameters.AddWithValue("$updatedAt", updated.UpdatedAtUtc.ToString("O")); + command.ExecuteNonQuery(); + if (updated.Id == BuiltInAdminId && nextPassword is not null) + { + UpdateLegacyAdminPassword(connection, transaction, nextPassword, updated.UpdatedAtUtc); + } + WriteAudit(connection, "auth", $"User '{updated.Username}' updated.", transaction); + transaction.Commit(); + return updated; + } + catch (SqliteException exception) when (exception.SqliteErrorCode == 19) + { + throw new DomainValidationException("Benutzername oder E-Mail-Adresse wird bereits verwendet."); + } + } + + public void ChangeUserPassword(Guid userId, string currentPassword, string newPassword) + { using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); using var command = connection.CreateCommand(); command.Transaction = transaction; + command.CommandText = "SELECT password_hash, password_salt, password_iterations FROM app_users WHERE id = $id AND active = 1;"; + command.Parameters.AddWithValue("$id", userId.ToString()); + using var reader = command.ExecuteReader(); + if (!reader.Read() || !_passwordService.Verify(currentPassword, (byte[])reader.GetValue(0), (byte[])reader.GetValue(1), reader.GetInt32(2))) + { + throw new DomainValidationException("Das aktuelle Passwort ist nicht korrekt."); + } + reader.Close(); + var next = _passwordService.Create(newPassword); + var now = DateTimeOffset.UtcNow; + using var update = connection.CreateCommand(); + update.Transaction = transaction; + update.CommandText = "UPDATE app_users SET password_hash = $hash, password_salt = $salt, password_iterations = $iterations, updated_at_utc = $updatedAt WHERE id = $id;"; + update.Parameters.AddWithValue("$id", userId.ToString()); + update.Parameters.AddWithValue("$hash", next.Hash); + update.Parameters.AddWithValue("$salt", next.Salt); + update.Parameters.AddWithValue("$iterations", next.Iterations); + update.Parameters.AddWithValue("$updatedAt", now.ToString("O")); + update.ExecuteNonQuery(); + if (userId == BuiltInAdminId) + { + UpdateLegacyAdminPassword(connection, transaction, next, now); + } + WriteAudit(connection, "auth", "User password changed.", transaction); + transaction.Commit(); + } + + public IReadOnlyList ListRoles() + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT name, label, permissions_json, is_system, updated_at_utc FROM app_roles ORDER BY is_system DESC, name COLLATE NOCASE;"; + using var reader = command.ExecuteReader(); + var roles = new List(); + while (reader.Read()) + { + roles.Add(ReadRole(reader)); + } + return roles; + } + + public GatewayRole SaveRole(SaveRoleRequest request) + { + var name = NormalizeRoleName(request.Name); + if (name == "admin" || name == "technician" || name == "viewer") + { + throw new DomainValidationException("Systemrollen können nicht geändert werden."); + } + var label = NormalizeDisplayName(request.Label); + var permissions = request.Permissions.Distinct(StringComparer.Ordinal).OrderBy(permission => permission, StringComparer.Ordinal).ToArray(); + if (permissions.Any(permission => !GatewayPermissions.Catalog.Contains(permission, StringComparer.Ordinal))) + { + throw new DomainValidationException("Die Rolle enthält eine unbekannte Berechtigung."); + } + + var role = new GatewayRole(name, label, permissions, false, DateTimeOffset.UtcNow); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); command.CommandText = """ - UPDATE admin_account - SET password_hash = $hash, password_salt = $salt, password_iterations = $iterations, changed_at_utc = $changedAt - WHERE id = 1; + INSERT INTO app_roles(name, label, permissions_json, is_system, updated_at_utc) + VALUES($name, $label, $permissions, 0, $updatedAt) + ON CONFLICT(name) DO UPDATE SET label = excluded.label, permissions_json = excluded.permissions_json, updated_at_utc = excluded.updated_at_utc; """; + command.Parameters.AddWithValue("$name", role.Name); + command.Parameters.AddWithValue("$label", role.Label); + command.Parameters.AddWithValue("$permissions", JsonSerializer.Serialize(role.Permissions, JsonOptions)); + command.Parameters.AddWithValue("$updatedAt", role.UpdatedAtUtc.ToString("O")); + command.ExecuteNonQuery(); + WriteAudit(connection, "auth", $"Role '{role.Name}' saved."); + return role; + } + + public void ChangeAdminPassword(string currentPassword, string newPassword) + { + ChangeUserPassword(BuiltInAdminId, currentPassword, newPassword); + } + + public GatewayUserPreferences GetUserPreferences(Guid userId) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT theme, csv_delimiter, sidebar_pinned, trend_line_width, updated_at_utc FROM app_user_preferences WHERE user_id = $userId;"; + command.Parameters.AddWithValue("$userId", userId.ToString()); + using var reader = command.ExecuteReader(); + return reader.Read() + ? new GatewayUserPreferences(reader.GetString(0), reader.GetString(1), reader.GetInt64(2) == 1, Convert.ToDecimal(reader.GetDouble(3), CultureInfo.InvariantCulture), ParseTimestamp(reader.GetString(4))) + : new GatewayUserPreferences("dark", ";", true, 1.8m, DateTimeOffset.MinValue); + } + + public GatewayUserPreferences UpdateUserPreferences(Guid userId, UpdateUserPreferencesRequest request) + { + var current = GetUserPreferences(userId); + var theme = request.Theme?.Trim().ToLowerInvariant() ?? current.Theme; + if (theme is not ("system" or "light" or "dark")) + { + throw new DomainValidationException("Das Farbschema muss System, Hell oder Dunkel sein."); + } + + var delimiter = request.CsvDelimiter ?? current.CsvDelimiter; + if (delimiter is not (";" or "," or "\t")) + { + throw new DomainValidationException("Als CSV-Trennzeichen sind Semikolon, Komma oder Tabulator zulässig."); + } + + var lineWidth = request.TrendLineWidth ?? current.TrendLineWidth; + if (lineWidth is < 0.5m or > 8m) + { + throw new DomainValidationException("Die Linienbreite muss zwischen 0,5 und 8 liegen."); + } + + var result = new GatewayUserPreferences(theme, delimiter, request.SidebarPinned ?? current.SidebarPinned, lineWidth, DateTimeOffset.UtcNow); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = """ + INSERT INTO app_user_preferences(user_id, theme, csv_delimiter, sidebar_pinned, trend_line_width, updated_at_utc) + VALUES($userId, $theme, $delimiter, $pinned, $lineWidth, $updatedAt) + ON CONFLICT(user_id) DO UPDATE SET + theme = excluded.theme, csv_delimiter = excluded.csv_delimiter, sidebar_pinned = excluded.sidebar_pinned, + trend_line_width = excluded.trend_line_width, updated_at_utc = excluded.updated_at_utc; + """; + command.Parameters.AddWithValue("$userId", userId.ToString()); + command.Parameters.AddWithValue("$theme", result.Theme); + command.Parameters.AddWithValue("$delimiter", result.CsvDelimiter); + command.Parameters.AddWithValue("$pinned", result.SidebarPinned ? 1 : 0); + command.Parameters.AddWithValue("$lineWidth", Convert.ToDouble(result.TrendLineWidth, CultureInfo.InvariantCulture)); + command.Parameters.AddWithValue("$updatedAt", result.UpdatedAtUtc.ToString("O")); + command.ExecuteNonQuery(); + return result; + } + + private static string NormalizeUsername(string? value) + { + var username = value?.Trim().ToLowerInvariant() ?? string.Empty; + if (username.Length is < 3 or > 80 || !username.All(character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.')) + { + throw new DomainValidationException("Der Benutzername muss 3 bis 80 Zeichen lang sein und darf nur Buchstaben, Ziffern, Punkt, Bindestrich und Unterstrich enthalten."); + } + return username; + } + + private static string NormalizeDisplayName(string? value) + { + var name = value?.Trim() ?? string.Empty; + if (name.Length is < 1 or > 120) + { + throw new DomainValidationException("Der Anzeigename muss zwischen 1 und 120 Zeichen lang sein."); + } + return name; + } + + private static string? NormalizeEmail(string? value) + { + var email = string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + if (email is not null && (email.Length > 160 || !email.Contains('@', StringComparison.Ordinal))) + { + throw new DomainValidationException("Die E-Mail-Adresse ist ungültig."); + } + return email; + } + + private static string NormalizeRoleName(string? value) + { + var name = value?.Trim().ToLowerInvariant() ?? string.Empty; + if (name.Length is < 3 or > 80 || !name.All(character => char.IsLetterOrDigit(character) || character is '-' or '_')) + { + throw new DomainValidationException("Der Rollenname muss 3 bis 80 Zeichen lang sein und darf nur Buchstaben, Ziffern, Bindestrich und Unterstrich enthalten."); + } + return name; + } + + private static void EnsureIdentityStore(SqliteConnection connection) + { + using var transaction = connection.BeginTransaction(); + var now = DateTimeOffset.UtcNow; + foreach (var seed in DefaultRoles) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "INSERT OR IGNORE INTO app_roles(name, label, permissions_json, is_system, updated_at_utc) VALUES($name, $label, $permissions, 1, $updatedAt);"; + command.Parameters.AddWithValue("$name", seed.Name); + command.Parameters.AddWithValue("$label", seed.Label); + command.Parameters.AddWithValue("$permissions", JsonSerializer.Serialize(seed.Permissions, JsonOptions)); + command.Parameters.AddWithValue("$updatedAt", now.ToString("O")); + command.ExecuteNonQuery(); + } + + using var legacy = connection.CreateCommand(); + legacy.Transaction = transaction; + legacy.CommandText = "SELECT password_hash, password_salt, password_iterations, changed_at_utc FROM admin_account WHERE id = 1;"; + using var reader = legacy.ExecuteReader(); + if (reader.Read()) + { + var passwordHash = new PasswordHash((byte[])reader.GetValue(0), (byte[])reader.GetValue(1), reader.GetInt32(2)); + var changedAt = ParseTimestamp(reader.GetString(3)); + reader.Close(); + UpsertBuiltInAdmin(connection, transaction, passwordHash, changedAt); + } + else + { + reader.Close(); + } + transaction.Commit(); + } + + private static void UpsertBuiltInAdmin(SqliteConnection connection, SqliteTransaction transaction, PasswordHash passwordHash, DateTimeOffset changedAt) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = """ + INSERT INTO app_users(id, username, display_name, email, password_hash, password_salt, password_iterations, role_name, active, created_at_utc, updated_at_utc) + VALUES($id, 'admin', 'Administrator', NULL, $hash, $salt, $iterations, 'admin', 1, $createdAt, $updatedAt) + ON CONFLICT(id) DO NOTHING; + """; + command.Parameters.AddWithValue("$id", BuiltInAdminId.ToString()); command.Parameters.AddWithValue("$hash", passwordHash.Hash); command.Parameters.AddWithValue("$salt", passwordHash.Salt); command.Parameters.AddWithValue("$iterations", passwordHash.Iterations); - command.Parameters.AddWithValue("$changedAt", DateTimeOffset.UtcNow.ToString("O")); + command.Parameters.AddWithValue("$createdAt", changedAt.ToString("O")); + command.Parameters.AddWithValue("$updatedAt", changedAt.ToString("O")); command.ExecuteNonQuery(); - WriteAudit(connection, "auth", "Admin password changed.", transaction); - transaction.Commit(); + } + + private static void UpdateLegacyAdminPassword(SqliteConnection connection, SqliteTransaction transaction, PasswordHash passwordHash, DateTimeOffset changedAt) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "UPDATE admin_account SET password_hash = $hash, password_salt = $salt, password_iterations = $iterations, changed_at_utc = $changedAt WHERE id = 1;"; + command.Parameters.AddWithValue("$hash", passwordHash.Hash); + command.Parameters.AddWithValue("$salt", passwordHash.Salt); + command.Parameters.AddWithValue("$iterations", passwordHash.Iterations); + command.Parameters.AddWithValue("$changedAt", changedAt.ToString("O")); + command.ExecuteNonQuery(); + } + + private static void BindUser(SqliteCommand command, GatewayUser user, PasswordHash passwordHash) + { + command.Parameters.AddWithValue("$id", user.Id.ToString()); + command.Parameters.AddWithValue("$username", user.Username); + command.Parameters.AddWithValue("$displayName", user.DisplayName); + command.Parameters.AddWithValue("$email", (object?)user.Email ?? DBNull.Value); + command.Parameters.AddWithValue("$hash", passwordHash.Hash); + command.Parameters.AddWithValue("$salt", passwordHash.Salt); + command.Parameters.AddWithValue("$iterations", passwordHash.Iterations); + command.Parameters.AddWithValue("$role", user.Role); + command.Parameters.AddWithValue("$active", user.Active ? 1 : 0); + command.Parameters.AddWithValue("$createdAt", user.CreatedAtUtc.ToString("O")); + command.Parameters.AddWithValue("$updatedAt", user.UpdatedAtUtc.ToString("O")); + } + + private static GatewayUser? GetUser(SqliteConnection connection, Guid userId, SqliteTransaction? transaction = null) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "SELECT id, username, display_name, email, role_name, active, created_at_utc, updated_at_utc FROM app_users WHERE id = $id;"; + command.Parameters.AddWithValue("$id", userId.ToString()); + using var reader = command.ExecuteReader(); + return reader.Read() ? ReadUser(reader) : null; + } + + private static GatewayUser ReadUser(SqliteDataReader reader) => new( + Guid.Parse(reader.GetString(0)), reader.GetString(1), reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetString(3), + reader.GetString(4), reader.GetInt64(5) == 1, ParseTimestamp(reader.GetString(6)), ParseTimestamp(reader.GetString(7))); + + private static GatewayRole? GetRole(SqliteConnection connection, string roleName, SqliteTransaction? transaction = null) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "SELECT name, label, permissions_json, is_system, updated_at_utc FROM app_roles WHERE name = $name;"; + command.Parameters.AddWithValue("$name", roleName); + using var reader = command.ExecuteReader(); + return reader.Read() ? ReadRole(reader) : null; + } + + private static GatewayRole ReadRole(SqliteDataReader reader) + { + var permissions = JsonSerializer.Deserialize(reader.GetString(2), JsonOptions) ?? []; + return new GatewayRole(reader.GetString(0), reader.GetString(1), permissions, reader.GetInt64(3) == 1, ParseTimestamp(reader.GetString(4))); + } + + private static int CountActiveAdministrators(SqliteConnection connection, SqliteTransaction transaction) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "SELECT COUNT(*) FROM app_users WHERE role_name = 'admin' AND active = 1;"; + return Convert.ToInt32(command.ExecuteScalar(), CultureInfo.InvariantCulture); } public GatewayConfiguration GetGatewayConfiguration() @@ -156,19 +580,96 @@ public sealed class GatewayStore public void UpdateGatewayConfiguration(GatewayConfiguration configuration) { - var savedConfiguration = GetGatewayConfiguration(); + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var savedConfiguration = ReadGatewayConfiguration(connection, transaction); configuration = configuration.Mqtt is null ? configuration with { Mqtt = MqttConfiguration.CreateDefault() } : configuration; configuration = configuration with { Installation = savedConfiguration.Installation }; ValidateGatewayConfiguration(configuration); - using var connection = _database.OpenConnection(); - using var transaction = connection.BeginTransaction(); SetSetting(connection, GatewayConfigurationKey, JsonSerializer.Serialize(configuration, JsonOptions), transaction); WriteAudit(connection, "configuration", "Gateway configuration updated.", transaction); transaction.Commit(); } + private readonly object _installationGate = new(); + + public InstallationIdentity UpdateInstallationIdentity(InstallationIdentity request) + { + var installation = NormalizeInstallationIdentity(request); + lock (_installationGate) + { + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var configuration = ReadGatewayConfiguration(connection, transaction); + if (configuration.Installation != installation) + { + SetSetting(connection, GatewayConfigurationKey, JsonSerializer.Serialize(configuration with { Installation = installation }, JsonOptions), transaction); + WriteAudit(connection, "configuration", $"Installation identity set to '{installation.HostName}'.", transaction); + } + transaction.Commit(); + try { WriteHostProvisioningRequest(installation); } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new DomainValidationException("Projekt und ISP wurden gespeichert. Die Anforderung für den Rechnernamen konnte nicht geschrieben werden."); + } + } + return installation; + } + + private static InstallationIdentity NormalizeInstallationIdentity(InstallationIdentity identity) + { + var normalized = identity with { ProjectNumber = identity.ProjectNumber?.Trim().ToUpperInvariant() ?? string.Empty }; + ValidateInstallationIdentity(normalized); + return normalized; + } + + public bool HasKomariEnrollmentToken() + { + using var connection = _database.OpenConnection(); + return GetSetting(connection, KomariEnrollmentTokenKey) is not null; + } + + /// Stores the one-time token encrypted at rest and signals the root-owned bootstrap path. + public void UpdateKomariEnrollmentToken(string enrollmentToken) + { + var token = enrollmentToken?.Trim() ?? string.Empty; + if (token.Length is < 8 or > 1024 || token.Any(char.IsWhiteSpace)) + { + throw new DomainValidationException("Der Komari-Token muss 8 bis 1024 Zeichen lang sein und darf keine Leerzeichen enthalten."); + } + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + SetSetting(connection, KomariEnrollmentTokenKey, _secretProtector.Protect(token), transaction); + WriteAudit(connection, "komari", "Komari enrollment token replaced.", transaction); + transaction.Commit(); + WriteKomariTokenRequest(); + } + + /// Called by a root NixOS unit; only writes a transient runtime credential. + public bool MaterializeKomariEnrollmentToken(string targetPath) + { + using var connection = _database.OpenConnection(); + var encrypted = GetSetting(connection, KomariEnrollmentTokenKey); + if (encrypted is null) + { + return false; + } + var directory = Path.GetDirectoryName(Path.GetFullPath(targetPath)) ?? throw new ArgumentException("Ungültiger Zielpfad.", nameof(targetPath)); + Directory.CreateDirectory(directory); + var temporaryPath = targetPath + ".tmp"; + File.WriteAllText(temporaryPath, _secretProtector.Unprotect(encrypted)); + File.Move(temporaryPath, targetPath, overwrite: true); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(targetPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + return true; + } + + public void ImportKomariEnrollmentTokenFile(string sourcePath) => UpdateKomariEnrollmentToken(File.ReadAllText(sourcePath).Trim()); + public MqttConfigurationView GetMqttConfiguration() { using var connection = _database.OpenConnection(); @@ -208,7 +709,13 @@ public sealed class GatewayStore public IReadOnlyList ListMqttMappings() { using var connection = _database.OpenConnection(); + return ReadMqttMappings(connection); + } + + private static List ReadMqttMappings(SqliteConnection connection, SqliteTransaction? transaction = null) + { using var command = connection.CreateCommand(); + command.Transaction = transaction; command.CommandText = """ SELECT id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc FROM mqtt_mappings @@ -224,13 +731,31 @@ public sealed class GatewayStore return mappings; } - public MqttMapping CreateMqttMapping(CreateMqttMappingRequest request) + public MqttMapping CreateMqttMapping(CreateMqttMappingRequest request) => SaveMqttMapping(null, request)!; + + public MqttMapping? UpdateMqttMapping(Guid id, CreateMqttMappingRequest request) => SaveMqttMapping(id, request); + + private MqttMapping? SaveMqttMapping(Guid? id, CreateMqttMappingRequest request) { - var point = ListPoints().SingleOrDefault(candidate => candidate.Id == request.PointId) + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var saved = SaveMqttMapping(connection, transaction, id, request); + transaction.Commit(); + return saved; + } + + private static MqttMapping? SaveMqttMapping(SqliteConnection connection, SqliteTransaction transaction, Guid? id, + CreateMqttMappingRequest request, Guid? newId = null) + { + var mappings = ReadMqttMappings(connection, transaction); + var existing = id.HasValue ? mappings.FirstOrDefault(mapping => mapping.Id == id.Value) : null; + if (id.HasValue && existing is null) return null; + + var point = FindActivePoint(connection, transaction, request.PointId) ?? throw new DomainValidationException("Der MQTT-Quellpunkt existiert nicht."); ValidateMqttMappingRequest(request, point); var mapping = new MqttMapping( - Guid.NewGuid(), + existing?.Id ?? newId ?? Guid.NewGuid(), request.PointId, request.Format, request.Direction, @@ -243,17 +768,27 @@ public sealed class GatewayStore NormalizeNullable(request.TopicName), NormalizeNullable(request.JsonTopic), NormalizeNullable(request.JsonProperty), - DateTimeOffset.UtcNow); + existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow); + + var topic = GetMqttTopic(mapping); + if (mappings.Any(other => other.Id != mapping.Id && GetMqttTopic(other) == topic && + (mapping.Format == MqttMappingFormat.SingleTopic || other.Format == MqttMappingFormat.SingleTopic || + other.PointId == mapping.PointId && other.Format == mapping.Format && + (mapping.Format != MqttMappingFormat.Json || other.JsonProperty == mapping.JsonProperty)))) + throw new DomainValidationException("Dieses MQTT-Topic ist bereits für eine kollidierende Zuordnung belegt."); - using var connection = _database.OpenConnection(); - using var transaction = connection.BeginTransaction(); try { using var command = connection.CreateCommand(); command.Transaction = transaction; - command.CommandText = """ + command.CommandText = existing is null ? """ INSERT INTO mqtt_mappings(id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc) VALUES($id, $pointId, $format, $direction, $qualityOfService, $retain, $projectYear, $projectNumber, $ispNumber, $category, $topicName, $jsonTopic, $jsonProperty, $createdAt); + """ : """ + UPDATE mqtt_mappings SET point_id=$pointId, format=$format, direction=$direction, + quality_of_service=$qualityOfService, retain=$retain, project_year=$projectYear, + project_number=$projectNumber, isp_number=$ispNumber, se_category=$category, + topic_name=$topicName, json_topic=$jsonTopic, json_property=$jsonProperty WHERE id=$id; """; command.Parameters.AddWithValue("$id", mapping.Id.ToString()); command.Parameters.AddWithValue("$pointId", mapping.PointId.ToString()); @@ -268,10 +803,9 @@ public sealed class GatewayStore command.Parameters.AddWithValue("$topicName", (object?)mapping.TopicName ?? DBNull.Value); command.Parameters.AddWithValue("$jsonTopic", (object?)mapping.JsonTopic ?? DBNull.Value); command.Parameters.AddWithValue("$jsonProperty", (object?)mapping.JsonProperty ?? DBNull.Value); - command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O")); + if (existing is null) command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O")); command.ExecuteNonQuery(); - WriteAudit(connection, "mqtt", $"MQTT mapping '{GetMqttTopic(mapping)}' created for point '{point.DisplayName}'.", transaction); - transaction.Commit(); + WriteAudit(connection, "mqtt", $"MQTT mapping '{topic}' {(existing is null ? "created" : "updated")} for point '{point.DisplayName}'.", transaction); return mapping; } catch (SqliteException exception) when (exception.SqliteErrorCode == 19) @@ -282,16 +816,22 @@ public sealed class GatewayStore public static string GetMqttTopic(MqttMapping mapping) => mapping.Format switch { - MqttMappingFormat.SeMonitoring => $"Projekte{mapping.ProjectYear}/{mapping.ProjectNumber}/{mapping.IspNumber}/{GetCategorySegment(mapping.SeCategory!.Value)}/{mapping.TopicName}_Wert", - MqttMappingFormat.Json => mapping.JsonTopic ?? throw new InvalidOperationException("The JSON MQTT topic is missing."), + MqttMappingFormat.SeMonitoring => BuildMonitoringTopic(new MqttMonitoringSite(mapping.ProjectYear, mapping.ProjectNumber, mapping.IspNumber), mapping.SeCategory!.Value, mapping.TopicName!), + MqttMappingFormat.Json or MqttMappingFormat.SingleTopic => mapping.JsonTopic ?? throw new InvalidOperationException("The MQTT topic is missing."), _ => throw new InvalidOperationException("Unknown MQTT mapping format.") }; public IReadOnlyList ListPoints() { using var connection = _database.OpenConnection(); + return ReadPoints(connection); + } + + private static List ReadPoints(SqliteConnection connection, SqliteTransaction? transaction = null) + { using var command = connection.CreateCommand(); - command.CommandText = "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 ORDER BY display_name COLLATE NOCASE;"; + command.Transaction = transaction; + command.CommandText = PointSelect + " WHERE deleted_at_utc IS NULL ORDER BY display_name COLLATE NOCASE;"; using var reader = command.ExecuteReader(); var points = new List(); while (reader.Read()) @@ -304,28 +844,17 @@ public sealed class GatewayStore public GatewayPoint CreatePoint(CreatePointRequest request) { - ValidatePointRequest(request); - var bacnetObjectInstance = request.BacnetObjectKind is null - ? null - : request.Scope == PointScope.Gateway - ? request.BacnetObjectInstance ?? GetNextBacnetObjectInstance(request.BacnetObjectKind.Value) - : request.BacnetObjectInstance; - var point = new GatewayPoint( - Guid.NewGuid(), - request.DisplayName.Trim(), - request.Protocol, - request.Scope, - request.ValueType.Trim(), - request.Readable, - request.Writable, - NormalizeNullable(request.ExternalIdentity), - request.Address.Clone(), - DateTimeOffset.UtcNow, - request.BacnetObjectKind, - bacnetObjectInstance); - using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); + var saved = InsertPoint(connection, transaction, request); + transaction.Commit(); + return saved; + } + + private static GatewayPoint InsertPoint(SqliteConnection connection, SqliteTransaction transaction, CreatePointRequest request, Guid? newId = null) + { + var point = PreparePoint(connection, transaction, request, null); + if (newId.HasValue) point = point with { Id = newId.Value }; try { using var command = connection.CreateCommand(); @@ -334,28 +863,15 @@ public sealed class GatewayStore INSERT INTO points(id, display_name, protocol, scope, value_type, readable, writable, external_identity, address_json, created_at_utc, bacnet_object_kind, bacnet_object_instance) VALUES($id, $displayName, $protocol, $scope, $valueType, $readable, $writable, $externalIdentity, $address, $createdAt, $bacnetObjectKind, $bacnetObjectInstance); """; - 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()); + BindPoint(command, point); command.Parameters.AddWithValue("$createdAt", point.CreatedAtUtc.ToString("O")); - command.Parameters.AddWithValue("$bacnetObjectKind", point.BacnetObjectKind is null ? DBNull.Value : point.BacnetObjectKind.ToString()); - command.Parameters.AddWithValue("$bacnetObjectInstance", point.BacnetObjectInstance is null ? DBNull.Value : point.BacnetObjectInstance); command.ExecuteNonQuery(); WriteAudit(connection, "point", $"Point '{point.DisplayName}' created.", transaction); - transaction.Commit(); return point; } catch (SqliteException exception) when (exception.SqliteErrorCode == 19) { - throw new DomainValidationException(point.Scope == PointScope.Gateway && point.BacnetObjectKind is not null - ? "BACnet-Objekttyp und -instanz sind bereits vergeben." - : "Die externe Punktadresse existiert bereits."); + throw PointIdentityConflict(point); } } @@ -365,20 +881,48 @@ public sealed class GatewayStore JsonElement value, PointProtocol sourceProtocol, DateTimeOffset timestampUtc, - string? status = null) + string? status = null, + Guid? originPointId = null, + int? bacnetPriority = null, + GatewayPoint? expectedDefinition = null, + PointMapping? expectedMapping = null) { if (value.ValueKind is JsonValueKind.Undefined) { throw new DomainValidationException("Ein Datenpunktwert darf nicht undefiniert sein."); } - if (ListPoints().All(point => point.Id != pointId)) + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var point = FindActivePoint(connection, transaction, pointId); + if (point is null) { throw new DomainValidationException("Der Datenpunkt existiert nicht."); } + if (expectedDefinition is not null && !MatchesPointDefinition(point, expectedDefinition)) + throw new DomainValidationException("Die Definition des Datenpunkts wurde geändert."); + if (expectedMapping is not null && !IsCurrentMapping(connection, transaction, expectedMapping)) + throw new DomainValidationException("Das Mapping wurde geändert oder gelöscht."); - var pointValue = new PointValue(pointId, value.Clone(), sourceProtocol, timestampUtc, NormalizeNullable(status)); - using var connection = _database.OpenConnection(); - using var transaction = connection.BeginTransaction(); + var pointValue = new PointValue(pointId, value.Clone(), sourceProtocol, timestampUtc, NormalizeNullable(status), originPointId ?? pointId); + // A BACnet command is not the effective Present_Value. The native priority + // array decides it; only its observation may enter mappings and trends. + if (point.Protocol == PointProtocol.Bacnet && point.Scope == PointScope.Gateway && + (sourceProtocol != PointProtocol.Bacnet || originPointId is not null && originPointId != pointId)) + { + EnqueueBacnetCommand(connection, transaction, point, pointValue, bacnetPriority ?? 16); + transaction.Commit(); + return pointValue; + } + WritePointValue(connection, transaction, pointValue); + EvaluateAlarms(connection, transaction, pointValue); + transaction.Commit(); + RecordPointObservation(pointId, pointValue.Value, sourceProtocol, pointValue.Status, timestampUtc); + PointValueUpdated?.Invoke(this, pointValue); + return pointValue; + } + + private static void WritePointValue(SqliteConnection connection, SqliteTransaction transaction, PointValue pointValue) + { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ @@ -396,10 +940,6 @@ public sealed class GatewayStore command.Parameters.AddWithValue("$updatedAt", pointValue.UpdatedAtUtc.ToString("O")); command.Parameters.AddWithValue("$status", (object?)pointValue.Status ?? DBNull.Value); command.ExecuteNonQuery(); - transaction.Commit(); - RecordPointObservation(pointId, pointValue.Value, sourceProtocol, pointValue.Status, timestampUtc); - PointValueUpdated?.Invoke(this, pointValue); - return pointValue; } public IReadOnlyList ListPointValues() @@ -425,7 +965,13 @@ public sealed class GatewayStore public IReadOnlyList ListMappings() { using var connection = _database.OpenConnection(); + return ReadMappings(connection); + } + + private static List ReadMappings(SqliteConnection connection, SqliteTransaction? transaction = null) + { using var command = connection.CreateCommand(); + command.Transaction = transaction; command.CommandText = "SELECT id, source_point_id, target_point_id, direction, enabled, bacnet_priority, acknowledge_multiple_external_writers, transform_json, created_at_utc FROM mappings ORDER BY created_at_utc;"; using var reader = command.ExecuteReader(); var mappings = new List(); @@ -441,7 +987,7 @@ public sealed class GatewayStore { using var connection = _database.OpenConnection(); using var command = connection.CreateCommand(); - command.CommandText = "SELECT id, source_point_id, name, bacnet_object_instance, interval_seconds, max_records, enabled, created_at_utc FROM trend_logs ORDER BY name COLLATE NOCASE;"; + command.CommandText = "SELECT id, source_point_id, name, bacnet_object_instance, interval_seconds, max_records, enabled, public_access, created_at_utc FROM trend_logs ORDER BY name COLLATE NOCASE;"; using var reader = command.ExecuteReader(); var trendLogs = new List(); while (reader.Read()) @@ -452,6 +998,11 @@ public sealed class GatewayStore return trendLogs; } + /// Only logs explicitly enabled by an administrator are exposed without authentication. + public IReadOnlyList ListPublicTrendLogs() => ListTrendLogs().Where(log => log.IsPublic).ToArray(); + + public bool IsPublicTrendLog(Guid trendLogId) => ListTrendLogs().Any(log => log.Id == trendLogId && log.IsPublic); + public GatewayTrendLog CreateTrendLog(CreateTrendLogRequest request) { var sourcePoint = ListPoints().SingleOrDefault(point => point.Id == request.SourcePointId) @@ -485,6 +1036,7 @@ public sealed class GatewayStore request.IntervalSeconds, request.MaxRecords, request.Enabled, + request.IsPublic, DateTimeOffset.UtcNow); using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); @@ -493,9 +1045,11 @@ public sealed class GatewayStore using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ - INSERT INTO trend_logs(id, source_point_id, name, bacnet_object_instance, interval_seconds, max_records, enabled, created_at_utc) - VALUES($id, $sourcePointId, $name, $instance, $interval, $maxRecords, $enabled, $createdAt); + INSERT INTO trend_logs(id, source_point_id, name, bacnet_object_instance, interval_seconds, max_records, enabled, public_access, created_at_utc) + VALUES($id, $sourcePointId, $name, $instance, $interval, $maxRecords, $enabled, $publicAccess, $createdAt); """; + if (FindActivePoint(connection, transaction, trendLog.SourcePointId) is not { Readable: true }) + throw new DomainValidationException("Der Quellpunkt ist nicht mehr lesbar."); command.Parameters.AddWithValue("$id", trendLog.Id.ToString()); command.Parameters.AddWithValue("$sourcePointId", trendLog.SourcePointId.ToString()); command.Parameters.AddWithValue("$name", trendLog.Name); @@ -503,6 +1057,7 @@ public sealed class GatewayStore command.Parameters.AddWithValue("$interval", trendLog.IntervalSeconds); command.Parameters.AddWithValue("$maxRecords", trendLog.MaxRecords); command.Parameters.AddWithValue("$enabled", trendLog.Enabled ? 1 : 0); + command.Parameters.AddWithValue("$publicAccess", trendLog.IsPublic ? 1 : 0); command.Parameters.AddWithValue("$createdAt", trendLog.CreatedAtUtc.ToString("O")); command.ExecuteNonQuery(); WriteAudit(connection, "trend", $"Trend Log '{trendLog.Name}' created for point '{sourcePoint.DisplayName}'.", transaction); @@ -552,6 +1107,11 @@ public sealed class GatewayStore { using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); + using var active = connection.CreateCommand(); + active.Transaction = transaction; + active.CommandText = "SELECT enabled FROM trend_logs WHERE id=$id;"; + active.Parameters.AddWithValue("$id", trendLog.Id.ToString()); + if (active.ExecuteScalar() is not 1L) continue; var lastTimestamp = GetLastTrendTimestamp(connection, trendLog.Id, transaction); if (lastTimestamp is not null && timestampUtc - lastTimestamp < TimeSpan.FromSeconds(trendLog.IntervalSeconds)) { @@ -599,29 +1159,256 @@ public sealed class GatewayStore return records; } - public CreateMappingResponse CreateMapping(CreateMappingRequest request) + public IReadOnlyList ListTrendSelections(Guid userId, bool isAdministrator) { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = isAdministrator + ? "SELECT id, name, description, owner_id, shared, trend_log_ids_json, created_at_utc, updated_at_utc FROM trend_selections ORDER BY name COLLATE NOCASE;" + : "SELECT id, name, description, owner_id, shared, trend_log_ids_json, created_at_utc, updated_at_utc FROM trend_selections WHERE shared = 1 OR owner_id = $userId ORDER BY name COLLATE NOCASE;"; + if (!isAdministrator) command.Parameters.AddWithValue("$userId", userId.ToString()); + using var reader = command.ExecuteReader(); + var selections = new List(); + while (reader.Read()) selections.Add(ReadTrendSelection(reader)); + return selections; + } + + public GatewayTrendSelection? GetTrendSelection(Guid selectionId) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT id, name, description, owner_id, shared, trend_log_ids_json, created_at_utc, updated_at_utc FROM trend_selections WHERE id = $id;"; + command.Parameters.AddWithValue("$id", selectionId.ToString()); + using var reader = command.ExecuteReader(); + return reader.Read() ? ReadTrendSelection(reader) : null; + } + + public GatewayTrendSelection CreateTrendSelection(CreateTrendSelectionRequest request, Guid ownerId) + { + var selection = BuildTrendSelection(Guid.NewGuid(), request.Name, request.Description, ownerId, request.Shared, request.TrendLogIds, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = """ + INSERT INTO trend_selections(id, name, description, owner_id, shared, trend_log_ids_json, created_at_utc, updated_at_utc) + VALUES($id, $name, $description, $ownerId, $shared, $trendLogs, $createdAt, $updatedAt); + """; + BindTrendSelection(command, selection); + command.ExecuteNonQuery(); + WriteAudit(connection, "trend", $"Trend selection '{selection.Name}' created."); + return selection; + } + + public GatewayTrendSelection UpdateTrendSelection(Guid selectionId, UpdateTrendSelectionRequest request, Guid actingUserId, bool isAdministrator) + { + var current = GetTrendSelection(selectionId) ?? throw new DomainValidationException("Die Trend-Auswahl existiert nicht."); + if (!isAdministrator && current.OwnerId != actingUserId) + { + throw new DomainValidationException("Nur der Besitzer oder ein Administrator kann diese Auswahl ändern."); + } + var updated = BuildTrendSelection( + current.Id, + request.Name ?? current.Name, + request.Description ?? current.Description, + current.OwnerId, + request.Shared ?? current.Shared, + request.TrendLogIds ?? current.TrendLogIds, + current.CreatedAtUtc, + DateTimeOffset.UtcNow); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = """ + UPDATE trend_selections SET name = $name, description = $description, shared = $shared, trend_log_ids_json = $trendLogs, updated_at_utc = $updatedAt + WHERE id = $id; + """; + BindTrendSelection(command, updated); + command.ExecuteNonQuery(); + WriteAudit(connection, "trend", $"Trend selection '{updated.Name}' updated."); + return updated; + } + + public void DeleteTrendSelection(Guid selectionId, Guid actingUserId, bool isAdministrator) + { + var current = GetTrendSelection(selectionId) ?? throw new DomainValidationException("Die Trend-Auswahl existiert nicht."); + if (!isAdministrator && current.OwnerId != actingUserId) + { + throw new DomainValidationException("Nur der Besitzer oder ein Administrator kann diese Auswahl löschen."); + } + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM trend_selections WHERE id = $id;"; + command.Parameters.AddWithValue("$id", selectionId.ToString()); + try + { + command.ExecuteNonQuery(); + } + catch (SqliteException exception) when (exception.SqliteErrorCode == 19) + { + throw new DomainValidationException("Die Auswahl wird noch von einem CSV-Runner-Job verwendet."); + } + WriteAudit(connection, "trend", $"Trend selection '{current.Name}' deleted."); + } + + public IReadOnlyList ListCsvRunnerJobs() + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT id, name, selection_id, time, range_hours, delimiter, enabled, mail_enabled, mail_to, mail_subject, mail_message, last_run_local_date, last_result_json, created_at_utc, updated_at_utc FROM csv_runner_jobs ORDER BY name COLLATE NOCASE;"; + using var reader = command.ExecuteReader(); + var jobs = new List(); + while (reader.Read()) jobs.Add(ReadCsvRunnerJob(reader)); + return jobs; + } + + public CsvRunnerJob? GetCsvRunnerJob(Guid jobId) => ListCsvRunnerJobs().SingleOrDefault(job => job.Id == jobId); + + public CsvRunnerJob CreateCsvRunnerJob(CreateCsvRunnerJobRequest request) + { + var job = BuildCsvRunnerJob(Guid.NewGuid(), request.Name, request.SelectionId, request.Time, request.RangeHours, request.Delimiter, request.Enabled, request.MailEnabled, request.MailTo, request.MailSubject, request.MailMessage, null, null, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow); + InsertOrUpdateCsvRunnerJob(job, false); + return job; + } + + public CsvRunnerJob UpdateCsvRunnerJob(Guid jobId, UpdateCsvRunnerJobRequest request) + { + var current = GetCsvRunnerJob(jobId) ?? throw new DomainValidationException("Der CSV-Runner-Job existiert nicht."); + var updated = BuildCsvRunnerJob(current.Id, request.Name ?? current.Name, request.SelectionId ?? current.SelectionId, request.Time ?? current.Time, request.RangeHours ?? current.RangeHours, request.Delimiter ?? current.Delimiter, request.Enabled ?? current.Enabled, request.MailEnabled ?? current.MailEnabled, request.MailTo ?? current.MailTo, request.MailSubject ?? current.MailSubject, request.MailMessage ?? current.MailMessage, current.LastRunLocalDate, current.LastResult, current.CreatedAtUtc, DateTimeOffset.UtcNow); + InsertOrUpdateCsvRunnerJob(updated, true); + return updated; + } + + public void DeleteCsvRunnerJob(Guid jobId) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM csv_runner_jobs WHERE id = $id;"; + command.Parameters.AddWithValue("$id", jobId.ToString()); + if (command.ExecuteNonQuery() == 0) throw new DomainValidationException("Der CSV-Runner-Job existiert nicht."); + WriteAudit(connection, "runner", $"CSV runner job '{jobId}' deleted."); + } + + public bool TryClaimScheduledCsvRunnerJob(Guid jobId, string localDate) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "UPDATE csv_runner_jobs SET last_run_local_date = $date, updated_at_utc = $updatedAt WHERE id = $id AND enabled = 1 AND (last_run_local_date IS NULL OR last_run_local_date <> $date);"; + command.Parameters.AddWithValue("$id", jobId.ToString()); + command.Parameters.AddWithValue("$date", localDate); + command.Parameters.AddWithValue("$updatedAt", DateTimeOffset.UtcNow.ToString("O")); + return command.ExecuteNonQuery() == 1; + } + + public void SetCsvRunnerJobResult(Guid jobId, CsvRunnerJobResult result) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "UPDATE csv_runner_jobs SET last_result_json = $result, updated_at_utc = $updatedAt WHERE id = $id;"; + command.Parameters.AddWithValue("$id", jobId.ToString()); + command.Parameters.AddWithValue("$result", JsonSerializer.Serialize(result, JsonOptions)); + command.Parameters.AddWithValue("$updatedAt", DateTimeOffset.UtcNow.ToString("O")); + command.ExecuteNonQuery(); + } + + public IReadOnlyList ListTrendExportRows(IReadOnlyList trendLogIds, DateTimeOffset sinceUtc) + { + if (trendLogIds.Count == 0) return []; + var presentations = ListPointPresentations().ToDictionary(item => item.PointId); + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + var placeholders = trendLogIds.Select((_, index) => "$id" + index).ToArray(); + command.CommandText = $""" + SELECT records.timestamp_utc, logs.name, logs.bacnet_object_instance, points.display_name, records.value_json, records.source_protocol, records.status, points.id + FROM trend_records records + INNER JOIN trend_logs logs ON logs.id = records.trend_log_id + INNER JOIN points ON points.id = logs.source_point_id + WHERE records.trend_log_id IN ({string.Join(",", placeholders)}) AND records.timestamp_utc >= $since + ORDER BY records.timestamp_utc ASC, logs.name COLLATE NOCASE, records.sequence_number ASC; + """; + for (var index = 0; index < trendLogIds.Count; index++) command.Parameters.AddWithValue(placeholders[index], trendLogIds[index].ToString()); + command.Parameters.AddWithValue("$since", sinceUtc.ToString("O")); + using var reader = command.ExecuteReader(); + var rows = new List(); + while (reader.Read()) + { + presentations.TryGetValue(Guid.Parse(reader.GetString(7)), out var presentation); + var value = ParseElement(reader.GetString(4)); + if (presentation is not null && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number)) + { + var scaled = number * presentation.Factor; + if (!double.IsFinite(scaled)) throw new DomainValidationException("Der Anzeigefaktor erzeugt einen ungültigen Exportwert."); + value = JsonSerializer.SerializeToElement(scaled); + } + rows.Add(new TrendExportRow(ParseTimestamp(reader.GetString(0)), reader.GetString(1), (uint)reader.GetInt64(2), presentation?.Alias ?? reader.GetString(3), value, Enum.Parse(reader.GetString(5)), reader.IsDBNull(6) ? null : reader.GetString(6), presentation?.Unit ?? "")); + } + return rows; + } + + public MailIntegrationView GetMailIntegration() + { + using var connection = _database.OpenConnection(); + return new MailIntegrationView(GetSetting(connection, MailApiKey) is not null, "https://mailapi.se-inno.de"); + } + + public void UpdateMailIntegration(UpdateMailIntegrationRequest request) + { + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + if (request.ClearApiKey) DeleteSetting(connection, MailApiKey, transaction); + else if (!string.IsNullOrWhiteSpace(request.ApiKey)) SetSetting(connection, MailApiKey, _secretProtector.Protect(request.ApiKey.Trim()), transaction); + else throw new DomainValidationException("Bitte einen API-Key angeben oder den gespeicherten Key löschen."); + WriteAudit(connection, "integration", request.ClearApiKey ? "Mail API key cleared." : "Mail API key updated.", transaction); + transaction.Commit(); + } + + public string? GetMailApiKey() + { + using var connection = _database.OpenConnection(); + var protectedKey = GetSetting(connection, MailApiKey); + return protectedKey is null ? null : _secretProtector.Unprotect(protectedKey); + } + + public CreateMappingResponse CreateMapping(CreateMappingRequest request) => SaveMapping(null, request)!; + + public CreateMappingResponse? UpdateMapping(Guid id, CreateMappingRequest request) => SaveMapping(id, request); + + private CreateMappingResponse? SaveMapping(Guid? id, CreateMappingRequest request) + { + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var saved = SaveMapping(connection, transaction, id, request); + transaction.Commit(); + return saved; + } + + private CreateMappingResponse? SaveMapping(SqliteConnection connection, SqliteTransaction transaction, Guid? id, + CreateMappingRequest request, Guid? newId = null) + { + if (!Enum.IsDefined(request.Direction)) + throw new DomainValidationException("Die Mapping-Richtung ist ungültig."); if (request.SourcePointId == request.TargetPointId) { throw new DomainValidationException("Quelle und Ziel eines Mappings müssen verschieden sein."); } - if (request.BacnetPriority is < 1 or > 16) + if (request.BacnetPriority is < 1 or > 16 or 6) { - throw new DomainValidationException("Eine BACnet-Priorität muss zwischen 1 und 16 liegen."); + throw new DomainValidationException("Eine BACnet-Priorität muss zwischen 1 und 16 liegen; Priorität 6 ist reserviert."); } if (request.Transform.ValueKind is not (JsonValueKind.Object or JsonValueKind.Null or JsonValueKind.Undefined)) { throw new DomainValidationException("Die Transformation muss ein JSON-Objekt sein."); } - var points = ListPoints(); + var mappings = ReadMappings(connection, transaction); + var existing = id.HasValue ? mappings.FirstOrDefault(mapping => mapping.Id == id.Value) : null; + if (id.HasValue && existing is null) return null; + + var points = ReadPoints(connection, transaction); if (points.All(point => point.Id != request.SourcePointId) || points.All(point => point.Id != request.TargetPointId)) { throw new DomainValidationException("Quelle oder Zielpunkt existiert nicht."); } var mapping = new PointMapping( - Guid.NewGuid(), + existing?.Id ?? newId ?? Guid.NewGuid(), request.SourcePointId, request.TargetPointId, request.Direction, @@ -629,20 +1416,21 @@ public sealed class GatewayStore request.BacnetPriority, request.AcknowledgeMultipleExternalWriters, request.Transform.ValueKind is JsonValueKind.Undefined ? EmptyObject() : request.Transform.Clone(), - DateTimeOffset.UtcNow); - var validation = _mappingValidator.Validate(points, [.. ListMappings(), mapping]); + existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow); + var validation = _mappingValidator.Validate(points, [.. mappings.Where(other => other.Id != mapping.Id), mapping]); if (!validation.IsValid) { throw new DomainValidationException(string.Join(" ", validation.Errors)); } - using var connection = _database.OpenConnection(); - using var transaction = connection.BeginTransaction(); using var command = connection.CreateCommand(); command.Transaction = transaction; - command.CommandText = """ + command.CommandText = existing is null ? """ INSERT INTO mappings(id, source_point_id, target_point_id, direction, enabled, bacnet_priority, acknowledge_multiple_external_writers, transform_json, created_at_utc) VALUES($id, $sourceId, $targetId, $direction, $enabled, $priority, $acknowledged, $transform, $createdAt); + """ : """ + UPDATE mappings SET source_point_id=$sourceId, target_point_id=$targetId, direction=$direction, enabled=$enabled, + bacnet_priority=$priority, acknowledge_multiple_external_writers=$acknowledged, transform_json=$transform WHERE id=$id; """; command.Parameters.AddWithValue("$id", mapping.Id.ToString()); command.Parameters.AddWithValue("$sourceId", mapping.SourcePointId.ToString()); @@ -652,17 +1440,51 @@ public sealed class GatewayStore command.Parameters.AddWithValue("$priority", (object?)mapping.BacnetPriority ?? DBNull.Value); command.Parameters.AddWithValue("$acknowledged", mapping.AcknowledgeMultipleExternalWriters ? 1 : 0); command.Parameters.AddWithValue("$transform", mapping.Transform.GetRawText()); - command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O")); + if (existing is null) command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O")); command.ExecuteNonQuery(); - WriteAudit(connection, "mapping", $"Mapping '{mapping.Id}' created.", transaction); + WriteAudit(connection, "mapping", $"Mapping '{mapping.Id}' {(existing is null ? "created" : "updated")}.", transaction); foreach (var warning in validation.Warnings) { WriteAudit(connection, "mapping-warning", warning, transaction); } - transaction.Commit(); return new CreateMappingResponse(mapping, validation.Warnings); } + public bool DeleteMapping(Guid id) => DeleteMappingEntry(id, "DELETE FROM mappings WHERE id=$id;", "mapping"); + + private static bool IsCurrentMapping(SqliteConnection connection, SqliteTransaction transaction, PointMapping mapping) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = """ + SELECT EXISTS(SELECT 1 FROM mappings WHERE id=$id AND source_point_id=$source AND target_point_id=$target + AND enabled=1 AND direction=$direction AND bacnet_priority IS $priority AND transform_json=$transform); + """; + command.Parameters.AddWithValue("$id", mapping.Id.ToString()); + command.Parameters.AddWithValue("$source", mapping.SourcePointId.ToString()); + command.Parameters.AddWithValue("$target", mapping.TargetPointId.ToString()); + command.Parameters.AddWithValue("$direction", mapping.Direction.ToString()); + command.Parameters.AddWithValue("$priority", (object?)mapping.BacnetPriority ?? DBNull.Value); + command.Parameters.AddWithValue("$transform", mapping.Transform.GetRawText()); + return (long)command.ExecuteScalar()! == 1; + } + + public bool DeleteMqttMapping(Guid id) => DeleteMappingEntry(id, "DELETE FROM mqtt_mappings WHERE id=$id;", "mqtt"); + + private bool DeleteMappingEntry(Guid id, string sql, string category) + { + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = sql; + command.Parameters.AddWithValue("$id", id.ToString()); + if (command.ExecuteNonQuery() == 0) return false; + WriteAudit(connection, category, $"Mapping '{id}' deleted.", transaction); + transaction.Commit(); + return true; + } + public IReadOnlyList ListAudit(int requestedLimit) { var limit = Math.Clamp(requestedLimit, 1, 500); @@ -694,14 +1516,14 @@ public sealed class GatewayStore reader.IsDBNull(10) ? null : Enum.Parse(reader.GetString(10)), reader.IsDBNull(11) ? null : checked((uint)reader.GetInt64(11))); - private uint GetNextBacnetObjectInstance(BacnetObjectKind objectKind) + private static uint GetNextBacnetObjectInstance(SqliteConnection connection, SqliteTransaction transaction, BacnetObjectKind objectKind) { - using var connection = _database.OpenConnection(); using var command = connection.CreateCommand(); + command.Transaction = transaction; command.CommandText = """ SELECT COALESCE(MAX(bacnet_object_instance), -1) + 1 FROM points - WHERE scope = 'Gateway' AND bacnet_object_kind = $objectKind; + WHERE scope = 'Gateway' AND bacnet_object_kind = $objectKind AND deleted_at_utc IS NULL; """; command.Parameters.AddWithValue("$objectKind", objectKind.ToString()); var next = Convert.ToInt64(command.ExecuteScalar(), CultureInfo.InvariantCulture); @@ -742,16 +1564,23 @@ public sealed class GatewayStore private static void ValidateMqttMappingRequest(CreateMqttMappingRequest request, GatewayPoint point) { + if (!Enum.IsDefined(request.Format) || !Enum.IsDefined(request.Direction) || !Enum.IsDefined(request.QualityOfService) || + request.SeCategory is { } category && !Enum.IsDefined(category)) + throw new DomainValidationException("MQTT-Format, Richtung, QoS oder Kategorie ist ungültig."); if (request.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional && !point.Writable) { throw new DomainValidationException("Ein MQTT-Subscribe benötigt einen beschreibbaren Zielpunkt."); } - if (request.Format == MqttMappingFormat.Json) + var classification = GetMqttPointClassification(point); + if (request.Format is MqttMappingFormat.Json or MqttMappingFormat.SingleTopic) { if (string.IsNullOrWhiteSpace(request.JsonTopic) || !IsValidMqttTopic(request.JsonTopic)) { - throw new DomainValidationException("Für JSON-MQTT ist ein gültiges Topic ohne Wildcards erforderlich."); + throw new DomainValidationException("Ein gültiges MQTT-Topic ohne Wildcards ist erforderlich."); } + if (request.Format == MqttMappingFormat.SingleTopic && + (classification == MqttPointClassification.Structured || !string.IsNullOrWhiteSpace(request.JsonProperty))) + throw new DomainValidationException("Ein Einzel-Topic benötigt einen numerischen oder digitalen Datenpunkt ohne JSON-Eigenschaft."); if (!string.IsNullOrWhiteSpace(request.JsonProperty) && !IsValidJsonProperty(request.JsonProperty)) { throw new DomainValidationException("Die JSON-Eigenschaft darf nur Buchstaben, Ziffern, Unterstrich und Bindestrich enthalten."); @@ -759,13 +1588,12 @@ public sealed class GatewayStore return; } - if (request.ProjectYear is < 2000 or > 2100 || !IsProjectNumber(request.ProjectNumber) || !IsIspNumber(request.IspNumber) || + if (request.ProjectYear is not (>= 2000 and <= 2100) || !IsProjectNumber(request.ProjectNumber) || !IsIspNumber(request.IspNumber) || request.SeCategory is null || !IsValidTopicName(request.TopicName)) { throw new DomainValidationException("SE-Monitoring benötigt Jahr, Projektnummer P…, ISP-Nummer ISP…, Kategorie und einen gültigen Punktnamen."); } - var classification = GetMqttPointClassification(point); if (classification == MqttPointClassification.Structured) { throw new DomainValidationException("Schedule, Calendar und strukturierte Objekte dürfen nur als JSON-MQTT übertragen werden."); @@ -774,7 +1602,7 @@ public sealed class GatewayStore { throw new DomainValidationException("Die MQTT-Kategorie 'Analog' akzeptiert nur analoge Datenpunkte."); } - if (request.SeCategory is SeMonitoringCategory.Notify or SeMonitoringCategory.Alarm && classification != MqttPointClassification.Digital) + if (request.SeCategory is SeMonitoringCategory.Notify or SeMonitoringCategory.Alarm or SeMonitoringCategory.Alarms && classification != MqttPointClassification.Digital) { throw new DomainValidationException("Die MQTT-Kategorien 'Notify' und 'Alarm' akzeptieren nur digitale Datenpunkte."); } @@ -790,10 +1618,8 @@ public sealed class GatewayStore BacnetObjectKind.BinaryInput or BacnetObjectKind.BinaryOutput or BacnetObjectKind.BinaryValue or BacnetObjectKind.MultiStateInput or BacnetObjectKind.MultiStateOutput or BacnetObjectKind.MultiStateValue => MqttPointClassification.Digital, BacnetObjectKind.Schedule or BacnetObjectKind.Calendar or BacnetObjectKind.EventEnrollment or BacnetObjectKind.NotificationClass or BacnetObjectKind.TrendLog => MqttPointClassification.Structured, - _ when point.ValueType.Equals("Boolean", StringComparison.OrdinalIgnoreCase) || point.ValueType.Equals("Bool", StringComparison.OrdinalIgnoreCase) => MqttPointClassification.Digital, - _ when point.ValueType.Equals("Real", StringComparison.OrdinalIgnoreCase) || point.ValueType.Equals("Double", StringComparison.OrdinalIgnoreCase) || - point.ValueType.Equals("Float", StringComparison.OrdinalIgnoreCase) || point.ValueType.Equals("Integer", StringComparison.OrdinalIgnoreCase) || - point.ValueType.Equals("Unsigned", StringComparison.OrdinalIgnoreCase) => MqttPointClassification.Analog, + _ when IsBooleanMqttPoint(point) => MqttPointClassification.Digital, + _ when OpcUaPointTypes.Resolve(point.ValueType) is >= Opc.Ua.BuiltInType.SByte and <= Opc.Ua.BuiltInType.Double => MqttPointClassification.Analog, _ => MqttPointClassification.Structured }; @@ -802,6 +1628,7 @@ public sealed class GatewayStore SeMonitoringCategory.Analog => "Analog", SeMonitoringCategory.Notify => "Notify", SeMonitoringCategory.Alarm => "Alarm", + SeMonitoringCategory.Alarms => "Alarms", SeMonitoringCategory.Setpoints => "Setpoints", _ => throw new ArgumentOutOfRangeException(nameof(category)) }; @@ -824,7 +1651,117 @@ public sealed class GatewayStore reader.GetInt32(4), reader.GetInt32(5), reader.GetInt64(6) == 1, - ParseTimestamp(reader.GetString(7))); + reader.GetInt64(7) == 1, + ParseTimestamp(reader.GetString(8))); + + private GatewayTrendSelection BuildTrendSelection(Guid id, string? name, string? description, Guid ownerId, bool shared, IReadOnlyList? trendLogIds, DateTimeOffset createdAtUtc, DateTimeOffset updatedAtUtc) + { + var normalizedName = NormalizeDisplayName(name); + var normalizedDescription = NormalizeNullable(description); + if (normalizedDescription?.Length > 600) + { + throw new DomainValidationException("Die Beschreibung der Trend-Auswahl darf höchstens 600 Zeichen haben."); + } + var ids = (trendLogIds ?? []).Distinct().ToArray(); + if (ids.Length is < 1 or > 500) + { + throw new DomainValidationException("Eine Trend-Auswahl benötigt zwischen 1 und 500 Trend Logs."); + } + var knownIds = ListTrendLogs().Select(log => log.Id).ToHashSet(); + if (ids.Any(id => !knownIds.Contains(id))) + { + throw new DomainValidationException("Die Trend-Auswahl enthält ein unbekanntes Trend Log."); + } + return new GatewayTrendSelection(id, normalizedName, normalizedDescription, ownerId, shared, ids, createdAtUtc, updatedAtUtc); + } + + private static GatewayTrendSelection ReadTrendSelection(SqliteDataReader reader) => new( + Guid.Parse(reader.GetString(0)), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), Guid.Parse(reader.GetString(3)), reader.GetInt64(4) == 1, + JsonSerializer.Deserialize(reader.GetString(5), JsonOptions) ?? [], ParseTimestamp(reader.GetString(6)), ParseTimestamp(reader.GetString(7))); + + private static void BindTrendSelection(SqliteCommand command, GatewayTrendSelection selection) + { + command.Parameters.AddWithValue("$id", selection.Id.ToString()); + command.Parameters.AddWithValue("$name", selection.Name); + command.Parameters.AddWithValue("$description", (object?)selection.Description ?? DBNull.Value); + command.Parameters.AddWithValue("$ownerId", selection.OwnerId.ToString()); + command.Parameters.AddWithValue("$shared", selection.Shared ? 1 : 0); + command.Parameters.AddWithValue("$trendLogs", JsonSerializer.Serialize(selection.TrendLogIds, JsonOptions)); + command.Parameters.AddWithValue("$createdAt", selection.CreatedAtUtc.ToString("O")); + command.Parameters.AddWithValue("$updatedAt", selection.UpdatedAtUtc.ToString("O")); + } + + private CsvRunnerJob BuildCsvRunnerJob(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) + { + if (GetTrendSelection(selectionId) is null) + { + throw new DomainValidationException("Die ausgewählte Trend-Gruppe existiert nicht."); + } + var normalizedTime = time?.Trim() ?? string.Empty; + if (!TimeOnly.TryParseExact(normalizedTime, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) + { + throw new DomainValidationException("Die Laufzeit muss im Format HH:mm angegeben werden."); + } + if (rangeHours is < 1 or > 8760) + { + throw new DomainValidationException("Der CSV-Zeitraum muss zwischen 1 und 8760 Stunden liegen."); + } + var normalizedDelimiter = delimiter ?? ";"; + if (normalizedDelimiter is not (";" or "," or "\t")) + { + throw new DomainValidationException("Als CSV-Trennzeichen sind Semikolon, Komma oder Tabulator zulässig."); + } + var recipients = NormalizeNullable(mailTo); + if (mailEnabled && (recipients is null || ParseMailRecipients(recipients).Length == 0)) + { + throw new DomainValidationException("Für den Mailversand ist mindestens ein Empfänger erforderlich."); + } + var subject = NormalizeNullable(mailSubject) ?? "SE-Inno Universalgateway CSV Export"; + var message = NormalizeNullable(mailMessage) ?? "Automatischer CSV Export aus dem SE-Inno Universalgateway."; + if (subject.Length > 200 || message.Length > 10_000 || recipients?.Length > 2000) + { + throw new DomainValidationException("Die Einstellungen für den CSV-Runner sind zu lang."); + } + return new CsvRunnerJob(id, NormalizeDisplayName(name), selectionId, normalizedTime, rangeHours, normalizedDelimiter, enabled, mailEnabled, recipients, subject, message, lastRunLocalDate, lastResult, createdAtUtc, updatedAtUtc); + } + + private void InsertOrUpdateCsvRunnerJob(CsvRunnerJob job, bool update) + { + using var connection = _database.OpenConnection(); + using var command = connection.CreateCommand(); + command.CommandText = update + ? """UPDATE csv_runner_jobs SET name = $name, selection_id = $selectionId, time = $time, range_hours = $rangeHours, delimiter = $delimiter, enabled = $enabled, mail_enabled = $mailEnabled, mail_to = $mailTo, mail_subject = $mailSubject, mail_message = $mailMessage, updated_at_utc = $updatedAt WHERE id = $id;""" + : """INSERT INTO csv_runner_jobs(id, name, selection_id, time, range_hours, delimiter, enabled, mail_enabled, mail_to, mail_subject, mail_message, last_run_local_date, last_result_json, created_at_utc, updated_at_utc) VALUES($id, $name, $selectionId, $time, $rangeHours, $delimiter, $enabled, $mailEnabled, $mailTo, $mailSubject, $mailMessage, $lastRunDate, $lastResult, $createdAt, $updatedAt);"""; + BindCsvRunnerJob(command, job); + if (command.ExecuteNonQuery() == 0 && update) throw new DomainValidationException("Der CSV-Runner-Job existiert nicht."); + WriteAudit(connection, "runner", $"CSV runner job '{job.Name}' {(update ? "updated" : "created")}."); + } + + private static CsvRunnerJob ReadCsvRunnerJob(SqliteDataReader reader) => new( + Guid.Parse(reader.GetString(0)), reader.GetString(1), Guid.Parse(reader.GetString(2)), reader.GetString(3), reader.GetInt32(4), reader.GetString(5), reader.GetInt64(6) == 1, + reader.GetInt64(7) == 1, reader.IsDBNull(8) ? null : reader.GetString(8), reader.GetString(9), reader.GetString(10), reader.IsDBNull(11) ? null : reader.GetString(11), + reader.IsDBNull(12) ? null : JsonSerializer.Deserialize(reader.GetString(12), JsonOptions), ParseTimestamp(reader.GetString(13)), ParseTimestamp(reader.GetString(14))); + + private static void BindCsvRunnerJob(SqliteCommand command, CsvRunnerJob job) + { + command.Parameters.AddWithValue("$id", job.Id.ToString()); + command.Parameters.AddWithValue("$name", job.Name); + command.Parameters.AddWithValue("$selectionId", job.SelectionId.ToString()); + command.Parameters.AddWithValue("$time", job.Time); + command.Parameters.AddWithValue("$rangeHours", job.RangeHours); + command.Parameters.AddWithValue("$delimiter", job.Delimiter); + command.Parameters.AddWithValue("$enabled", job.Enabled ? 1 : 0); + command.Parameters.AddWithValue("$mailEnabled", job.MailEnabled ? 1 : 0); + command.Parameters.AddWithValue("$mailTo", (object?)job.MailTo ?? DBNull.Value); + command.Parameters.AddWithValue("$mailSubject", job.MailSubject); + command.Parameters.AddWithValue("$mailMessage", job.MailMessage); + command.Parameters.AddWithValue("$lastRunDate", (object?)job.LastRunLocalDate ?? DBNull.Value); + command.Parameters.AddWithValue("$lastResult", job.LastResult is null ? DBNull.Value : JsonSerializer.Serialize(job.LastResult, JsonOptions)); + command.Parameters.AddWithValue("$createdAt", job.CreatedAtUtc.ToString("O")); + command.Parameters.AddWithValue("$updatedAt", job.UpdatedAtUtc.ToString("O")); + } + + private static string[] ParseMailRecipients(string value) => value.Split(MailRecipientSeparators, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); private static long NextTrendSequence(SqliteConnection connection, Guid trendLogId, SqliteTransaction transaction) { @@ -882,6 +1819,9 @@ public sealed class GatewayStore private static void ValidatePointRequest(CreatePointRequest request) { + if (!Enum.IsDefined(request.Protocol) || !Enum.IsDefined(request.Scope) || + request.BacnetObjectKind is { } kind && !Enum.IsDefined(kind)) + throw new DomainValidationException("Protokoll, Bereich oder BACnet-Objekttyp ist ungültig."); if (string.IsNullOrWhiteSpace(request.DisplayName) || request.DisplayName.Trim().Length > 160) { throw new DomainValidationException("Der Punktname muss zwischen 1 und 160 Zeichen haben."); @@ -894,6 +1834,10 @@ public sealed class GatewayStore { throw new DomainValidationException("Die Punktadresse muss ein JSON-Objekt sein."); } + if (request.Protocol == PointProtocol.OpcUa && request.Scope == PointScope.Gateway && OpcUaPointTypes.Resolve(request.ValueType) == Opc.Ua.BuiltInType.Null) + { + throw new DomainValidationException("OPC-UA-Serverpunkte unterstützen Boolean, Real/Float, Double, Integer/Int32, Unsigned/UInt32, SByte, Byte, Int16, UInt16, Int64, UInt64 und String."); + } if (request.Scope == PointScope.External && string.IsNullOrWhiteSpace(request.ExternalIdentity)) { throw new DomainValidationException("Externe Punkte benötigen eine eindeutige externe Identität."); @@ -944,6 +1888,19 @@ public sealed class GatewayStore } ValidatePort(configuration.Bacnet.IpPort, "BACnet/IP-Port"); ValidatePort(configuration.OpcUa.Port, "OPC-UA-Port"); + var opcUaClientNames = new HashSet(StringComparer.OrdinalIgnoreCase); + var opcUaClientIds = new HashSet(); + foreach (var client in configuration.OpcUa.Clients ?? []) + { + if (client.Id == Guid.Empty || !opcUaClientIds.Add(client.Id) || string.IsNullOrWhiteSpace(client.Name) || !opcUaClientNames.Add(client.Name) || + !Uri.TryCreate(client.EndpointUrl, UriKind.Absolute, out var endpoint) || endpoint.Scheme != "opc.tcp" || + !string.IsNullOrEmpty(endpoint.UserInfo) || client.PublishingIntervalMilliseconds is < 100 or > 60000 || + client.AuthenticationMode is not (OpcUaAuthenticationMode.Anonymous or OpcUaAuthenticationMode.Username) || + client.AuthenticationMode == OpcUaAuthenticationMode.Username && (string.IsNullOrWhiteSpace(client.Username) || !client.UseSecurity)) + { + throw new DomainValidationException("Eine OPC-UA-Clientverbindung ist ungültig."); + } + } if (configuration.Bacnet.BbmdMode == BbmdMode.ForeignDevice && (string.IsNullOrWhiteSpace(configuration.Bacnet.BbmdAddress) || configuration.Bacnet.ForeignDeviceTtlSeconds is < 1 or > 65_535)) { @@ -972,6 +1929,48 @@ public sealed class GatewayStore } } + var serialPorts = configuration.SerialPorts ?? []; + var aliases = new HashSet(StringComparer.OrdinalIgnoreCase); + var devicePaths = new HashSet(StringComparer.Ordinal); + foreach (var serialPort in serialPorts) + { + if (string.IsNullOrWhiteSpace(serialPort.Alias) || + !System.Text.RegularExpressions.Regex.IsMatch(serialPort.Alias, "^[A-Za-z0-9_-]{1,64}$")) + { + throw new DomainValidationException("Ein COM-Port-Alias darf nur Buchstaben, Ziffern, - und _ enthalten."); + } + if (!aliases.Add(serialPort.Alias)) + { + throw new DomainValidationException("Jeder COM-Port benötigt einen eindeutigen Alias."); + } + if (string.IsNullOrWhiteSpace(serialPort.DevicePath) || !serialPort.DevicePath.StartsWith("/dev/", StringComparison.Ordinal)) + { + throw new DomainValidationException("Der serielle Gerätepfad muss mit /dev/ beginnen."); + } + if (!devicePaths.Add(serialPort.DevicePath) || serialPort.BaudRate is < 1_200 or > 921_600 || + serialPort.DataBits is < 5 or > 8 || serialPort.StopBits is < 1 or > 2 || + serialPort.Parity is not ("None" or "Odd" or "Even")) + { + throw new DomainValidationException($"Die Einstellungen für den seriellen Port '{serialPort.Alias}' sind ungültig."); + } + } + + foreach (var server in configuration.ModbusRtuServers ?? []) + { + if (string.IsNullOrWhiteSpace(server.Name) || !aliases.Contains(server.SerialPortAlias) || + server.UnitId is < 1 or > 247 || server.FirstHoldingRegister is < 0 or > 65_535 || + server.HoldingRegisterCount is < 1 or > 65_536) + { + throw new DomainValidationException($"Die Modbus-RTU-Serverkonfiguration '{server.Name}' ist ungültig."); + } + } + + if (configuration.Knx.Transport == KnxTransport.Tp && + (string.IsNullOrWhiteSpace(configuration.Knx.SerialPortAlias) || !aliases.Contains(configuration.Knx.SerialPortAlias))) + { + throw new DomainValidationException("KNX TP benötigt einen vorhandenen seriellen Port-Alias."); + } + ValidateMqttConfiguration(configuration.Mqtt ?? MqttConfiguration.CreateDefault()); if (configuration.Installation is not null) { @@ -1037,17 +2036,18 @@ public sealed class GatewayStore private static DateTimeOffset ParseTimestamp(string value) => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); - private static string? GetSetting(SqliteConnection connection, string key) + private static string? GetSetting(SqliteConnection connection, string key, SqliteTransaction? transaction = null) { using var command = connection.CreateCommand(); + if (transaction is not null) command.Transaction = transaction; command.CommandText = "SELECT value FROM settings WHERE key = $key;"; command.Parameters.AddWithValue("$key", key); return command.ExecuteScalar() as string; } - private static GatewayConfiguration ReadGatewayConfiguration(SqliteConnection connection) + private static GatewayConfiguration ReadGatewayConfiguration(SqliteConnection connection, SqliteTransaction? transaction = null) { - var json = GetSetting(connection, GatewayConfigurationKey) + var json = GetSetting(connection, GatewayConfigurationKey, transaction) ?? throw new InvalidOperationException("Gateway configuration is missing."); return JsonSerializer.Deserialize(json, JsonOptions) ?? throw new InvalidOperationException("Gateway configuration is invalid."); @@ -1068,6 +2068,18 @@ public sealed class GatewayStore } } + private void WriteKomariTokenRequest() + { + var provisioningDirectory = Path.Combine(_database.DataDirectory, "provisioning"); + Directory.CreateDirectory(provisioningDirectory); + var requestPath = Path.Combine(provisioningDirectory, "komari-token.request"); + File.WriteAllText(requestPath, DateTimeOffset.UtcNow.ToString("O")); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(requestPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead); + } + } + private static void SetSetting(SqliteConnection connection, string key, string value, SqliteTransaction? transaction = null) { using var command = connection.CreateCommand(); diff --git a/src/Gateway.Api/Services/HardwareDiscoveryService.cs b/src/Gateway.Api/Services/HardwareDiscoveryService.cs new file mode 100644 index 0000000..384caf0 --- /dev/null +++ b/src/Gateway.Api/Services/HardwareDiscoveryService.cs @@ -0,0 +1,81 @@ +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace Gateway.Api.Services; + +/// Read-only inventory of interfaces that are visible to the local gateway process. +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(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 NetworkInterfaces, + IReadOnlyList SerialDevices); + +public sealed record GatewayNetworkInterface(string Name, string Description, bool IsUp, string MacAddress, IReadOnlyList Addresses); + +public sealed record GatewaySerialDevice(string DevicePath, string? TargetPath); diff --git a/src/Gateway.Api/Services/HostNetworkService.cs b/src/Gateway.Api/Services/HostNetworkService.cs new file mode 100644 index 0000000..c9a9c8a --- /dev/null +++ b/src/Gateway.Api/Services/HostNetworkService.cs @@ -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 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); + } + } +} diff --git a/src/Gateway.Api/Services/KnxEtsImporter.cs b/src/Gateway.Api/Services/KnxEtsImporter.cs new file mode 100644 index 0000000..56d6005 --- /dev/null +++ b/src/Gateway.Api/Services/KnxEtsImporter.cs @@ -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 Errors); + +/// Imports ETS group-address exports (.knxproj ZIP or XML) without trusting project metadata as executable content. +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(); + 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 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(); + 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); +} diff --git a/src/Gateway.Api/Services/MappingRuntimeService.cs b/src/Gateway.Api/Services/MappingRuntimeService.cs new file mode 100644 index 0000000..4e82091 --- /dev/null +++ b/src/Gateway.Api/Services/MappingRuntimeService.cs @@ -0,0 +1,86 @@ +using Gateway.Api.Domain; + +namespace Gateway.Api.Services; + +/// +/// 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. +/// +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? 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. + } + } + } + +} diff --git a/src/Gateway.Api/Services/ModbusAddressing.cs b/src/Gateway.Api/Services/ModbusAddressing.cs new file mode 100644 index 0000000..d4fdc60 --- /dev/null +++ b/src/Gateway.Api/Services/ModbusAddressing.cs @@ -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 + }; + } +} diff --git a/src/Gateway.Api/Services/ModbusCsvImporter.cs b/src/Gateway.Api/Services/ModbusCsvImporter.cs new file mode 100644 index 0000000..dd060fc --- /dev/null +++ b/src/Gateway.Api/Services/ModbusCsvImporter.cs @@ -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 Errors); + +/// Imports an intentionally small, documented CSV dialect for field Modbus point lists. +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(); + 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(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 + { + ["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 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(); + 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(); + } + } +} diff --git a/src/Gateway.Api/Services/ModbusProtocolService.cs b/src/Gateway.Api/Services/ModbusProtocolService.cs new file mode 100644 index 0000000..985a014 --- /dev/null +++ b/src/Gateway.Api/Services/ModbusProtocolService.cs @@ -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. + +/// +/// 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. +/// +public sealed class ModbusProtocolService : BackgroundService +{ + private readonly GatewayStore _store; + private readonly WriteJournal _journal; + private readonly ILogger _logger; + private readonly ConcurrentDictionary _servers = new(); + private readonly ConcurrentDictionary _serverErrors = new(); + private readonly ConcurrentDictionary _pointErrors = new(); + private readonly ConcurrentDictionary _nextPollAt = new(); + private readonly ModbusFactory _factory = new(); + private CancellationToken _serviceStopping; + private int _disposed; + + public ModbusProtocolService(GatewayStore store, WriteJournal journal, ILogger 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 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 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 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(configuration.Parity, true), + configuration.DataBits, + Enum.Parse(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 diff --git a/src/Gateway.Api/Services/MqttClientService.cs b/src/Gateway.Api/Services/MqttClientService.cs index 00c408b..f95e067 100644 --- a/src/Gateway.Api/Services/MqttClientService.cs +++ b/src/Gateway.Api/Services/MqttClientService.cs @@ -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; /// /// 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. /// public sealed class MqttClientService : BackgroundService { private readonly GatewayStore _store; private readonly MqttClientFactory _factory = new(); private readonly SemaphoreSlim _publishGate = new(1, 1); + private readonly ConcurrentDictionary _initialPublications = new(); private readonly object _clientLock = new(); + private Dictionary _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 /// Applies changed broker or subscription configuration without a process restart. public void RequestReconfigure() => Interlocked.Exchange(ref _reconfigureRequested, 1); + public void QueueInitialPublications(IReadOnlyList mappingIds) + { + foreach (var id in mappingIds) _initialPublications.TryAdd(id, 0); + } + public async Task PublishPointValueAsync(PointValue pointValue, CancellationToken cancellationToken = default) { var client = GetConnectedClient(); @@ -42,25 +50,20 @@ public sealed class MqttClientService : BackgroundService return 0; } - var mappings = _store.ListMqttMappings() - .Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional) - .ToArray(); var published = 0; await _publishGate.WaitAsync(cancellationToken); try { + var mappings = _store.ListMqttMappings() + .Where(mapping => mapping.PointId == pointValue.PointId && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional); foreach (var mapping in mappings) { - var payload = CreateOutboundPayload(mapping, pointValue); - var message = _factory.CreateApplicationMessageBuilder() - .WithTopic(GatewayStore.GetMqttTopic(mapping)) - .WithPayload(payload) - .WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService)) - .WithRetainFlag(mapping.Retain) - .Build(); - await client.PublishAsync(message, cancellationToken); - published++; - UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null }); + try + { + await PublishMappedValueAsync(client, mapping, pointValue, cancellationToken); + published++; + } + catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); } } } catch (Exception exception) when (!cancellationToken.IsCancellationRequested) @@ -84,20 +87,33 @@ public sealed class MqttClientService : BackgroundService try { var (configuration, password) = _store.GetMqttConnectionConfiguration(); + if (configuration.Enabled) + { + var sources = _store.ListMqttExternalPoints() + .Where(point => point.Readable) + .GroupBy(point => MqttExternalTopics.Address(point)!, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal); + var previous = Interlocked.Exchange(ref _externalPoints, sources); + if (sources.Count != previous.Count || sources.Keys.Any(topic => !previous.ContainsKey(topic))) + RequestReconfigure(); + } if (!configuration.Enabled) { await DisconnectCurrentAsync(stoppingToken); - SetStatus(new MqttClientStatus(false, false, null, null, null, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc)); + UpdateStatus(status => status with { Enabled = false, Connected = false, Endpoint = null, ConnectedAtUtc = null, LastError = null }); } else if (Interlocked.Exchange(ref _reconfigureRequested, 0) == 1 || GetConnectedClient() is null) { await DisconnectCurrentAsync(stoppingToken); + UpdateStatus(status => status with { Enabled = true, Connected = false, Endpoint = $"{configuration.Host}:{configuration.Port}", ConnectedAtUtc = null }); await ConnectAsync(configuration, password, stoppingToken); } + if (configuration.Enabled && !_initialPublications.IsEmpty && GetConnectedClient() is not null) + await PublishInitialValuesAsync(stoppingToken); } catch (Exception exception) when (!stoppingToken.IsCancellationRequested) { - UpdateStatus(status => status with { Connected = false, LastError = exception.Message }); + UpdateStatus(status => status with { Connected = GetConnectedClient() is not null, LastError = exception.Message }); } try @@ -113,6 +129,46 @@ public sealed class MqttClientService : BackgroundService await DisconnectCurrentAsync(CancellationToken.None); } + private async Task PublishInitialValuesAsync(CancellationToken cancellationToken) + { + await _publishGate.WaitAsync(cancellationToken); + try + { + if (GetConnectedClient() is not { } client) return; + var mappings = _store.ListMqttMappings().Where(mapping => mapping.Direction == MqttDirection.Publish) + .ToDictionary(mapping => mapping.Id); + var values = _store.ListPointValues().ToDictionary(value => value.PointId); + foreach (var id in _initialPublications.Keys) + { + if (mappings.TryGetValue(id, out var mapping) && values.TryGetValue(mapping.PointId, out var value) && + value.SourceProtocol != PointProtocol.Mqtt && IsGoodValue(value)) + { + try + { + await PublishMappedValueAsync(client, mapping, value, cancellationToken); + continue; + } + catch (DomainValidationException exception) { RecordPayloadError("Senden", mapping, exception); } + } + _initialPublications.TryRemove(id, out _); + } + } + finally { _publishGate.Release(); } + } + + private async Task PublishMappedValueAsync(IMqttClient client, MqttMapping mapping, PointValue pointValue, CancellationToken cancellationToken) + { + var message = _factory.CreateApplicationMessageBuilder() + .WithTopic(GatewayStore.GetMqttTopic(mapping)) + .WithPayload(CreateOutboundPayload(mapping, pointValue)) + .WithQualityOfServiceLevel(ToMqttQualityOfService(mapping.QualityOfService)) + .WithRetainFlag(mapping.Retain) + .Build(); + await client.PublishAsync(message, cancellationToken); + _initialPublications.TryRemove(mapping.Id, out _); + UpdateStatus(status => status with { LastPublishedAtUtc = DateTimeOffset.UtcNow, LastError = null }); + } + public override void Dispose() { _store.PointValueUpdated -= OnPointValueUpdated; @@ -120,10 +176,10 @@ public sealed class MqttClientService : BackgroundService base.Dispose(); } - private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken) + internal static MqttClientOptions BuildClientOptions(MqttClientFactory factory, MqttConfiguration configuration, string? password, string clientId) { - var builder = _factory.CreateClientOptionsBuilder() - .WithClientId(configuration.ClientId) + var builder = factory.CreateClientOptionsBuilder() + .WithClientId(clientId) .WithTcpServer(configuration.Host, configuration.Port) // MQTT 3.1.1 gives the widest compatibility with existing field brokers. .WithProtocolVersion(MqttProtocolVersion.V311); @@ -145,25 +201,39 @@ public sealed class MqttClientService : BackgroundService }); } + return builder.Build(); + } + + private async Task ConnectAsync(MqttConfiguration configuration, string? password, CancellationToken cancellationToken) + { var client = _factory.CreateMqttClient(); client.ApplicationMessageReceivedAsync += HandleReceivedMessageAsync; - client.DisconnectedAsync += HandleDisconnectedAsync; - await client.ConnectAsync(builder.Build(), cancellationToken); lock (_clientLock) { _client = client; } - - var now = DateTimeOffset.UtcNow; - SetStatus(new MqttClientStatus(true, true, $"{configuration.Host}:{configuration.Port}", null, now, GetStatus().LastReceivedAtUtc, GetStatus().LastPublishedAtUtc)); - await SubscribeMappedTopicsAsync(client, cancellationToken); + client.DisconnectedAsync += arguments => HandleDisconnectedAsync(client, arguments); + try + { + var result = await client.ConnectAsync(BuildClientOptions(_factory, configuration, password, configuration.ClientId), cancellationToken); + if (!client.IsConnected) throw new DomainValidationException($"Broker-Verbindung abgewiesen ({result.ResultCode})."); + var subscriptionError = await SubscribeMappedTopicsAsync(client, cancellationToken); + UpdateStatus(status => status with { Connected = client.IsConnected, LastError = subscriptionError, ConnectedAtUtc = DateTimeOffset.UtcNow }); + } + catch + { + await DisconnectCurrentAsync(cancellationToken); + throw; + } } - private async Task SubscribeMappedTopicsAsync(IMqttClient client, CancellationToken cancellationToken) + private async Task 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(); + foreach (var batch in subscriptions.Chunk(100)) { - builder.WithTopicFilter(filter => filter - .WithTopic(subscription.Topic) - .WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService))); + var builder = _factory.CreateSubscribeOptionsBuilder(); + foreach (var subscription in batch) + builder.WithTopicFilter(filter => filter.WithTopic(subscription.Topic) + .WithQualityOfServiceLevel(ToMqttQualityOfService(subscription.QualityOfService))); + var result = await client.SubscribeAsync(builder.Build(), cancellationToken); + rejected.AddRange(result.Items.Where(item => (int)item.ResultCode >= 128).Select(item => item.TopicFilter.Topic)); } - - await client.SubscribeAsync(builder.Build(), cancellationToken); + return rejected.Count == 0 ? null : + $"Broker hat {rejected.Count} Abonnement(s) abgelehnt · {string.Join(", ", rejected.Take(3))}"; } private async Task HandleReceivedMessageAsync(MqttApplicationMessageReceivedEventArgs arguments) @@ -191,27 +264,57 @@ public sealed class MqttClientService : BackgroundService try { var topic = arguments.ApplicationMessage.Topic; + var payload = arguments.ApplicationMessage.Payload; + var receivedAt = DateTimeOffset.UtcNow; + var stored = false; + if (Volatile.Read(ref _externalPoints).TryGetValue(topic, out var sources)) + { + var sample = MqttExternalTopics.Read(topic, payload, inferDigital: false); + foreach (var source in sources) + { + if (sample.Value is not { } value || MqttExternalTopics.ConvertToPoint(value, source.ValueType) is not { } converted) + { + UpdateStatus(status => status with { LastError = $"Empfang · {topic} · Wert passt nicht zum Typ '{source.ValueType}'." }); + continue; + } + try + { + _store.SetPointValue(source.Id, converted, PointProtocol.Mqtt, receivedAt, "Good", expectedDefinition: source); + stored = true; + } + catch (DomainValidationException exception) + { + UpdateStatus(status => status with { LastError = $"Empfang · {topic} · {exception.Message}" }); + } + } + } var mappings = _store.ListMqttMappings() .Where(mapping => mapping.Direction is MqttDirection.Subscribe or MqttDirection.Bidirectional) .Where(mapping => string.Equals(GatewayStore.GetMqttTopic(mapping), topic, StringComparison.Ordinal)) .ToArray(); if (mappings.Length == 0) { + if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt }); return; } - var payload = arguments.ApplicationMessage.Payload; var payloadBytes = new byte[checked((int)payload.Length)]; payload.CopyTo(payloadBytes); var rawPayload = Encoding.UTF8.GetString(payloadBytes); using var document = ParsePayload(rawPayload); foreach (var mapping in mappings) { - var value = ExtractInboundValue(document.RootElement, mapping); - _store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, DateTimeOffset.UtcNow); + try + { + var point = _store.GetMqttPoint(mapping.PointId); + if (point is not { Writable: true }) continue; + var value = ExtractInboundValue(document.RootElement, mapping, point); + _store.SetPointValue(mapping.PointId, value, PointProtocol.Mqtt, receivedAt, expectedDefinition: point); + stored = true; + } + catch (DomainValidationException exception) { RecordPayloadError("Empfang", mapping, exception); } } - - UpdateStatus(status => status with { LastReceivedAtUtc = DateTimeOffset.UtcNow, LastError = null }); + if (stored) UpdateStatus(status => status with { LastReceivedAtUtc = receivedAt }); } catch (Exception exception) { @@ -221,11 +324,11 @@ public sealed class MqttClientService : BackgroundService await Task.CompletedTask; } - private Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs arguments) + private Task HandleDisconnectedAsync(IMqttClient client, MqttClientDisconnectedEventArgs arguments) { lock (_clientLock) { - _client = null; + if (!ReferenceEquals(client, _client)) return Task.CompletedTask; } if (arguments.Exception is not null) @@ -275,8 +378,9 @@ public sealed class MqttClientService : BackgroundService private void OnPointValueUpdated(object? sender, PointValue pointValue) { + if (!IsGoodValue(pointValue)) return; // MQTT-originated values must not be reflected to the same broker again. - if (pointValue.SourceProtocol == PointProtocol.Mqtt || !GetStatus().Connected) + if ((pointValue.SourceProtocol == PointProtocol.Mqtt && pointValue.OriginPointId == pointValue.PointId) || !GetStatus().Connected) { return; } @@ -284,6 +388,9 @@ public sealed class MqttClientService : BackgroundService _ = PublishPointValueSafelyAsync(pointValue); } + private static bool IsGoodValue(PointValue value) => string.IsNullOrWhiteSpace(value.Status) || + value.Status.Equals("Good", StringComparison.OrdinalIgnoreCase) || value.Status.Equals("ok", StringComparison.OrdinalIgnoreCase); + private async Task PublishPointValueSafelyAsync(PointValue pointValue) { try @@ -299,7 +406,7 @@ public sealed class MqttClientService : BackgroundService } } - private static JsonDocument ParsePayload(string rawPayload) + internal static JsonDocument ParsePayload(string rawPayload) { try { @@ -311,7 +418,7 @@ public sealed class MqttClientService : BackgroundService } } - private static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping) + internal static JsonElement ExtractInboundValue(JsonElement payload, MqttMapping mapping, GatewayPoint point) { if (mapping.Format == MqttMappingFormat.Json && !string.IsNullOrWhiteSpace(mapping.JsonProperty)) { @@ -323,14 +430,30 @@ public sealed class MqttClientService : BackgroundService return property.Clone(); } - return payload.Clone(); + if (mapping.Format == MqttMappingFormat.Json) return payload.Clone(); + if (GatewayStore.IsBooleanMqttPoint(point)) + { + if (payload.ValueKind is JsonValueKind.True or JsonValueKind.False) return payload.Clone(); + if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var digital) && digital is 0 or 1) + return JsonSerializer.SerializeToElement(digital == 1); + throw new DomainValidationException("Der digitale Datenpunkt erwartet 0 oder 1."); + } + if (payload.ValueKind == JsonValueKind.Number && payload.TryGetDouble(out var analog) && double.IsFinite(analog)) + return payload.Clone(); + throw new DomainValidationException("Der Datenpunkt erwartet eine endliche Zahl."); } - private static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue) + internal static string CreateOutboundPayload(MqttMapping mapping, PointValue pointValue) { - if (mapping.Format == MqttMappingFormat.SeMonitoring) + if (mapping.Format is MqttMappingFormat.SeMonitoring or MqttMappingFormat.SingleTopic) { - return pointValue.Value.GetRawText(); + return pointValue.Value.ValueKind switch + { + JsonValueKind.True => "1", + JsonValueKind.False => "0", + JsonValueKind.Number when pointValue.Value.TryGetDouble(out var number) && double.IsFinite(number) => pointValue.Value.GetRawText(), + _ => throw new DomainValidationException("Das Topic erwartet eine endliche Zahl oder einen digitalen Zustand.") + }; } if (string.IsNullOrWhiteSpace(mapping.JsonProperty)) @@ -354,7 +477,19 @@ public sealed class MqttClientService : BackgroundService _ => throw new ArgumentOutOfRangeException(nameof(qualityOfService)) }; - private void SetStatus(MqttClientStatus status) => Volatile.Write(ref _status, status); + private void RecordPayloadError(string direction, MqttMapping mapping, DomainValidationException exception) => + UpdateStatus(status => status with { LastError = $"{direction} · {GatewayStore.GetMqttTopic(mapping)} · {exception.Message}" }); - private void UpdateStatus(Func update) => SetStatus(update(GetStatus())); + private void UpdateStatus(Func 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)); + } } diff --git a/src/Gateway.Api/Services/MqttExternalTopics.cs b/src/Gateway.Api/Services/MqttExternalTopics.cs new file mode 100644 index 0000000..01c3998 --- /dev/null +++ b/src/Gateway.Api/Services/MqttExternalTopics.cs @@ -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 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 + }; + } +} diff --git a/src/Gateway.Api/Services/MqttTopicBrowserService.cs b/src/Gateway.Api/Services/MqttTopicBrowserService.cs new file mode 100644 index 0000000..dfc4034 --- /dev/null +++ b/src/Gateway.Api/Services/MqttTopicBrowserService.cs @@ -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 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 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 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 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 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); + } +} diff --git a/src/Gateway.Api/Services/NotificationTransport.cs b/src/Gateway.Api/Services/NotificationTransport.cs new file mode 100644 index 0000000..8f2220f --- /dev/null +++ b/src/Gateway.Api/Services/NotificationTransport.cs @@ -0,0 +1,126 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Gateway.Api.Domain; + +namespace Gateway.Api.Services; + +/// SE-Inno APIs use PHP-style multipart form fields, not Meta's direct JSON API. +public sealed class NotificationTransport(IHttpClientFactory clients) +{ + public static readonly IReadOnlyList 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 { ["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."); + } + } + } +} diff --git a/src/Gateway.Api/Services/OpcUaApplicationFactory.cs b/src/Gateway.Api/Services/OpcUaApplicationFactory.cs new file mode 100644 index 0000000..9fd6e22 --- /dev/null +++ b/src/Gateway.Api/Services/OpcUaApplicationFactory.cs @@ -0,0 +1,119 @@ +using Opc.Ua; +using Opc.Ua.Configuration; +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace Gateway.Api.Services; + +#pragma warning disable CS0618 // OPC UA 1.5 retains this constructor while its telemetry migration is in progress. + +/// Creates one persistent PKI layout for both OPC UA client and server roles. +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 CreateClientConfigurationAsync() + { + var configuration = CreateBaseConfiguration(ApplicationType.Client); + await configuration.ValidateAsync(ApplicationType.Client); + await EnsureCertificateAsync(configuration); + return configuration; + } + + public async Task CreateServerConfigurationAsync(int port, bool allowAnonymous) + { + var configuration = CreateBaseConfiguration(ApplicationType.Server); + configuration.ServerConfiguration = new ServerConfiguration + { + BaseAddresses = [$"opc.tcp://0.0.0.0:{port}"], + SecurityPolicies = [ + new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.Sign, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }, + new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.SignAndEncrypt, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 } + ], + UserTokenPolicies = allowAnonymous + ? [new UserTokenPolicy(UserTokenType.UserName), new UserTokenPolicy(UserTokenType.Anonymous)] + : [new UserTokenPolicy(UserTokenType.UserName)], + DiagnosticsEnabled = false, + MaxSessionCount = 100, + MaxChannelCount = 100 + }; + await configuration.ValidateAsync(ApplicationType.Server); + await EnsureCertificateAsync(configuration); + return configuration; + } + + private ApplicationConfiguration CreateBaseConfiguration(ApplicationType type) + { + var pkiDirectory = Path.Combine(_database.DataDirectory, "pki", "opcua"); + Directory.CreateDirectory(pkiDirectory); + return new ApplicationConfiguration + { + ApplicationName = "SE-Inno Universalgateway", + ApplicationUri = $"urn:{Utils.GetHostName()}:se-inno:universalgateway" + (type == ApplicationType.Server ? ":server" : ""), + ApplicationType = type, + ProductUri = "urn:se-inno:universalgateway", + SecurityConfiguration = new SecurityConfiguration + { + ApplicationCertificate = new CertificateIdentifier + { + StoreType = CertificateStoreType.Directory, + // Client certificates can lack server DNS names. Keep the existing + // client identity, and create a separate server identity without deleting it. + StorePath = Path.Combine(pkiDirectory, type == ApplicationType.Server ? "server-own" : "own"), + SubjectName = $"CN=SE-Inno Universalgateway{(type == ApplicationType.Server ? " Server" : "")}, DC={Utils.GetHostName()}" + }, + TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "trusted") }, + TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "issuers") }, + RejectedCertificateStore = new CertificateStoreIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pkiDirectory, "rejected") }, + AutoAcceptUntrustedCertificates = false, + AddAppCertToTrustedStore = true + }, + ClientConfiguration = new ClientConfiguration + { + DefaultSessionTimeout = 60_000, + WellKnownDiscoveryUrls = [] + }, + TransportQuotas = new TransportQuotas { OperationTimeout = 15_000, MaxMessageSize = 4 * 1024 * 1024 }, + TransportConfigurations = [] + }; + } + + private static async Task EnsureCertificateAsync(ApplicationConfiguration configuration) + { + await CertificateGate.WaitAsync(); + try + { + var identity = configuration.SecurityConfiguration.ApplicationCertificate; + if (configuration.ApplicationType == ApplicationType.Server && await identity.Find(false) is null) + { + // A wildcard listener address is not the address clients connect to. + // Include real local addresses in the first server certificate. Existing + // certificates are never silently replaced after a network change. + var names = configuration.GetServerDomainNames().Concat([Utils.GetHostName(), "localhost", "127.0.0.1", "::1"]) + .Concat(NetworkInterface.GetAllNetworkInterfaces().Where(adapter => adapter.OperationalStatus == OperationalStatus.Up) + .SelectMany(adapter => adapter.GetIPProperties().UnicastAddresses) + .Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork || address.Address.AddressFamily == AddressFamily.InterNetworkV6 && !address.Address.IsIPv6LinkLocal) + .Select(address => address.Address.ToString())).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + using var certificate = CertificateFactory.CreateCertificate(configuration.ApplicationUri, configuration.ApplicationName, identity.SubjectName, names) + .SetLifeTime(24).SetRSAKeySize(2048).CreateForRSA(); + using var certificateStore = identity.OpenStore(); + await certificateStore.AddAsync(certificate); + } + var application = new ApplicationInstance(configuration); + if (!await application.CheckApplicationInstanceCertificatesAsync(false, null, CancellationToken.None)) + throw new DomainValidationException("Das OPC-UA-Anwendungszertifikat konnte nicht erzeugt oder geladen werden."); + } + finally + { + CertificateGate.Release(); + } + } +} + +#pragma warning restore CS0618 diff --git a/src/Gateway.Api/Services/OpcUaBrowserService.cs b/src/Gateway.Api/Services/OpcUaBrowserService.cs new file mode 100644 index 0000000..e04a9bc --- /dev/null +++ b/src/Gateway.Api/Services/OpcUaBrowserService.cs @@ -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> 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> 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(); + var metadata = new Dictionary(); + 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(); + 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 diff --git a/src/Gateway.Api/Services/OpcUaClientService.cs b/src/Gateway.Api/Services/OpcUaClientService.cs new file mode 100644 index 0000000..0c73e10 --- /dev/null +++ b/src/Gateway.Api/Services/OpcUaClientService.cs @@ -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); + +/// One long-lived secure session/subscription per connection. Writes are never retried after an ambiguous result. +public sealed class OpcUaClientService(GatewayStore store, OpcUaApplicationFactory applications, ILogger logger) : BackgroundService +{ + private readonly ConcurrentDictionary _status = new(); + private readonly ConcurrentDictionary _workers = new(); + private int _disposed; + + public IReadOnlyList 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>(); + var seen = new Dictionary(); + // 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(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 Writes { get; } = Channel.CreateBounded(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 diff --git a/src/Gateway.Api/Services/OpcUaPointTypes.cs b/src/Gateway.Api/Services/OpcUaPointTypes.cs new file mode 100644 index 0000000..c9fba61 --- /dev/null +++ b/src/Gateway.Api/Services/OpcUaPointTypes.cs @@ -0,0 +1,45 @@ +using System.Text.Json; +using Opc.Ua; + +namespace Gateway.Api.Services; + +/// Explicit scalar conversions; no implicit Boolean/numeric or string/numeric coercion. +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."); +} diff --git a/src/Gateway.Api/Services/OpcUaServerService.cs b/src/Gateway.Api/Services/OpcUaServerService.cs new file mode 100644 index 0000000..97f1726 --- /dev/null +++ b/src/Gateway.Api/Services/OpcUaServerService.cs @@ -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. + +/// +/// 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. +/// +public sealed class OpcUaServerService : BackgroundService +{ + private readonly GatewayStore _store; + private readonly OpcUaApplicationFactory _applications; + private readonly ILogger _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 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 diff --git a/src/Gateway.Api/Services/SecretProtector.cs b/src/Gateway.Api/Services/SecretProtector.cs index e906265..b483799 100644 --- a/src/Gateway.Api/Services/SecretProtector.cs +++ b/src/Gateway.Api/Services/SecretProtector.cs @@ -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) diff --git a/src/Gateway.Api/Services/SessionService.cs b/src/Gateway.Api/Services/SessionService.cs index 83f70d0..cacf7ef 100644 --- a/src/Gateway.Api/Services/SessionService.cs +++ b/src/Gateway.Api/Services/SessionService.cs @@ -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 _sessions = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _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); } diff --git a/src/Gateway.Api/wwwroot/app.js b/src/Gateway.Api/wwwroot/app.js index 9081f69..1eb9dfe 100644 --- a/src/Gateway.Api/wwwroot/app.js +++ b/src/Gateway.Api/wwwroot/app.js @@ -1,12 +1,41 @@ const app = document.querySelector('#app'); -const state = { token: sessionStorage.getItem('seiugw-token'), view: 'overview', points: [], mappings: [], trendLogs: [], configuration: null, mqtt: null, mqttMappings: [], mqttStatus: null }; +const state = { token: sessionStorage.getItem('seiugw-token'), user: null, preferences: null, view: 'overview', points: [], mappings: [], trendLogs: [], trendSelections: [], runnerJobs: [], mailIntegration: null, configuration: null, hardware: { networkInterfaces: [], serialDevices: [] }, mqtt: null, mqttMappings: [], mqttStatus: null, users: [], roles: [], permissionCatalog: [], userEditId: null }; +const can = permission => state.user?.permissions?.includes(permission); +Object.assign(state, { adminTab: 'aliases', pointsTab: 'points', presentation: { points: [], units: [] }, dashboard: [], notifications: [], alarms: [], deliveries: [], komari: null, alarmPointId: null, alarmEditId: null, alarmSource: '', aliasSource: '', runnerEditId: null }); + +function resolveTheme(theme) { + return theme === 'system' ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : theme; +} + +function applyTheme(theme) { + const selected = ['system', 'light', 'dark'].includes(theme) ? theme : 'system'; + document.documentElement.dataset.theme = resolveTheme(selected); + document.documentElement.dataset.themeMode = selected; + try { localStorage.setItem('seiugw-theme', selected); } catch { /* Private browsers may disable storage. */ } + document.querySelectorAll('button[data-theme]').forEach(button => { + const active = button.dataset.theme === selected; + button.classList.toggle('active', active); + button.setAttribute('aria-pressed', String(active)); + }); +} + +function applyStoredTheme() { + let theme = 'dark'; + try { theme = localStorage.getItem('seiugw-theme') || theme; } catch { /* Use the dark default. */ } + applyTheme(theme); +} + +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { + if (document.documentElement.dataset.themeMode === 'system') applyTheme('system'); +}); +applyStoredTheme(); async function api(path, options = {}) { const headers = { ...(options.headers || {}) }; if (state.token) headers.Authorization = `Bearer ${state.token}`; if (options.body) headers['Content-Type'] = 'application/json'; const response = await fetch(path, { ...options, headers }); - if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; await boot(); throw new Error('Sitzung abgelaufen.'); } + if (response.status === 401) { sessionStorage.removeItem('seiugw-token'); state.token = null; state.user = null; state.preferences = null; await boot(); throw new Error('Sitzung abgelaufen.'); } if (!response.ok) { const body = await response.json().catch(() => ({})); throw new Error(body.error || `Anfrage fehlgeschlagen (${response.status})`); @@ -29,12 +58,20 @@ async function boot() { const setup = await api('/api/setup'); if (!setup.adminConfigured) return renderSetup(); if (!state.token) return renderLogin(); + if (!state.user) state.user = (await api('/api/auth/me')).user; + if (!state.preferences) { + state.preferences = await api('/api/auth/preferences'); + applyTheme(state.preferences.theme); + } + state.view = can('view_dashboard') ? 'overview' : can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system'; await loadData(); + if (!can('view_dashboard')) state.view = can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system'; + if (can('manage_gateway') && new URLSearchParams(location.search).has('network-confirm')) state.view = 'system'; renderShell(); } function renderSetup() { - app.innerHTML = `
SG SEIU GATEWAY

Erstinbetriebnahme

Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.

Der Rechner wird als SE-UGW-P-ISP01 in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.
`; + app.innerHTML = `
SE-INNO UNIVERSALGATEWAY

Erstinbetriebnahme

Es gibt keinen Standardzugang. Das Passwort wird ausschließlich als Hash in der lokalen Datenbank abgelegt.

Der Rechner wird als SE-UGW-P-ISP01 in Komari angezeigt. Die Komari-Registrierung selbst nutzt einen nur auf dem Server hinterlegten Einmal-Schlüssel.
`; const updateHostName = () => { const project = document.querySelector('#setup-project').value.trim().toUpperCase() || 'P'; const isp = String(document.querySelector('#setup-isp').value || '1').padStart(2, '0'); @@ -52,40 +89,69 @@ function renderSetup() { } function renderLogin() { - app.innerHTML = `
SG SEIU GATEWAY

Anmelden

Lokaler Administrationszugang.

`; + app.innerHTML = `
SE-INNO UNIVERSALGATEWAY

Anmelden

Lokaler Zugang zum Gateway.

`; 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 `
Darstellung
${[['light','Hell'],['dark','Dunkel'],['system','System']].map(([value, label]) => ``).join('')}
`; } function renderShell() { - app.innerHTML = `
`; + const nav = `${can('view_dashboard') ? '' : ''}${can('view_trends') ? '' : ''}${can('manage_sources') || can('manage_gateway') || can('manage_integrations') ? '' : ''}${can('manage_sources') ? '' : ''}${adminTabs().length ? '' : ''}`; + const theme = state.preferences?.theme || 'system'; + app.innerHTML = `
`; + document.querySelector('#sidebar-logout').addEventListener('click', logout); + document.querySelector('.shell').classList.toggle('unpinned', state.preferences?.sidebarPinned === false); + document.querySelector('#sidebar-pin').addEventListener('click', async () => { try { state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ sidebarPinned: state.preferences?.sidebarPinned === false }) }); renderShell(); } catch (error) { window.alert(error.message); } }); document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => { state.view = button.dataset.view; renderView(); })); + document.querySelectorAll('button[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme))); renderView(); } function renderView() { document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view)); const content = document.querySelector('#content'); - const views = { overview: viewOverview, points: viewPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, protocols: viewProtocols, system: viewSystem }; + const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem }; content.innerHTML = views[state.view](); bindView(state.view); } function header(title, status = 'Konfiguration geladen') { - return `

${title}

${status}
`; + return `
ANSICHT

${title}

SE-Inno Universalgateway · ${escapeHtml(status)}
`; } function viewOverview() { @@ -98,78 +164,437 @@ function viewOverview() {
Datenpunkte
${state.points.length}
${state.points.filter(point => point.scope === 'External').length} extern
Mappings
${state.mappings.length}
Schreibownership geprüft
MQTT-Mappings
${state.mqttMappings.length}
${escapeHtml(mqttStatus)}
-

Inbetriebnahme

Projekt / ISP${installation}
Rechnername${hostName}
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.

Schreibregeln

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.

`; +

Inbetriebnahme

Projekt / ISP${installation}
Rechnername${hostName}
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.

Schreibregeln

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.

`; } function viewPoints() { - const rows = state.points.map(point => `${escapeHtml(point.displayName)}${point.protocol}${point.scope}${escapeHtml(point.valueType)}${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance !== null && point.bacnetObjectInstance !== undefined ? ` · ${point.bacnetObjectInstance}` : ''}${point.writable ? 'R/W' : 'R'}${escapeHtml(point.externalIdentity || '—')}`).join(''); - return `${header('Datenpunkte')}

Neuer Datenpunkt

Registrierte Punkte ${state.points.length}

${state.points.length ? `${rows}
NameProtokollBereichWerttypBACnet-ObjektZugriffIdentität
` : '
Noch keine Datenpunkte.
'}
`; + const editing = state.points.find(point => point.id === state.pointEditId); + const select = (options, value) => options.map(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 => ` + ${escapeHtml(point.displayName)} + ${escapeHtml(point.protocol)} + ${escapeHtml(point.scope)} + ${escapeHtml(point.valueType)} + ${escapeHtml(point.bacnetObjectKind || '—')}${point.bacnetObjectInstance == null ? '' : ` · ${point.bacnetObjectInstance}`} + ${(point.readable ? 'R' : '') + (point.readable && point.writable ? '/' : '') + (point.writable ? 'W' : '') || '—'} + ${escapeHtml((point.protocol === 'Mqtt' && point.address?.topic) || point.externalIdentity || '—')} +
+
+ `).join(''); + return `${header('Datenpunkte')}
+

${editing ? 'Datenpunkt bearbeiten' : 'Neuer Datenpunkt'}

+
+ +
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ ${editing ? '' : ''}
+
+
+
+

Registrierte Punkte ${state.points.length}

${configurationCsvButtons('points')}
+
+ ${rows ? `
+ ${rows}
NameProtokollBereichWerttypBACnet-ObjektZugriffIdentitätAktionen
` + : '
Noch keine Datenpunkte.
'} +
+
`; +} + +function mappingPointOptions(selected, detail) { + const options = state.points.map(point => + ``); + if (selected && !state.points.some(point => point.id === selected)) + options.unshift(``); + return options.join(''); +} + +function mappingActions(id, kind) { + return `
+ + +
`; } function viewMappings() { - const pointOptions = state.points.map(point => ``).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 => `${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)}${mapping.direction === 'Bidirectional' ? '⇄' : '→'}${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)}${mapping.bacnetPriority || '—'}${mapping.enabled ? 'aktiv' : 'inaktiv'}`).join(''); - return `${header('Mappings')}

Mapping anlegen

${state.points.length < 2 ? '
Mindestens zwei Punkte anlegen, bevor ein Mapping erzeugt werden kann.
' : `
`}

Aktive Mapping-Tabelle

${state.mappings.length ? `${rows}
QuelleZielPrioStatus
` : '
Noch keine Mappings.
'}
`; + const rows = state.mappings.map(mapping => ` + ${escapeHtml(names[mapping.sourcePointId] || mapping.sourcePointId)} + ${mapping.direction === 'Bidirectional' ? '⇄' : '→'} + ${escapeHtml(names[mapping.targetPointId] || mapping.targetPointId)} + ${mapping.bacnetPriority ?? '—'} + ${mapping.enabled ? 'aktiv' : 'inaktiv'} + ${mappingActions(mapping.id, 'mapping')} + `).join(''); + const form = state.points.length < 2 && !editing ? '
Für ein Mapping werden zwei Datenpunkte benötigt.
' : ` +
+ + +
+ + +
+ + + +
+ ${editing ? '' : ''}
+
+
`; + return `${header('Mappings')}${viewMappingBatch()}
+

${editing ? 'Mapping bearbeiten' : 'Mapping anlegen'}

${form}
+

Mapping-Tabelle

${configurationCsvButtons('mappings')}
+ ${rows ? `
${rows}
QuelleZielPrioStatusAktionen
` + : '
Noch keine Mappings.
'} +
+
`; } 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 => ``).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 `${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}${mapping.format === 'SeMonitoring' ? 'SE-Monitoring' : 'JSON'}${escapeHtml(mapping.direction)}${escapeHtml(entry.topic)}${escapeHtml(mapping.qualityOfService)}${mapping.retain ? 'ja' : 'nein'}`; + return `${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}${escapeHtml(mqttMappingFormatLabel(mapping.format))}${escapeHtml(mapping.direction)}${escapeHtml(entry.topic)}${escapeHtml(mapping.qualityOfService)}${mapping.retain ? 'ja' : 'nein'}${mappingActions(mapping.id, 'mqtt-mapping')}`; }).join(''); - return `${header('MQTT / MQTTS', connection)}

Broker-Verbindung

${status.connected ? 'online' : 'offline'}
Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.

SE-Monitoring-Schema

Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert

AnalogNur analoge Punkte (AI/AO/AV usw.)
NotifyNur digitale Zustände, keine Störungen
AlarmNur digitale Alarm-Punkte
SetpointsAnaloge oder digitale Sollwerte, immer senden und empfangen

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.

MQTT-Mapping anlegen

${pointOptions ? `

SE-Monitoring

JSON

` : '
Zuerst einen Datenpunkt anlegen.
'}

Konfigurierte MQTT-Mappings ${state.mqttMappings.length}

${state.mqttMappings.length ? `${rows}
PunktFormatRichtungTopicQoSRetain
` : '
Noch keine MQTT-Mappings.
'}
`; + return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}

Broker-Verbindung

${status.connected ? 'online' : 'offline'}
Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.

SE-Monitoring-Schema

Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert

AnalogNur analoge Punkte (AI/AO/AV usw.)
NotifyNur digitale Zustände, keine Störungen
AlarmsDigitale Alarm-Punkte
SetpointsAnaloge oder digitale Sollwerte, immer senden und empfangen

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.

${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}

${mqttMappingForm(editing)}

Konfigurierte MQTT-Mappings ${state.mqttMappings.length}

${configurationCsvButtons('mqtt')}
${state.mqttMappings.length ? `
${rows}
PunktFormatRichtungTopicQoSRetainAktionen
` : '
Noch keine MQTT-Mappings.
'}
`; } function viewTrends() { const pointNames = Object.fromEntries(state.points.map(point => [point.id, point.displayName])); const sourceOptions = state.points.filter(point => point.readable).map(point => ``).join(''); - const rows = state.trendLogs.map(log => `${escapeHtml(log.name)}${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}${log.bacnetObjectInstance}${log.intervalSeconds}s${log.maxRecords.toLocaleString('de-DE')}${log.enabled ? 'aktiv' : 'inaktiv'}`).join(''); - return `${header('Trend Logs')}

Internes Trend Log

${sourceOptions ? `
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.
` : '
Zuerst mindestens einen lesbaren Datenpunkt anlegen.
'}

Konfigurierte Trend Logs

${state.trendLogs.length ? `${rows}
NameQuelleBACnetIntervallRetentionStatus
` : '
Noch keine Trend Logs.
'}
`; + const rows = state.trendLogs.map(log => `${escapeHtml(log.name)}${escapeHtml(pointNames[log.sourcePointId] || log.sourcePointId)}${log.bacnetObjectInstance}${log.intervalSeconds}s${log.maxRecords.toLocaleString('de-DE')}${log.isPublic ? `öffentlich` : 'intern'}${log.enabled ? 'aktiv' : 'inaktiv'}`).join(''); + const createPanel = can('manage_sources') ? (sourceOptions ? `
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.
` : '
Zuerst mindestens einen lesbaren Datenpunkt anlegen.
') : '
Ihre Rolle darf Trenddaten ansehen, aber keine Trend Logs anlegen oder verändern.
'; + const selectionOptions = state.trendLogs.map(log => ``).join(''); + const selectionRows = state.trendSelections.map(selection => `${escapeHtml(selection.name)}${selection.trendLogIds.length}${selection.shared ? 'geteilt' : 'privat'}${selection.ownerId === state.user?.user?.id || state.user?.user?.role === 'admin' ? `` : '—'}`).join(''); + const selectionPanel = state.trendLogs.length ? `

Trend-Gruppe speichern

Gespeicherte Gruppen

${state.trendSelections.length}
${selectionRows ? `${selectionRows}
NameLogsZugriff
` : '
Noch keine Trend-Gruppe gespeichert.
'}
` : ''; + return `${header('Trend Logs')}

Internes Trend Log

${createPanel}

Konfigurierte Trend Logs

${state.trendLogs.length ? `${rows}
NameQuelleBACnetIntervallRetentionFreigabeStatus
` : '
Noch keine Trend Logs.
'}
${selectionPanel}`; +} + +function viewRunner() { + const selections = state.trendSelections; + const selectionOptions = selections.map(selection => ``).join(''); + const rows = state.runnerJobs.map(job => `${escapeHtml(job.name)}${escapeHtml(selections.find(selection => selection.id === job.selectionId)?.name || job.selectionId)}${escapeHtml(job.time)} · ${job.rangeHours}h${job.mailEnabled ? escapeHtml(job.mailTo || '—') : 'kein Mailversand'}${job.enabled ? 'aktiv' : 'inaktiv'}${job.lastResult ? (job.lastResult.success ? `${escapeHtml(new Date(job.lastResult.ranAtUtc).toLocaleString())}` : `${escapeHtml(job.lastResult.error || 'Fehler')}`) : 'noch nicht gelaufen'}
`).join(''); + const mail = state.mailIntegration || { mailConfigured: false, endpoint: 'https://mailapi.se-inno.de' }; + const mailPanel = can('manage_integrations') ? `

Mail-API

${mail.mailConfigured ? 'Key gespeichert' : 'kein Key'}

Endpoint: ${escapeHtml(mail.endpoint)}. Der Key wird verschlüsselt in der lokalen Datenbank abgelegt.

` : ''; + const create = selections.length ? `
` : '
Zuerst in Trend Logs eine gespeicherte Trend-Gruppe anlegen.
'; + return `${header('CSV Runner')}

Neuer Job

${create}
${mailPanel}

Vorhandene Runner

${state.runnerJobs.length}
${rows ? `${rows}
NameAuswahlLaufzeitMailStatusLetztes Ergebnis
` : '
Keine Runner-Jobs angelegt.
'}
`; +} + +function bacnetInterfaceOptions(selected) { + const interfaces = state.hardware.networkInterfaces; + const missing = selected && !interfaces.some(card => card.name === selected) + ? `` : ''; + return missing + interfaces.map(card => + `` + ).join(''); } function viewProtocols() { const c = state.configuration; - return `${header('Protokolle')}

BACnet/IP

B-BC

OPC UA & Modbus

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.

KNXnet/IP

vorgesehen

Routing, Tunneling und KNX Secure bleiben vorbereitet, werden aber erst nach BACnet, OPC UA und Modbus aktiviert.

`; + const servers = c.modbusServers || []; + const serialPorts = c.serialPorts || []; + const aliases = serialPorts.map(port => ``).join(''); + const serialDeviceOptions = (state.hardware?.serialDevices || []).map(device => ``).join(''); + const serverRows = servers.map(server => `${escapeHtml(server.name)}${escapeHtml(server.bindAddress)}:${server.port}${server.unitId}${server.firstHoldingRegister}–${server.firstHoldingRegister + server.holdingRegisterCount - 1}${server.allowedClientIps?.length ? escapeHtml(server.allowedClientIps.join(', ')) : 'alle'}`).join(''); + const serialRows = serialPorts.map(port => `${escapeHtml(port.alias)}${escapeHtml(port.devicePath)}${port.baudRate}, ${escapeHtml(port.parity)}, ${port.dataBits}/${port.stopBits}`).join(''); + return `${header('Protokolle')}${serialDeviceOptions} + ${pointPanel('bacnet', `

BACnet/IP

Native Objekte

Die Liste bietet alle auf diesem Gateway sichtbaren Netzwerkschnittstellen an.

`)} + ${pointPanel('opcua', `

OPC UA

Client + Server
Serverzertifikat, Trustlist und Clientzertifikate liegen persistent unter /var/lib/seiugw/pki. Für den Produktivbetrieb bleibt anonymer Zugriff deaktiviert.
`)} + ${pointPanel('modbus', `

Modbus-TCP-Server

${servers.length}
+

TCP-Serverinstanzen

${servers.length ? `${serverRows}
NameBindungUnitHoldingClient-Allowlist
` : '
Keine Modbus-TCP-Serverinstanz angelegt.
'}
+

Modbus-Datenpunkte importieren

Unterstützt TCP und RTU, Coil, Discrete Input, Input/Holding Register sowie UInt16/Int16/UInt32/Int32/Float32/Word-Swap.

`)} + ${pointPanel('knx', `

KNX

Der Import übernimmt Gruppenadresse und DPT als externe KNX-Datenpunkte. Bereits vorhandene Gruppenadressen werden übersprungen.

`)} + ${pointPanel('serial', `

USB / COM-Aliase

Die Liste enthält die aktuell sichtbaren USB-/COM-Geräte. Ein stabiler /dev/serial/by-id/…-Pfad ist vorzuziehen.

+

Serielle Schnittstellen

${serialPorts.length ? `${serialRows}
AliasGerätParameter
` : '
Noch kein USB-/COM-Port aliasiert.
'}
Modbus RTU verwendet diese Aliase direkt in der CSV (SerialPortAlias). KNX TP verwendet denselben Alias für einen USB-TP-Adapter.
`)}`; } -function viewSystem() { - return `${header('System')}

Passwort ändern

Audit

Wird geladen …
`; +function viewSystem(section = 'settings') { + const theme = state.preferences?.theme || 'system'; + const roleOptions = state.roles.map(role => ``).join(''); + const editUser = state.users.find(user => user.id === state.userEditId) || null; + const userRows = state.users.map(user => `${escapeHtml(user.username)}${escapeHtml(user.displayName)}${escapeHtml(user.email || '—')}${escapeHtml(user.role)}${user.active ? 'aktiv' : 'deaktiviert'}
${user.id === state.user?.user?.id ? '' : ``}
`).join(''); + const roleRows = state.roles.map(role => `${escapeHtml(role.label)}${escapeHtml(role.name)}${role.permissions.map(permission => `${escapeHtml(permission)}`).join(' ')}${role.isSystem ? 'System' : 'Benutzerdefiniert'}`).join(''); + const auditPanel = can('view_debug') ? '

Audit

Wird geladen …
' : ''; + const userPanel = can('manage_users') ? `

${editUser ? `Benutzer bearbeiten · ${escapeHtml(editUser.username)}` : 'Benutzer anlegen'}

${editUser ? '' : ''}
${editUser ? '' : ''}

Konten

${state.users.length}
${userRows ? `${userRows}
BenutzerNameE-MailRolleStatus
` : '
Keine Konten.
'}
` : ''; + const rolePanel = can('manage_roles') ? `

Benutzerdefinierte Rolle

Verfügbar: ${state.permissionCatalog.map(permission => `${escapeHtml(permission)}`).join(', ')}

Rollen

${roleRows}
BezeichnungNameBerechtigungenTyp
` : ''; + if (section === 'users') return userPanel; + if (section === 'roles') return rolePanel; + if (section === 'debug') return auditPanel; + return `${header('Einstellungen')}

Passwort ändern

Darstellung

${can('manage_gateway') ? viewInstallationSettings() : ''}
${can('manage_gateway') ? '

Netzwerk · IPv4

Netzwerkstatus wird geladen …

' : ''}`; } function bindView(view) { - if (view === 'points') document.querySelector('#point-form')?.addEventListener('submit', submitPoint); - if (view === 'mappings') document.querySelector('#mapping-form')?.addEventListener('submit', submitMapping); - if (view === 'mqtt') { document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration); document.querySelector('#mqtt-mapping-form')?.addEventListener('submit', submitMqttMapping); } - if (view === 'trends') document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog); - if (view === 'protocols') document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet); - if (view === 'system') { document.querySelector('#password-form').addEventListener('submit', submitPassword); document.querySelector('#logout').addEventListener('click', logout); loadAudit(); } + if (view === 'overview') return bindDashboard(); + if (view === 'admin') return bindAdmin(); + if (view === 'points') { + bindPointTabs(); + bindGatewayStatus(); + // Keep each panel mounted: tab/theme changes must not discard forms or browse results. + if (can('manage_gateway')) bindView('protocols'); + if (can('manage_integrations')) bindView('mqtt'); + } + if (view === 'points' && can('manage_sources')) { + bindPointEditor(); + bindConfigurationCsv('points', 'point-list-message'); + } + if (view === 'mappings') { + bindMappingEditor('mapping', submitMapping); + bindMappingBatch(); + bindConfigurationCsv('mappings', 'mapping-list-message'); + } + if (view === 'mqtt') { + bindMqttTopicBrowser(); + document.querySelector('#mqtt-configuration-form')?.addEventListener('submit', submitMqttConfiguration); + bindMqttMappingOptions(document.querySelector('#mqtt-mapping-form')); + bindMappingEditor('mqtt-mapping', submitMqttMapping); + bindConfigurationCsv('mqtt', 'mqtt-mapping-list-message'); + } + if (view === 'trends') { + bindTrendViewer(); + document.querySelector('#trend-form')?.addEventListener('submit', submitTrendLog); + document.querySelector('#trend-selection-form')?.addEventListener('submit', submitTrendSelection); + document.querySelectorAll('[data-delete-selection]').forEach(button => button.addEventListener('click', deleteTrendSelection)); + } + if (view === 'runner') { + document.querySelector('#runner-form')?.addEventListener('submit', submitRunnerJob); + document.querySelector('#mail-integration-form')?.addEventListener('submit', submitMailIntegration); + document.querySelectorAll('[data-test-runner]').forEach(button => button.addEventListener('click', testRunnerJob)); + document.querySelectorAll('[data-delete-runner]').forEach(button => button.addEventListener('click', deleteRunnerJob)); + } + if (view === 'protocols') { + if (can('manage_sources')) { renderBacnetBrowser(); renderOpcUaBrowser(); } + document.querySelector('#bacnet-form')?.addEventListener('submit', submitBacnet); + document.querySelector('#bacnet-scan-form')?.addEventListener('submit', submitBacnetScan); + document.querySelector('#opcua-form')?.addEventListener('submit', submitOpcUa); + document.querySelector('#opcua-browse-form')?.addEventListener('submit', submitOpcUaBrowse); + document.querySelector('#modbus-server-form')?.addEventListener('submit', submitModbusServer); + document.querySelector('#serial-port-form')?.addEventListener('submit', submitSerialPort); + document.querySelector('#modbus-import-form')?.addEventListener('submit', submitModbusImport); + document.querySelector('#download-modbus-example')?.addEventListener('click', downloadModbusExample); + document.querySelector('#knx-form')?.addEventListener('submit', submitKnx); + document.querySelector('#knx-ets-import')?.addEventListener('click', submitKnxEtsImport); + document.querySelectorAll('[data-remove-modbus-server]').forEach(button => button.addEventListener('click', removeModbusServer)); + document.querySelectorAll('[data-remove-serial-port]').forEach(button => button.addEventListener('click', removeSerialPort)); + } + if (view === 'system') { + document.querySelector('#password-form')?.addEventListener('submit', submitPassword); + bindInstallationSettings(); + const networkPanel = document.querySelector('#host-network'); + if (networkPanel) bindHostNetwork(networkPanel); + document.querySelector('#content').querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme))); + document.querySelector('#user-form')?.addEventListener('submit', submitUser); + const userPassword = document.querySelector('#user-form [name=password]'); + const userConfirmation = document.querySelector('#user-form [name=passwordConfirmation]'); + if (userConfirmation) userPassword.addEventListener('input', () => { + userConfirmation.required = Boolean(userPassword.value); + }); + document.querySelector('#cancel-user-edit')?.addEventListener('click', () => { state.userEditId = null; renderView(); }); + document.querySelector('#role-form')?.addEventListener('submit', submitRole); + document.querySelectorAll('[data-edit-user]').forEach(button => button.addEventListener('click', () => { state.userEditId = button.dataset.editUser; renderView(); })); + document.querySelectorAll('[data-toggle-user]').forEach(button => button.addEventListener('click', toggleUser)); + if (document.querySelector('#audit-content')) loadAudit(); + } +} + +function renderBacnetBrowser() { + const card = document.querySelector('#bacnet-form')?.closest('article'); + if (card) { + card.querySelector('.tag').textContent = 'Native Objekte'; + card.insertAdjacentHTML('beforeend', '

Laufzeitstatus wird gelesen …

'); + 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', ``); +} + +function renderOpcUaBrowser() { + document.querySelector('#opcua-browser').insertAdjacentHTML('beforeend', `

OPC-UA-Browser

Gültigkeit und Zertifikatsangaben werden weiterhin geprüft. Gateway-Server: Web-Benutzer verwenden; Schreiben erfordert „Quellen verwalten“. Anonymer Zugriff ist nur lesend.

Gefundene Nodes

Noch keine Abfrage.
`); + 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', `
`); + form.querySelector('.buttons').insertAdjacentHTML('beforeend', ''); + const select = form.elements.clientId; + select.addEventListener('change', () => { + const saved = state.opcuaClients.clients.find(item => item.configuration.id === select.value); + form.elements.password.value = ''; form.elements.nodeId.value = ''; + document.querySelector('#opcua-browse-results').textContent = 'Noch keine Abfrage.'; + if (!saved) { document.querySelector('#opcua-client-status').textContent = ''; return; } + const c = saved.configuration; + form.elements.connectionName.value = c.name; form.elements.endpointUrl.value = c.endpointUrl; + form.elements.useSecurity.value = String(c.useSecurity); form.elements.authenticationMode.value = c.authenticationMode; + form.elements.username.value = c.username || ''; form.elements.publishingInterval.value = c.publishingIntervalMilliseconds; + form.elements.acceptUntrusted.checked = c.acceptUntrustedServerCertificate; form.elements.enabled.checked = c.enabled; + form.elements.password.placeholder = saved.hasPassword ? 'Gespeichert – leer lassen zum Beibehalten' : ''; + const status = state.opcuaClients.status.find(item => item.clientId === c.id); + document.querySelector('#opcua-client-status').textContent = status ? `${status.state} · ${status.subscribedPoints} abonnierte Punkte` : 'Deaktiviert / startet'; + }); + document.querySelector('#opcua-client-save').addEventListener('click', async () => { + try { + if (!form.reportValidity()) return; + const f = new FormData(form); + const configuration = { id: select.value || uuid(), name: String(f.get('connectionName')).trim(), endpointUrl: String(f.get('endpointUrl')).trim(), authenticationMode: f.get('authenticationMode'), username: String(f.get('username')).trim(), useSecurity: f.get('useSecurity') === 'true', acceptUntrustedServerCertificate: f.get('acceptUntrusted') === 'on', enabled: f.get('enabled') === 'on', publishingIntervalMilliseconds: Number(f.get('publishingInterval')) }; + const saved = await api('/api/opcua/clients', { method: 'POST', body: JSON.stringify({ configuration, password: String(f.get('password')) || null }) }); + await loadData(); + if (![...select.options].some(option => option.value === saved.configuration.id)) select.add(new Option(saved.configuration.name, saved.configuration.id)); + select.value = saved.configuration.id; select.dispatchEvent(new Event('change')); + errorTarget('opcua-browse-message', 'Gespeichert. Importierte Punkte werden automatisch abonniert.', true); + } catch (error) { errorTarget('opcua-browse-message', error.message); } + }); +} + +function bindPointEditor() { + const form = document.querySelector('#point-form'); + if (!form) return; + function syncFields() { + const external = form.elements.scope.value === 'External'; + const bacnet = form.elements.protocol.value === 'Bacnet' && form.elements.scope.value !== 'Internal'; + form.querySelector('[data-point-external]').hidden = !external; + form.elements.externalIdentity.disabled = !external; + form.elements.externalIdentity.required = external; + form.querySelector('[data-point-bacnet]').hidden = !bacnet; + form.elements.bacnetObjectKind.disabled = form.elements.bacnetObjectInstance.disabled = !bacnet; + form.elements.bacnetObjectKind.required = bacnet && form.elements.scope.value === 'Gateway'; + } + syncFields(); + form.elements.protocol.addEventListener('change', syncFields); + form.elements.scope.addEventListener('change', syncFields); + form.addEventListener('submit', submitPoint); + document.querySelectorAll('[data-edit-point]').forEach(button => button.addEventListener('click', () => { + state.pointEditId = button.dataset.editPoint; + renderView(); + document.querySelector('#point-form input[name="displayName"]')?.focus(); + })); + document.querySelector('#cancel-point-edit')?.addEventListener('click', () => { + state.pointEditId = null; + renderView(); + }); + document.querySelectorAll('[data-delete-point]').forEach(button => button.addEventListener('click', () => deletePoint(button))); } async function submitPoint(event) { - event.preventDefault(); const form = new FormData(event.currentTarget); + event.preventDefault(); + const form = new FormData(event.currentTarget); + const id = state.pointEditId; + const submit = event.currentTarget.querySelector('button[type="submit"]'); + submit.disabled = true; try { const address = JSON.parse(form.get('address')); const scope = form.get('scope'); const objectInstance = form.get('bacnetObjectInstance'); - await api('/api/points', { method: 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: true, writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) }); + await api(id ? `/api/points/${encodeURIComponent(id)}` : '/api/points', { method: id ? 'PUT' : 'POST', body: JSON.stringify({ displayName: form.get('displayName'), protocol: form.get('protocol'), scope, valueType: form.get('valueType'), readable: form.get('readable') === 'on', writable: form.get('writable') === 'on', externalIdentity: scope === 'External' ? form.get('externalIdentity') : null, address, bacnetObjectKind: form.get('bacnetObjectKind') || null, bacnetObjectInstance: objectInstance ? Number(objectInstance) : null }) }); + state.pointEditId = null; await loadData(); renderView(); - } catch (error) { errorTarget('point-message', error.message); } + errorTarget('point-list-message', id ? 'Änderungen gespeichert.' : 'Datenpunkt angelegt.', true); + } catch (error) { + errorTarget('point-message', error instanceof SyntaxError ? 'Die Adresse enthält ungültiges JSON.' : error.message); + } finally { submit.disabled = false; } +} + +async function deletePoint(button) { + const id = button.dataset.deletePoint; + const point = state.points.find(item => item.id === id); + if (!point) return; + button.disabled = true; + try { + const path = `/api/points/${encodeURIComponent(id)}`; + const usage = await api(path + '/dependencies'); + const effects = [ + usage.mappings && `${usage.mappings} Mapping(s) werden entfernt.`, + usage.mqttMappings && `${usage.mqttMappings} MQTT-Zuordnung(en) werden entfernt.`, + usage.alarms && `${usage.alarms} Alarmregel(n) werden entfernt.`, + usage.trendLogs && `${usage.trendLogs} Trendlog(s) werden gestoppt. Aufzeichnungen bleiben abrufbar.` + ].filter(Boolean); + if (!window.confirm([`Datenpunkt „${point.displayName}“ löschen?`, ...effects].join('\n'))) return; + await api(path + '?confirmation=' + encodeURIComponent(usage.confirmation), { method: 'DELETE' }); + if (state.pointEditId === id) state.pointEditId = null; + await loadData(); renderView(); + errorTarget('point-list-message', 'Datenpunkt gelöscht.', true); + } catch (error) { + errorTarget('point-list-message', error.message); + } finally { button.disabled = false; } +} + +function bindMappingEditor(kind, submit) { + const mqtt = kind === 'mqtt-mapping'; + const editKey = mqtt ? 'mqttMappingEditId' : 'mappingEditId'; + const endpoint = mqtt ? '/api/mqtt/mappings' : '/api/mappings'; + const form = document.querySelector(`#${kind}-form`); + form?.addEventListener('submit', submit); + document.querySelectorAll(`[data-edit-${kind}]`).forEach(button => button.addEventListener('click', () => { + state[editKey] = button.getAttribute(`data-edit-${kind}`); + renderView(); + document.querySelector(`#${kind}-form select`)?.focus(); + })); + document.querySelector(`#cancel-${kind}-edit`)?.addEventListener('click', () => { + state[editKey] = null; + renderView(); + }); + document.querySelectorAll(`[data-delete-${kind}]`).forEach(button => button.addEventListener('click', async () => { + const id = button.getAttribute(`data-delete-${kind}`); + if (!window.confirm(mqtt ? 'MQTT-Verknüpfung löschen?' : 'Verknüpfung zwischen diesen Datenpunkten löschen?')) return; + button.disabled = true; + try { + await api(`${endpoint}/${encodeURIComponent(id)}`, { method: 'DELETE' }); + if (state[editKey] === id) state[editKey] = null; + await loadData(); + renderView(); + errorTarget(`${kind}-list-message`, 'Verknüpfung gelöscht.', true); + } catch (error) { + errorTarget(`${kind}-list-message`, error.message); + } finally { + button.disabled = false; + } + })); } async function submitMapping(event) { - event.preventDefault(); const form = new FormData(event.currentTarget); + event.preventDefault(); + const form = new FormData(event.currentTarget); + const id = state.mappingEditId; + const submit = event.currentTarget.querySelector('button[type="submit"], button:not([type])'); + submit.disabled = true; try { - const priority = form.get('bacnetPriority'); const transform = JSON.parse(form.get('transform')); - const response = await api('/api/mappings', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'), direction: form.get('direction'), enabled: true, bacnetPriority: priority ? Number(priority) : null, acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform }) }); + const priority = form.get('bacnetPriority'); + const transform = JSON.parse(form.get('transform')); + const response = await api(id ? `/api/mappings/${encodeURIComponent(id)}` : '/api/mappings', { + method: id ? 'PUT' : 'POST', + body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), targetPointId: form.get('targetPointId'), + direction: form.get('direction'), enabled: form.get('enabled') === 'on', bacnetPriority: priority ? Number(priority) : null, + acknowledgeMultipleExternalWriters: form.get('acknowledge') === 'on', transform }) + }); + state.mappingEditId = null; await loadData(); renderView(); - if (response.warnings?.length) window.alert(response.warnings.join('\n')); - } catch (error) { errorTarget('mapping-message', error.message); } + errorTarget('mapping-list-message', response.warnings?.length ? response.warnings.join(' ') : 'Mapping gespeichert.', !response.warnings?.length); + } catch (error) { + errorTarget('mapping-message', error instanceof SyntaxError ? 'Die Transformation enthält ungültiges JSON.' : error.message); + } finally { submit.disabled = false; } } async function submitMqttConfiguration(event) { @@ -179,46 +604,292 @@ async function submitMqttConfiguration(event) { try { const password = String(form.get('password') || ''); await api('/api/mqtt/configuration', { method: 'PUT', body: JSON.stringify({ configuration: { enabled: form.get('enabled') === 'on', host: String(form.get('host') || '').trim(), port: Number(form.get('port')), useTls: form.get('useTls') === 'on', ignoreCertificateErrors, clientId: String(form.get('clientId') || '').trim(), username: String(form.get('username') || '').trim() || null }, password: password || null, clearPassword: form.get('clearPassword') === 'on' }) }); + state.mqttBrowser = null; await loadData(); renderView(); errorTarget('mqtt-configuration-message', 'Gespeichert; die Verbindung wird neu aufgebaut.', true); } catch (error) { errorTarget('mqtt-configuration-message', error.message); } } async function submitMqttMapping(event) { - event.preventDefault(); const form = new FormData(event.currentTarget); + event.preventDefault(); + const form = new FormData(event.currentTarget); + const id = state.mqttMappingEditId; + const submit = event.currentTarget.querySelector('button[type="submit"]'); + submit.disabled = true; try { - const format = form.get('format'); - await api('/api/mqtt/mappings', { method: 'POST', body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'), qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on', projectYear: format === 'SeMonitoring' ? Number(form.get('projectYear')) : null, projectNumber: format === 'SeMonitoring' ? form.get('projectNumber') : null, ispNumber: format === 'SeMonitoring' ? form.get('ispNumber') : null, seCategory: format === 'SeMonitoring' ? form.get('seCategory') : null, topicName: format === 'SeMonitoring' ? form.get('topicName') : null, jsonTopic: format === 'Json' ? form.get('jsonTopic') : null, jsonProperty: format === 'Json' ? form.get('jsonProperty') : null }) }); + const format = form.has('seMonitoring') ? 'SeMonitoring' : form.get('freeFormat'); + const monitoring = format === 'SeMonitoring'; + await api(id ? `/api/mqtt/mappings/${encodeURIComponent(id)}` : '/api/mqtt/mappings', { + method: id ? 'PUT' : 'POST', + body: JSON.stringify({ pointId: form.get('pointId'), format, direction: form.get('direction'), + qualityOfService: form.get('qualityOfService'), retain: form.get('retain') === 'on', + ...(monitoring ? mqttSiteFromForm(form) : {}), seCategory: monitoring ? form.get('seCategory') : null, + topicName: monitoring ? form.get('topicName') : null, jsonTopic: monitoring ? null : form.get('jsonTopic'), + jsonProperty: format === 'Json' ? form.get('jsonProperty') : null }) + }); + state.mqttMappingEditId = null; await loadData(); renderView(); + errorTarget('mqtt-mapping-list-message', 'MQTT-Mapping gespeichert.', true); } catch (error) { errorTarget('mqtt-mapping-message', error.message); } + finally { submit.disabled = false; } } async function submitTrendLog(event) { event.preventDefault(); const form = new FormData(event.currentTarget); try { - await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true }) }); + await api('/api/trend-logs', { method: 'POST', body: JSON.stringify({ sourcePointId: form.get('sourcePointId'), name: form.get('name'), bacnetObjectInstance: Number(form.get('bacnetObjectInstance')), intervalSeconds: Number(form.get('intervalSeconds')), maxRecords: Number(form.get('maxRecords')), enabled: true, isPublic: form.get('isPublic') === 'on' }) }); await loadData(); renderView(); } catch (error) { errorTarget('trend-message', error.message); } } +async function submitTrendSelection(event) { + event.preventDefault(); const form = new FormData(event.currentTarget); + try { + await api('/api/trend-selections', { method: 'POST', body: JSON.stringify({ name: form.get('name'), description: String(form.get('description') || '').trim() || null, shared: form.get('shared') === 'on', trendLogIds: form.getAll('trendLogIds') }) }); + await loadData(); renderView(); + } catch (error) { errorTarget('trend-selection-message', error.message); } +} + +async function deleteTrendSelection(event) { + const id = event.currentTarget.dataset.deleteSelection; + if (!window.confirm('Diese gespeicherte Trend-Gruppe löschen?')) return; + try { await api(`/api/trend-selections/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); } + catch (error) { errorTarget('trend-selection-message', error.message); } +} + +async function submitRunnerJob(event) { + event.preventDefault(); const form = new FormData(event.currentTarget); + try { + await api('/api/runner/jobs', { method: 'POST', body: JSON.stringify({ name: form.get('name'), selectionId: form.get('selectionId'), time: form.get('time'), rangeHours: Number(form.get('rangeHours')), delimiter: form.get('delimiter'), enabled: form.get('enabled') === 'on', mailEnabled: form.get('mailEnabled') === 'on', mailTo: String(form.get('mailTo') || '').trim() || null, mailSubject: String(form.get('mailSubject') || '').trim() || null, mailMessage: String(form.get('mailMessage') || '').trim() || null }) }); + await loadData(); renderView(); + } catch (error) { errorTarget('runner-message', error.message); } +} + +async function testRunnerJob(event) { + const button = event.currentTarget; + try { + const result = await api(`/api/runner/jobs/${encodeURIComponent(button.dataset.testRunner)}/test`, { method: 'POST' }); + await loadData(); renderView(); + window.alert(result.success ? `CSV erzeugt: ${result.filePath}${result.filePath && state.runnerJobs.find(job => job.id === button.dataset.testRunner)?.mailEnabled ? '\nMailversand abgeschlossen.' : ''}` : `CSV-Runner fehlgeschlagen: ${result.error}`); + } catch (error) { window.alert(`CSV-Runner fehlgeschlagen: ${error.message}`); } +} + +async function deleteRunnerJob(event) { + const id = event.currentTarget.dataset.deleteRunner; + if (!window.confirm('Diesen CSV-Runner-Job löschen?')) return; + try { await api(`/api/runner/jobs/${encodeURIComponent(id)}`, { method: 'DELETE' }); await loadData(); renderView(); } + catch (error) { window.alert(error.message); } +} + +async function submitMailIntegration(event) { + event.preventDefault(); const form = new FormData(event.currentTarget); + try { + const apiKey = String(form.get('apiKey') || '').trim(); const clearApiKey = form.get('clearApiKey') === 'on'; + if (!apiKey && !clearApiKey) throw new Error('Bitte einen neuen API-Key eintragen oder das Löschen auswählen.'); + await api('/api/integrations/mail', { method: 'PUT', body: JSON.stringify({ apiKey: apiKey || null, clearApiKey }) }); + await loadData(); renderView(); + } catch (error) { errorTarget('mail-integration-message', error.message); } +} + async function submitBacnet(event) { event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration; try { c.deviceInstance = Number(form.get('deviceInstance')); c.deviceName = `SEIU-Gateway-${c.deviceInstance}`; c.bacnet.interface = form.get('interface'); c.bacnet.ipPort = Number(form.get('ipPort')); c.bacnet.bbmdMode = form.get('bbmdMode'); c.bacnet.bbmdAddress = form.get('bbmdAddress') || null; c.bacnet.foreignDeviceTtlSeconds = form.get('ttl') ? Number(form.get('ttl')) : null; - await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Aktivierung erfolgt beim nächsten Adapter-Start.', true); + await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(c) }); await loadData(); errorTarget('bacnet-message', 'Gespeichert. Der native Dienst übernimmt die Änderung automatisch; Netzwerkänderungen lösen einen kurzen Neustart aus. Abweichende Ports müssen auch in der NixOS-Firewall freigegeben sein.', true); } catch (error) { errorTarget('bacnet-message', error.message); } } +async function submitBacnetScan(event) { + event.preventDefault(); const form = new FormData(event.currentTarget); + try { + const devices = await api('/api/bacnet/scan', { method: 'POST', body: JSON.stringify({ interface: String(form.get('interface') || '').trim() || null, targetAddress: String(form.get('targetAddress') || '').trim() || null, targetPort: Number(form.get('targetPort')), timeoutSeconds: Number(form.get('timeoutSeconds')) }) }); + renderBacnetDevices(devices, form.get('interface')); + errorTarget('bacnet-scan-message', `${devices.length} Gerät(e) gefunden.`, true); + } catch (error) { errorTarget('bacnet-scan-message', error.message); } +} + +async function saveGatewayConfiguration(messageTarget, message) { + try { + await api('/api/gateway/configuration', { method: 'PUT', body: JSON.stringify(state.configuration) }); + await loadData(); renderView(); errorTarget(messageTarget, message, true); + } catch (error) { errorTarget(messageTarget, error.message); } +} + +async function submitOpcUa(event) { + event.preventDefault(); const form = new FormData(event.currentTarget); const c = state.configuration; + c.opcUa.port = Number(form.get('port')); c.opcUa.clientEnabled = form.get('clientEnabled') === 'on'; c.opcUa.serverEnabled = form.get('serverEnabled') === 'on'; c.opcUa.allowAnonymous = form.get('allowAnonymous') === 'on'; + await saveGatewayConfiguration('opcua-message', 'Gespeichert. Der OPC-UA-Dienst übernimmt die Änderung automatisch.'); +} + +async function submitOpcUaBrowse(event) { + event.preventDefault(); const element = event.currentTarget; const form = new FormData(element); + const submit = element.querySelector('button[type="submit"], button:not([type])'); submit.disabled = true; + errorTarget('opcua-browse-message', 'Verbindung wird aufgebaut …', true); + try { + const clientId = form.get('clientId') || null; + if (clientId) { + const saved = state.opcuaClients.clients.find(item => item.configuration.id === clientId)?.configuration; + if (!saved || String(form.get('endpointUrl')).trim() !== saved.endpointUrl || form.get('authenticationMode') !== saved.authenticationMode || String(form.get('username')).trim() !== (saved.username || '') || (form.get('useSecurity') === 'true') !== saved.useSecurity || (form.get('acceptUntrusted') === 'on') !== saved.acceptUntrustedServerCertificate || form.get('password')) + throw new Error('Geänderte Verbindungsdaten bitte zuerst speichern. Browsen verwendet die gespeicherten Zugangsdaten.'); + } + const items = await api('/api/opcua/browse', { method: 'POST', body: JSON.stringify({ clientId, endpointUrl: String(form.get('endpointUrl')).trim(), nodeId: String(form.get('nodeId') || '').trim() || null, useSecurity: form.get('useSecurity') === 'true', authenticationMode: form.get('authenticationMode'), username: String(form.get('username') || '').trim(), password: String(form.get('password') || ''), acceptUntrustedServerCertificate: form.get('acceptUntrusted') === 'on' }) }); + const target = document.querySelector('#opcua-browse-results'); + target.innerHTML = items.length ? `${items.map(item => ``).join('')}
NameKlasseNodeIdWert
${escapeHtml(item.displayName)}${escapeHtml(item.nodeClass)}${escapeHtml(item.nodeId)}${item.value === null || item.value === undefined ? '—' : escapeHtml(typeof item.value === 'string' ? item.value : JSON.stringify(item.value))}${item.hasChildren ? `` : ''}
` : '
Keine untergeordneten Nodes.
'; + 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 ? `${entries.map(entry => ``).join('')}
${escapeHtml(new Date(entry.occurredAtUtc).toLocaleString())}${escapeHtml(entry.category)}${escapeHtml(entry.message)}
` : '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 = `

Startfehler

${escapeHtml(error.message)}

`; }); +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 = `

Startfehler

${escapeHtml(error.message)}

`; +}); diff --git a/src/Gateway.Api/wwwroot/assets/se-inno-logo.png b/src/Gateway.Api/wwwroot/assets/se-inno-logo.png new file mode 100644 index 0000000..7f03bb4 Binary files /dev/null and b/src/Gateway.Api/wwwroot/assets/se-inno-logo.png differ diff --git a/src/Gateway.Api/wwwroot/assets/se-ltd-dark.png b/src/Gateway.Api/wwwroot/assets/se-ltd-dark.png new file mode 100644 index 0000000..64d4fea Binary files /dev/null and b/src/Gateway.Api/wwwroot/assets/se-ltd-dark.png differ diff --git a/src/Gateway.Api/wwwroot/assets/se-ltd-light.png b/src/Gateway.Api/wwwroot/assets/se-ltd-light.png new file mode 100644 index 0000000..c14d036 Binary files /dev/null and b/src/Gateway.Api/wwwroot/assets/se-ltd-light.png differ diff --git a/src/Gateway.Api/wwwroot/bacnet-browser.js b/src/Gateway.Api/wwwroot/bacnet-browser.js new file mode 100644 index 0000000..9da67ea --- /dev/null +++ b/src/Gateway.Api/wwwroot/bacnet-browser.js @@ -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 ? ` + ${devices.map(device => ` + + + + + `).join('')}
GerätInstanzAdresseVendor
${escapeHtml(device.deviceName || '—')}${device.deviceInstance}${escapeHtml(device.address)}:${device.port}${device.network ? `
BACnet-Netz ${device.network} · ${escapeHtml(device.mac || '—')}
` : ''}
${device.vendorId ?? '—'}
` : '
Keine BACnet-Geräte gefunden.
'; + 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 = `
Device-Instanz ${device.deviceInstance} · ${escapeHtml(device.address)}
+
+ + + +
+
+
+
Typ / InstanzObjektnameBeschreibungAktueller Wert
+
`; + 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 ? 'angelegt' : object.valueType + ? `` : '—'; + return `${pick}${escapeHtml(object.objectType)} · ${object.objectInstance} + ${escapeHtml(object.name || '—')}${escapeHtml(object.description || '—')} + ${escapeHtml(object.value == null ? '—' : String(object.value))}`; + }).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); + } +} diff --git a/src/Gateway.Api/wwwroot/gateway-status.js b/src/Gateway.Api/wwwroot/gateway-status.js new file mode 100644 index 0000000..39216a6 --- /dev/null +++ b/src/Gateway.Api/wwwroot/gateway-status.js @@ -0,0 +1,160 @@ +function canViewGatewayStatus() { + return can('manage_sources') || can('manage_gateway') || can('manage_integrations'); +} + +function viewGatewayStatus() { + return `
+
+
+
+
`; +} + +function connectionStatusTag(text, tone = '') { + return `${escapeHtml(text)}`; +} + +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 `

${name}

${tag}
${content}
`; +} + +function statusError(text) { + return text ? `

${escapeHtml(text)}

` : ''; +} + +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, `
+
Broker
${escapeHtml(mqtt.endpoint || '—')}
+
Verbunden seit
${statusTime(mqtt.connectedAtUtc)}
+
Letzter Empfang
${statusTime(mqtt.lastReceivedAtUtc)}
+
Zuletzt gesendet
${statusTime(mqtt.lastPublishedAtUtc)}
+
${lastFailure ? `

Letzter Fehler · ${statusTime(mqtt.lastFailureAtUtc)}

${statusError(lastFailure)}` : ''}`)); + } + if (bacnet) { + cards.push(connectionStatusCard('BACnet/IP', bacnet.connected ? connectionStatusTag('Dienst aktiv') : connectionStatusTag('Dienst nicht erreichbar', 'warn'), + `
Letztes Lebenszeichen
${statusTime(bacnet.heartbeatUtc)}
+
Offene Befehle
${bacnet.pendingCommands}
+ ${bacnet.failedCommands.length ? `

Fehlgeschlagene Befehle

    ${bacnet.failedCommands.map(command => { + const name = state.points.find(point => point.id === command.pointId)?.displayName || command.pointId; + return `
  • ${escapeHtml(name)} · ${escapeHtml(command.result)} · ${statusTime(command.occurredAtUtc)}
  • `; + }).join('')}
` : ''} + ${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 ? `
    ${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 `
  • ${escapeHtml(client.name)} · ${escapeHtml(clientState)}${detail}
  • `; + }).join('')}
` : '

Keine Client-Verbindung eingerichtet.

'}`)); + } + if (modbus) { + cards.push(connectionStatusCard('Modbus TCP / RTU', '', ` + ${modbus.servers.length ? `
    ${modbus.servers.map(server => `
  • + ${escapeHtml(server.name)} · TCP ${server.port} · ${server.listening ? 'Lauscht' : 'Nicht bereit'} + ${statusError(server.error?.error)}
  • `).join('')}
` : '

Kein TCP-Server eingerichtet.

'} + ${modbus.pointErrors.length ? `

Lesefehler

    ${modbus.pointErrors.map(issue => + `
  • ${escapeHtml(issue.name)} · ${escapeHtml(issue.error)} · ${statusTime(issue.occurredAtUtc)}
  • `).join('')}
` : ''}`)); + } + if (snapshot.pointErrors) { + cards.push(connectionStatusCard('Datenpunktqualität', connectionStatusTag(`${snapshot.pointErrors.length} auffällig`, snapshot.pointErrors.length ? 'warn' : 'gray'), + snapshot.pointErrors.length ? `
+ ${snapshot.pointErrors.map(point => ``).join('')}
DatenpunktTreiberQualitätZeit
${escapeHtml(point.name)}${escapeHtml(point.sourceProtocol)}${escapeHtml(point.status)}${statusTime(point.updatedAtUtc)}
` + : '

Keine schlechte Qualität gemeldet.

')); + } + 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 `

Projekt und ISP

+
+
+ + +
+
Rechnername
+
+
+
+
`; +} + +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; } + }); +} diff --git a/src/Gateway.Api/wwwroot/index.html b/src/Gateway.Api/wwwroot/index.html index 5062460..db81d3d 100644 --- a/src/Gateway.Api/wwwroot/index.html +++ b/src/Gateway.Api/wwwroot/index.html @@ -1,13 +1,27 @@ - + - SEIU Gateway - + SE-Inno Universalgateway + + +
- + + + + + + + + diff --git a/src/Gateway.Api/wwwroot/ltd.css b/src/Gateway.Api/wwwroot/ltd.css new file mode 100644 index 0000000..c4b18db --- /dev/null +++ b/src/Gateway.Api/wwwroot/ltd.css @@ -0,0 +1,151 @@ +/* Layout and palette from SE-LTD, with gateway screens sharing the same shell. */ +/* Theme colors live in styles.css only; layout must not overwrite the palette. */ +:root { font-family: "Segoe UI", Tahoma, sans-serif; font-size: 12px; } +body { min-width:360px; font-size:12px; } +[hidden] { display:none !important; } +.shell { grid-template-columns:184px minmax(0,1fr); } +.sidebar { position:sticky; top:0; height:100dvh; overflow-y:auto; padding:12px 9px 10px; display:flex; flex-direction:column; border-left:5px solid transparent; border-image:linear-gradient(#ef4444,#dc3b68 55%,#4f8df7) 1; border-right:1px solid var(--line); } +.shell.unpinned .sidebar { position:relative; } +.brand { padding:0 0 12px; gap:8px; font-size:12px; letter-spacing:0; line-height:1.15; border-bottom:1px solid var(--line); margin-bottom:10px; } +.brand-logo { width:32px; height:32px; } +.brand .pin { margin-left:auto; padding:5px 7px; } +.eyebrow { color:#ef4444; font-size:9px; font-weight:400; letter-spacing:.12em; } +.nav { gap:6px; } +.nav button { border:1px solid var(--line); color:var(--text); border-radius:12px; padding:9px 10px; } +.nav button.active { color:#ef4444; background:#ef444412; border-color:#ef444440; box-shadow:none; } +.sidebar-foot { position:static; margin-top:auto; padding:10px 0 0; border-top:1px solid var(--line); gap:8px; } +.sidebar-foot .btn { justify-self:start; } +.sidebar-foot small { font-size:9px; text-align:center; } +.theme-control { display:grid; gap:6px; } +.theme-caption { color:var(--muted); font-size:10px; } +.sidebar-foot .theme-toggle { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; } +.sidebar-foot .theme-option { padding:7px 2px; font-size:10px; } +.theme-option.active { background:var(--blue-soft); color:var(--blue); border-color:var(--blue); } +#theme-message:empty { display:none; } +#theme-message { font-size:10px; margin:0; } +.user-caption { display:grid; gap:6px; } +.user-caption strong { color:var(--text); font-size:11px; overflow-wrap:anywhere; } +.content { max-width:none; min-width:0; padding:12px 12px 28px; } +.topline { margin-bottom:10px; min-height:27px; } +h1 { font-size:13px; font-weight:600; letter-spacing:0; } +h2 { font-size:14px; } +.status { font-size:10px; } +.grid { gap:10px; } +.grid.equal { grid-template-columns:repeat(2,minmax(0,1fr)); align-items:start; } +.grid.two { grid-template-columns:minmax(300px,1fr) minmax(0,1.4fr); } +.card { border-radius:14px; padding:12px; min-width:0; background:var(--panel); color:var(--text); box-shadow:0 12px 30px #0000000d; } +.card-head { margin-bottom:10px; } +.card-head .note { margin-top:3px; } +input,select,textarea { border-radius:10px; min-height:34px; padding:7px 10px; } +input[type="checkbox"] { min-height:0; accent-color:#93c5fd; } +input[type="color"] { padding:4px; width:36px; flex:0 0 36px; } +.btn,.theme-option { border-radius:18px; padding:7px 11px; background:transparent; font-size:11px; } +.btn.primary { border-color:transparent; background:linear-gradient(135deg,#ef4444,#b8275a 62%,#4f8df7); } +.btn:disabled { cursor:not-allowed; opacity:.5; } +.tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; } +.tabs .btn { border-radius:12px; min-height:33px; } +.tabs .active { color:#ef4444; border-color:#ef444440; background:#ef444412; } +.protocol-tabs { padding-bottom:10px; border-bottom:1px solid var(--line); } +.protocol-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); } +.protocol-panel { min-width:0; } +.bacnet-layout { + display:grid; + grid-template-columns:minmax(0,1fr) minmax(0,1.4fr); + grid-template-areas:"settings devices" "search devices"; + grid-template-rows:auto 1fr; + align-items:start; + gap:10px; +} +#bacnet-browser { display:contents; } +.bacnet-settings { grid-area:settings; } +.bacnet-search { grid-area:search; } +.bacnet-settings .note,.bacnet-search .note { margin:4px 0; } +.bacnet-devices { + grid-area:devices; + position:sticky; + top:12px; + display:flex; + flex-direction:column; + max-height:max(240px,calc(100dvh - 145px)); +} +.bacnet-device-scroll { + min-height:0; + overflow:auto; + overscroll-behavior:contain; + scrollbar-color:var(--line-strong) transparent; +} +.bacnet-device-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); padding-top:8px; } +.bacnet-device-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; } +.bacnet-object-panel { min-height:0; display:flex; flex-direction:column; gap:8px; } +.bacnet-object-panel .buttons { flex-wrap:wrap; } +.bacnet-object-panel input[type="checkbox"] { width:auto; } +.mapping-batch { margin-bottom:10px; } +.mapping-batch .point-tabs { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:10px; } +.mapping-batch .point-tabs .active { color:var(--blue); border-color:var(--blue); background:var(--blue-soft); } +.mapping-batch-grid { align-items:start; } +.mapping-batch [data-bulk-modbus]:not([hidden]) { display:grid; gap:8px; } +.bulk-point-list { max-height:36dvh; margin-top:8px; } +.bulk-point-list thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); } +.bulk-point-list td:first-child { width:5rem; } +.bulk-point-list input { width:auto; } +.bulk-point-list tr[data-bulk-point] { cursor:pointer; } +.bulk-point-list tr:has(input:checked) { background:var(--blue-soft); } +[data-bulk-assignments] ul { max-height:24dvh; overflow:auto; overflow-wrap:anywhere; } +.connection-status-card p { margin:6px 0; overflow-wrap:anywhere; } +.connection-facts { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:4px 12px; margin:6px 0; } +.connection-facts dt { color:var(--muted); } +.connection-facts dd { margin:0; overflow-wrap:anywhere; } +.connection-issues { max-height:35dvh; overflow:auto; overflow-wrap:anywhere; } +[data-mqtt-preview] { overflow-wrap:anywhere; } +.mqtt-topic-browser { margin-bottom:10px; } +.mqtt-browser-start { align-self:end; } +.mqtt-browser-content { margin-top:12px; } +.mqtt-browser-selection { margin:8px 0; flex-wrap:wrap; } +.mqtt-topic-tree { max-height:50dvh; min-height:70px; overflow:auto; border:1px solid var(--line); border-radius:10px; margin-top:8px; padding:6px; } +.mqtt-topic-tree ul { padding:0 0 0 16px; margin:0; list-style:none; } +.mqtt-topic-tree > ul { padding-left:0; } +.mqtt-tree-row { display:flex; align-items:center; gap:7px; min-width:0; margin-bottom:3px; } +.mqtt-tree-row .btn { white-space:nowrap; border-radius:7px; text-align:left; padding:4px 7px; } +.mqtt-tree-row input { width:auto; flex:none; } +.mqtt-tree-row .mqtt-topic-value { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.mqtt-topic-item[aria-pressed="true"] { color:var(--blue); border-color:var(--blue); } +.mqtt-topic-detail { border:1px solid var(--line); border-radius:10px; padding:10px; min-width:0; } +.mqtt-topic-detail h3 { margin:0 0 8px; } +.mqtt-topic-preview,.mqtt-topic-path { white-space:pre-wrap; overflow-wrap:anywhere; } +.list { display:grid; gap:4px; } +.list-item { padding:7px 8px; border:1px solid var(--line); border-radius:12px; background:color-mix(in srgb,var(--panel-2) 50%,transparent); display:flex; align-items:center; justify-content:space-between; gap:10px; min-width:0; text-align:left; color:var(--text); } +.list-item strong,.list-item .note { display:block; overflow-wrap:anywhere; } +.list-item.active { border-color:var(--blue); } +.scroll { max-height:60vh; overflow:auto; scrollbar-width:thin; scrollbar-color:var(--line-strong) transparent; } +.alias-table { min-width:860px; } +.alias-table th { text-transform:none; font-size:11px; letter-spacing:0; } +.alias-table td { padding:3px 4px; border:0; vertical-align:middle; } +.alias-table th:first-child,.alias-table td:first-child { color:#ef4444; width:85px; } +.alias-table .color-field { display:flex; align-items:center; gap:6px; } +.alias-table input { min-width:70px; } +.alias-table input[type="color"] { min-width:36px; } +.alias-table td:nth-child(2) { width:32%; } +.alias-table td:nth-child(3) { width:18%; } +.alias-table td:nth-child(4) { width:12%; } +.alias-table td:nth-child(5) { width:12%; } +.alias-table td:nth-child(6) { width:18%; } +.full { grid-column:1/-1; } +.form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; } +.alarm-destination { border:1px solid var(--line); border-radius:10px; padding:8px; display:grid; gap:8px; } +.chart { display:block; width:100%; height:225px; } +.chart-legend { display:flex; flex-wrap:wrap; gap:10px; color:var(--muted); font-size:11px; } +.chart-legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; } +.widget-grid { margin-top:10px; } +.table-scroll { overflow:auto; } +.empty { text-align:center; padding:28px 10px; } +.runner-columns { min-height:230px; } +details > summary { cursor:pointer; color:var(--muted); padding:7px 0; } +button:focus-visible,a:focus-visible { outline:2px solid var(--blue); outline-offset:2px; } +@media(min-width:1800px) { .alias-table .scroll { max-height:65vh; } } +@media(max-width:1100px) { + .grid.two,.grid.equal { grid-template-columns:1fr; } + .status { max-width:45%; text-align:right; } + .bacnet-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"settings" "search" "devices"; grid-template-rows:auto; } + .bacnet-devices { position:static; max-height:60dvh; } +} +@media(max-width:650px) { .shell { grid-template-columns:145px minmax(0,1fr); } .brand .pin { display:none; } .content { padding:10px 8px; } .form-grid,.row,.row.three { grid-template-columns:1fr; } .topline .status { display:none; } .sidebar { padding:10px 6px; } .brand { font-size:10px; } .card-head { flex-wrap:wrap; } } diff --git a/src/Gateway.Api/wwwroot/ltd.js b/src/Gateway.Api/wwwroot/ltd.js new file mode 100644 index 0000000..bf9dfb4 --- /dev/null +++ b/src/Gateway.Api/wwwroot/ltd.js @@ -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 ``; } +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 `${[...new Set(state.points.map(sourceKey))].sort().map(key => ``).join('')}`; } +function unitOptions(selected) { return `${state.presentation.units.map(unit => ``).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 = ``; + 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 `
${markup}
`; +} +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 `

Aliase

Aliase, Einheiten und Farben direkt als CSV importieren oder exportieren. Faktoren gelten für die Anzeige, nicht für Protokollwerte.
${points.map((point,index) => { const item = presentation(point,index); return ``; }).join('')}
DatenpunktAliasEinheitFaktorTypFarbe
${escapeHtml(point.bacnetObjectInstance ?? `Wert ${state.points.indexOf(point)+1}`)}
${points.length ? '' : '
Noch keine Datenpunkte in dieser Quelle.
'}
`; +} +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 { 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 `

Einheiten

Einheiten zentral verwalten und bei Aliasen auswählen.
${state.presentation.units.map((unit,index)=>`
${escapeHtml(unit.symbol)}${escapeHtml(unit.name)}
${unit.isSystem?'Systemeinheit':'Eigene Einheit'}
`).join('')}
`; } +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 `
${state.notifications.map(item=>`

${labels[item.channel]}

${item.hasApiKey?'Key gespeichert':'nicht freigeschaltet'}
${escapeHtml(item.endpoint)}
`).join('')}${can('manage_gateway')?`

Komari

${state.komari?.hasEnrollmentToken?'Key gespeichert':'kein Key'}
Verschlüsselt in der Datenbank. Alternativ über die serverseitige Token-Datei importierbar.
`:''}

Gespeicherte Schlüssel werden nicht an den Browser zurückgegeben. Die API-Annahme einer Nachricht bestätigt noch keine Zustellung beim Empfänger.

`; +} +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 `

Alarme

Datenpunkte unabhängig vom Trendlogging überwachen.

Quellen

Verfügbare Datenpunkte

${available.length}
${available.map(item=>`
${escapeHtml(pointTitle(item))}${escapeHtml(item.protocol)} · ${escapeHtml(item.scope)}
`).join('')||'
Keine lesbaren Datenpunkte.
'}

Wird alarmiert

${rules.length}
${rules.map(rule=>`
${escapeHtml(rule.name)}${escapeHtml(state.points.find(p=>p.id===rule.pointId)?.displayName||rule.pointId)} · ${rule.enabled?'aktiv':'inaktiv'}
${rule.destinations.map(d=>escapeHtml(d.channel+' → '+d.recipient)).join(' · ')}
`).join('')||'
Noch kein Datenpunkt im Alarming.
'}
${point?alarmEditor(point,edit):''}

Versandstatus

${state.deliveries.map(item=>``).join('')}
ZeitMeldungKanalStatus
${escapeHtml(new Date(item.createdAtUtc).toLocaleString('de-DE'))}${escapeHtml(item.title)}${escapeHtml(item.destination.channel)}${escapeHtml(deliveryState(item.state))}${item.result?`
${escapeHtml(item.result)}
`:''}
${state.deliveries.length?'':'
Noch keine Meldungen.
'}
`; +} +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 `

${rule?'Alarm bearbeiten':'Alarm anlegen'} · ${escapeHtml(pointTitle(point))}

${['Mail','WhatsApp','Ntfy'].map(channel=>{ const dest=destinations.find(item=>item.channel===channel),ready=state.notifications.find(item=>item.channel===channel)?.hasApiKey;return `
${channel}${channel==='WhatsApp'?`
Vorlagenparameter: Zeilenumbrüche und Tabs werden zu Leerzeichen. Unicode bleibt erhalten. Max. 1024 Zeichen je Meldungsparameter.
`:channel==='Ntfy'?`
`:''}
`;}).join('')}
Versand nur bei Zustandswechsel. Grenzwerte beziehen sich auf den unveränderten Datenpunktwert. Keine automatische Wiederholung bei unklarem Versandstatus.
`; +} +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')}

Widget

Aus einer gespeicherten Trend-Auswahl.

Auswahlen

Gespeicherte Punktgruppen für Trend und Dashboard.
${state.trendSelections.map(selection=>`
${selection.ownerId===state.user?.user?.id||state.user?.user?.role==='admin'?``:''}
`).join('')||'
Noch keine Auswahl. Im Reiter Trend eine Gruppe speichern.
'}
${state.dashboard.map(widget=>`

${escapeHtml(widget.title)}

${widget.rangeHours} h
Daten werden geladen …
`).join('')}
`; +} +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='
Keine numerischen Trendwerte in diesem Zeitraum.
';return;} + if(widget.type==='Values') {target.innerHTML=`
${series.map(item=>`
${escapeHtml(item.name)}${item.values.length?escapeHtml(item.values.at(-1).y.toLocaleString('de-DE')):'—'} ${escapeHtml(item.unit)}
`).join('')}
`;return;} + target.innerHTML=`
${series.map(item=>`${escapeHtml(item.name)} ${escapeHtml(item.unit)}`).join('')}
Bis zu 2.000 letzte Werte je Trend. Unterschiedliche Einheiten teilen sich hier eine Achse.
`; + drawTrendChart(target.querySelector('canvas'),series,start,Date.now()); + } catch(error) { if(target?.isConnected){target.innerHTML='
';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=`
`; + 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='
Noch keine Trenddaten.
';}; + 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 `

CSV-Runner

Gespeicherte Auswahlen automatisch als CSV ins Dateisystem exportieren und optional per Mail verschicken.

Vorhandene Runner

${state.runnerJobs.length}
${state.runnerJobs.map(item=>`
${escapeHtml(item.name)}${escapeHtml(state.trendSelections.find(selection=>selection.id===item.selectionId)?.name||'Auswahl fehlt')} · ${item.time} Uhr · ${item.enabled?'aktiv':'inaktiv'}
${item.lastResult?escapeHtml(item.lastResult.success?'Letzter Lauf: '+new Date(item.lastResult.ranAtUtc).toLocaleString('de-DE'):item.lastResult.error||'Fehler'):'Noch nicht gelaufen'}
`).join('')||'
Keine Runner angelegt.
'}

Ausführung

Geplante Jobs werden zur eingestellten Uhrzeit ausgeführt. Der letzte Lauf steht beim jeweiligen Job.
`; +} +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 ? `
${items.map(item => `
${escapeHtml(item.name)}${item.state === 'Running' ? 'Wird ausgeführt' : 'Wartend'} · ${escapeHtml(new Date(item.enqueuedAtUtc).toLocaleTimeString('de-DE'))}
`).join('')}
` : '
Keine Aufträge warten auf die Ausführung.
'; + } 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);}}); +} diff --git a/src/Gateway.Api/wwwroot/mapping-batch.js b/src/Gateway.Api/wwwroot/mapping-batch.js new file mode 100644 index 0000000..645dce9 --- /dev/null +++ b/src/Gateway.Api/wwwroot/mapping-batch.js @@ -0,0 +1,240 @@ +const bulkProtocolTabs = [['All', 'Alle'], ['Bacnet', 'BACnet'], ['OpcUa', 'OPC UA'], + ['Modbus', 'Modbus'], ['Knx', 'KNX'], ['Mqtt', 'MQTT'], ['Internal', 'Intern']]; + +function viewMappingBatch() { + return `
+

Sammelmapping

+
+ ${bulkProtocolTabs.map(([key, label]) => ``).join('')} +
+
+
+
+ + + +
+
+ + + +
AuswahlDatenpunktProtokollTyp
+
+

Strg oder ⌘ wählt einzelne Zeilen zu oder ab. Umschalt wählt einen Bereich.

+
+
+ + + +
+
+
+
+
+
`; +} + +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 => ` + + ${escapeHtml(point.displayName)}${escapeHtml(point.protocol)}${escapeHtml(point.valueType)} + `).join('') || 'Keine lesbaren Datenpunkte.'; + updateSelection(); + } + + tabs.forEach(tab => tab.addEventListener('click', () => { + protocol = state.bulkMappingProtocol = tab.dataset.bulkProtocol; + anchor = undefined; + renderPoints(); + })); + body.addEventListener('click', event => { + const row = event.target.closest('[data-bulk-point]'); + if (!row) return; + const id = row.dataset.bulkPoint; + const from = visiblePoints.findIndex(point => point.id === anchor); + if (event.shiftKey && from >= 0) { + const to = visiblePoints.findIndex(point => point.id === id); + for (const point of visiblePoints.slice(Math.min(from, to), Math.max(from, to) + 1)) selected.add(point.id); + } else { + if (event.target.type !== 'checkbox' && !event.ctrlKey && !event.metaKey) { + const onlySelected = selected.size === 1 && selected.has(id); + selected.clear(); + if (!onlySelected) selected.add(id); + } else if (selected.has(id)) selected.delete(id); + else selected.add(id); + anchor = id; + } + updateSelection(); + }); + card.querySelector('[data-bulk-select-all]').addEventListener('click', () => { + visiblePoints.forEach(point => selected.add(point.id)); + updateSelection(); + }); + card.querySelector('[data-bulk-clear]').addEventListener('click', () => { + selected.clear(); + anchor = undefined; + updateSelection(); + }); + + async function updateTarget() { + const modbus = target.value === 'Modbus'; + const mqtt = target.value === 'Mqtt'; + const prefix = form.elements.mqttTopicPrefix; + card.querySelector('[data-bulk-modbus]').hidden = !modbus; + card.querySelector('[data-bulk-mqtt]').hidden = !mqtt; + const monitoring = mqtt && form.elements.seMonitoring.checked; + card.querySelector('[data-bulk-mqtt-site]').hidden = !monitoring; + card.querySelector('[data-bulk-mqtt-free]').hidden = !mqtt || monitoring; + card.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; }); + prefix.required = mqtt && !monitoring; + serverSelect.required = modbus; + if (!modbus || serverRequest) return; + serverSelect.innerHTML = ''; + try { + serverRequest = api('/api/mappings/bulk/modbus-servers'); + const servers = await serverRequest; + serverSelect.innerHTML = servers.map(server => ``).join('') + || ''; + } catch (error) { + serverRequest = null; + serverSelect.innerHTML = ''; + message.textContent = error.message; + } + } + target.addEventListener('change', updateTarget); + form.elements.seMonitoring.addEventListener('change', updateTarget); + + form.addEventListener('submit', async event => { + event.preventDefault(); + if (running || selected.size === 0) return; + if (selected.size > 500) { message.textContent = 'Maximal 500 Datenpunkte pro Sammelmapping.'; return; } + const fields = new FormData(form); + const mqtt = target.value === 'Mqtt'; + const monitoring = mqtt && fields.has('seMonitoring'); + running = true; + updateSelection(); + assignments.replaceChildren(); + message.textContent = 'Mappings werden angelegt …'; + try { + const result = await api('/api/mappings/bulk', { method: 'POST', body: JSON.stringify({ + sourcePointIds: state.points.filter(point => selected.has(point.id)).map(point => point.id), + target: target.value, + modbusServerId: target.value === 'Modbus' ? fields.get('modbusServerId') || null : null, + firstRegister: target.value === 'Modbus' && fields.get('firstRegister') !== '' ? Number(fields.get('firstRegister')) : null, + mqttFormat: mqtt ? monitoring ? 'SeMonitoring' : fields.get('mqttFreeFormat') : null, + mqttSite: monitoring ? mqttSiteFromForm(fields) : null, + mqttTopicPrefix: mqtt && !monitoring ? fields.get('mqttTopicPrefix') : null + }) }); + state.bulkMappingResult = result; + await loadData(); + if (state.view === 'mappings') renderView(); + } catch (error) { + message.textContent = error.message; + } finally { running = false; updateSelection(); } + }); + renderPoints(); + updateTarget(); + if (state.bulkMappingResult) { + const { created, existing, assignments: entries } = state.bulkMappingResult; + state.bulkMappingResult = null; + message.textContent = `${created} angelegt, ${existing} bereits vorhanden.`; + if (entries.length) assignments.innerHTML = `
Zugewiesene Ziele anzeigen
    ${entries.map(entry => `
  • ${escapeHtml(entry)}
  • `).join('')}
`; + } +} + +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 `
+ + + +
`; +} + +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; } + }); +} diff --git a/src/Gateway.Api/wwwroot/mqtt-mapping-form.js b/src/Gateway.Api/wwwroot/mqtt-mapping-form.js new file mode 100644 index 0000000..7331b20 --- /dev/null +++ b/src/Gateway.Api/wwwroot/mqtt-mapping-form.js @@ -0,0 +1,120 @@ +function mqttPointDefaults(id) { + return state.mqttMappingDefaults?.points.find(point => point.pointId === id); +} + +function mqttMonitoringSiteFields(site = state.mqttMappingDefaults?.site) { + return `
+ + + +
`; +} + +function mqttTopicFormatOptions(selected) { + return ` + `; +} + +function mqttMappingFormatLabel(format) { + return { SeMonitoring: 'SE-Monitoring', SingleTopic: 'Einzel-Topic', Json: 'JSON' }[format] || format; +} + +function mqttSiteFromForm(form) { + return { + projectYear: Number(form.get('projectYear')), + projectNumber: form.get('projectNumber').trim(), + ispNumber: form.get('ispNumber').trim() + }; +} + +function mqttMappingForm(editing) { + const points = mappingPointOptions(editing?.pointId, 'valueType'); + if (!points) return '
Zuerst einen Datenpunkt anlegen.
'; + const suggested = mqttPointDefaults(editing?.pointId ?? state.points[0]?.id); + const monitoring = editing ? editing.format === 'SeMonitoring' : !!suggested?.category; + const option = (value, label, selected) => ``; + const categories = ['Analog', 'Notify', 'Alarms', 'Setpoints']; + if (editing?.seCategory === 'Alarm') categories.push('Alarm'); + return `
+ +
+ + +
+ + +
+ ${mqttMonitoringSiteFields(editing?.format === 'SeMonitoring' ? editing : undefined)} +
+ + +
+ +
+
+
+ + +
+ +
+
+ ${editing ? '' : ''}
+
+
`; +} + +function bindMqttMappingOptions(form) { + if (!form) return; + const fields = form.elements; + let preferMonitoring = !state.mqttMappingEditId || fields.seMonitoring.checked; + let preferFreeFormat = state.mqttMappingEditId ? fields.freeFormat.value : 'SingleTopic'; + function update(reselect = false) { + const selected = mqttPointDefaults(fields.pointId.value); + const supportsNumbers = !!selected?.category; + fields.seMonitoring.disabled = !supportsNumbers; + fields.freeFormat.options[0].disabled = !supportsNumbers; + if (reselect) { + fields.seMonitoring.checked = supportsNumbers && preferMonitoring; + fields.seCategory.value = selected?.category || 'Analog'; + fields.topicName.value = selected?.topicName || ''; + fields.freeFormat.value = supportsNumbers ? preferFreeFormat : 'Json'; + } + if (!supportsNumbers) { + fields.seMonitoring.checked = false; + fields.freeFormat.value = 'Json'; + } + const monitoring = fields.seMonitoring.checked; + form.querySelector('[data-mqtt-monitoring]').hidden = !monitoring; + form.querySelector('[data-mqtt-free]').hidden = monitoring; + form.querySelector('[data-mqtt-json-property]').hidden = fields.freeFormat.value !== 'Json'; + fields.jsonTopic.required = !monitoring; + form.querySelectorAll('[data-mqtt-required]').forEach(input => { input.required = monitoring; input.disabled = !monitoring; }); + fields.direction.options[0].disabled = monitoring && fields.seCategory.value === 'Setpoints'; + fields.direction.options[1].disabled = fields.direction.options[0].disabled; + if (fields.direction.options[0].disabled) fields.direction.value = 'Bidirectional'; + form.querySelector('[data-mqtt-preview]').textContent = `Projekte${fields.projectYear.value}/${fields.projectNumber.value}/${fields.ispNumber.value}/${fields.seCategory.value}/${fields.topicName.value}_Wert`; + } + fields.pointId.addEventListener('change', () => update(true)); + fields.seMonitoring.addEventListener('change', () => { + preferMonitoring = fields.seMonitoring.checked; + update(); + }); + fields.freeFormat.addEventListener('change', () => { + preferFreeFormat = fields.freeFormat.value; + update(); + }); + fields.seCategory.addEventListener('change', () => update()); + form.querySelector('[data-mqtt-monitoring]').addEventListener('input', () => update()); + update(); +} diff --git a/src/Gateway.Api/wwwroot/mqtt-topic-browser.js b/src/Gateway.Api/wwwroot/mqtt-topic-browser.js new file mode 100644 index 0000000..f535358 --- /dev/null +++ b/src/Gateway.Api/wwwroot/mqtt-topic-browser.js @@ -0,0 +1,273 @@ +function viewMqttTopicBrowser() { + return `
+

Topic-Browser

+
+
+ +
+
+
+
+ +
`; +} + +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 `
+ ${canImport && importable(topic) ? `` : ''} + + ${escapeHtml(topic.preview)} + ${topic.pointId ? 'übernommen' : ''}
`; + } + + function renderBranch(branch) { + const opened = model.expanded.get(branch.path) ?? !!model.query; + visibleBranches.set(branch.path, branch.selectable); + return `
  • + ${canImport && branch.selectable.length ? `` : ''} + +
    ${opened ? `
      ${branch.topic ? `
    • ${renderLeaf(branch.topic, branch.label)}
    • ` : ''} + ${renderNodes(branch.children)}
    ` : ''}
  • `; + } + + function renderNodes(branches) { + return [...branches.values()].map(branch => branch.children.size ? renderBranch(branch) : + `
  • ${renderLeaf(branch.topic, branch.label)}
  • `).join(''); + } + + function renderDetail() { + const topic = model.snapshot?.topics.find(item => item.topic === model.focused); + detail.innerHTML = topic ? `

    Topic-Details

    + ${escapeHtml(topic.topic)} +
    +
    Werttyp
    ${displayType(topic.valueType)}
    +
    Empfangen
    ${statusTime(topic.receivedAtUtc)}
    +
    Retained
    ${topic.retained ? 'Ja' : '—'}
    +
    +
    ${escapeHtml(topic.preview)}
    + ${topic.pointId ? '

    Als externer Datenpunkt angelegt.

    ' : + canImport && importable(topic) ? '' : + !topic.valueType ? '

    Dieser Nachrichtenwert kann nicht als Datenpunkt übernommen werden.

    ' : ''}` + : '

    Ein Topic auswählen, um Wert und Details zu sehen.

    '; + } + + 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 ? `
      ${renderNodes(mqttTopicNodes(visibleTopics))}
    ` : + `
    ${query ? 'Keine passenden Topics.' : 'Warte auf Retained- oder neue Nachrichten.'}
    `; + 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(); +} diff --git a/src/Gateway.Api/wwwroot/network-settings.js b/src/Gateway.Api/wwwroot/network-settings.js new file mode 100644 index 0000000..74fdffa --- /dev/null +++ b/src/Gateway.Api/wwwroot/network-settings.js @@ -0,0 +1,133 @@ +function bindHostNetwork(panel) { + let selected; + let pendingLayout; + let timer; + const base = '/api/system/network'; + const heading = '

    Netzwerk · IPv4

    '; + 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}

    ${escapeHtml(error.message)}

    `; + 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}

    Netzwerkdienst übernimmt die Einstellungen …

    `; + schedule(2000); + return; + } + const cards = status.interfaces; + const card = cards.find(item => item.name === selected) ?? cards[0]; + if (!card) { + panel.innerHTML = `${heading}

    Keine verwaltbare Netzwerkkarte gefunden.

    `; + 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 ? `

    ${escapeHtml(status.notice)}

    ` : ''} +
    + +
    Aktuell: ${escapeHtml(card.addresses.map(item => `${item.address}/${item.prefixLength}`).join(', ') || 'keine IPv4-Adresse')} + ${routes[0]?.gateway ? ` · Gateway ${escapeHtml(routes[0].gateway)}` : ''}
    +
    + + +
    +
    + Statische IPv4-Einstellungen +
    + + +
    +
    + + +
    +
    +
    Nach dem Anwenden bleiben zwei Minuten zum Bestätigen. Eine niedrigere Routenmetrik hat Vorrang.
    +
    +
    +
    `; + 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}

    Änderung für ${escapeHtml(profile.interface)} · ${profile.mode === 'static' ? 'Statisch' : 'DHCP'}

    +

    + ${link && link.hostname !== location.hostname ? `

    Gateway unter ${escapeHtml(address)} öffnen

    ` : ''} +
    + + +
    `; + 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(); +} diff --git a/src/Gateway.Api/wwwroot/public-trends.html b/src/Gateway.Api/wwwroot/public-trends.html new file mode 100644 index 0000000..0248213 --- /dev/null +++ b/src/Gateway.Api/wwwroot/public-trends.html @@ -0,0 +1,17 @@ + + + + + + SE-Inno Universalgateway · Trend Logs + + + + +
    +
    SE-INNO UNIVERSALGATEWAY
    öffentliche Trendansicht
    +

    Trend Logs

    Öffentliche Trenddaten werden geladen …
    +
    + + + diff --git a/src/Gateway.Api/wwwroot/public-trends.js b/src/Gateway.Api/wwwroot/public-trends.js new file mode 100644 index 0000000..26b9b83 --- /dev/null +++ b/src/Gateway.Api/wwwroot/public-trends.js @@ -0,0 +1,31 @@ +const trendSelect = document.querySelector('#trend-log'); +const trendStatus = document.querySelector('#trend-status'); +const trendTable = document.querySelector('#trend-table'); +const escapeHtml = value => String(value ?? '').replace(/[&<>'"]/g, character => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); + +async function loadRecords(id) { + if (!id) return; + trendStatus.textContent = 'Werte werden geladen …'; + trendTable.innerHTML = ''; + const response = await fetch(`/api/public/trend-logs/${encodeURIComponent(id)}/records?limit=2000`); + if (!response.ok) throw new Error('Dieses Trend Log ist nicht öffentlich freigegeben oder nicht mehr verfügbar.'); + const records = await response.json(); + trendStatus.textContent = records.length ? `${records.length} aufgezeichnete Werte` : 'Noch keine Werte aufgezeichnet.'; + trendTable.innerHTML = records.length ? `${records.map(record => ``).join('')}
    ZeitpunktWertQuelleStatus
    ${escapeHtml(new Date(record.timestampUtc).toLocaleString('de-DE'))}${escapeHtml(typeof record.value === 'string' ? record.value : JSON.stringify(record.value))}${escapeHtml(record.sourceProtocol)}${escapeHtml(record.status || '—')}
    ` : ''; +} + +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 = ''; 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 => ``).join(''); + trendSelect.addEventListener('change', () => loadRecords(trendSelect.value).catch(error => { trendStatus.textContent = error.message; })); + await loadRecords(selected); + } catch (error) { trendStatus.textContent = error.message; } +} + +bootPublicTrends(); diff --git a/src/Gateway.Api/wwwroot/styles.css b/src/Gateway.Api/wwwroot/styles.css index 7802441..a480d9e 100644 --- a/src/Gateway.Api/wwwroot/styles.css +++ b/src/Gateway.Api/wwwroot/styles.css @@ -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)); } } diff --git a/tests/Gateway.SmokeTests/BacnetBridgeTests.cs b/tests/Gateway.SmokeTests/BacnetBridgeTests.cs new file mode 100644 index 0000000..9a4fd6e --- /dev/null +++ b/tests/Gateway.SmokeTests/BacnetBridgeTests.cs @@ -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.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); } +} diff --git a/tests/Gateway.SmokeTests/LtdFeatureTests.cs b/tests/Gateway.SmokeTests/LtdFeatureTests.cs new file mode 100644 index 0000000..7ac3992 --- /dev/null +++ b/tests/Gateway.SmokeTests/LtdFeatureTests.cs @@ -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 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()) 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(); + 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()) 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 SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Address = request.RequestUri!.AbsoluteUri; + Multipart = request.Content is MultipartFormDataContent; + return Task.FromResult(new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) }); + } + } +} diff --git a/tests/Gateway.SmokeTests/OpcUaClientTests.cs b/tests/Gateway.SmokeTests/OpcUaClientTests.cs new file mode 100644 index 0000000..a17e384 --- /dev/null +++ b/tests/Gateway.SmokeTests/OpcUaClientTests.cs @@ -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.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 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 diff --git a/tests/Gateway.SmokeTests/OpcUaFeatureTests.cs b/tests/Gateway.SmokeTests/OpcUaFeatureTests.cs new file mode 100644 index 0000000..c6a1130 --- /dev/null +++ b/tests/Gateway.SmokeTests/OpcUaFeatureTests.cs @@ -0,0 +1,128 @@ +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}"; + var selected = await CoreClientUtils.SelectEndpointAsync(clientConfiguration, url, true, 15_000, CancellationToken.None); + 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(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 diff --git a/tests/Gateway.SmokeTests/Program.cs b/tests/Gateway.SmokeTests/Program.cs index 7f5085d..d5f541a 100644 --- a/tests/Gateway.SmokeTests/Program.cs +++ b/tests/Gateway.SmokeTests/Program.cs @@ -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,133 @@ 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 = ""; +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 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()) +{ + 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.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 +208,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 +288,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 +313,26 @@ 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!); 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) { diff --git a/tests/native_bacnet_test.py b/tests/native_bacnet_test.py new file mode 100644 index 0000000..5e61d2f --- /dev/null +++ b/tests/native_bacnet_test.py @@ -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}") diff --git a/tests/ui-theme-tabs.test.cjs b/tests/ui-theme-tabs.test.cjs new file mode 100644 index 0000000..1a0e90c --- /dev/null +++ b/tests/ui-theme-tabs.test.cjs @@ -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(/