diff --git a/ANLEITUNG.md b/ANLEITUNG.md new file mode 100644 index 0000000..525c603 --- /dev/null +++ b/ANLEITUNG.md @@ -0,0 +1,90 @@ +# Anleitung: Lernklima-System starten + +Alles liegt in diesem Ordner: Firmware (`firmware/`), Backend (`backend/`), Webinterface (`frontend/ambient`) und Unity-Zwilling (`frontend/SmartLectureRoom`). Wie und wann entschieden wird: [docs/regeln.md](docs/regeln.md). + +``` +Arduino + ESP-01 ──WLAN──▶ backend/server.js :3000 ◀──▶ Webinterface (Bedienung, beliebig viele Tabs/Geräte) + │ + └──▶ Unity-Zwilling (zeigt, was die Werte im Raum auslösen) +``` + +## 1. Was man braucht + +| Programm | wofür | Hinweis | +|---|---|---| +| **Node.js ≥ 18** | Backend | kein `npm install` nötig | +| Python 3 | nur für den Simulator (Test ohne Arduino) | | +| Unity 6 (6000.x) | nur für den 3D-Zwilling | Projekt `frontend/SmartLectureRoom` | +| Arduino IDE | nur zum Hochladen der Firmware | Bibliotheken: DHT sensor library, Adafruit CCS811, LiquidCrystal | + +## 2. Schnellstart ohne Arduino (zum Ausprobieren) + +Im Ordner dieses Repos, jeweils in einem eigenen Terminal: + +```bash +node backend/server.js +``` +```bash +python3 backend/simulator.py --szenario demo +``` + +- **Webinterface:** http://localhost:3000 im Browser öffnen. +- **Unity:** Unity Hub → *Add project from disk* → `frontend/SmartLectureRoom` → Menü **Smart Room → Ambient-Szene öffnen** → **Play**. + +`--szenario demo` spielt nacheinander normal → stickig → Lärm → normal → Hitze → dunkel → kalt durch (je ca. 1 min). Einzeln: `--szenario normal|hitze|stickig|kalt|laerm|dunkel`. +Ohne Internet: `WETTER=aus node backend/server.js` (dann fehlen nur Wind und Außentemperatur). + +## 3. Mit dem Arduino + +1. **Hotspot:** iPhone-Hotspot mit „Maximale Kompatibilität“ (2,4 GHz) einschalten, Laptop verbinden. + - **Mac:** Systemeinstellungen → WLAN → Details (beim Hotspot) → TCP/IP → *IPv6 konfigurieren: Nur Link-lokal*. Sonst bekommt der Mac nur `192.0.0.2` und der ESP erreicht ihn nicht. Nach der Vorführung wieder auf „Automatisch“. + - **Windows:** einmalig `backend/firewall_freigeben.bat` als Administrator ausführen. +2. **Backend starten:** `node backend/server.js` (Windows: Doppelklick auf `backend/start.bat`). + Es muss „**OK: SERVER_IP … passt**“ melden. Bei „ACHTUNG“: die angezeigte IP in `firmware/dht11_lcd/wifi_config.h` als `SERVER_IP` eintragen und Firmware neu hochladen. +3. **Firmware** (nur wenn nötig, z. B. neue IP): `wifi_config.example.h` als `wifi_config.h` kopieren und Hotspot, Passwort, Laptop-IP eintragen (nicht committen!). **ESP-Kabel an Pin 0/1 abziehen**, `firmware/dht11_lcd` hochladen, Kabel wieder anstecken (ESP TX → Pin 0, ESP RX → Pin 1), Reset. +4. LCD zeigt „WLAN OK“. Im Backend-Fenster erscheint alle ~7 s eine Zeile mit den Messwerten (Absender `172.20.10.x`). +5. Webinterface oben rechts: „**Arduino verbunden**“. Demo-Szenario auf **Live** lassen, sonst werden Beispielwerte gezeigt. + +## 4. Webinterface bedienen (http://localhost:3000) + +| Bereich | Funktion | +|---|---| +| Studierende / Dozent | Ansicht wechseln; die Dozentensteuerung gibt es nur in „Dozent“ | +| Raumstatus | alle Arduino-Werte (CO₂, Temperatur, Lärm, Luftfeuchte, TVOC, Helligkeit), Wind vom Wetterdienst, Zustand von Fenster, Jalousie, Lüftung, Heizung, Licht, Beamer | +| **Nächste Prüfung in m:ss** | das Backend entscheidet alle 2 min | +| **Jetzt prüfen** | sofort entscheiden | +| **Zeitraffer 1× / 5× / 10×** | Prüfung alle 2 min / 24 s / 12 s | +| Dein Temperaturwunsch | mit − / + in 0,5-°C-Schritten einstellen, **Wunsch senden**; „Rückgängig“ zieht ihn zurück | +| Fenster öffnen? Auf / Zu | Mehrheit „Auf“ öffnet das Fenster auch bei Außenlärm | +| Dozentensteuerung | Beamer-Modus (30/60/90 min), Jalousien ↑/↓ (manuell, 90 min), „Automatik fortsetzen“ | +| Demo-Szenarien | Beispielwerte für Vorführungen (gelten auch in Unity); **Live** = echte Werte | + +**Mehrere Personen:** Jeder Browser-Tab ist eine eigene Person (eigene Kennung unten im Wunsch-Kasten). Andere Geräte im selben Hotspot öffnen `http://:3000` (die IP zeigt das Backend beim Start). Neue Stimmen erscheinen sofort, wirken aber erst bei der nächsten Prüfung (Hinweis „Nach der nächsten Prüfung: …“). Stimmen verfallen nach 30 min. + +## 5. Unity-Zwilling + +- Startet automatisch im Modus **Backend** (`http://localhost:3000`) und **zeigt nur an**: Fenster, Jalousie, Heizung, Lüftung, Licht und Beamer bewegen sich so, wie das Backend entscheidet. Bedient wird im Webinterface. +- Oben rechts: **„Arduino verbunden / nicht verbunden“** und der Umschalter **Arduino-Werte | Simulation**. „Simulation“ stellt Beispielwerte her und lässt Unity selbst rechnen (zum Ausprobieren mit den Unity-eigenen Szenarien). +- Lärm wird sichtbar: Schallwellen vor der Fensterfront, ab 70 dB rot, Schild „Fenster gesperrt“. +- Ohne Backend rechnet Unity mit derselben Logik selbst (Ersatzlogik), bis das Backend wieder antwortet. +- Für die Vorführung im Browser (WebGL) siehe [backend/README.md](backend/README.md#live-demo-im-browser-webinterface--zwilling-für-alle). + +## 6. Prüfen, ob alles stimmt + +```bash +node --test backend/test +``` +Erwartet: alle Tests bestanden. + +## 7. Fehlerbehebung + +| Problem | Lösung | +|---|---| +| Webinterface: „Backend nicht erreichbar“ | `node backend/server.js` läuft nicht oder auf einem anderen Port | +| „Arduino nicht verbunden“, LCD „WLAN OK“ | Backend meldet „ACHTUNG“? → Laptop-IP stimmt nicht mit `SERVER_IP` überein. Mac: IPv6 auf „Nur Link-lokal“. Windows: Firewall freigeben | +| LCD „WLAN Fehler E1“ | ESP antwortet nicht: Kabel gekreuzt? (TX→0, RX→1), gemeinsame Masse, lose Kabel; siehe README | +| LCD „WLAN Fehler E3“ | Hotspot nicht gefunden: SSID/Passwort, „Maximale Kompatibilität“, Hotspot-Seite am iPhone offen lassen | +| Werte ändern sich, Entscheidung nicht | gewollt: erst bei der nächsten Prüfung → „Jetzt prüfen“ oder Zeitraffer | +| Webinterface zeigt Beispielwerte statt Arduino | Demo-Szenario steht nicht auf **Live** | +| Unity zeigt „Simulation“ | Umschalter oben rechts auf **Arduino-Werte** stellen; Backend muss laufen | +| Wind/Außentemperatur „–“ | kein Internet oder `WETTER=aus` | diff --git a/CLAUDE.md b/CLAUDE.md index 9f62133..8321c95 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,8 +7,10 @@ UCPS-Projekt (Gruppe C): Lernklima-Aggregation für Vorlesungsräume. Konzept: ` ## Architektur Sensoren (Uno + ESP-01) ➔ `backend/server.js` (Node, Port 3000) ➔ Webinterface (`frontend/ambient`) und Unity-Zwilling (`frontend/SmartLectureRoom`). -- **Die gesamte Logik liegt im Backend** (`backend/logik.js`, reine Funktionen; Zustand in `raum.js`; Wetter in `wetter.js`). Webinterface und Unity rechnen nichts selbst, sie holen Entscheidungen über `/api/zustand` bzw. `/api/unity` und schicken Stimmen/Einstellungen an dieselben Endpunkte. -- Regeländerungen gehören nach `logik.js` (Grenzwerte in `GRENZWERTE`) und müssen mit `docs/aktivitaetsdiagramm.png` und den Tests übereinstimmen. Die Ersatzlogik in Unity (`ClimateController`) muss gleich bleiben, sie springt nur ein, wenn das Backend > 5 s nicht antwortet. +- **Die gesamte Logik liegt im Backend** (`backend/logik.js`, reine Funktionen; Zustand in `raum.js`; Wetter in `wetter.js`). Entschieden wird im **Prüfzyklus alle 2 min** (`PRUEF_SEKUNDEN`), dazu „Jetzt prüfen“ (`POST /api/pruefen`), Zeitraffer 1/5/10× (`POST /api/zeitraffer`) und sofort bei Demo-Szenario, Vortragsmodus, manuellen Einstellungen und der ersten Messung nach einem Sensorausfall. Messwerte und Stimmen werden sofort angezeigt. +- **Webinterface** (`frontend/ambient`: `index.html`, `app.js`, `ambient.css` = unverändertes CSS aus `frontend/figma/Ambient2_v2.html`, `ergaenzungen.css`) ist die Bedienoberfläche, ohne Framework/Build. Jeder Browser-Tab ist ein eigener Client (`sessionStorage`). Es rechnet nichts selbst. +- **Unity-Zwilling** zeigt nur an (`/api/unity`), Bedienung nur im Webinterface. Regeln, Ablauf und Auslöser: `docs/regeln.md`. +- Regeländerungen gehören nach `logik.js` (Grenzwerte in `GRENZWERTE`) und müssen mit `docs/aktivitaetsdiagramm.png`, `docs/regeln.md` und den Tests übereinstimmen. Die Ersatzlogik in Unity (`ClimateController`) muss gleich bleiben, sie springt nur ein, wenn das Backend > 5 s nicht antwortet oder im Unity-Umschalter „Simulation“ gewählt ist. - `backend/server.py` ist veraltet (nur Messwerte, keine Logik); nicht weiterentwickeln. - API-Referenz und Datenformate: `backend/README.md`. Hardware, Verkabelung, Fehlerbehebung: `README.md`. @@ -16,7 +18,7 @@ Sensoren (Uno + ESP-01) ➔ `backend/server.js` (Node, Port 3000) ➔ Webinterfa ```bash node backend/server.js # Backend starten, http://localhost:3000 (oder backend/start.bat) node --test backend/test # Tests der Logik -python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario hitze|stickig|kalt|normal|demo) +python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario hitze|stickig|kalt|laerm|dunkel|normal|demo) ``` - Node.js ≥ 18, keine Abhängigkeiten, kein `npm install`. `WETTER=aus` schaltet den Open-Meteo-Abruf ab. - Firmware (`firmware/dht11_lcd`) wird in der Arduino IDE hochgeladen, nicht über die CLI. `wifi_config.h` (Hotspot-Zugang) ist lokal und nicht im Repo; Vorlage `wifi_config.example.h`. Nie Zugangsdaten committen. @@ -27,7 +29,7 @@ python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario h - Änderungen an Regeln oder API in `backend/README.md` und ggf. `docs/aggregationskonzept.md` nachziehen. ## Fachliche Kernregeln (nicht verletzen) -- Temperatur/Licht: Durchschnitt aller Live-Eingaben. +- Temperatur/Licht: Durchschnitt aller Live-Eingaben (auch die Zahlenwünsche des Webinterfaces; der Figma-Text „Median“ wurde deshalb in „Durchschnitt“ geändert). - CO2 ist Hard-Constraint (Standard 1000 ppm): Nutzer können nicht überschreiben. - Sensor-Veto: extremer Außenlärm sperrt das automatische Öffnen (Lüftungsanlage statt Fenster), nur ein Mehrheitswunsch „Fenster auf“ öffnet trotzdem (Aktivitätsdiagramm `docs/aktivitaetsdiagramm.png`); extremer Wind ➔ max. gekippt, auch manuell. - Manuelle Dozenteneinstellungen haben Vorrang, gelten 90 min; CO₂ hält die Lüftungsanlage trotzdem an. diff --git a/README.md b/README.md index a28ef8c..b53ae61 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,19 @@ Dynamische, kontextsensitive Steuerung des Lernklimas im Vorlesungsraum: Sensord Das vollständige Konzept steht in [docs/aggregationskonzept.md](docs/aggregationskonzept.md). +**Starten:** [ANLEITUNG.md](ANLEITUNG.md) · **Regeln (wer entscheidet wo, wann, was):** [docs/regeln.md](docs/regeln.md) + ## Datenfluss Sensoren (Arduino UNO) ➔ WiFi/Bluetooth ➔ Backend (Aggregation & Regeln) ➔ Frontend (Webinterface + 3D-Zwilling) Aktuell umgesetzt: ``` -DHT11 + CCS811 ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Handy-Hotspot)─▶ Laptop: backend/server.js :3000 ◀──▶ Browser (Ambient²-Webinterface) +DHT11 + CCS811 + MAX9814 + LDR ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Handy-Hotspot)─▶ Laptop: backend/server.js :3000 ◀──▶ Browser (Ambient²-Webinterface) ▲ └──▶ Unity-Zwilling (frontend/SmartLectureRoom) ``` -Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind-Veto, Vortragsmodus) läuft im **gemeinsamen Node-Backend** `backend/server.js`. Webinterface und Unity-Zwilling holen Werte und Entscheidungen nur dort ab (`/api/zustand` bzw. `/api/unity`) und schicken Stimmen, Szenario, Vortragsmodus und Jalousie an dieselben Endpunkte. So zeigen beide immer denselben Zustand. API und Regeln: [backend/README.md](backend/README.md), Zwilling: [frontend/SmartLectureRoom/README.md](frontend/SmartLectureRoom/README.md). +Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind-Veto, Vortragsmodus) läuft im **gemeinsamen Node-Backend** `backend/server.js` und wird **alle 2 Minuten** geprüft („Jetzt prüfen“ und Zeitraffer 5×/10× im Webinterface). Das **Webinterface** (`frontend/ambient`, Figma-Design Ambient² v2) ist die Bedienoberfläche: Es zeigt alle Arduino-Werte und nimmt Stimmen (jeder Browser-Tab = eine Person), Fensterwunsch, Vortragsmodus, Jalousie und Demo-Szenarien an. Der **Unity-Zwilling** zeigt nur, was die Entscheidung im Raum auslöst (`/api/unity`). API und Regeln: [backend/README.md](backend/README.md), Zwilling: [frontend/SmartLectureRoom/README.md](frontend/SmartLectureRoom/README.md). ## Repo-Struktur | Ordner | Inhalt | @@ -22,10 +24,10 @@ Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind- | `docs/` | Konzept, Architektur- und Entscheidungsdokumente | | `firmware/` | Arduino-Sketches für Sensorik und Übertragung | | `backend/` | Aggregationslogik (Durchschnitt, CO2-Hard-Constraint, Kontext-Sperren), API, Wetterdaten | -| `frontend/` | Responsive Webinterface (Live-Werte, Präferenz-Slider) und 3D-Raum | +| `frontend/` | `ambient/` Webinterface (Figma v2, angebunden), `figma/` unveränderter Figma-Export, `ambient-v1/` ältere angebundene Fassung, `SmartLectureRoom/` Unity-Zwilling, `index.html` einfache Messwert-Seite | ## Status -Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂ und TVOC, zeigt sie auf dem LCD und sendet sie per ESP-01 ans Backend. Das Node-Backend aggregiert Stimmen und entscheidet. Webinterface (Figma-Prototyp `frontend/ambient`, http://localhost:3000) und Unity-Zwilling (`frontend/SmartLectureRoom`) sind beide daran angebunden. Mit dem echten Arduino ist der Zwilling noch nicht getestet. Offene Punkte: [docs/offene-punkte.md](docs/offene-punkte.md). +Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂ und TVOC, zeigt sie auf dem LCD und sendet sie per ESP-01 ans Backend. Das Node-Backend aggregiert Stimmen und entscheidet. Webinterface (Figma-Prototyp v2 `frontend/ambient`, http://localhost:3000) und Unity-Zwilling (`frontend/SmartLectureRoom`) sind beide daran angebunden, mit Simulator getestet; Lautstärke und Helligkeit kamen am echten Aufbau bis Unity an (vor der Umstellung auf das Node-Backend). Offene Punkte: [docs/offene-punkte.md](docs/offene-punkte.md). ## Komponenten und ihre Aufgabe @@ -79,6 +81,8 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e Der 3,3-V-Pin des Uno liefert nur ca. 150 mA, der ESP-01 braucht beim Start kurz bis zu 300 mA. Wir versorgen den ESP deshalb aus einer eigenen 3,3-V-Quelle (zweiter Uno); deren **GND muss mit dem GND des Haupt-Uno verbunden** sein. ## Starten +Ausführlich mit Test ohne Arduino, Webinterface, Unity und Fehlerbehebung: [ANLEITUNG.md](ANLEITUNG.md). Kurzfassung: + 1. `firmware/dht11_lcd/wifi_config.example.h` als `wifi_config.h` kopieren und Hotspot-Name, Passwort und Laptop-IP eintragen (die Datei ist in `.gitignore`). 2. iPhone-Hotspot mit **„Maximale Kompatibilität“** einschalten (ESP-01 kann nur 2,4 GHz), Laptop verbinden. 3. Einmalig `backend/firewall_freigeben.bat` als Administrator ausführen. diff --git a/backend/README.md b/backend/README.md index a18cf8b..eb907f2 100644 --- a/backend/README.md +++ b/backend/README.md @@ -14,8 +14,8 @@ Nur Node-Bordmittel, kein `npm install` nötig. Voraussetzung: **Node.js ≥ 18* ``` ESP8266 ─────────POST /api/messwerte─────────▶ ┐ Open-Meteo ◀──────── alle 10 min ───────────── │ server.js -Webinterface ── GET /api/zustand, POST /api/stimme, /api/vortragsmodus, /api/jalousie, /api/szenario -Unity-Zwilling ─ GET /api/unity (Werte + Steuerbefehl), POST wie das Webinterface +Webinterface ── GET /api/zustand, POST /api/stimme, /api/vortragsmodus, /api/jalousie, /api/manuell, /api/szenario, /api/pruefen, /api/zeitraffer +Unity-Zwilling ─ GET /api/unity (Werte + Steuerbefehl), nur Anzeige ``` ```bash @@ -23,7 +23,10 @@ node backend/server.js # oder Doppelklick auf backend/start.bat node --test backend/test # Tests der Logik python backend/simulator.py # optional: Fake-Sensordaten ohne Hardware (funktioniert mit beiden Servern) ``` -Webinterface: http://localhost:3000 (Figma-Prototyp Ambient², angebunden). Die alte einfache Messwert-Seite liegt unter http://localhost:3000/index.html. +Webinterface: http://localhost:3000 (leitet auf `/ambient/` um: Figma-Prototyp Ambient² v2, angebunden). Ältere Fassung: `/ambient-v1/`, einfache Messwert-Seite: `/index.html`. + +### Prüfzyklus +Entschieden wird **alle 2 Minuten** (`PRUEF_SEKUNDEN=…` zum Ändern). Neue Messwerte und Stimmen erscheinen sofort im Webinterface, wirken aber erst bei der nächsten Prüfung. Sofort geprüft wird bei „Jetzt prüfen“ (`POST /api/pruefen`), Demo-Szenario, Vortragsmodus, manuellen Einstellungen, ablaufenden Modi und bei der ersten Messung nach Start oder Sensorausfall. Zeitraffer (`POST /api/zeitraffer`, 1/5/10×) verkürzt den Abstand auf 2 min / 24 s / 12 s. Übersicht mit Diagramm: [../docs/regeln.md](../docs/regeln.md). Ohne Internet (Hotspot ohne Daten) fehlen nur die Wetterwerte; mit `WETTER=aus` wird der Abruf abgeschaltet. | Datei | Aufgabe | @@ -40,7 +43,7 @@ Ohne Internet (Hotspot ohne Daten) fehlen nur die Wetterwerte; mit `WETTER=aus` | 1 Gesundheit | eCO₂ > **1000 ppm** ➔ Lüften erzwungen (Fenster offen). Nutzerstimmen können das nicht verhindern. Ist die Außenluft belastet (PM10 > 50 µg/m³) oder draußen < 5 °C, läuft stattdessen die Lüftungsanlage. Auch bei manuell geschlossenem Fenster bleibt die Lüftungsanlage an. | | 2 Kontext-Veto | Außenlärm > **70 dB** ➔ Fensteröffnung gesperrt, Lüftungsanlage statt Fenster. **Nur wenn die Mehrheit „Fenster auf“ stimmt, öffnet es trotzdem.** Wind > **60 km/h** ➔ Fenster höchstens gekippt (auch manuell), Lüftungsanlage unterstützt. | | 3 Dozent | Manuelle Einstellungen (Fenster, Jalousie, Licht, Lüftungsanlage) haben Vorrang vor der Automatik und werden nach **90 min** gelöscht. | -| 3 Mehrheit | Temperaturwunsch = **Durchschnitt aller Stimmen** (kühler −1, angenehm 0, wärmer +1) × 1,5 °C um 22 °C, begrenzt auf 20–24 °C. Liegt der Durchschnitt unter ±0,2, bleibt der Zielwert (Ausreißer). Licht ebenso: Durchschnitt aus dunkler/passt/heller. Fenster: offen, wenn mehr Stimmen für „auf“ als für „zu“. | +| 3 Mehrheit | Temperaturwunsch = **Durchschnitt aller Stimmen**: Zahlenwünsche aus dem Webinterface (18–26 °C, je Wunsch begrenzt) und Kategorien (kühler −1, angenehm 0, wärmer +1, je 1,5 °C um 22 °C) werden gemeinsam gemittelt, begrenzt auf 20–24 °C. Liegt der Durchschnitt unter ±0,2, bleibt der Zielwert (Ausreißer). Licht ebenso: Durchschnitt aus dunkler/passt/heller. Fenster: offen, wenn mehr Stimmen für „auf“ als für „zu“. | | 4 Energie | Sonst Zielwerte halten: heizen unter Ziel − 0,5 °C, lüften über Ziel + 1 °C (wenn draußen kühler). | Jalousie und Licht: Beamermodus (= Vortragsmodus) ➔ Beamer an, Licht aus, Jalousie unten. Sonst zu hell (Lichtsensor `helligkeit` > **80 %**, ohne Sensor Sonne > 500 W/m²) ➔ Jalousie unten, Licht an; sonst Jalousie oben. Zu dunkel (< **30 %**) ➔ Licht heller. Manuelle Werte gehen vor. Alle Grenzwerte stehen oben in `logik.js` (`GRENZWERTE`); die Lichtschwellen sind relative Werte des Fotowiderstands und müssen am Aufbau abgeglichen werden. @@ -51,27 +54,32 @@ Demo-Szenarien (aus dem Figma-Prototyp: Normal, CO₂ zu hoch, CO₂ + Außenlä | Methode & Pfad | Inhalt | |---|---| | `POST /api/messwerte` | ESP8266: `{"temperatur":22.5,"luftfeuchte":45,"eco2":612,"tvoc":30,"lautstaerke":48,"helligkeit":55}` – alle Felder optional. `lautstaerke` (Mikrofon, dB) gilt als Außenlärm, `helligkeit` ist der Fotowiderstand in % (relativ). | -| `GET /api/zustand?client=` | Alles fürs Webinterface: `werte` (je Feld `wert` + `quelle`: sensor/wetter/demo), `entscheidung` (Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Zielwert, Priorität, Status), `stimmen` (Temperatur, Licht, Fenster), `vortrag`, `manuell`, `verlauf`, `szenarien`. | -| `POST /api/stimme` | `{"client":"","rolle":"studierende","temperatur":"kuehler\|angenehm\|waermer","licht":"dunkler\|passt\|heller","fenster":"auf\|zu"}` – eine Stimme pro Client, Felder einzeln überschreibbar. | +| `GET /api/zustand?client=` | Alles fürs Webinterface: `werte` (je Feld `wert` + `quelle`: sensor/wetter/demo), `entscheidung` (Stand der letzten Prüfung: Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Zielwert, Priorität, Status), `pruefung` (Intervall, Zeitraffer, `restSekunden`), `stimmen` (live: Kategorien, `verteilung` je Grad, `durchschnittC`, `zielNachPruefung`, eigene Stimme), `vortrag`, `manuell`, `verlauf`, `szenarien`. | +| `POST /api/stimme` | `{"client":"","rolle":"studierende","temperaturWunsch":22.5}` (Webinterface, °C in 0,5er-Schritten) oder `"temperatur":"kuehler\|angenehm\|waermer"`, dazu `"licht":"dunkler\|passt\|heller"`, `"fenster":"auf\|zu"` – eine Stimme pro Client (Webinterface: pro Browser-Tab), Felder einzeln überschreibbar. `{"client":"","zuruecknehmen":true}` löscht die Stimme. | +| `POST /api/pruefen` | `{}` – sofort prüfen, der 2-min-Zyklus beginnt neu | +| `POST /api/zeitraffer` | `{"faktor":1\|5\|10}` – Prüfung alle 2 min / 24 s / 12 s | | `POST /api/vortragsmodus` | `{"rolle":"dozent","aktiv":true,"dauerMinuten":60}` (30/60/90) | | `POST /api/manuell` | `{"rolle":"dozent","fenster":"closed\|tilted\|open\|auto","jalousie":0…100\|"auto","licht":0…100\|"auto","lueftung":"an\|aus\|auto"}` – fehlende Felder bleiben, gilt 90 min. `{"rolle":"dozent","zuruecksetzen":true}` löscht alles. | | `POST /api/jalousie` | `{"rolle":"dozent","position":100}` (0 = offen, 100 = zu), Kurzform von `/api/manuell` | -| `POST /api/szenario` | `{"id":"live\|normal\|co2\|noise\|storm\|presentation\|outlier\|noisewish"}` | +| `POST /api/szenario` | `{"id":"live\|normal\|co2\|noise\|storm\|presentation\|outlier\|noisewish\|offline"}` | | `GET /api/unity` | Für den Unity-Zwilling, siehe unten | | `GET /api/messwerte`, `GET /api/steuerung` | kompatibel zu `server.py` | Die Rolle wird nicht geprüft (keine Anmeldung, siehe `docs/offene-punkte.md`). ### Unity-Zwilling anbinden -Der Zwilling (`frontend/SmartLectureRoom`) startet im Modus **Verbindung → Backend** (`BackendLink.cs`). Er fragt jede Sekunde `GET /api/unity?client=` ab und **führt nur aus**. Seine eigene `ClimateController`-Logik ruht, solange das Backend antwortet. Bei mehr als 5 s ohne Antwort springt sie als Fallback ein. - -Eingaben im Unity-HUD gehen an **dieselben Endpunkte wie beim Webinterface**: Stimme (`/api/stimme`, Kennung `unity-…`), Szenario, Vortragsmodus, manuelle Einstellungen. Website und Zwilling zeigen daher immer denselben Zustand. Die eigene Handsteuerung des Zwillings ist dann aus; manuelle Werte laufen über `/api/manuell`, damit die Schutzregeln greifen. +Der Zwilling (`frontend/SmartLectureRoom`, Verbindung **Backend**, Klasse `ArduinoBridge`) fragt jede Sekunde `GET /api/unity` ab und **zeigt nur an**: Er übernimmt die Werte (nur echte Sensorwerte gelten als „Sensor“, siehe `quellen`) und führt den Steuerbefehl aus. Bedient wird ausschließlich im Webinterface. Antwortet das Backend länger als 5 s nicht oder steht der Unity-Umschalter auf „Simulation“, rechnet die Ersatzlogik (`ClimateController`) mit denselben Regeln. Die Abfrage nutzt `UnityWebRequest` und läuft deshalb auch als WebGL im Browser. ```json { "szenario": "noise", "sensor": {"t":22.5,"co2":1374,"nout":86,"tout":14,"wind":2.2,"sun":200}, - "sensorFelder": ["t","co2","nout","tout","wind","sun"], + "sensorFelder": ["t","co2","rh","tvoc","lightpct","nout","tout","wind","sun"], + "quellen": {"t":"sensor","co2":"sensor","nout":"sensor","tout":"wetter","…":"…"}, + "sensorOnline": true, "ton": "warning", "prioritaetNummer": 1, "fensterGesperrt": true, + "vetos": {"co2":true,"laerm":true,"wind":false,"aussenluft":false}, + "pruefung": {"intervallSekunden":120,"zeitraffer":1,"abstandSekunden":120,"restSekunden":84,"letzteUhrzeit":"11:06"}, + "verlauf": [{"uhrzeit":"11:06","titel":"Lüftungsanlage gestartet","grund":"…","ton":"warning"}], "steuerung": {"window":"tilted","blind":0.32,"heat":0,"vent":1,"light":0.6,"beamer":0}, "status": "Frischluft, trotz hoher Außenlautstärke", "detail": "CO₂ erfordert Lüften. Der Lärmschutz begrenzt die Öffnung.", diff --git a/backend/logik.js b/backend/logik.js index 1e30fcb..885f4a8 100644 --- a/backend/logik.js +++ b/backend/logik.js @@ -33,6 +33,8 @@ const GRENZWERTE = { totzone: 0.2, // |Durchschnitt| darunter: Zielwert bleibt (Ausreisser) heizenAbC: 0.5, // unter Ziel - 0,5 °C wird geheizt kuehlenAbC: 1, // ueber Ziel + 1 °C wird gelueftet (Zielbereich im Webinterface: Ziel ± 1 °C) + wunschMinC: 18, // Eingabebereich fuer Zahlenwuensche im Webinterface (Schritte von 0,5 °C) + wunschMaxC: 26, }; const STIMME_WERT = { kuehler: -1, angenehm: 0, waermer: 1, dunkler: -1, passt: 0, heller: 1 }; @@ -67,13 +69,39 @@ function zaehle(stimmen, feld, namen) { return { anzahl, gesamt, durchschnitt: gesamt ? summe / gesamt : 0 }; } +/** + * Temperaturstimmen: entweder Zahlenwunsch in °C (`wunschC`, Webinterface) oder kuehler/angenehm/waermer. + * Beide werden in Stufen um die Baseline umgerechnet (1 Stufe = gradProStimme °C) und gemittelt. + * `anzahl` ordnet Zahlenwuensche den drei Kategorien zu, `verteilung` zaehlt sie je ganzes Grad (≤19 … ≥25). + */ +function temperaturStimmen(stimmen, g) { + const anzahl = { kuehler: 0, angenehm: 0, waermer: 0 }; + const verteilung = { "19": 0, "20": 0, "21": 0, "22": 0, "23": 0, "24": 0, "25": 0 }; + let summe = 0; + let gesamt = 0; + for (const s of stimmen) { + let stufe; + if (typeof s.wunschC === "number" && Number.isFinite(s.wunschC)) { + stufe = (begrenze(s.wunschC, g.wunschMinC, g.wunschMaxC) - g.basisTemperaturC) / g.gradProStimme; + } else if (s.temperatur in anzahl) { + stufe = STIMME_WERT[s.temperatur]; + } else continue; + anzahl[stufe < -1 / 3 ? "kuehler" : stufe > 1 / 3 ? "waermer" : "angenehm"] += 1; + const grad = Math.round(g.basisTemperaturC + stufe * g.gradProStimme); + verteilung[String(begrenze(grad, 19, 25))] += 1; + summe += stufe; + gesamt += 1; + } + return { anzahl, verteilung, gesamt, durchschnitt: gesamt ? summe / gesamt : 0 }; +} + /** * Temperatur und Licht: Durchschnitt aller Live-Eingaben (jede Stimme zaehlt gleich, auch die des Dozenten). * Liegt der Durchschnitt in der Totzone, bleibt der Zielwert (Ausreisser veraendern ihn nicht). * Fenster: gewuenscht, wenn mehr Stimmen fuer "auf" als fuer "zu" abgegeben wurden. */ function aggregiere(stimmen, g = GRENZWERTE) { - const temp = zaehle(stimmen, "temperatur", ["kuehler", "angenehm", "waermer"]); + const temp = temperaturStimmen(stimmen, g); const licht = zaehle(stimmen, "licht", ["dunkler", "passt", "heller"]); const fenster = zaehle(stimmen, "fenster", ["auf", "zu"]); @@ -84,7 +112,10 @@ function aggregiere(stimmen, g = GRENZWERTE) { const begrenzt = wunsch < g.zielMinC || wunsch > g.zielMaxC; return { - temperatur: { ...temp, durchschnitt: runde(temp.durchschnitt, 2), zielTemperatur, ausreisser, begrenzt }, + temperatur: { + ...temp, durchschnitt: runde(temp.durchschnitt, 2), zielTemperatur, ausreisser, begrenzt, + durchschnittC: temp.gesamt ? runde(g.basisTemperaturC + temp.durchschnitt * g.gradProStimme, 1) : null, + }, licht: { ...licht, durchschnitt: runde(licht.durchschnitt, 2) }, fenster: { anzahl: fenster.anzahl, gesamt: fenster.gesamt, gewuenscht: fenster.anzahl.auf > fenster.anzahl.zu }, }; diff --git a/backend/raum.js b/backend/raum.js index 2ccfa5d..7b3d9e1 100644 --- a/backend/raum.js +++ b/backend/raum.js @@ -1,6 +1,6 @@ // Zustand des Raums im Speicher: Messwerte, Wetter, Stimmen, Dozentenvorgaben, Demo-Szenario und Verlauf. // Die Zeit wird als Parameter `jetzt` (ms) uebergeben, damit sich alles ohne Warten testen laesst. -const { GRENZWERTE, KEIN_MANUELL, entscheide, unityBefehl } = require("./logik"); +const { GRENZWERTE, KEIN_MANUELL, aggregiere, entscheide, unityBefehl } = require("./logik"); const MESSWERT_FELDER = ["temperatur", "luftfeuchte", "eco2", "tvoc", "lautstaerke", "helligkeit"]; const MAX_MESSWERTE = 100; @@ -11,6 +11,7 @@ const MANUELL_GUELTIG_MS = 90 * 60 * 1000; // manuelle Einstellungen gelten eine const FENSTER_CODES = ["closed", "tilted", "open"]; const STIMMEN_FELD = { kuehler: "temperatur", angenehm: "temperatur", waermer: "temperatur", dunkler: "licht", passt: "licht", heller: "licht", auf: "fenster", zu: "fenster" }; const VORTRAG_DAUERN_MIN = [30, 60, 90]; +const ZEITRAFFER_FAKTOREN = [1, 5, 10]; // Demo-Szenarien aus dem Figma-Prototyp. Sie ueberschreiben die Sensorwerte, solange sie aktiv sind. // "live" nutzt nur echte Sensordaten, echtes Wetter und echte Stimmen. @@ -51,6 +52,10 @@ const SZENARIEN = [ innen: { temperatur: 22.5, eco2: 1374 }, aussen: { laerm: 86, wind: 8, feinstaub: 9 }, stimmen: { kuehler: 1, angenehm: 7, waermer: 1, auf: 6, zu: 3 }, }, + { + id: "offline", text: "Sensor offline", beschreibung: "Ehrlicher Fehlerzustand", offline: true, + stimmen: { kuehler: 1, angenehm: 7, waermer: 1 }, + }, ]; const DEMO_AUSSEN = { temperatur: 14, sonne: 200 }; @@ -70,7 +75,17 @@ function ohneLichtUndJalousie(manuell) { } class Raum { - constructor(jetzt = Date.now()) { + /** + * @param {number} jetzt + * @param {{pruefIntervallMs?: number}} optionen pruefIntervallMs: Abstand der Pruefzyklen (0 = bei jeder Abfrage, + * so arbeiten die Tests; server.js nutzt 2 Minuten). Messwerte und Stimmen werden sofort angezeigt, + * entschieden wird erst bei der naechsten Pruefung. + */ + constructor(jetzt = Date.now(), { pruefIntervallMs = 0 } = {}) { + this.pruefIntervallMs = pruefIntervallMs; + this.zeitraffer = 1; + this.letztePruefung = null; + this.naechstePruefung = jetzt; // erste Entscheidung sofort this.messwerte = []; // { zeit, temperatur, luftfeuchte, eco2, tvoc, lautstaerke, helligkeit } this.wetter = null; // { zeit, temperatur, wind, sonne, feinstaub, aqi } this.stimmen = new Map(); // client -> { rolle, temperatur, licht, zeit } @@ -88,6 +103,7 @@ class Raum { /** Messwertsatz vom ESP8266. Wirft einen Fehler mit Meldung, wenn ein Feld keine Zahl ist. */ messwertEmpfangen(daten, jetzt = Date.now()) { + const warOffline = this.aktuellerMesswert(jetzt) === null && !this.szenario.offline; const eintrag = { zeit: new Date(jetzt).toISOString() }; for (const feld of MESSWERT_FELDER) { const wert = daten[feld]; @@ -97,7 +113,11 @@ class Raum { } this.messwerte.push(eintrag); if (this.messwerte.length > MAX_MESSWERTE) this.messwerte.shift(); - this.aktualisiere(jetzt); + // Erste Messung nach Start oder Ausfall: sofort pruefen, statt bis zu 2 min mit alten Annahmen zu warten + if (warOffline) { + this.protokolliere(jetzt, "Sensor verbunden", "Der Arduino liefert wieder Messwerte. Die Steuerung prüft sofort.", "good"); + this.pruefe(jetzt); + } else this.aktualisiere(jetzt); return eintrag; } @@ -106,8 +126,21 @@ class Raum { this.aktualisiere(jetzt); } - stimmeAbgeben({ client, rolle, temperatur, licht, fenster }, jetzt = Date.now()) { + /** + * Stimme eines Clients (Browser-Tab, Geraet oder Unity). temperaturWunsch: Zahl in °C (Webinterface, wird auf + * 0,5 °C gerundet und auf 18–26 °C begrenzt) oder temperatur kuehler|angenehm|waermer. `zuruecknehmen: true` + * loescht die Stimme. Die Entscheidung folgt beim naechsten Pruefzyklus. + */ + stimmeAbgeben({ client, rolle, temperatur, temperaturWunsch, licht, fenster, zuruecknehmen }, jetzt = Date.now()) { if (typeof client !== "string" || client.length < 4 || client.length > 64) throw new Error("Feld 'client' fehlt"); + if (zuruecknehmen === true) { + this.stimmen.delete(client); + this.aktualisiere(jetzt); + return; + } + if (temperaturWunsch !== undefined && (typeof temperaturWunsch !== "number" || !Number.isFinite(temperaturWunsch))) { + throw new Error("Feld 'temperaturWunsch' muss eine Zahl in °C sein"); + } if (temperatur !== undefined && !["kuehler", "angenehm", "waermer"].includes(temperatur)) { throw new Error("Feld 'temperatur' muss kuehler, angenehm oder waermer sein"); } @@ -116,9 +149,13 @@ class Raum { } if (fenster !== undefined && !["auf", "zu"].includes(fenster)) throw new Error("Feld 'fenster' muss auf oder zu sein"); const alt = this.stimmen.get(client) || {}; + const wunschC = temperaturWunsch !== undefined + ? Math.round(Math.min(GRENZWERTE.wunschMaxC, Math.max(GRENZWERTE.wunschMinC, temperaturWunsch)) * 2) / 2 + : temperatur !== undefined ? undefined : alt.wunschC; // eine Temperaturmeinung pro Client this.stimmen.set(client, { rolle: rolle === "dozent" ? "dozent" : "studierende", - temperatur: temperatur ?? alt.temperatur, + wunschC, + temperatur: temperaturWunsch !== undefined ? undefined : temperatur ?? alt.temperatur, licht: licht ?? alt.licht, fenster: fenster ?? alt.fenster, zeit: jetzt, @@ -142,7 +179,7 @@ class Raum { this.manuell = ohneLichtUndJalousie(this.manuell); this.protokolliere(jetzt, "Vortragsmodus beendet", "Die reguläre Raumautomatik ist wieder aktiv.", "info"); } - this.aktualisiere(jetzt); + this.pruefe(jetzt); // Befehl des Dozenten wirkt sofort } /** @@ -176,7 +213,7 @@ class Raum { aktiv ? `Gültig bis ${uhrzeit(this.manuell.bis)}. CO₂-Grenzwert und Sturmschutz bleiben aktiv.` : "Alle manuellen Einstellungen wurden zurückgesetzt.", aktiv ? "warning" : "info", ); - this.aktualisiere(jetzt); + this.pruefe(jetzt); // Befehl des Dozenten wirkt sofort } /** Jalousie manuell fahren (0 = offen, 100 = zu), wie im Webinterface. Kurzform von manuellSetzen. */ @@ -193,9 +230,27 @@ class Raum { if (szenario.vortrag) this.vortragEnde = jetzt + this.vortragDauer * 60000; else this.vortragEnde = null; this.letzteAktion = null; // Entscheidung des neuen Szenarios immer protokollieren + this.pruefe(jetzt); // Demo-Szenario wirkt sofort + } + + /** "Jetzt pruefen": Entscheidung sofort neu berechnen statt auf den naechsten Pruefzyklus zu warten. */ + jetztPruefen(jetzt = Date.now()) { + return this.pruefe(jetzt); + } + + /** Zeitraffer 1×, 5× oder 10×: Pruefzyklen entsprechend oefter (2 min → 24 s → 12 s). */ + zeitrafferSetzen(faktor, jetzt = Date.now()) { + if (!ZEITRAFFER_FAKTOREN.includes(faktor)) throw new Error("Zeitraffer muss 1, 5 oder 10 sein"); + this.zeitraffer = faktor; + const basis = this.letztePruefung ?? jetzt; + this.naechstePruefung = Math.min(this.naechstePruefung, basis + this.pruefAbstandMs()); this.aktualisiere(jetzt); } + pruefAbstandMs() { + return this.pruefIntervallMs / this.zeitraffer; + } + // ---------- Auswertung ---------- vortragAktiv(jetzt) { @@ -203,6 +258,7 @@ class Raum { } aktuellerMesswert(jetzt) { + if (this.szenario.offline) return null; // Demo "Sensor offline" const letzter = this.messwerte[this.messwerte.length - 1]; if (!letzter || jetzt - Date.parse(letzter.zeit) > MESSWERT_VERALTET_MS) return null; return letzter; @@ -247,18 +303,29 @@ class Raum { }; } - /** Rechnet die Entscheidung neu, beendet abgelaufene Modi und schreibt Aenderungen in den Verlauf. */ + /** + * Haelt den Zustand aktuell: Messwerte fuer die Anzeige immer, die Entscheidung nur zum Pruefzyklus + * (alle 2 min, mit Zeitraffer oefter) oder wenn ein Vortragsmodus bzw. manuelle Einstellungen ablaufen. + */ aktualisiere(jetzt = Date.now()) { + let faellig = this.entscheidung === undefined || jetzt >= this.naechstePruefung; if (this.vortragEnde !== null && this.vortragEnde <= jetzt) { this.vortragEnde = null; if (this.szenario.vortrag) this.szenario = SZENARIEN.find((s) => s.id === "normal"); this.protokolliere(jetzt, "Vortragsmodus beendet", "Die eingestellte Dauer ist abgelaufen. Die reguläre Raumautomatik übernimmt.", "info"); + faellig = true; } if (this.manuell.bis !== null && this.manuell.bis <= jetzt) { this.manuell = { ...KEIN_MANUELL, bis: null }; this.protokolliere(jetzt, "Manuelle Einstellungen gelöscht", "Nach 90 Minuten übernimmt wieder die Automatik.", "info"); + faellig = true; } + this.eingabeWerte = this.eingaben(jetzt); + return faellig ? this.pruefe(jetzt) : this.entscheidung; + } + /** Pruefzyklus: Entscheidung aus den aktuellen Eingaben berechnen und Aenderungen protokollieren. */ + pruefe(jetzt = Date.now()) { const e = this.eingaben(jetzt); const entscheidung = entscheide({ innen: { temperatur: e.temperatur.wert, eco2: e.eco2.wert, helligkeit: e.helligkeit.wert }, @@ -274,9 +341,23 @@ class Raum { } this.entscheidung = entscheidung; this.eingabeWerte = e; + this.letztePruefung = jetzt; + this.naechstePruefung = jetzt + this.pruefAbstandMs(); return entscheidung; } + /** Stand der Pruefzyklen fuer Webinterface und Unity. */ + pruefungInfo(jetzt) { + return { + intervallSekunden: Math.round(this.pruefIntervallMs / 1000), + zeitraffer: this.zeitraffer, + abstandSekunden: Math.round(this.pruefAbstandMs() / 1000), + letzte: this.letztePruefung === null ? null : new Date(this.letztePruefung).toISOString(), + letzteUhrzeit: this.letztePruefung === null ? "" : uhrzeit(this.letztePruefung), + restSekunden: Math.max(0, Math.ceil((this.naechstePruefung - jetzt) / 1000)), + }; + } + protokolliere(jetzt, titel, grund, ton) { this.verlauf.unshift({ zeit: new Date(jetzt).toISOString(), uhrzeit: uhrzeit(jetzt), titel, grund, ton }); if (this.verlauf.length > MAX_VERLAUF) this.verlauf.pop(); @@ -289,8 +370,12 @@ class Raum { const d = this.aktualisiere(jetzt); const eigene = client ? this.stimmen.get(client) : null; const sensor = this.aktuellerMesswert(jetzt); + // Stimmen sofort anzeigen; der Zielwert daraus gilt erst nach der naechsten Pruefung + const liveAgg = aggregiere(this.gueltigeStimmen(jetzt)); + const live = liveAgg.temperatur; return { jetzt: new Date(jetzt).toISOString(), + pruefung: this.pruefungInfo(jetzt), szenario: this.szenario.id, szenarien: SZENARIEN.map(({ id, text, beschreibung }) => ({ id, text, beschreibung })), sensorOnline: sensor !== null, @@ -313,11 +398,16 @@ class Raum { bis: this.manuell.bis === null ? null : new Date(this.manuell.bis).toISOString(), }, stimmen: { - temperatur: d.aggregation.temperatur.anzahl, - licht: d.aggregation.licht.anzahl, - fenster: d.aggregation.fenster.anzahl, - gesamt: d.aggregation.temperatur.gesamt, - eigene: eigene ? { temperatur: eigene.temperatur ?? null, licht: eigene.licht ?? null, fenster: eigene.fenster ?? null } : null, + temperatur: live.anzahl, + verteilung: live.verteilung, + durchschnittC: live.durchschnittC, + zielNachPruefung: live.zielTemperatur, + licht: liveAgg.licht.anzahl, + fenster: liveAgg.fenster.anzahl, + gesamt: live.gesamt, + eigene: eigene + ? { temperatur: eigene.temperatur ?? null, temperaturWunsch: eigene.wunschC ?? null, licht: eigene.licht ?? null, fenster: eigene.fenster ?? null, zeit: new Date(eigene.zeit).toISOString() } + : null, }, verlauf: this.verlauf, }; @@ -334,13 +424,22 @@ class Raum { const setze = (feld, wert) => { if (wert !== null) sensor[feld] = wert; }; - setze("t", e.temperatur.wert); - setze("co2", e.eco2.wert); - setze("nout", e.laerm.wert); - setze("tout", e.aussenTemperatur.wert); - setze("wind", e.wind.wert === null ? null : Math.round((e.wind.wert / 3.6) * 10) / 10); // km/h -> m/s - setze("sun", e.sonne.wert); - setze("aq", e.aqi.wert); + const quellen = {}; + const mit = (feld, eingabe, umrechnen = (w) => w) => { + if (eingabe.wert === null) return; + setze(feld, umrechnen(eingabe.wert)); + quellen[feld] = eingabe.quelle; + }; + mit("t", e.temperatur); + mit("co2", e.eco2); + mit("rh", e.luftfeuchte); + mit("tvoc", e.tvoc); + mit("lightpct", e.helligkeit); + mit("nout", e.laerm); // Mikrofon MAX9814 = Aussenlaerm + mit("tout", e.aussenTemperatur); + mit("wind", e.wind, (w) => Math.round((w / 3.6) * 10) / 10); // km/h -> m/s + mit("sun", e.sonne); + mit("aq", e.aqi); const eigene = client ? this.stimmen.get(client) : null; const vortrag = this.vortragAktiv(jetzt); return { @@ -348,10 +447,19 @@ class Raum { szenario: this.szenario.id, sensor, sensorFelder: Object.keys(sensor), // JsonUtility kennt kein "fehlt" – Unity simuliert die uebrigen Felder + quellen, // je Feld sensor | wetter | demo + sensorOnline: this.aktuellerMesswert(jetzt) !== null, steuerung: unityBefehl(d), status: d.status.titel, detail: d.status.detail, + ton: d.status.ton, prioritaet: d.prioritaet.text, + prioritaetNummer: d.prioritaet.nummer, + vetos: d.vetos, + fensterGesperrt: d.fenster.gesperrt, + grenzwerte: { co2Ppm: GRENZWERTE.co2Ppm, laermDb: GRENZWERTE.laermDb, windKmh: GRENZWERTE.windKmh }, + pruefung: this.pruefungInfo(jetzt), + verlauf: this.verlauf.slice(0, 5).map(({ uhrzeit: zeit, titel, grund, ton }) => ({ uhrzeit: zeit, titel, grund, ton })), pfad: d.pfad, zielTemperatur: d.zielTemperatur, stimmen: { diff --git a/backend/server.js b/backend/server.js index 8dd29ee..f9e2091 100644 --- a/backend/server.js +++ b/backend/server.js @@ -14,7 +14,6 @@ const { holeWetter } = require("./wetter"); const PORT = Number(process.argv[2] || process.env.PORT || 3000); const FRONTEND_DIR = path.resolve(__dirname, "..", "frontend"); -const STARTSEITE = path.join(FRONTEND_DIR, "ambient", "index.html"); const WIFI_CONFIG = path.resolve(__dirname, "..", "firmware", "dht11_lcd", "wifi_config.h"); const MAX_BODY_BYTES = 1024; const WETTER_INTERVALL_MS = 10 * 60 * 1000; @@ -37,7 +36,9 @@ const MIME = { ".data": "application/octet-stream", }; -const raum = new Raum(); +// Pruefzyklus: alle 2 Minuten wird entschieden (PRUEF_SEKUNDEN=… zum Aendern), "Jetzt pruefen" und Zeitraffer im Webinterface +const PRUEF_SEKUNDEN = Number(process.env.PRUEF_SEKUNDEN || 120); +const raum = new Raum(Date.now(), { pruefIntervallMs: PRUEF_SEKUNDEN * 1000 }); function zeitstempel() { return new Date().toLocaleTimeString("de-DE"); @@ -117,6 +118,14 @@ const POST_ROUTEN = { "/api/vortragsmodus": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.vortragsmodus(daten)), "/api/jalousie": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.jalousieFahren(daten.position)), "/api/manuell": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.manuellSetzen(daten)), + "/api/pruefen": (res) => aendere(res, () => { + raum.jetztPruefen(); + console.log(zeitstempel(), "Pruefung von Hand ausgeloest"); + }), + "/api/zeitraffer": (res, daten) => aendere(res, () => { + raum.zeitrafferSetzen(daten.faktor); + console.log(zeitstempel(), `Zeitraffer ${daten.faktor}x (Pruefung alle ${raum.pruefAbstandMs() / 1000} s)`); + }), "/api/szenario": (res, daten) => aendere(res, () => { raum.szenarioWaehlen(daten.id); console.log(zeitstempel(), "Szenario:", daten.id); @@ -143,7 +152,12 @@ const GET_ROUTEN = { }; function sendeDatei(res, pfad) { - const datei = pfad === "/" ? STARTSEITE : path.resolve(FRONTEND_DIR, "." + decodeURIComponent(pfad)); + if (pfad === "/") { + // Startseite = Webinterface; Weiterleitung, damit relative Pfade (ambient.css, app.js) stimmen + res.writeHead(302, { Location: "/ambient/" }); + return res.end(); + } + const datei = path.resolve(FRONTEND_DIR, "." + decodeURIComponent(pfad)); if (!datei.startsWith(FRONTEND_DIR + path.sep)) return sendeJson(res, 403, { fehler: "Verboten" }); const ziel = fs.existsSync(datei) && fs.statSync(datei).isDirectory() ? path.join(datei, "index.html") : datei; fs.readFile(ziel, (fehler, inhalt) => { @@ -212,6 +226,7 @@ function ipHinweis() { // 0.0.0.0, damit der ESP8266 im WLAN/Hotspot den Server erreicht server.listen(PORT, "0.0.0.0", () => { console.log(`Backend laeuft auf Port ${PORT} (Webinterface: http://localhost:${PORT})`); + console.log(`Pruefzyklus alle ${PRUEF_SEKUNDEN} s (Zeitraffer und "Jetzt pruefen" im Webinterface)`); ipHinweis(); console.log("Beenden mit Strg+C\n"); }); diff --git a/backend/simulator.py b/backend/simulator.py index 20557a7..ce62fd9 100644 --- a/backend/simulator.py +++ b/backend/simulator.py @@ -1,13 +1,15 @@ # Simuliert den ESP8266: schickt alle 2 s Fantasiewerte an den Server (Entwicklung ohne Hardware). # Start: python simulator.py [Server-URL] [--szenario NAME] z. B. http://localhost:3000 --szenario hitze # -# Szenarien (fuer Vorfuehrungen; das Backend entscheidet, Website und Unity-Zwilling zeigen es): +# Szenarien (fuer Vorfuehrungen; das Backend entscheidet, Webinterface und Unity-Zwilling zeigen es): # wechsel (Standard) Temperatur und CO2 schwanken, CO2 ueberschreitet zeitweise 1000 ppm -# normal angenehmes Raumklima (22 °C, ca. 650 ppm) +# normal angenehmes Raumklima (22 °C, ca. 650 ppm, ca. 45 dB) # hitze Temperatur steigt langsam auf ca. 30 °C -> Fenster oeffnen # stickig CO2 steigt langsam auf ca. 1600 ppm -> Lueften (Fenster oder Lueftungsanlage) -# kalt Temperatur faellt auf ca. 17 °C -> Heizen -# demo laeuft nacheinander normal -> stickig -> normal -> hitze -> kalt durch (je ca. 1 min) +# kalt Temperatur faellt auf ca. 17 °C -> Heizung +# laerm CO2 hoch und Lautstaerke ca. 80 dB -> Laerm-Veto: Fenster zu, Lueftungsanlage (ausser Mehrheit will lueften) +# dunkel Helligkeit faellt auf ca. 10 % -> Licht heller +# demo laeuft nacheinander normal -> stickig -> laerm -> normal -> hitze -> dunkel -> kalt durch (je ca. 1 min) import argparse import json import math @@ -16,19 +18,27 @@ import urllib.request parser = argparse.ArgumentParser(description="Fake-Messwerte wie vom ESP8266") parser.add_argument("basis", nargs="?", default="http://localhost:3000", help="Server-URL") -parser.add_argument("--szenario", default="wechsel", choices=["wechsel", "normal", "hitze", "stickig", "kalt", "demo"]) +parser.add_argument("--szenario", default="wechsel", + choices=["wechsel", "normal", "hitze", "stickig", "kalt", "laerm", "dunkel", "demo"]) args = parser.parse_args() -ZIELE = { # Zielwerte (Temperatur °C, eCO2 ppm), auf die sich die Werte langsam zubewegen - "normal": (22.0, 650), - "hitze": (30.0, 750), - "stickig": (23.0, 1600), - "kalt": (17.0, 600), +ZIELE = { # Zielwerte (Temperatur °C, eCO2 ppm, Lautstaerke dB, Helligkeit %), auf die sich die Werte langsam zubewegen + "normal": (22.0, 650, 45.0, 60), + "hitze": (30.0, 750, 48.0, 85), + "stickig": (23.0, 1600, 52.0, 60), + "kalt": (17.0, 600, 42.0, 35), + "laerm": (23.0, 1400, 80.0, 60), + "dunkel": (22.0, 700, 44.0, 10), } -DEMO_ABLAUF = ["normal", "stickig", "normal", "hitze", "kalt"] +DEMO_ABLAUF = ["normal", "stickig", "laerm", "normal", "hitze", "dunkel", "kalt"] DEMO_SCHRITTE = 30 # 30 x 2 s = 1 min je Abschnitt -temperatur, eco2 = 22.0, 650.0 + +def naeher(wert, ziel, schritt): + return wert + max(-schritt, min(schritt, ziel - wert)) + + +temperatur, eco2, lautstaerke, helligkeit = 22.0, 650.0, 45.0, 60.0 schritt = 0 while True: @@ -36,28 +46,32 @@ while True: if args.szenario == "wechsel": temperatur = 22 + 2 * math.sin(schritt / 20) eco2 = 800 + 400 * math.sin(schritt / 25) # ueberschreitet zeitweise 1000 ppm + lautstaerke = 50 + 10 * math.sin(schritt / 7) + helligkeit = 55 + 30 * math.sin(schritt / 30) aktiv = "wechsel" else: aktiv = args.szenario if aktiv == "demo": aktiv = DEMO_ABLAUF[(schritt // DEMO_SCHRITTE) % len(DEMO_ABLAUF)] - ziel_t, ziel_co2 = ZIELE[aktiv] - temperatur += max(-0.4, min(0.4, ziel_t - temperatur)) - eco2 += max(-60.0, min(60.0, ziel_co2 - eco2)) + ziel_t, ziel_co2, ziel_laut, ziel_licht = ZIELE[aktiv] + temperatur = naeher(temperatur, ziel_t, 0.4) + eco2 = naeher(eco2, ziel_co2, 60.0) + lautstaerke = naeher(lautstaerke, ziel_laut, 4.0) + helligkeit = naeher(helligkeit, ziel_licht, 6.0) messwert = { "temperatur": round(temperatur + 0.1 * math.sin(schritt), 1), "luftfeuchte": round(45 + 5 * math.sin(schritt / 15), 1), "eco2": round(eco2 + 10 * math.sin(schritt / 3)), "tvoc": round(70 + 30 * math.sin(schritt / 10) + max(0.0, eco2 - 800) / 10), - "lautstaerke": round(50 + 10 * math.sin(schritt / 7), 1), # Mikrofon, gilt im Backend als Aussenlaerm - "helligkeit": round(55 + 30 * math.sin(schritt / 30)), # Fotowiderstand in %, zeitweise zu hell + "lautstaerke": round(lautstaerke + 1.5 * math.sin(schritt / 2), 1), + "helligkeit": max(0, min(100, round(helligkeit + 2 * math.sin(schritt / 4)))), } anfrage = urllib.request.Request(args.basis + "/api/messwerte", data=json.dumps(messwert).encode(), headers={"Content-Type": "application/json"}) try: urllib.request.urlopen(anfrage, timeout=3).read() - print(f"gesendet [{aktiv}]", json.dumps(messwert)) + print(f"gesendet [{aktiv}]", json.dumps(messwert), flush=True) except OSError as fehler: - print("Server nicht erreichbar:", fehler) + print("Server nicht erreichbar:", fehler, flush=True) time.sleep(2) diff --git a/backend/test/logik.test.js b/backend/test/logik.test.js index f6a2b02..394a2d8 100644 --- a/backend/test/logik.test.js +++ b/backend/test/logik.test.js @@ -240,3 +240,79 @@ test("Unity und Webinterface sehen denselben Zustand", () => { // Keine null-Werte: Unitys JsonUtility kann sie nicht lesen assert.ok(!JSON.stringify(v).includes("null")); }); + +test("Pruefzyklus: Messwerte sofort sichtbar, Entscheidung erst zur Pruefung, Jetzt pruefen und Zeitraffer", () => { + const t0 = Date.parse("2026-11-24T09:00:00Z"); + const raum = new Raum(t0, { pruefIntervallMs: 120000 }); + raum.messwertEmpfangen({ temperatur: 22, eco2: 600, lautstaerke: 45 }, t0); + raum.jetztPruefen(t0); + assert.equal(raum.zustand(t0).entscheidung.fenster.code, "closed"); + + raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + 10000); + let z = raum.zustand(t0 + 10000); + assert.equal(z.werte.eco2.wert, 1400); // Anzeige sofort + assert.equal(z.entscheidung.fenster.code, "closed"); // Entscheidung noch alt + assert.equal(z.pruefung.restSekunden, 110); + + for (let t = 20000; t <= 115000; t += 5000) raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + t); // Station sendet laufend + assert.equal(raum.zustand(t0 + 115000).entscheidung.fenster.code, "closed"); + assert.equal(raum.zustand(t0 + 120000).entscheidung.fenster.code, "open"); // naechster Zyklus + + raum.messwertEmpfangen({ temperatur: 22, eco2: 600, lautstaerke: 45 }, t0 + 125000); + raum.jetztPruefen(t0 + 125000); // Knopf "Jetzt pruefen" + assert.equal(raum.zustand(t0 + 125000).entscheidung.fenster.code, "closed"); + + raum.zeitrafferSetzen(10, t0 + 125000); + assert.equal(raum.zustand(t0 + 125000).pruefung.restSekunden, 12); + assert.throws(() => raum.zeitrafferSetzen(3, t0)); +}); + +test("Zahlenwuensche (Webinterface) werden gemittelt, eine Stimme pro Client, zuruecknehmen moeglich", () => { + const t0 = Date.parse("2026-11-24T09:00:00Z"); + const raum = new Raum(t0); + raum.stimmeAbgeben({ client: "tab-aaaa", temperaturWunsch: 23.5 }, t0); + raum.stimmeAbgeben({ client: "tab-bbbb", temperaturWunsch: 23.5 }, t0); + raum.stimmeAbgeben({ client: "tab-cccc", temperaturWunsch: 23 }, t0); + let z = raum.zustand(t0, "tab-aaaa"); + assert.equal(z.stimmen.gesamt, 3); + assert.equal(z.stimmen.durchschnittC, 23.3); + assert.equal(z.entscheidung.zielTemperatur, 23.5); + assert.equal(z.stimmen.eigene.temperaturWunsch, 23.5); + assert.equal(z.stimmen.verteilung["24"], 2); // 23,5 °C rundet auf 24 + + raum.stimmeAbgeben({ client: "tab-aaaa", temperaturWunsch: 30 }, t0); // Ueberschreiben, auf 26 °C begrenzt + assert.equal(raum.zustand(t0, "tab-aaaa").stimmen.eigene.temperaturWunsch, 26); + assert.equal(raum.zustand(t0).stimmen.gesamt, 3); + + raum.stimmeAbgeben({ client: "tab-aaaa", zuruecknehmen: true }, t0); + z = raum.zustand(t0, "tab-aaaa"); + assert.equal(z.stimmen.gesamt, 2); + assert.equal(z.stimmen.eigene, null); +}); + +test("Unity bekommt alle Sensorwerte mit Quelle; Szenario Sensor offline", () => { + const t0 = Date.parse("2026-11-24T09:00:00Z"); + const raum = new Raum(t0); + raum.messwertEmpfangen({ temperatur: 23, luftfeuchte: 44, eco2: 1300, tvoc: 200, lautstaerke: 82, helligkeit: 48 }, t0); + let u = raum.unity(t0); + assert.deepEqual([u.sensor.rh, u.sensor.tvoc, u.sensor.lightpct, u.sensor.nout], [44, 200, 48, 82]); + assert.equal(u.quellen.nout, "sensor"); + assert.equal(u.sensorOnline, true); + assert.equal(u.vetos.laerm, true); + assert.equal(u.steuerung.window, "closed"); // Laerm sperrt, keine Mehrheit fuer "auf" -> Lueftungsanlage + assert.equal(u.steuerung.vent, 1); + + raum.szenarioWaehlen("offline", t0); + u = raum.unity(t0); + assert.equal(u.sensorOnline, false); + assert.equal(u.sensor.co2, undefined); +}); + +test("Pruefzyklus: erste Messung nach Start oder Ausfall wird sofort geprueft", () => { + const t0 = Date.parse("2026-11-24T09:00:00Z"); + const raum = new Raum(t0, { pruefIntervallMs: 120000 }); + assert.equal(raum.zustand(t0).sensorOnline, false); + raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + 5000); + assert.equal(raum.zustand(t0 + 5000).entscheidung.fenster.code, "open"); // nicht erst nach 2 min + assert.ok(raum.verlauf.some((e) => e.titel === "Sensor verbunden")); +}); diff --git a/docs/regeln.md b/docs/regeln.md new file mode 100644 index 0000000..08f39e8 --- /dev/null +++ b/docs/regeln.md @@ -0,0 +1,107 @@ +# Regeln: Wer entscheidet wo, wann und was wird ausgelöst + +Kurzfassung: **Entschieden wird nur im Backend** (`backend/logik.js`), und zwar **alle 2 Minuten** (Prüfzyklus). Das Webinterface ist die Bedienoberfläche (Anzeige + Eingaben), der Unity-Zwilling zeigt nur, was die Entscheidung im Raum bewirkt. Der Ablauf folgt dem Aktivitätsdiagramm [`aktivitaetsdiagramm.png`](aktivitaetsdiagramm.png). + +## 1. Wo wird entschieden? + +```mermaid +flowchart LR + subgraph Raum["Raum 2.14"] + A["Arduino Uno
DHT11 · CCS811 · MAX9814 · LDR"] -->|seriell| E["ESP-01"] + end + E -->|"POST /api/messwerte
alle ~7 s"| B + W["Open-Meteo
Wetter, Feinstaub"] -->|alle 10 min| B + subgraph Laptop + B["backend/server.js
raum.js + logik.js
entscheidet"] + end + B -->|"GET /api/zustand (1 s)"| F["Webinterface Ambient²
Anzeige + Bedienung
(jeder Tab = 1 Person)"] + F -->|"POST Stimme, Vortragsmodus,
Jalousie, Szenario,
Jetzt prüfen, Zeitraffer"| B + B -->|"GET /api/unity (1 s)"| U["Unity-Zwilling
nur Anzeige:
3D-Raum führt aus"] +``` + +| Teil | Aufgabe | Entscheidet? | +|---|---|---| +| Arduino + ESP-01 (`firmware/dht11_lcd`) | misst Temperatur, Luftfeuchte, eCO₂, TVOC, Lautstärke, Helligkeit; sendet ca. alle 7–8 s | nein | +| Backend (`backend/server.js`, `raum.js`, `logik.js`) | sammelt Messwerte, Wetter und Stimmen, prüft alle 2 min, merkt sich den Verlauf | **ja, nur hier** | +| Webinterface (`frontend/ambient`) | zeigt Werte und Entscheidung, nimmt Stimmen und Dozentenbefehle an | nein | +| Unity-Zwilling (`frontend/SmartLectureRoom`) | zeigt im 3D-Raum, was die Entscheidung auslöst (Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Schallwellen bei Lärm) | nein (nur im Modus „Simulation“ oder ohne Backend rechnet er mit derselben Logik selbst) | + +## 2. Wann wird entschieden? + +| Auslöser | Wirkung | +|---|---| +| **Prüfzyklus alle 2 min** | Entscheidung aus den aktuellen Messwerten und Stimmen neu berechnen | +| **„Jetzt prüfen“** (Webinterface) | sofort prüfen, Zyklus beginnt neu | +| **Zeitraffer 1× / 5× / 10×** (Webinterface) | Prüfung alle 2 min / 24 s / 12 s | +| Erste Messung nach Start oder Ausfall des Arduino | sofort prüfen („Sensor verbunden“) | +| Demo-Szenario, Vortragsmodus, manuelle Dozenteneinstellung | sofort prüfen (ausdrücklicher Befehl) | +| Vortragsmodus oder manuelle Einstellung läuft ab | sofort prüfen | +| neuer Messwert, neue Stimme | **wird sofort angezeigt**, wirkt aber erst bei der nächsten Prüfung („Nach der nächsten Prüfung: 23,0 °C“) | + +Einstellbar: `PRUEF_SEKUNDEN=60 node backend/server.js` (Standard 120). + +## 3. Was wird ausgelöst? (Ablauf eines Prüfzyklus) + +```mermaid +flowchart TD + S([Prüfzyklus]) --> D[Eingaben sammeln:
Arduino, Wetter, Stimmen,
Vortragsmodus, manuelle Einstellungen] + D --> AG["Zielwert = Ø aller Wünsche
(begrenzt auf 20–24 °C)"] + AG --> C{"CO₂ > 1000 ppm
oder T > Ziel + 1 °C
(draußen kühler)?"} + C -- nein --> FW{"Mehrheit will
Fenster auf?"} + FW -- ja --> FO[Fenster offen] + FW -- nein --> FZ[Fenster zu] + C -- ja: Lüften nötig --> L1{"Außenluft belastet
(PM10 > 50) oder
draußen < 5 °C?"} + L1 -- ja --> LA[Lüftungsanlage an,
Fenster zu] + L1 -- nein --> L2{"Außenlärm > 70 dB?
(Mikrofon)"} + L2 -- nein --> FO2[Fenster offen] + L2 -- ja --> L3{"Mehrheit will
Fenster auf?"} + L3 -- ja --> FO3[Fenster offen
trotz Lärm] + L3 -- nein --> LA2[Lüftungsanlage an,
Fenster gesperrt] + FO & FZ & LA & FO2 & FO3 & LA2 --> M[Manuelle Dozenteneinstellungen
überschreiben – 90 min] + M --> SR{"Schutzregeln"} + SR --> W1["Wind > 60 km/h → höchstens gekippt"] + SR --> W2["CO₂ zu hoch und Fenster nicht offen
→ Lüftungsanlage bleibt an"] + W1 & W2 --> H{"T < Ziel − 0,5 °C
und Fenster nicht offen?"} + H -- ja --> HZ[Heizung an] + H -- nein --> HA[Heizung aus] + HZ & HA --> J{"Beamer-Modus?"} + J -- ja --> JB[Beamer an, Licht aus,
Jalousie unten] + J -- nein --> J2{"Lichtsensor > 80 %
(ohne Sensor: Sonne > 500 W/m²)"} + J2 -- ja --> JH[Jalousie unten, Licht an] + J2 -- nein --> J3{"Lichtsensor < 30 %?"} + J3 -- ja --> JD[Jalousie oben, Licht heller] + J3 -- nein --> JN[Jalousie oben] + JB & JH & JD & JN --> O([Ausgabe an Webinterface und Unity,
Eintrag im Verlauf]) +``` + +### Regeln als Tabelle + +| Priorität | Bedingung | Wird ausgelöst | Kann ein Nutzer das überstimmen? | +|---|---|---|---| +| 1 Gesundheit | eCO₂ > **1000 ppm** | Lüften: Fenster offen; bei belasteter Außenluft (PM10 > 50 µg/m³) oder < 5 °C draußen stattdessen Lüftungsanlage | **Nein** (Hard-Constraint). Auch bei manuell geschlossenem Fenster bleibt die Lüftungsanlage an. | +| 2 Kontext-Veto | Außenlärm > **70 dB** (Mikrofon MAX9814) | automatisches Öffnen gesperrt → Lüftungsanlage statt Fenster | nur die **Mehrheit** („Fenster auf“ > „zu“) öffnet trotzdem | +| 2 Kontext-Veto | Wind > **60 km/h** (Wetterdienst) | Fenster höchstens gekippt, Lüftungsanlage hilft | **Nein**, auch manuell nur gekippt | +| 3 Dozent | manuelle Einstellung (Fenster, Jalousie, Licht, Lüftung) | hat Vorrang vor der Automatik, gilt **90 min** | Schutzregeln (CO₂, Wind) gelten trotzdem | +| 3 Mehrheit | Temperaturwünsche | Zielwert = **Durchschnitt** aller Wünsche (jeder Wunsch auf 18–26 °C begrenzt), Ergebnis auf 20–24 °C begrenzt, auf 0,5 °C gerundet; Abweichung < 0,3 °C von 22 °C zählt als Ausreißer (Ziel bleibt) | jede Stimme zählt gleich, auch die des Dozenten | +| 4 Energie | T < Ziel − 0,5 °C | Heizung an (bei offenem Fenster aus) | – | +| 4 Energie | T > Ziel + 1 °C und draußen kühler | Lüften zum Kühlen | – | +| – | Beamer-Modus (30/60/90 min) | Beamer an, Licht aus, Jalousie unten | Dozent schaltet ihn | +| – | Lichtsensor > 80 % (ohne Sensor: Sonne > 500 W/m²) | Jalousie unten, Licht an | Lichtwunsch verschiebt das Licht | +| – | Lichtsensor < 30 % | Licht heller | – | + +Alle Grenzwerte stehen oben in [`backend/logik.js`](../backend/logik.js) (`GRENZWERTE`). Die Ersatzlogik in Unity (`ClimateController`) verwendet dieselben Werte. + +## 4. Welche Eingabe wirkt wie? + +| Eingabe | Quelle | wirkt auf | +|---|---|---| +| eCO₂ | Arduino (CCS811) | Lüften (Priorität 1) | +| Temperatur | Arduino (DHT11) | Heizen / Kühlen | +| Lautstärke | Arduino (MAX9814), gilt als **Außenlärm** | Fenster-Sperre ab 70 dB | +| Helligkeit | Arduino (Fotowiderstand, %) | Jalousie, Licht | +| Luftfeuchte, TVOC | Arduino | nur Anzeige | +| Wind, Außentemperatur, Feinstaub, Sonne | Open-Meteo (ohne Internet: fehlen) | Wind-Veto, Lüftungsanlage statt Fenster, Jalousie ohne Lichtsensor | +| Temperaturwunsch (°C) | Webinterface, **eine Stimme pro Browser-Tab**, verfällt nach 30 min | Zielwert (Durchschnitt) | +| Fensterwunsch auf/zu | Webinterface | öffnet trotz Lärm, wenn Mehrheit „auf“ | +| Beamer-Modus, Jalousie ↑/↓ | Webinterface (Dozent) | Jalousie/Licht/Beamer, manuelle Phase 90 min | +| Demo-Szenario | Webinterface | ersetzt Messwerte durch Beispielwerte (auch in Unity); „Live“ = echte Werte | diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Editor/SmartRoomSceneSetup.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Editor/SmartRoomSceneSetup.cs index f8c4570..c6c4730 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Editor/SmartRoomSceneSetup.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Editor/SmartRoomSceneSetup.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEditor.SceneManagement; @@ -6,13 +7,15 @@ using UnityEngine; namespace SmartRoom.EditorTools { /// - /// Legt beim ersten Öffnen des Projekts die Szene "Assets/Scenes/SmartRoom.unity" an und öffnet sie. - /// Menü: Smart Room → Szene öffnen / neu erstellen. + /// Legt beim ersten Öffnen des Projekts die Szenen "Assets/Scenes/SmartRoom.unity" (Classic) und + /// "Assets/Scenes/SmartRoomAmbient.unity" (Optik des Web-Frontends) an. + /// Menü: Smart Room → Szene öffnen / Ambient-Szene öffnen / … neu erstellen. /// [InitializeOnLoad] static class SmartRoomSceneSetup { const string ScenePath = "Assets/Scenes/SmartRoom.unity"; + const string AmbientScenePath = "Assets/Scenes/SmartRoomAmbient.unity"; static SmartRoomSceneSetup() { @@ -22,28 +25,58 @@ namespace SmartRoom.EditorTools { if (EditorApplication.isPlayingOrWillChangePlaymode) return; if (!File.Exists(ScenePath)) CreateScene(); + if (!File.Exists(AmbientScenePath)) CreateInBackground(AmbientScenePath, RoomStyle.Ambient); }; } [MenuItem("Smart Room/Szene öffnen")] - static void OpenScene() - { - if (!File.Exists(ScenePath)) { CreateScene(); return; } - if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) - EditorSceneManager.OpenScene(ScenePath); - } + static void OpenScene() => Open(ScenePath, RoomStyle.Classic); + + [MenuItem("Smart Room/Ambient-Szene öffnen")] + static void OpenAmbientScene() => Open(AmbientScenePath, RoomStyle.Ambient); [MenuItem("Smart Room/Szene neu erstellen")] - static void CreateScene() + static void CreateScene() => Create(ScenePath, RoomStyle.Classic); + + [MenuItem("Smart Room/Ambient-Szene neu erstellen")] + static void CreateAmbientScene() => Create(AmbientScenePath, RoomStyle.Ambient); + + static void Open(string path, RoomStyle style) + { + if (!File.Exists(path)) { Create(path, style); return; } + if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) + EditorSceneManager.OpenScene(path); + } + + static void Create(string path, RoomStyle style) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) return; var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); - new GameObject("SmartRoom").AddComponent(); - Directory.CreateDirectory(Path.GetDirectoryName(ScenePath)); - EditorSceneManager.SaveScene(scene, ScenePath); - EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(ScenePath, true) }; + new GameObject("SmartRoom").AddComponent().style = style; + Save(scene, path); + Debug.Log("[Smart Room] Szene erstellt: " + path + " – Play drücken, um den Raum zu simulieren."); + } + + /// Szene anlegen, ohne die gerade geöffnete Szene zu wechseln. + static void CreateInBackground(string path, RoomStyle style) + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive); + var go = new GameObject("SmartRoom"); + go.AddComponent().style = style; + UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(go, scene); + Save(scene, path); + EditorSceneManager.CloseScene(scene, true); + Debug.Log("[Smart Room] Szene erstellt: " + path + " – öffnen über Smart Room → Ambient-Szene öffnen."); + } + + static void Save(UnityEngine.SceneManagement.Scene scene, string path) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + EditorSceneManager.SaveScene(scene, path); + var scenes = new List(EditorBuildSettings.scenes); + if (!scenes.Exists(s => s.path == path)) scenes.Add(new EditorBuildSettingsScene(path, true)); + EditorBuildSettings.scenes = scenes.ToArray(); AssetDatabase.Refresh(); - Debug.Log("[Smart Room] Szene erstellt: " + ScenePath + " – Play drücken, um den Raum zu simulieren."); } } } diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs index 6d9cdf9..f94c7aa 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs @@ -19,7 +19,7 @@ namespace SmartRoom } } - /// Grenzwerte wie GRENZWERTE in backend/logik.js, damit Fallback und Backend gleich entscheiden. + /// Grenzwerte wie GRENZWERTE in backend/logik.js, damit Ersatzlogik und Backend gleich entscheiden. [Serializable] public class ClimateThresholds { @@ -29,10 +29,13 @@ namespace SmartRoom [Tooltip("°C – über Ziel plus diesem Wert wird gelüftet")] public float coolAbove = 1f; [Tooltip("dB(A) – extremer Außenlärm")] public float noiseLimit = 70f; [Tooltip("m/s – extremer Wind (60 km/h)")] public float windLimit = 16.7f; - [Tooltip("W/m² – Sonneneinstrahlung zu hoch")] public float sunLimit = 500f; + [Tooltip("W/m² – Sonneneinstrahlung zu hoch (nur ohne Lichtsensor)")] public float sunLimit = 500f; + [Tooltip("% – Lichtsensor: darüber zu hell (Jalousie runter)")] public float brightPercent = 80f; + [Tooltip("% – Lichtsensor: darunter zu dunkel (Licht heller)")] public float darkPercent = 30f; [Tooltip("°C – draußen zu kalt zum Lüften per Fenster")] public float outdoorColdLimit = 5f; [Tooltip("European AQI – Außenluft schlecht")] public float outdoorAqiLimit = 60f; [Tooltip("lx – Zielbeleuchtung")] public float targetLux = 500f; + [Tooltip("°C – Eingabebereich eines einzelnen Wunschs (Ausreißer werden begrenzt)")] public float wishMin = 18f, wishMax = 26f; } /// Ergebnis eines Prüfzyklus inkl. durchlaufenem Pfad im Aktivitätsdiagramm. @@ -41,17 +44,16 @@ namespace SmartRoom public WindowState window = WindowState.Closed; public float blinds, heating, ventilation, lights; public string time; + public string scenario; public bool applied; public readonly List path = new List(); } /// - /// Automatische Steuerentscheidung nach dem Aktivitätsdiagramm: - /// Datenerfassung → Aggregation (Nutzerwünsche) → CO2/Temperatur → Lüftung/Fenster → Heizung - /// → Soll/Ist-Abgleich Fenster → Jalousie → Licht → virtuelle Aktoren ansteuern → nach 10 min erneut prüfen. - /// Ist das gemeinsame Backend verbunden, entscheidet dieses und die lokale Logik ruht (nur Fallback ohne Backend). - /// Die Regeln entsprechen backend/logik.js: Lärm sperrt das Fenster außer auf Mehrheitswunsch, Wind max. gekippt, - /// Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang, gelten 90 min, CO2 hält die Lüftung an. + /// Steuerung des Raums. Im Normalfall entscheidet das gemeinsame Backend (backend/logik.js) und Unity führt + /// nur aus (). Ohne Backend oder im Modus „Simulation“ entscheidet diese Ersatzlogik + /// nach denselben Regeln (Aktivitätsdiagramm): CO2 → Lüftung, Lärm sperrt das Fenster außer auf Mehrheitswunsch, + /// Wind max. gekippt, Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang (90 min). /// public class ClimateController : MonoBehaviour { @@ -73,10 +75,6 @@ namespace SmartRoom public RoomEnvironment env; public RoomDevices devices; - public BackendLink backend; - - /// true, solange das Backend entscheidet. - public bool External => backend != null && backend.Connected; public Decision Last { get; private set; } public event Action Decided; @@ -84,6 +82,12 @@ namespace SmartRoom double nextCheckAt = double.NegativeInfinity; double manualSince; bool wasCritical, wasRunning = true, wasAuto = true; + string lastScenario; + + public const string NormalScenario = "Normalbetrieb"; + + /// Erkanntes Szenario (aus Sensor- bzw. Simulationswerten), Namen wie die Szenario-Knöpfe im HUD. + public string Scenario { get; private set; } = NormalScenario; public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes)); public float ManualMinutesLeft => autoMode ? 0f : Mathf.Max(0f, (float)(manualSince + manualMinutes - env.simMinutes)); @@ -91,25 +95,93 @@ namespace SmartRoom /// Zielwert = Ø-Wunschtemperatur, begrenzt auf den zulässigen Bereich. public float TargetTemp => Mathf.Clamp(AverageWish, limits.tempLow, limits.tempHigh); + /// Ø aller Temperaturwünsche; jeder Wunsch wird vorher auf den Eingabebereich begrenzt (wie im Backend). public float AverageWish { get { if (wishes.Count == 0) return 22f; float s = 0f; - foreach (var w in wishes) s += w.temperature; + foreach (var w in wishes) s += Mathf.Clamp(w.temperature, limits.wishMin, limits.wishMax); return s / wishes.Count; } } + /// Anzahl der Wünsche außerhalb des Eingabebereichs. + public int ClampedWishes => wishes.FindAll(w => w.temperature < limits.wishMin || w.temperature > limits.wishMax).Count; + public int WindowVotes => wishes.FindAll(w => w.windowOpen).Count; public bool WindowWanted => wishes.Count > 0 && WindowVotes * 2 > wishes.Count; + // ---------------------------------------------------------------- Jalousie von Hand (Simulation) + double blindOverrideUntil = double.NegativeInfinity; + float blindOverride; + + public bool BlindOverrideActive => env != null && env.simMinutes < blindOverrideUntil; + public float BlindOverrideMinutesLeft => BlindOverrideActive ? (float)(blindOverrideUntil - env.simMinutes) : 0f; + + /// Jalousien von Hand fahren; die Automatik übernimmt nach simulierten Minuten wieder. + public void OverrideBlinds(float position, float minutes = 30f) + { + blindOverride = Mathf.Clamp01(position); + blindOverrideUntil = env.simMinutes + minutes; + devices.SetBlinds(blindOverride); + } + + // ---------------------------------------------------------------- Gemeinsames Backend + float remoteUntil = -1f; + CentralCommand lastRemote; + string lastRemoteStatus; + + /// Das Backend entscheidet gerade (Unity führt nur aus, die Ersatzlogik ruht). + public bool RemoteActive => Time.unscaledTime < remoteUntil; + + /// Entscheidung des Backends ausführen (GET /api/unity, ca. jede Sekunde). + public void ApplyRemote(CentralState s) + { + remoteUntil = Time.unscaledTime + 5f; + var c = s.steuerung ?? new CentralCommand(); + bool changed = lastRemote == null || lastRemote.window != c.window || !Same(lastRemote.blind, c.blind) || + !Same(lastRemote.heat, c.heat) || !Same(lastRemote.vent, c.vent) || !Same(lastRemote.light, c.light) || + lastRemote.beamer != c.beamer || lastRemoteStatus != s.status; + lastRemote = c; + lastRemoteStatus = s.status; + + var d = new Decision + { + time = env.ClockText, + scenario = s.status, + window = c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed, + blinds = c.blind, heating = c.heat, ventilation = c.vent, lights = c.light, + }; + d.path.Add($"Backend: {s.status} (Priorität {s.prioritaetNummer}: {s.prioritaet})"); + if (s.pfad != null) d.path.AddRange(s.pfad); + if (s.vetos != null && s.vetos.laerm) d.path.Add("Lärmsensor: Außenlärm über dem Grenzwert → Fenster gesperrt"); + Apply(d); + if (devices.projector != null) devices.projector.beamerOn = c.beamer == 1; + d.path.Add("Unity führt nur aus: virtuelle Aktoren angesteuert"); + Last = d; + if (changed) Decided?.Invoke(d); + } + + /// Zurück zur Ersatzlogik (Umschalter „Simulation“), sofort neu prüfen. + public void ReleaseRemote() + { + remoteUntil = -1f; + lastRemote = null; + lastRemoteStatus = null; + nextCheckAt = double.NegativeInfinity; + } + + static bool Same(float a, float b) => Mathf.Abs(a - b) < 0.005f; + + // ---------------------------------------------------------------- Ersatzlogik void Update() { if (env == null || devices == null) return; - if (External) + if (RemoteActive) { + Scenario = DetectScenario(); // nur zur Anzeige, entschieden wird im Backend nextCheckAt = double.NegativeInfinity; // fällt das Backend aus, sofort selbst prüfen return; } @@ -133,17 +205,39 @@ namespace SmartRoom } if (!autoMode) EnforceSafety(null); + // Szenarien werden aus den Messwerten erkannt: Kommt ein neues hinzu, wird sofort geprüft + Scenario = DetectScenario(); float target = TargetTemp; bool critical = env.co2 > limits.co2Limit || env.indoorTemp > target + limits.coolAbove || env.indoorTemp < target - limits.heatBelow; - if (env.simMinutes >= nextCheckAt || (reactImmediately && critical && !wasCritical)) + bool newScenario = Scenario != lastScenario && Scenario != NormalScenario; + if (env.simMinutes >= nextCheckAt || (reactImmediately && ((critical && !wasCritical) || newScenario))) RunCycle(); wasCritical = critical; + lastScenario = Scenario; } - /// Einen kompletten Prüfzyklus ausführen (auch per HUD "Jetzt prüfen"). + /// Ordnet die aktuellen Werte einem Szenario zu (Anzeige und Demo-Knöpfe). Reihenfolge = Priorität. + public string DetectScenario() + { + var L = limits; + float target = TargetTemp; + bool co2High = env.co2 > L.co2Limit; + bool ventNeeded = co2High || env.indoorTemp > target + L.coolAbove; + if (ventNeeded && env.outdoorAqi > L.outdoorAqiLimit) return "Schlechte Außenluft"; + if (ventNeeded && env.outdoorTemp < L.outdoorColdLimit) return "Stickig + kalt"; + if (ventNeeded && env.outdoorNoise > L.noiseLimit) return "Baustellenlärm"; + if (ventNeeded && env.windSpeed > L.windLimit) return "Sturm"; + if (co2High) return "Stickige Luft"; + if (env.indoorTemp > target + L.coolAbove) return "Hitze"; + if (env.indoorTemp < target - L.heatBelow) return "Wintermorgen"; + if (env.solar > L.sunLimit) return "Pralle Sonne"; + return NormalScenario; + } + + /// Einen kompletten Prüfzyklus der Ersatzlogik ausführen (auch per HUD "Jetzt prüfen"). public void RunCycle() { - if (External) return; + if (RemoteActive) return; var d = Evaluate(); if (autoMode) { @@ -164,14 +258,17 @@ namespace SmartRoom public Decision Evaluate() { var L = limits; - var d = new Decision { time = env.ClockText }; + var d = new Decision { time = env.ClockText, scenario = DetectScenario() }; var p = d.path; float t = env.indoorTemp, co2 = env.co2; float target = TargetTemp; bool wantWindow = WindowWanted; - p.Add($"Sensordaten: {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx"); + p.Add($"Sensordaten ({SourceText()}): {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx"); + p.Add($"Erkanntes Szenario: {d.scenario}"); p.Add($"Nutzerwünsche: Ziel {target:0.0} °C (Ø {AverageWish:0.0} °C), Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})"); + if (ClampedWishes > 0) + p.Add($"Temperaturwunsch begrenzt: {ClampedWishes} Wunsch außerhalb {L.wishMin:0}–{L.wishMax:0} °C"); // --- CO2 / Temperatur bool co2High = co2 > L.co2Limit; @@ -251,28 +348,51 @@ namespace SmartRoom ? $"Aktueller Fensterzustand = Sollzustand ({d.window.Label()}) → beibehalten" : $"Fensterzustand {current.Label()} ≠ Soll {d.window.Label()} → anpassen"); - // --- Beamer / Sonne → Jalousie und Licht + // --- Beamer / Helligkeit → Jalousie und Licht (wie im Backend: Lichtsensor vor Sonnenstand) + bool lightSensor = env.IsMeasured("lightpct"); + bool tooBright = lightSensor ? env.lightPercent > L.brightPercent : env.solar > L.sunLimit; + bool tooDark = lightSensor && env.lightPercent < L.darkPercent; if (devices.BeamerOn) { d.blinds = 1f; d.lights = 0f; p.Add("Beamermodus aktiv → Lichter aus, Jalousie nach unten"); } - else if (env.solar > L.sunLimit) + else if (tooBright) { d.blinds = 1f; - d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f); - p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten"); + d.lights = lightSensor ? 0.6f : Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f); + p.Add(lightSensor + ? $"Lichtsensor {env.lightPercent:0} % > {L.brightPercent:0} % → zu hell, Jalousie unten, Licht an" + : $"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten"); } else { d.blinds = 0f; - d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f); - p.Add($"Sonneneinstrahlung ok ({env.solar:0} W/m²) → Jalousie nach oben, Licht {d.lights * 100:0} %"); + d.lights = lightSensor ? (tooDark ? 0.8f : 0.4f) : Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f); + p.Add(tooDark + ? $"Lichtsensor {env.lightPercent:0} % < {L.darkPercent:0} % → zu dunkel, Licht heller" + : $"Helligkeit ok → Jalousie nach oben, Licht {d.lights * 100:0} %"); + } + if (BlindOverrideActive) + { + d.blinds = blindOverride; + p.Add($"Jalousien manuell auf {blindOverride * 100:0} % (Automatik pausiert, noch {BlindOverrideMinutesLeft:0} min)"); } return d; } + string SourceText() + { + var measured = new List(); + if (env.IsMeasured("t")) measured.Add("Temperatur"); + if (env.IsMeasured("co2")) measured.Add("CO2"); + if (env.IsMeasured("lightpct")) measured.Add("Licht"); + if (env.IsMeasured("noise")) measured.Add("Lärm innen"); + if (env.IsMeasured("nout")) measured.Add("Außenlärm"); + return measured.Count == 0 ? "Simulation" : "Arduino: " + string.Join(", ", measured); + } + /// /// Schutzregeln, die auch manuelle Einstellungen nicht aufheben (wie im Backend): /// bei Sturm höchstens gekippt, bei zu hohem CO2 läuft die Lüftungsanlage, solange das Fenster nicht offen ist. diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs index 1d9e382..6af935e 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs @@ -3,13 +3,17 @@ #define SMARTROOM_SERIAL #endif using System; +using System.Collections; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; +using System.Text.RegularExpressions; using System.Threading; using UnityEngine; +using UnityEngine.Networking; #if SMARTROOM_SERIAL using System.IO.Ports; #endif @@ -33,17 +37,26 @@ namespace SmartRoom public float wind = float.NaN; // Wind m/s public float sun = float.NaN; // Sonneneinstrahlung W/m² public float persons = float.NaN; // Personen im Raum + public float rh = float.NaN; // Luftfeuchte innen % + public float tvoc = float.NaN; // TVOC innen ppb + public float lightpct = float.NaN; // Helligkeit innen % (Fotowiderstand, relativ) } + /// + /// Backend = GruppeC-Aufbau: Arduino Uno + ESP-01 schicken per HTTP-POST an das Backend auf dem Laptop. + /// Zentrales Node-Backend (server.js): Unity holt Werte und Entscheidung per GET /api/unity und führt nur aus. + /// Älteres server.py (ohne /api/unity): Unity holt die Messwerte per GET /api/messwerte und entscheidet selbst. + /// public enum LinkMode { Simulation, Serial, Udp, Backend } /// - /// Verbindung zum Arduino: empfängt Sensordaten (JSON-Zeilen) per USB-Seriell oder UDP (WLAN, z. B. ESP32) - /// und sendet die Steuerbefehle der virtuellen Aktoren zurück. - /// Im Modus Backend (Standard) kommen Sensorwerte und Entscheidungen vom gemeinsamen Backend, siehe . + /// Verbindung zu den Messwerten. Standard ist das gemeinsame Backend (backend/server.js): Unity holt jede Sekunde + /// GET /api/unity und zeigt nur an, was das Backend entscheidet (Bedienung läuft über das Webinterface). + /// Läuft UnityWebRequest-basiert, also auch als WebGL im Browser. Daneben USB-Seriell und UDP für eigene Aufbauten. /// public class ArduinoBridge : MonoBehaviour { + [Tooltip("Backend = Werte und Entscheidungen vom Backend (server.js, sonst server.py); ohne laufenden Server bleibt die Simulation aktiv")] public LinkMode mode = LinkMode.Backend; [Tooltip("macOS: /dev/cu.usbmodem… · Windows: COM3")] public string serialPort = "/dev/cu.usbmodem101"; @@ -51,11 +64,85 @@ namespace SmartRoom public int udpListenPort = 5005; [Tooltip("Port, an den Steuerbefehle an den Absender zurückgeschickt werden")] public int udpReplyPort = 5006; + [Tooltip("Adresse des Backends (server.js oder server.py) – dort kommen die Messwerte des ESP-01 an")] + public string backendUrl = "http://localhost:3000"; + [Tooltip("Abfrageintervall beim Backend in Sekunden")] + public float backendPollSeconds = 1f; + [Tooltip("Ältere Messwerte im Backend gelten als veraltet und werden ignoriert (Sekunden)")] + public float backendMaxAge = 30f; + [Tooltip("MAX9814: an = Mikrofon steht draußen (Außenlärm, Sensor-Veto für Fenster), aus = Lärm im Raum")] + [SerializeField] bool microphoneOutdoor; + [Tooltip("Umrechnung Fotowiderstand % → lx (grob, 100 % ≈ 1000 lx)")] + public float luxPerLightPercent = 10f; public bool sendCommands = true; + /// Optional: Name des erkannten Szenarios, wird mit den Steuerbefehlen ans Backend gemeldet. + public Func scenarioProvider; + public RoomEnvironment env; public RoomDevices devices; - public BackendLink backend; + public ClimateController controller; + + /// Letzter Zustand des zentralen Backends (null bei server.py oder ohne Verbindung). + public CentralState Central { get; private set; } + /// Das zentrale Backend antwortet gerade (letzte Antwort jünger als 5 s). + public bool CentralActive => useArduinoData && CentralFresh; + bool CentralFresh => Central != null && Connected && Time.unscaledTime - centralAt < 5f; + float centralAt = -100f; + + [Tooltip("an = Werte vom Arduino übernehmen, aus = Beispielwerte der Simulation (die Verbindung bleibt für die Statusanzeige bestehen)")] + [SerializeField] bool useArduinoData = true; + float arduinoSeenAt = -100f; // letzte Messung vom Arduino (auch wenn sie gerade nicht übernommen wird) + float backendReplyAt = -100f; // letzte Antwort des Backends + + /// + /// Umschalter Arduino-Werte ↔ Simulation. Aus: Beispielwerte wiederherstellen, Unity entscheidet selbst. + /// An: Werte (und beim zentralen Backend auch die Entscheidungen) wieder vom Arduino bzw. Backend übernehmen. + /// + public bool UseArduinoData + { + get => useArduinoData; + set + { + if (value == useArduinoData) return; + useArduinoData = value; + if (!value) + { + env?.ResetToExampleValues(); + controller?.ReleaseRemote(); + return; + } + if (mode == LinkMode.Simulation) mode = LinkMode.Backend; + if (!Connected) Connect(); + } + } + + /// Kommen gerade Messwerte vom Arduino an (egal ob sie übernommen werden)? + public bool ArduinoConnected + { + get + { + if (!Connected) return false; + if (CentralFresh) return Central.sensorOnline; + return Time.unscaledTime - arduinoSeenAt < (env != null ? env.measurementTimeout : 25f); + } + } + + public bool BackendReachable => Connected && Time.unscaledTime - backendReplyAt < 5f; + + /// Statuszeile zum Arduino für die Dashboards. + public string ArduinoDetail + { + get + { + if (ArduinoConnected) + return $"Arduino verbunden · letzte Messung vor {Mathf.Max(0f, Time.unscaledTime - arduinoSeenAt):0} s"; + if (!Connected) return "Arduino nicht verbunden · keine Verbindung eingestellt"; + if (mode == LinkMode.Backend && !BackendReachable) return "Arduino nicht verbunden · Backend nicht erreichbar (läuft server.js?)"; + if (mode == LinkMode.Backend) return "Arduino nicht verbunden · Backend läuft, aber keine Messwerte"; + return "Arduino nicht verbunden · keine Messwerte"; + } + } public string Status { get; private set; } = "Simulation aktiv"; public bool Connected { get; private set; } @@ -64,6 +151,17 @@ namespace SmartRoom public float LastPacketTime { get; private set; } = -1f; public int PacketCount { get; private set; } + public bool MicrophoneOutdoor + { + get => microphoneOutdoor; + set + { + if (value == microphoneOutdoor) return; + microphoneOutdoor = value; + env?.Forget(value ? "noise" : "nout"); // alter Kanal soll nicht noch als "Sensor" gelten + } + } + public static bool SerialSupported { get @@ -83,6 +181,13 @@ namespace SmartRoom UdpClient udp; IPEndPoint remote; float nextSend; + string pendingCommand; // Rueckmeldung an server.py (veraltet), server.js braucht keine + string lastBackendTime; + const string HttpPrefix = "!HTTP "; + const string CentralPrefix = "!UNITY "; + Coroutine backendLoop; + static readonly Regex AktuellRx = new Regex("\"aktuell\"\\s*:\\s*(null|\\{[^{}]*\\})"); + static readonly Regex FieldRx = new Regex("\"(\\w+)\"\\s*:\\s*(\"[^\"]*\"|[^,}\\s]+)"); #if SMARTROOM_SERIAL SerialPort port; #endif @@ -96,6 +201,15 @@ namespace SmartRoom #endif } + void Awake() + { +#if UNITY_WEBGL && !UNITY_EDITOR + // Im Browser läuft der Zwilling auf der Seite des Backends: dessen Adresse übernehmen, nicht "localhost" + if (Application.absoluteURL.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + backendUrl = new Uri(Application.absoluteURL).GetLeftPart(UriPartial.Authority); +#endif + } + void Start() { if (mode != LinkMode.Simulation) Connect(); @@ -110,11 +224,7 @@ namespace SmartRoom { case LinkMode.Serial: OpenSerial(); break; case LinkMode.Udp: OpenUdp(); break; - case LinkMode.Backend: - backend.Begin(); - Connected = true; - Status = "Gemeinsames Backend " + backend.serverUrl; - break; + case LinkMode.Backend: OpenBackend(); break; default: Status = "Simulation aktiv"; break; } } @@ -141,11 +251,22 @@ namespace SmartRoom { #if UNITY_WEBGL && !UNITY_EDITOR Status = "UDP im Browser nicht verfügbar: Verbindung → Backend nutzen"; -#else + return; +#endif udp = new UdpClient(udpListenPort); StartWorker(UdpLoop); Status = $"Lausche auf UDP-Port {udpListenPort}"; -#endif + } + + void OpenBackend() + { + lastBackendTime = null; + pendingCommand = null; + Central = null; + running = true; + Connected = true; + backendLoop = StartCoroutine(BackendPoll()); + Status = "Frage " + backendUrl + " ab …"; } void StartWorker(ThreadStart loop) @@ -166,8 +287,9 @@ namespace SmartRoom port = null; #endif try { udp?.Close(); } catch { } - if (backend != null) backend.End(); udp = null; + if (backendLoop != null) StopCoroutine(backendLoop); + backendLoop = null; if (worker != null && worker.IsAlive) worker.Join(800); worker = null; lock (remoteLock) remote = null; @@ -216,6 +338,173 @@ namespace SmartRoom } } + // ---------------------------------------------------------------- Backend (HTTP, auch WebGL) + IEnumerator BackendPoll() + { + string baseUrl = backendUrl.Trim().TrimEnd('/'); + bool legacy = false; // true: altes server.py ohne /api/unity + while (running) + { + if (!legacy) + { + using (var req = UnityWebRequest.Get(baseUrl + "/api/unity")) + { + req.timeout = 3; + yield return req.SendWebRequest(); + if (!running) yield break; + if (req.result == UnityWebRequest.Result.Success) ApplyCentral(req.downloadHandler.text); + else if (req.responseCode == 404) legacy = true; // server.py: Messwerte holen und selbst entscheiden + else Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ") – läuft backend/server.js?"; + } + } + else + { + using (var req = UnityWebRequest.Get(baseUrl + "/api/messwerte")) + { + req.timeout = 3; + yield return req.SendWebRequest(); + if (!running) yield break; + if (req.result == UnityWebRequest.Result.Success) ApplyBackend(req.downloadHandler.text); + else + { + Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ")"; + legacy = false; // evtl. wurde inzwischen server.js gestartet + } + } + if (pendingCommand != null) + { + string cmd = pendingCommand; + pendingCommand = null; + using (var req = new UnityWebRequest(baseUrl + "/api/steuerung", UnityWebRequest.kHttpVerbPOST)) + { + req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(cmd)); + req.downloadHandler = new DownloadHandlerBuffer(); + req.SetRequestHeader("Content-Type", "application/json"); + req.timeout = 3; + yield return req.SendWebRequest(); + } + } + } + yield return new WaitForSecondsRealtime(backendPollSeconds); + } + } + + /// + /// Wertet GET /api/unity des zentralen Backends aus: Sensorwerte (mit Quelle) übernehmen, Entscheidung ausführen. + /// + void ApplyCentral(string json) + { + CentralState s; + try { s = JsonUtility.FromJson(json); } + catch (Exception ex) + { + Status = "Antwort des Backends nicht lesbar: " + ex.Message; + return; + } + if (s == null) return; + + var p = new SensorPacket(); + string sensorJson = JsonObject(json, "sensor"); + if (sensorJson != null) JsonUtility.FromJsonOverwrite(sensorJson, p); + if (!float.IsNaN(p.lightpct)) p.lux = p.lightpct * luxPerLightPercent; + + Central = s; + centralAt = backendReplyAt = Time.unscaledTime; + PacketCount++; + if (s.sensorOnline) LastPacketTime = arduinoSeenAt = Time.unscaledTime; + LastLine = sensorJson ?? ""; + if (!useArduinoData) + { + Status = "Zentrales Backend (server.js) erreichbar · Simulation aktiv, Werte werden nicht übernommen"; + return; + } + env.ApplyRemote(p, channel => s.SourceOf(channel) == "sensor"); + controller?.ApplyRemote(s); + Status = s.sensorOnline ? "Zentrales Backend (server.js) · Arduino live" + : s.szenario != null && s.szenario != "live" ? $"Zentrales Backend (server.js) · Demo-Szenario „{s.szenario}“" + : "Zentrales Backend (server.js) · kein Arduino (Werte aus Wetter/Simulation)"; + } + + /// Unterobjekt "key":{…} aus einem JSON-Text (für Felder, die NaN-Vorgaben brauchen). + static string JsonObject(string json, string key) + { + int i = json.IndexOf("\"" + key + "\"", StringComparison.Ordinal); + if (i < 0) return null; + i = json.IndexOf('{', i); + if (i < 0) return null; + int depth = 0; + for (int j = i; j < json.Length; j++) + { + if (json[j] == '{') depth++; + else if (json[j] == '}' && --depth == 0) return json.Substring(i, j - i + 1); + } + return null; + } + + /// + /// Wertet die Antwort von GET /api/messwerte aus: + /// {"aktuell":{"zeit":"…Z","temperatur":22.5,"luftfeuchte":45,"eco2":612,"tvoc":30,"lautstaerke":48.5,"helligkeit":60},"verlauf":[…]} + /// + void ApplyBackend(string json) + { + backendReplyAt = Time.unscaledTime; + var m = AktuellRx.Match(json); + if (!m.Success || m.Groups[1].Value == "null") + { + Status = "Backend erreichbar · noch keine Messwerte vom Arduino"; + return; + } + + var f = new Dictionary(); + foreach (Match fm in FieldRx.Matches(m.Groups[1].Value)) + f[fm.Groups[1].Value] = fm.Groups[2].Value.Trim('"'); + f.TryGetValue("zeit", out var zeit); + + if (zeit != null && zeit == lastBackendTime) + { + // kein neuer Messwert seit der letzten Abfrage + if (LastPacketTime < 0f || Time.unscaledTime - LastPacketTime > env.measurementTimeout) + Status = "Backend erreichbar · keine neuen Messwerte (Arduino/ESP aus?)"; + return; + } + lastBackendTime = zeit; + + if (zeit != null && DateTime.TryParse(zeit, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var ts)) + { + double age = (DateTime.UtcNow - ts.ToUniversalTime()).TotalSeconds; + if (age > backendMaxAge) + { + Status = $"Letzter Messwert im Backend ist {age:0} s alt – Arduino sendet gerade nicht"; + return; + } + } + + float laut = Num(f, "lautstaerke"), licht = Num(f, "helligkeit"); + var p = new SensorPacket + { + t = Num(f, "temperatur"), + rh = Num(f, "luftfeuchte"), + co2 = Num(f, "eco2"), + tvoc = Num(f, "tvoc"), + lightpct = licht, + lux = licht * luxPerLightPercent, // NaN bleibt NaN + }; + if (microphoneOutdoor) p.nout = laut; else p.noise = laut; + LastLine = m.Groups[1].Value; + LastPacketTime = arduinoSeenAt = Time.unscaledTime; + PacketCount++; + if (!useArduinoData) + { + Status = "Backend verbunden · Simulation aktiv, Arduino-Werte werden nicht übernommen"; + return; + } + env.ApplyMeasurement(p); + Status = "Backend verbunden · Messwerte vom Arduino (ESP-01)"; + } + + static float Num(Dictionary f, string key) + => f.TryGetValue(key, out var s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : float.NaN; + void Update() { while (inbox.TryDequeue(out var line)) @@ -225,14 +514,24 @@ namespace SmartRoom Status = "Verbindungsfehler: " + line.Substring(4).Trim(); continue; } + if (line.StartsWith(HttpPrefix)) + { + ApplyBackend(line.Substring(HttpPrefix.Length)); + continue; + } + if (line.StartsWith(CentralPrefix)) + { + ApplyCentral(line.Substring(CentralPrefix.Length)); + continue; + } LastLine = line; if (!line.StartsWith("{")) continue; // Debug-Ausgaben des Arduino ignorieren try { var p = new SensorPacket(); JsonUtility.FromJsonOverwrite(line, p); - env.ApplyMeasurement(p); - LastPacketTime = Time.unscaledTime; + if (useArduinoData) env.ApplyMeasurement(p); + LastPacketTime = arduinoSeenAt = Time.unscaledTime; PacketCount++; } catch (Exception ex) @@ -242,8 +541,7 @@ namespace SmartRoom } // Steuerbefehle senden, sobald sie sich ändern (spätestens alle 10 s als Heartbeat) - // Im Backend-Modus entscheidet das Backend; Unity schickt keine eigenen Befehle - if (Connected && sendCommands && devices != null && mode != LinkMode.Backend) + if (Connected && sendCommands && useArduinoData && devices != null && !CentralFresh) // das zentrale Backend braucht keine Rückmeldung { string cmd = BuildCommand(); if (cmd != LastSent || Time.unscaledTime >= nextSend) @@ -264,6 +562,9 @@ namespace SmartRoom sb.Append(",\"vent\":").Append(devices.VentTarget.ToString("0.00", ci)); sb.Append(",\"light\":").Append(devices.LightTarget.ToString("0.00", ci)); sb.Append(",\"beamer\":").Append(devices.BeamerOn ? 1 : 0); + string scenario = scenarioProvider?.Invoke(); + if (mode == LinkMode.Backend && !string.IsNullOrEmpty(scenario)) + sb.Append(",\"szenario\":\"").Append(scenario.Replace("\"", "'")).Append('"'); sb.Append('}'); return sb.ToString(); } @@ -276,6 +577,7 @@ namespace SmartRoom #if SMARTROOM_SERIAL if (mode == LinkMode.Serial && port != null && port.IsOpen) port.WriteLine(json); #endif + if (mode == LinkMode.Backend) pendingCommand = json; // nur fuer server.py, server.js entscheidet selbst if (mode == LinkMode.Udp && udp != null) { IPEndPoint target; diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/BackendLink.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/BackendLink.cs deleted file mode 100644 index 6a65905..0000000 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/BackendLink.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.Collections; -using System.Text; -using UnityEngine; -using UnityEngine.Networking; - -namespace SmartRoom -{ - // Antwort von GET /api/unity (backend/raum.js → unity()). Das Backend liefert keine null-Werte. - [Serializable] public class BackendCommand { public string window = "closed"; public float blind, heat, vent, light; public int beamer; } - [Serializable] public class BackendVotes - { - public int kuehler, angenehm, waermer, dunkler, passt, heller, auf, zu, gesamt; - public string eigeneTemperatur = "", eigeneLicht = "", eigeneFenster = ""; - } - [Serializable] public class BackendLecture { public bool aktiv; public int restMinuten, dauerMinuten = 60; } - /// Manuelle Einstellungen des Dozenten: -1 bzw. "" = Automatik. - [Serializable] public class BackendManual - { - public bool aktiv; - public string fenster = "", bis = ""; - public int jalousie = -1, licht = -1, lueftung = -1; - } - [Serializable] public class BackendScenario { public string id, text, beschreibung; } - [Serializable] public class BackendState - { - public string zeit, szenario, status, detail, prioritaet; - public SensorPacket sensor = new SensorPacket(); - public string[] sensorFelder = new string[0]; - public BackendCommand steuerung = new BackendCommand(); - public string[] pfad = new string[0]; - public float zielTemperatur = 22f; - public BackendVotes stimmen = new BackendVotes(); - public BackendLecture vortrag = new BackendLecture(); - public BackendManual manuell = new BackendManual(); - public BackendScenario[] szenarien = new BackendScenario[0]; - } - - /// - /// Gemeinsames Backend (backend/server.js): Es entscheidet für Webinterface und Zwilling gleichermaßen. - /// Holt jede Sekunde GET /api/unity, übernimmt Sensorwerte und führt den Steuerbefehl nur aus. - /// Stimmen, Szenario, Vortragsmodus und Jalousie aus dem HUD gehen an dieselben Endpunkte wie beim Webinterface. - /// - public class BackendLink : MonoBehaviour - { - public string serverUrl = "http://localhost:3000"; - [Tooltip("Abfrageintervall in Sekunden")] public float pollSeconds = 1f; - [Tooltip("So lange ohne Antwort gilt das Backend als getrennt; dann übernimmt die lokale Logik")] - public float timeoutSeconds = 5f; - - public RoomEnvironment env; - public RoomDevices devices; - - public bool Active { get; private set; } - public bool Connected => Active && LastPacketTime >= 0f && Time.unscaledTime - LastPacketTime < timeoutSeconds; - public string Status { get; private set; } = "aus"; - public BackendState State { get; private set; } - public float LastPacketTime { get; private set; } = -1f; - public int PacketCount { get; private set; } - - /// Eigene Kennung als "Client" – wie ein Browser im Webinterface, eine Stimme pro Zwilling. - public string ClientId { get; private set; } - - Coroutine loop; - - void Awake() - { - string id = SystemInfo.deviceUniqueIdentifier; - if (string.IsNullOrEmpty(id) || id == SystemInfo.unsupportedIdentifier) id = Guid.NewGuid().ToString("N"); - ClientId = "unity-" + id.Substring(0, Mathf.Min(12, id.Length)); -#if UNITY_WEBGL && !UNITY_EDITOR - // Im Browser läuft der Zwilling auf der Seite des Backends: dessen Adresse übernehmen, nicht "localhost". - // Nur bei http(s); beim Öffnen per file:// bleibt die eingestellte URL. - if (Application.absoluteURL.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - serverUrl = new Uri(Application.absoluteURL).GetLeftPart(UriPartial.Authority); -#endif - } - - string Base => serverUrl.TrimEnd('/'); - - public void Begin() - { - End(); - Active = true; - Status = "Verbinde mit " + Base + " …"; - loop = StartCoroutine(Poll()); - } - - public void End() - { - if (loop != null) StopCoroutine(loop); - loop = null; - Active = false; - Status = "aus"; - } - - IEnumerator Poll() - { - while (Active) - { - using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId))) - { - req.timeout = 3; - yield return req.SendWebRequest(); - if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text); - else Status = $"Backend nicht erreichbar ({req.error}) – lokale Logik aktiv"; - } - yield return new WaitForSecondsRealtime(pollSeconds); - } - } - - void Receive(string json) - { - BackendState s; - try { s = JsonUtility.FromJson(json); } - catch (Exception ex) { Status = "Ungültige Antwort: " + ex.Message; return; } - if (s == null) return; - - // Nur Felder übernehmen, die das Backend wirklich kennt – der Rest bleibt simuliert - var p = new SensorPacket(); - foreach (var f in s.sensorFelder) - { - switch (f) - { - case "t": p.t = s.sensor.t; break; - case "co2": p.co2 = s.sensor.co2; break; - case "lux": p.lux = s.sensor.lux; break; - case "noise": p.noise = s.sensor.noise; break; - case "tout": p.tout = s.sensor.tout; break; - case "aq": p.aq = s.sensor.aq; break; - case "nout": p.nout = s.sensor.nout; break; - case "wind": p.wind = s.sensor.wind; break; - case "sun": p.sun = s.sensor.sun; break; - case "persons": p.persons = s.sensor.persons; break; - } - } - env.ApplyMeasurement(p); - - var c = s.steuerung; - devices.SetWindows(c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed); - devices.SetBlinds(c.blind); - devices.SetHeating(c.heat); - devices.SetVentilation(c.vent); - devices.SetLights(c.light); - if (devices.projector != null) devices.projector.beamerOn = c.beamer != 0; - - State = s; - LastPacketTime = Time.unscaledTime; - PacketCount++; - Status = $"Verbunden mit {Base} · Szenario {s.szenario}"; - } - - // ---------------------------------------------------------------- Eingaben ans Backend - // Werte wie im Webinterface: temperatur kuehler|angenehm|waermer, licht dunkler|passt|heller - - public void VoteTemperature(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"temperatur\":\"{wert}\"}}"); - public void VoteLight(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"licht\":\"{wert}\"}}"); - /// auf | zu - public void VoteWindow(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"fenster\":\"{wert}\"}}"); - public void ChooseScenario(string id) => Post("/api/szenario", $"{{\"id\":\"{id}\"}}"); - public void SetLecture(bool aktiv) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"aktiv\":{(aktiv ? "true" : "false")}}}"); - public void SetLectureDuration(int minuten) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"dauerMinuten\":{minuten}}}"); - /// - /// Manuelle Einstellung (gilt 90 min): feld fenster|jalousie|licht|lueftung, wert als JSON, - /// z. B. "\"open\"", "100", "\"an\"" oder "\"auto\"" für Automatik. - /// - public void SetManual(string feld, string jsonWert) => Post("/api/manuell", $"{{\"rolle\":\"dozent\",\"{feld}\":{jsonWert}}}"); - public void ResetManual() => Post("/api/manuell", "{\"rolle\":\"dozent\",\"zuruecksetzen\":true}"); - - void Post(string path, string json) - { - if (Active) StartCoroutine(PostRoutine(path, json)); - } - - IEnumerator PostRoutine(string path, string json) - { - using (var req = new UnityWebRequest(Base + path, UnityWebRequest.kHttpVerbPOST)) - { - req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json)); - req.downloadHandler = new DownloadHandlerBuffer(); - req.SetRequestHeader("Content-Type", "application/json"); - req.timeout = 3; - yield return req.SendWebRequest(); - if (req.result != UnityWebRequest.Result.Success) - { - Status = $"{path} fehlgeschlagen: {req.error} {req.downloadHandler.text}"; - yield break; - } - } - // Ergebnis sofort abholen statt bis zur nächsten Abfrage zu warten - using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId))) - { - req.timeout = 3; - yield return req.SendWebRequest(); - if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text); - } - } - - void OnDisable() => End(); - } -} diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/CentralState.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/CentralState.cs new file mode 100644 index 0000000..20c178b --- /dev/null +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/CentralState.cs @@ -0,0 +1,119 @@ +using System; + +namespace SmartRoom +{ + /// + /// Antwort von GET /api/unity des gemeinsamen Backends (backend/raum.js → unity()). + /// Das Backend entscheidet für Webinterface und Unity gemeinsam; Unity zeigt nur an und führt aus. + /// Das Backend liefert keine null-Werte (in "manuell" bedeutet -1 bzw. "" Automatik). + /// Die Sensorwerte ("sensor") liest separat in ein . + /// + [Serializable] + public class CentralState + { + public string zeit, szenario, status, detail, ton, prioritaet; + public int prioritaetNummer; + public float zielTemperatur; + public bool sensorOnline, fensterGesperrt; + public CentralCommand steuerung = new CentralCommand(); + public CentralSources quellen = new CentralSources(); + public CentralVetos vetos = new CentralVetos(); + public CentralLimits grenzwerte = new CentralLimits(); + public CentralVotes stimmen = new CentralVotes(); + public CentralTimer vortrag = new CentralTimer(); + public CentralManual manuell = new CentralManual(); + public CentralCheck pruefung = new CentralCheck(); + public string[] pfad = new string[0]; + public CentralEntry[] verlauf = new CentralEntry[0]; + public CentralScenario[] szenarien = new CentralScenario[0]; + + /// Quelle eines Sensorkanals: "sensor", "wetter", "demo" oder null. + public string SourceOf(string channel) + { + switch (channel) + { + case "t": return quellen.t; + case "co2": return quellen.co2; + case "rh": return quellen.rh; + case "tvoc": return quellen.tvoc; + case "lightpct": + case "lux": return quellen.lightpct; + case "nout": return quellen.nout; + case "tout": return quellen.tout; + case "wind": return quellen.wind; + case "sun": return quellen.sun; + case "aq": return quellen.aq; + default: return null; + } + } + } + + /// Steuerbefehl, gleiches Format wie . + [Serializable] + public class CentralCommand + { + public string window = "closed"; + public float blind, heat, vent, light; + public int beamer; + } + + [Serializable] + public class CentralSources + { + public string t, co2, rh, tvoc, lightpct, nout, tout, wind, sun, aq; + } + + [Serializable] + public class CentralVetos + { + public bool co2, laerm, wind, aussenluft; + } + + [Serializable] + public class CentralLimits + { + public float co2Ppm = 1000f, laermDb = 70f, windKmh = 60f; + } + + [Serializable] + public class CentralVotes + { + public int kuehler, angenehm, waermer, auf, zu, gesamt; + } + + [Serializable] + public class CentralTimer + { + public bool aktiv; + public int restMinuten, dauerMinuten; + } + + /// Manuelle Dozenteneinstellungen aus dem Webinterface (-1 bzw. "" = Automatik). + [Serializable] + public class CentralManual + { + public bool aktiv; + public string fenster = "", bis = ""; + public int jalousie = -1, licht = -1, lueftung = -1; + } + + /// Prüfzyklus des Backends (alle 2 min, Zeitraffer 1×/5×/10×). + [Serializable] + public class CentralCheck + { + public int intervallSekunden = 120, zeitraffer = 1, abstandSekunden = 120, restSekunden; + public string letzteUhrzeit = ""; + } + + [Serializable] + public class CentralEntry + { + public string uhrzeit, titel, grund, ton; + } + + [Serializable] + public class CentralScenario + { + public string id, text, beschreibung; + } +} diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomBuilder.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomBuilder.cs index 4a711c9..27e4d7f 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomBuilder.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomBuilder.cs @@ -2,6 +2,9 @@ using UnityEngine; namespace SmartRoom { + /// Optik des Raums: Classic = ursprünglicher Zwilling, Ambient = Look des Web-Frontends (Ambient²). + public enum RoomStyle { Classic, Ambient } + /// /// Baut den Vorlesungsraum komplett prozedural auf (keine externen Assets nötig). /// Koordinaten: x = links(-)/rechts(+), z = hinten(-)/vorne(+, Leinwand), y = oben. @@ -18,13 +21,15 @@ namespace SmartRoom public static readonly float[] VentZ = { -3.2f, 2.4f }; public static readonly Color Accent = new Color(0.16f, 0.70f, 0.75f); + /// Grün des Ambient-Frontends (--green #175c45). + public static readonly Color AmbientGreen = new Color(0.090f, 0.361f, 0.271f); static Material wall, accentWall, floor, ceiling, frame, glass, alu, white, oak, doorWood, dark, seat, metal, grass, leaves, bark, stone, exitSign, heaterMat, panelMat, ledMat, lensMat, slideMat, slideAccent, screenMat; - public static RoomDevices Build(Transform root) + public static RoomDevices Build(Transform root, RoomStyle style = RoomStyle.Classic) { - CreateMaterials(); + if (style == RoomStyle.Ambient) CreateAmbientMaterials(); else CreateMaterials(); var devices = root.GetComponent(); if (devices == null) devices = root.gameObject.AddComponent(); @@ -70,6 +75,36 @@ namespace SmartRoom slideAccent = Mat.Emissive(Accent, Accent); } + /// Helle, matte Salbei-/Grüntöne wie in der Raumansicht des Web-Frontends. + static void CreateAmbientMaterials() + { + wall = Mat.Solid(new Color(0.945f, 0.957f, 0.949f), 0f); + accentWall = Mat.Solid(new Color(0.910f, 0.953f, 0.929f), 0f); // --green-soft + floor = Mat.Solid(new Color(0.760f, 0.800f, 0.776f), 0.05f); + ceiling = Mat.Solid(new Color(0.975f, 0.980f, 0.976f), 0f); + frame = Mat.Solid(new Color(0.870f, 0.900f, 0.882f), 0.1f); + glass = Mat.Transparent(new Color(0.80f, 0.90f, 0.85f, 0.16f)); + alu = Mat.Solid(new Color(0.420f, 0.470f, 0.447f), 0.1f); // Jalousie-Lamellen + white = Mat.Solid(new Color(0.965f, 0.972f, 0.968f), 0.1f); + oak = Mat.Solid(new Color(0.455f, 0.506f, 0.478f), 0.05f); // Tische graugrün + doorWood = Mat.Solid(new Color(0.835f, 0.871f, 0.851f), 0.05f); + dark = Mat.Solid(new Color(0.290f, 0.333f, 0.314f), 0.1f); + seat = Mat.Solid(new Color(0.310f, 0.365f, 0.341f), 0.05f); + metal = Mat.Solid(new Color(0.680f, 0.720f, 0.700f), 0.2f); + grass = Mat.Solid(new Color(0.700f, 0.800f, 0.730f), 0f); + leaves = Mat.Solid(new Color(0.560f, 0.700f, 0.610f), 0f); + bark = Mat.Solid(new Color(0.540f, 0.520f, 0.480f), 0f); + stone = Mat.Solid(new Color(0.900f, 0.920f, 0.905f), 0f); + screenMat = Mat.Solid(new Color(0.985f, 0.990f, 0.986f), 0f); + exitSign = Mat.Emissive(AmbientGreen, AmbientGreen * 1.2f); + heaterMat = Mat.Emissive(new Color(0.94f, 0.95f, 0.945f), Color.black); + panelMat = Mat.Emissive(new Color(0.95f, 0.96f, 0.955f), Color.white); + ledMat = Mat.Emissive(Color.gray, Color.black); + lensMat = Mat.Emissive(new Color(0.2f, 0.24f, 0.22f), Color.black); + slideMat = Mat.Emissive(Color.white, Color.black); + slideAccent = Mat.Emissive(AmbientGreen, AmbientGreen); + } + // ---------------------------------------------------------------- Gebäudehülle static void BuildShell(Transform p) { diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomDevices.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomDevices.cs index fed7dd1..ef6040b 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomDevices.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Room/RoomDevices.cs @@ -20,9 +20,11 @@ namespace SmartRoom public Light sun; public RoomEnvironment env; - static readonly Color AmbSky = new Color(0.62f, 0.68f, 0.78f); - static readonly Color AmbEquator = new Color(0.52f, 0.52f, 0.54f); - static readonly Color AmbGround = new Color(0.30f, 0.29f, 0.28f); + [Header("Umgebungslicht (wird von der Optik gesetzt)")] + public Color ambSky = new Color(0.62f, 0.68f, 0.78f); + public Color ambEquator = new Color(0.52f, 0.52f, 0.54f); + public Color ambGround = new Color(0.30f, 0.29f, 0.28f); + [Tooltip("Grundhelligkeit des Umgebungslichts")] public float ambBase = 0.22f; // ---------------------------------------------------------------- Fenster public void SetWindows(WindowState s) { foreach (var w in windows) w.target = s; } @@ -74,11 +76,11 @@ namespace SmartRoom sun.intensity = Mathf.Lerp(0.08f, 1.25f, day); sun.color = Color.Lerp(new Color(1f, 0.8f, 0.65f), new Color(1f, 0.97f, 0.92f), day); } - float k = 0.22f + 0.5f * LightLevel + 0.45f * day * (1f - 0.85f * BlindClosure); + float k = ambBase + 0.5f * LightLevel + 0.45f * day * (1f - 0.85f * BlindClosure); RenderSettings.ambientMode = AmbientMode.Trilight; - RenderSettings.ambientSkyColor = AmbSky * k; - RenderSettings.ambientEquatorColor = AmbEquator * k; - RenderSettings.ambientGroundColor = AmbGround * k; + RenderSettings.ambientSkyColor = ambSky * k; + RenderSettings.ambientEquatorColor = ambEquator * k; + RenderSettings.ambientGroundColor = ambGround * k; } } } diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/NoiseVisualizer.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/NoiseVisualizer.cs new file mode 100644 index 0000000..4b6cb0f --- /dev/null +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/NoiseVisualizer.cs @@ -0,0 +1,142 @@ +using UnityEngine; + +namespace SmartRoom +{ + /// + /// Macht den Außenlärm (Lautstärkesensor MAX9814 bzw. Simulation) im 3D-Raum sichtbar: Schallwellen-Ringe + /// vor der Fensterfront, je lauter, desto mehr, größer und schneller. Über dem Grenzwert (Standard 70 dB) werden + /// sie rot – dann gilt das Sensor-Veto: Fenster gesperrt, Lüftungsanlage statt Fenster (außer die Mehrheit will lüften). Ein Schild an der Fassade zeigt den Pegel. + /// + public class NoiseVisualizer : MonoBehaviour + { + public RoomEnvironment env; + public ClimateController controller; + public ArduinoBridge bridge; + [Tooltip("Unterhalb dieses Pegels keine Wellen (dB)")] public float quietDb = 55f; + + static readonly Color Calm = new Color(0.55f, 0.72f, 0.64f, 0.55f); + static readonly Color Loud = new Color(0.66f, 0.25f, 0.21f, 0.8f); + + ParticleSystem waves; + TextMesh label; + Material ringMat; + Texture2D ringTex; + + void Start() + { + // Wellen kommen von der Straße links vor der Fensterfront (x < 0) und laufen auf den Raum zu + var go = new GameObject("Schallwellen"); + go.transform.SetParent(transform, false); + go.transform.localPosition = new Vector3(-RoomBuilder.W / 2f - 2.2f, 1.7f, 0f); + waves = go.AddComponent(); + waves.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear); + + var main = waves.main; + main.loop = true; + main.startLifetime = 2.2f; + main.startSpeed = 0f; + main.startSize = 0.4f; + main.maxParticles = 80; + main.simulationSpace = ParticleSystemSimulationSpace.World; + main.playOnAwake = true; + + var shape = waves.shape; + shape.shapeType = ParticleSystemShapeType.Box; + shape.scale = new Vector3(0.2f, 1.2f, RoomBuilder.D * 0.8f); + + var vel = waves.velocityOverLifetime; + vel.enabled = true; + vel.space = ParticleSystemSimulationSpace.World; + vel.x = new ParticleSystem.MinMaxCurve(0.6f); + vel.y = new ParticleSystem.MinMaxCurve(0f); + vel.z = new ParticleSystem.MinMaxCurve(0f); + + var size = waves.sizeOverLifetime; + size.enabled = true; + size.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.Linear(0f, 0.3f, 1f, 3.2f)); + + var col = waves.colorOverLifetime; + col.enabled = true; + var g = new Gradient(); + g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, + new[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(1f, 0.15f), new GradientAlphaKey(0f, 1f) }); + col.color = g; + + ringTex = RingTexture(64); + ringMat = new Material(Shader.Find("Sprites/Default")) { mainTexture = ringTex }; + var r = go.GetComponent(); + r.material = ringMat; + r.renderMode = ParticleSystemRenderMode.Billboard; + r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + r.receiveShadows = false; + + var emission = waves.emission; + emission.rateOverTime = 0f; + waves.Play(); + + // Pegelanzeige an der Fassade (von innen durch die Fenster lesbar) + var sign = new GameObject("Pegelanzeige"); + sign.transform.SetParent(transform, false); + sign.transform.localPosition = new Vector3(-RoomBuilder.W / 2f - 0.6f, RoomBuilder.WinTopY + 0.32f, 0f); + sign.transform.localRotation = Quaternion.Euler(0f, -90f, 0f); + label = sign.AddComponent(); + label.anchor = TextAnchor.MiddleCenter; + label.alignment = TextAlignment.Center; + label.characterSize = 0.05f; + label.fontSize = 64; + var font = Prim.BuiltinFont(); + if (font != null) + { + label.font = font; + sign.GetComponent().sharedMaterial = font.material; + } + } + + void Update() + { + if (env == null || waves == null) return; + float db = env.outdoorNoise; + float limit = bridge != null && bridge.CentralActive ? bridge.Central.grenzwerte.laermDb + : controller != null ? controller.limits.noiseLimit : 70f; + bool veto = db > limit; + float k = Mathf.InverseLerp(quietDb, 95f, db); // 0 = ruhig, 1 = sehr laut + + var emission = waves.emission; + emission.rateOverTime = db <= quietDb ? 0f : Mathf.Lerp(2f, 22f, k); + var main = waves.main; + main.startColor = veto ? Loud : Color.Lerp(Calm, new Color(0.85f, 0.6f, 0.25f, 0.65f), k); + main.startSize = Mathf.Lerp(0.35f, 0.9f, k); + var vel = waves.velocityOverLifetime; + vel.x = new ParticleSystem.MinMaxCurve(Mathf.Lerp(0.4f, 1.6f, k)); + + if (label != null) + { + bool sensor = env.IsMeasured("nout"); + label.text = $"Außenlärm {db:0} dB{(sensor ? " · Sensor" : "")}{(veto ? "\nFenster gesperrt" : "")}"; + label.color = veto ? new Color(0.75f, 0.2f, 0.15f) : new Color(0.25f, 0.33f, 0.3f); + } + } + + static Texture2D RingTexture(int n) + { + var t = new Texture2D(n, n, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, hideFlags = HideFlags.HideAndDontSave }; + var px = new Color[n * n]; + for (int y = 0; y < n; y++) + for (int x = 0; x < n; x++) + { + float d = Vector2.Distance(new Vector2(x + 0.5f, y + 0.5f), new Vector2(n / 2f, n / 2f)) / (n / 2f); + float a = Mathf.Clamp01(1f - Mathf.Abs(d - 0.82f) / 0.12f); // Ring bei 82 % des Radius + px[y * n + x] = new Color(1f, 1f, 1f, a * a); + } + t.SetPixels(px); + t.Apply(); + return t; + } + + void OnDestroy() + { + if (ringMat != null) Destroy(ringMat); + if (ringTex != null) Destroy(ringTex); + } + } +} diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/RoomEnvironment.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/RoomEnvironment.cs index cab5991..127bcbd 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/RoomEnvironment.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/RoomEnvironment.cs @@ -27,6 +27,12 @@ namespace SmartRoom public float co2 = 650f; // ppm public float indoorLux = 300f; // lx public float indoorNoise = 42f; // dB(A) + [Tooltip("Nur gemessen (DHT11), wird nicht simuliert")] + public float indoorHumidity = 45f; // % + [Tooltip("Nur gemessen (CCS811), wird nicht simuliert")] + public float tvoc = 0f; // ppb + [Tooltip("Nur gemessen (Fotowiderstand), relativ 0–100 %")] + public float lightPercent = 0f; [Header("Außen (Wetterdaten / Sensoren / manuell)")] public float outdoorTemp = 14f; // °C @@ -36,11 +42,12 @@ namespace SmartRoom public float solar = 350f; // W/m² Globalstrahlung [Tooltip("Sekunden, die ein Messwert als 'live' gilt")] - public float measurementTimeout = 15f; + public float measurementTimeout = 25f; // Station sendet ca. alle 7–8 s, fällt eine Sendung aus ca. alle 15 s public RoomDevices devices; - readonly Dictionary measuredAt = new Dictionary(); + readonly Dictionary measuredAt = new Dictionary(); // echter Sensorwert + readonly Dictionary providedAt = new Dictionary(); // von außen vorgegeben (Sensor, Wetter, Demo) public string ClockText { @@ -51,9 +58,34 @@ namespace SmartRoom } } + // Beispielwerte beim Start (Umschalter "Simulation" stellt sie wieder her) + float[] example; + + void Awake() + { + example = new[] { indoorTemp, co2, indoorLux, indoorNoise, indoorHumidity, tvoc, lightPercent, + outdoorTemp, outdoorAqi, outdoorNoise, windSpeed, solar, occupants }; + } + + /// Zurück zu den Beispielwerten der Simulation; alle Arduino-/Backend-Werte werden verworfen. + public void ResetToExampleValues() + { + measuredAt.Clear(); + providedAt.Clear(); + if (example == null) return; + indoorTemp = example[0]; co2 = example[1]; indoorLux = example[2]; indoorNoise = example[3]; + indoorHumidity = example[4]; tvoc = example[5]; lightPercent = example[6]; + outdoorTemp = example[7]; outdoorAqi = example[8]; outdoorNoise = example[9]; + windSpeed = example[10]; solar = example[11]; occupants = Mathf.RoundToInt(example[12]); + } + public bool IsMeasured(string channel) => measuredAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout; + /// Wert kommt von außen (Arduino oder zentrales Backend) und wird nicht simuliert. + public bool IsProvided(string channel) + => providedAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout; + public bool AnyMeasured { get @@ -65,8 +97,25 @@ namespace SmartRoom } /// Übernimmt ein Datenpaket vom Arduino. Fehlende Felder (NaN) werden ignoriert. - public void ApplyMeasurement(SensorPacket p) + public void ApplyMeasurement(SensorPacket p) => Apply(p, _ => true); + + /// + /// Übernimmt Werte des zentralen Backends. Alle gesendeten Werte ersetzen die Simulation, + /// als "Sensor" gelten aber nur die, für die true liefert (nicht Wetter/Demo). + /// + public void ApplyRemote(SensorPacket p, Func isSensor) => Apply(p, isSensor); + + void Apply(SensorPacket p, Func isSensor) { + void Set(string channel, float v, Action apply) + { + if (float.IsNaN(v)) return; + apply(v); + providedAt[channel] = Time.unscaledTime; + if (isSensor(channel)) measuredAt[channel] = Time.unscaledTime; + else measuredAt.Remove(channel); + } + Set("t", p.t, v => indoorTemp = v); Set("co2", p.co2, v => co2 = v); Set("lux", p.lux, v => indoorLux = v); @@ -77,13 +126,16 @@ namespace SmartRoom Set("wind", p.wind, v => windSpeed = v); Set("sun", p.sun, v => solar = v); Set("persons", p.persons, v => occupants = Mathf.RoundToInt(v)); + Set("rh", p.rh, v => indoorHumidity = v); + Set("tvoc", p.tvoc, v => tvoc = v); + Set("lightpct", p.lightpct, v => lightPercent = v); } - void Set(string channel, float v, Action apply) + /// Kanal sofort wieder simulieren (z. B. wenn das Mikrofon von innen nach außen wechselt). + public void Forget(string channel) { - if (float.IsNaN(v)) return; - apply(v); - measuredAt[channel] = Time.unscaledTime; + measuredAt.Remove(channel); + providedAt.Remove(channel); } /// Geschätzte Tageslicht-Beleuchtungsstärke im Raum bei gegebener Jalousie-Abschirmung. @@ -101,9 +153,9 @@ namespace SmartRoom for (int i = 0; i < steps; i++) Integrate(h); float win = devices.WindowAirflow; - if (!IsMeasured("lux")) + if (!IsProvided("lux")) indoorLux = DaylightLux(devices.BlindClosure) + devices.LightLevel * 520f; - if (!IsMeasured("noise")) + if (!IsProvided("noise")) { float people = lectureRunning ? 45f : 30f; float outside = outdoorNoise - Mathf.Lerp(32f, 8f, win); @@ -120,14 +172,14 @@ namespace SmartRoom float achVent = vent * 6f; int persons = lectureRunning ? occupants : 0; - if (!IsMeasured("co2")) + if (!IsProvided("co2")) { float gen = persons * 0.0083f; // ppm/s pro Person (~0,005 l/s CO2) co2 += (gen - (achWindow + achVent) / 3600f * (co2 - OutdoorCo2)) * h; co2 = Mathf.Max(OutdoorCo2, co2); } - if (!IsMeasured("t")) + if (!IsProvided("t")) { float pHeat = devices.HeatingLevel * 9000f; float pPeople = persons * 80f; diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs index 334d631..54e814a 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs @@ -10,24 +10,22 @@ namespace SmartRoom [DefaultExecutionOrder(-100)] public class SmartRoomApp : MonoBehaviour { + [Tooltip("Classic = ursprünglicher Zwilling mit dunklem Dashboard, Ambient = Optik des Web-Frontends (Ambient²)")] + public RoomStyle style = RoomStyle.Classic; + public RoomDevices Devices { get; private set; } void Awake() { - Devices = RoomBuilder.Build(transform); + Devices = RoomBuilder.Build(transform, style); var env = GetOrAdd(); env.devices = Devices; Devices.env = env; - var backend = GetOrAdd(); - backend.env = env; - backend.devices = Devices; - var bridge = GetOrAdd(); bridge.env = env; bridge.devices = Devices; - bridge.backend = backend; var weather = GetOrAdd(); weather.env = env; @@ -35,26 +33,63 @@ namespace SmartRoom var controller = GetOrAdd(); controller.env = env; controller.devices = Devices; - controller.backend = backend; + bridge.scenarioProvider = () => controller.Scenario; + bridge.controller = controller; + + // Außenlärm im 3D-Raum sichtbar machen (Schallwellen vor der Fensterfront) + var noise = new GameObject("Außenlärm (Visualisierung)").AddComponent(); + noise.transform.SetParent(transform, false); + noise.env = env; + noise.controller = controller; + noise.bridge = bridge; Devices.sun = SetupSun(); var orbit = SetupCamera(); + QualitySettings.pixelLightCount = Mathf.Max(QualitySettings.pixelLightCount, 8); + + if (style == RoomStyle.Ambient) + { + SetupAmbient(env, controller, bridge, weather, orbit); + return; + } var hud = GetOrAdd(); hud.env = env; hud.devices = Devices; hud.controller = controller; hud.bridge = bridge; - hud.backend = backend; hud.weather = weather; hud.orbit = orbit; Devices.projector.contentProvider = () => $"Innen {env.indoorTemp:0.0} °C · CO2 {env.co2:0} ppm · {env.indoorLux:0} lx\n" + $"Außen {env.outdoorTemp:0.0} °C · Wind {env.windSpeed:0.0} m/s · AQI {env.outdoorAqi:0}\n" + - $"Fenster {Devices.WindowLabel} · Lüftung {Devices.VentLevel * 100f:0} % · Heizung {Devices.HeatingLevel * 100f:0} %"; + $"Fenster {Devices.WindowLabel} · Lüftung {Devices.VentLevel * 100f:0} % · Heizung {Devices.HeatingLevel * 100f:0} %\n" + + $"Szenario {controller.Scenario} · Quelle {(env.AnyMeasured ? "Arduino" : "Simulation")}"; + } - QualitySettings.pixelLightCount = Mathf.Max(QualitySettings.pixelLightCount, 8); + /// Helles, weiches Licht und das Dashboard im Look des Web-Frontends. + void SetupAmbient(RoomEnvironment env, ClimateController controller, ArduinoBridge bridge, WeatherService weather, OrbitCamera orbit) + { + Devices.ambSky = new Color(0.93f, 0.96f, 0.94f); + Devices.ambEquator = new Color(0.86f, 0.89f, 0.87f); + Devices.ambGround = new Color(0.72f, 0.75f, 0.73f); + Devices.ambBase = 0.55f; + Devices.sun.shadowStrength = 0.35f; + + var hud = GetOrAdd(); + hud.env = env; + hud.devices = Devices; + hud.controller = controller; + hud.bridge = bridge; + hud.weather = weather; + hud.orbit = orbit; + hud.roomCamera = orbit.GetComponent(); + + Devices.projector.contentProvider = () => + $"{hud.roomName.ToUpperInvariant()}\n" + + $"{env.indoorTemp:0.0} °C · CO2 {env.co2:0} ppm · Ziel {controller.AverageWish:0.0} °C\n" + + $"Szenario: {controller.Scenario} · Quelle: {(env.AnyMeasured ? "Arduino" : "Simulation")}"; } T GetOrAdd() where T : Component diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/AmbientHUD.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/AmbientHUD.cs new file mode 100644 index 0000000..b8407bb --- /dev/null +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/AmbientHUD.cs @@ -0,0 +1,1219 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using UnityEngine; + +namespace SmartRoom +{ + /// + /// Dashboard im Look des Web-Frontends „Ambient²“ (hell, Salbei/Grün, Karten): Raumstatus mit 3D-Ansicht, + /// Messwert-Kacheln, Dozentensteuerung, Raumstimmung, Verlauf und Demo-Szenarien. + /// Gleiche Logik wie , nur andere Optik. Ausgelegt auf 1440 × 900, wird auf den Bildschirm skaliert. + /// Die Raumkamera rendert in eine Textur, die in der Karte „Raumstatus“ angezeigt wird. + /// + public class AmbientHUD : MonoBehaviour + { + public RoomEnvironment env; + public RoomDevices devices; + public ClimateController controller; + public ArduinoBridge bridge; + public WeatherService weather; + public OrbitCamera orbit; + public Camera roomCamera; + + [Header("Texte")] + public string campus = "KlimaCampus"; + public string roomName = "Raum 2.14"; + public string building = "Gebäude West"; + public string roomLong = "Seminarraum 2.14"; + public string lecturer = "Frau Weber"; + + [Header("Bedienung")] + public bool lecturerView = true; + [Tooltip("Dauer des Beamer-Modus in simulierten Minuten")] public float[] beamerDurations = { 30f, 60f, 90f }; + public int beamerDurationIndex = 1; + [Tooltip("Jalousien manuell: Automatik pausiert für (simulierte) Minuten")] public float manualBlindMinutes = 30f; + + // Farben des Frontends (CSS-Variablen in Ambient2) + static readonly Color Ink = Hex(0x16221d), Muted = Hex(0x68746f), Line = Hex(0xdfe6e1), Surface = Color.white, + Soft = Hex(0xf7f9f7), Green = Hex(0x175c45), Green2 = Hex(0x2b8063), GreenSoft = Hex(0xe8f3ed), Mint = Hex(0xcbe6d8), + Amber = Hex(0xa86518), AmberSoft = Hex(0xfff3dc), Red = Hex(0xa83f35), RedSoft = Hex(0xfceae7), + Blue = Hex(0x3e6578), BlueSoft = Hex(0xe9f2f5), CoolVote = Hex(0x9fb8c6), WarmVote = Hex(0xc99a64), + SkyColor = new Color(0.88f, 0.93f, 0.91f); + + static Color Hex(int rgb) => new Color(((rgb >> 16) & 255) / 255f, ((rgb >> 8) & 255) / 255f, (rgb & 255) / 255f); + static readonly CultureInfo De = new CultureInfo("de-DE"); + + struct Tone + { + public Color fg, bg; + public Tone(Color fg, Color bg) { this.fg = fg; this.bg = bg; } + } + static readonly Tone ToneGreen = new Tone(Green, GreenSoft), ToneAmber = new Tone(Amber, AmberSoft), + ToneRed = new Tone(Red, RedSoft), ToneBlue = new Tone(Blue, BlueSoft); + + struct BannerState { public string title, text, icon, priorityText; public Tone tone; public int priority; } + + /// Zustand des zentralen Backends (server.js), solange es antwortet – dann entscheidet es, Unity zeigt nur an. + CentralState C => bridge != null && bridge.CentralActive ? bridge.Central : null; + int centralVote = -1; // eigene Stimme beim zentralen Backend (0 kühler, 1 angenehm, 2 wärmer) + + static Tone ToneOf(string ton) => ton == "good" ? ToneGreen : ton == "danger" ? ToneRed : ton == "info" ? ToneBlue : ToneAmber; + + class Demo { public string name, sub; public Action apply; } + class Entry { public string time, title, text; public Color dot; } + + const float RefW = 1440f, RefH = 900f; + float k = 1f; // Skalierung virtuelle Einheit → Pixel + Vector2 origin; // linke obere Ecke der virtuellen Fläche + Font sans, serif; + readonly Dictionary textStyles = new Dictionary(); + readonly Dictionary roundStyles = new Dictionary(); + readonly Dictionary holeStyles = new Dictionary(); + readonly List textures = new List(); + GUIStyle fieldStyle; + float stylesFor = -1f; + + readonly List demos = new List(); + readonly List history = new List(); + Decision prevDecision; + int prevClamped; + + RenderTexture rt; + Camera bgCam; + Rect vpRect, popRect; + bool settingsOpen, drawingPopover, wasBeamer; + double beamerUntil = double.NegativeInfinity; + string fieldText; + LinkMode fieldMode = (LinkMode)(-1); + + float BeamerMinutes => beamerDurations[Mathf.Clamp(beamerDurationIndex, 0, beamerDurations.Length - 1)]; + + // ================================================================ Start / Update + void Start() + { + SeedWishes(); + BuildDemos(); + controller.Decided += OnDecided; + if (controller.Last != null) OnDecided(controller.Last); + SetupCameras(); + } + + void OnDestroy() + { + if (controller != null) controller.Decided -= OnDecided; + if (roomCamera != null) roomCamera.targetTexture = null; + if (rt != null) { rt.Release(); Destroy(rt); } + foreach (var t in textures) if (t != null) Destroy(t); + } + + /// Wie im Frontend: 9 Stimmen (1 kühler, 7 angenehm, 1 wärmer), falls noch die Standardliste aktiv ist. + void SeedWishes() + { + if (controller.wishes.Count != 5) return; + float[] extra = { 22f, 22f, 21.8f, 22.2f }; + for (int i = 0; i < extra.Length; i++) + controller.wishes.Add(new UserWish($"Teilnehmer {5 + i}", extra[i], false)); + } + + void SetupCameras() + { + if (roomCamera == null) roomCamera = orbit != null ? orbit.GetComponent() : Camera.main; + if (roomCamera == null) return; + roomCamera.clearFlags = CameraClearFlags.SolidColor; + roomCamera.backgroundColor = SkyColor; + roomCamera.fieldOfView = 44f; + + // Hintergrundkamera füllt den Bildschirm, die Raumkamera rendert nur in die Textur der Karte "Raumstatus" + bgCam = new GameObject("Hintergrund (Ambient-Dashboard)").AddComponent(); + bgCam.clearFlags = CameraClearFlags.SolidColor; + bgCam.backgroundColor = Soft; + bgCam.cullingMask = 0; + bgCam.depth = roomCamera.depth - 10f; + + if (orbit != null) + { + orbit.rayProvider = p => roomCamera.ViewportPointToRay(new Vector3( + (p.x - vpRect.x) / Mathf.Max(1f, vpRect.width), 1f - (p.y - vpRect.y) / Mathf.Max(1f, vpRect.height), 0f)); + FrontView(true); + } + } + + /// Frontansicht wie die Raumillustration im Frontend: Blick auf Leinwand, Fenster links. + void FrontView(bool snap) => orbit?.SetView(new Vector3(0f, 1.5f, 2.6f), 0f, 6f, 9.4f, snap); + + void Update() + { + if (env == null || devices == null || controller == null) return; + if (C != null) { wasBeamer = devices.BeamerOn; return; } // Vortragsmodus läuft im Backend ab + // Beamer-Modus endet nach der gewählten Dauer + bool on = devices.BeamerOn; + if (on && !wasBeamer && beamerUntil <= env.simMinutes) beamerUntil = env.simMinutes + BeamerMinutes; + if (on && env.simMinutes >= beamerUntil) + { + devices.projector.beamerOn = false; + on = false; + controller.RunCycle(); + } + wasBeamer = on; + } + + void SetBeamer(bool on) + { + if (devices.projector == null) return; + devices.projector.beamerOn = on; + beamerUntil = on ? env.simMinutes + BeamerMinutes : double.NegativeInfinity; + wasBeamer = on; + controller.RunCycle(); + } + + // ================================================================ Demo-Szenarien + void BuildDemos() + { + demos.Add(new Demo { name = "Normal", sub = "Alle Werte im Zielbereich", apply = () => + { + Outdoor(14f, 25f, 45f, 2.5f, 350f); + env.indoorTemp = 22f; env.co2 = 650f; + RemoveOutlier(); + if (devices.BeamerOn) SetBeamer(false); + } }); + demos.Add(new Demo { name = "CO₂ zu hoch", sub = "Gesundheit priorisiert Lüften", apply = () => + { + Outdoor(14f, 25f, 45f, 2.5f, 350f); + env.co2 = 1350f; + } }); + demos.Add(new Demo { name = "CO₂ + Außenlärm", sub = "Frischluft mit Lärmschutz", apply = () => + { + Outdoor(14f, 25f, 82f, 2.5f, 350f); + env.co2 = 1350f; + } }); + demos.Add(new Demo { name = "Sturm", sub = "Fenster werden gesperrt", apply = () => + { + Outdoor(12f, 25f, 50f, 16f, 250f); + env.co2 = 1300f; + } }); + demos.Add(new Demo { name = "Vortragsmodus", sub = "Licht und Jalousien angepasst", apply = () => SetBeamer(true) }); + demos.Add(new Demo { name = "Ausreißer-Stimme", sub = "Mehrheit bleibt ausschlaggebend", apply = () => + { + RemoveOutlier(); + controller.wishes.Add(new UserWish("Ausreißer", 30f, false)); + } }); + demos.Add(new Demo { name = "Hitze", sub = "Zu warm, Fenster öffnen", apply = () => + { + Outdoor(24f, 25f, 45f, 2f, 750f); + env.indoorTemp = 29f; env.co2 = 700f; + } }); + demos.Add(new Demo { name = "Kalter Morgen", sub = "Heizen auf Ø-Wunsch", apply = () => + { + Outdoor(-3f, 25f, 40f, 3f, 80f); + env.indoorTemp = 17.5f; env.co2 = 600f; + } }); + } + + void Outdoor(float temp, float aqi, float noise, float wind, float sun) + { + env.outdoorTemp = temp; env.outdoorAqi = aqi; env.outdoorNoise = noise; env.windSpeed = wind; env.solar = sun; + } + + void RemoveOutlier() => controller.wishes.RemoveAll(w => w.name == "Ausreißer"); + + /// Welche Demo-Kachel zum erkannten Zustand passt (Sensorwerte lösen sie automatisch aus). + string ActiveDemo() + { + if (devices.BeamerOn) return "Vortragsmodus"; + switch (controller.Scenario) + { + case "Stickige Luft": + case "Stickig + kalt": + case "Schlechte Außenluft": return "CO₂ zu hoch"; + case "Baustellenlärm": return "CO₂ + Außenlärm"; + case "Sturm": return "Sturm"; + case "Hitze": return "Hitze"; + case "Wintermorgen": return "Kalter Morgen"; + case ClimateController.NormalScenario: return controller.ClampedWishes > 0 ? "Ausreißer-Stimme" : "Normal"; + default: return null; + } + } + + // ================================================================ Verlauf + void OnDecided(Decision d) + { + var e = Describe(d); + if (controller.ClampedWishes > prevClamped) + Push(new Entry { time = d.time, title = "Temperaturwunsch begrenzt", text = "Wunsch liegt außerhalb des zulässigen Bereichs.", dot = Amber }); + prevClamped = controller.ClampedWishes; + Push(e); + prevDecision = d; + } + + void Push(Entry e) + { + e.time = e.time?.Replace(" Uhr", ""); + if (history.Count > 0 && history[0].title == e.title && history[0].text == e.text) + { + history[0].time = e.time; // gleiche Meldung nicht stapeln + return; + } + history.Insert(0, e); + if (history.Count > 8) history.RemoveAt(history.Count - 1); + } + + Entry Describe(Decision d) + { + var e = new Entry { time = d.time, dot = Green }; + var p = prevDecision; + if (!env.lectureRunning) + { + e.title = "Energiesparmodus"; e.text = "Keine Vorlesung – Fenster zu, Geräte aus."; e.dot = Blue; + } + else if (p != null && p.window == d.window && Same(p.ventilation, d.ventilation) && Same(p.heating, d.heating) && Same(p.blinds, d.blinds)) + { + e.title = "Zielwerte gehalten"; e.text = "Raumklima stabil. Keine Anpassung erforderlich."; + } + else if (d.window != WindowState.Closed && (p == null || p.window != d.window)) + { + e.title = d.window == WindowState.Open ? "Gelüftet" : "Fenster gekippt"; + e.text = env.co2 > controller.limits.co2Limit ? $"CO₂ {N(env.co2, 0)} ppm über dem Grenzwert." + : env.indoorTemp > controller.limits.tempHigh ? $"Zu warm ({N(env.indoorTemp, 1)} °C)." + : "Fensteröffnung gewünscht."; + if (d.window == WindowState.Tilted) e.text += " Wind begrenzt die Öffnung."; + e.dot = Amber; + } + else if (d.ventilation > 0.01f && (p == null || p.ventilation <= 0.01f)) + { + e.title = "Lüftungsanlage an"; + e.text = env.outdoorAqi > controller.limits.outdoorAqiLimit ? "Außenluft belastet – Fenster bleiben zu." + : env.outdoorTemp < controller.limits.outdoorColdLimit ? "Draußen zu kalt – Fenster bleiben zu." + : env.outdoorNoise > controller.limits.noiseLimit ? "Außenlärm – Fenster bleiben zu." + : "Frischluft über die Anlage."; + e.dot = Amber; + } + else if (d.heating > 0.01f && (p == null || p.heating <= 0.01f)) + { + e.title = "Heizung an"; e.text = $"Zielwert {N(Target, 1)} °C wird angesteuert."; e.dot = Blue; + } + else if (p != null && p.window != WindowState.Closed && d.window == WindowState.Closed) + { + e.title = "Fenster geschlossen"; e.text = $"Zielwert {N(Target, 1)} °C wird wieder angesteuert."; + } + else if (p != null && !Same(p.blinds, d.blinds)) + { + e.title = d.blinds > p.blinds ? "Jalousien geschlossen" : "Jalousien geöffnet"; + e.text = devices.BeamerOn ? "Vortragsmodus: Raum abgedunkelt." : env.solar > controller.limits.sunLimit ? "Sonnenschutz." : "Tageslicht nutzen."; + e.dot = Blue; + } + else + { + e.title = "Steuerung angepasst"; e.text = $"Fenster {d.window.Label()}, Heizung {d.heating * 100:0} %, Lüftung {d.ventilation * 100:0} %."; + } + return e; + } + + static bool Same(float a, float b) => Mathf.Abs(a - b) < 0.02f; + + // ================================================================ Zustand → Texte + float Target => C != null ? C.zielTemperatur : Mathf.Clamp(controller.AverageWish, 18f, 26f); + + BannerState Banner() + { + var c = C; + if (c != null) + { + var tone = ToneOf(c.ton); + return new BannerState + { + title = c.status, text = c.detail, tone = tone, priority = Mathf.Clamp(c.prioritaetNummer, 1, 4), priorityText = c.prioritaet, + icon = c.ton == "good" ? "✓" : c.ton == "info" ? "i" : "!", + }; + } + var L = controller.limits; + if (!env.lectureRunning) + return new BannerState { title = "Keine Vorlesung", text = "Raum im Energiesparmodus – Fenster zu, Geräte aus.", icon = "i", tone = ToneBlue, priority = 4 }; + switch (controller.Scenario) + { + case "Stickige Luft": + return new BannerState { title = "CO₂ zu hoch – es wird gelüftet", text = $"{N(env.co2, 0)} ppm über dem Grenzwert von {N(L.co2Limit, 0)} ppm. Gesundheit hat Vorrang.", icon = "!", tone = ToneAmber, priority = 1 }; + case "Stickig + kalt": + return new BannerState { title = "CO₂ zu hoch, draußen zu kalt", text = "Lüftungsanlage statt Fenster, damit der Raum nicht auskühlt.", icon = "!", tone = ToneAmber, priority = 1 }; + case "Schlechte Außenluft": + return new BannerState { title = "Lüften ohne Fenster", text = $"Außenluft belastet (AQI {env.outdoorAqi:0}). Die Lüftungsanlage übernimmt.", icon = "!", tone = ToneAmber, priority = 1 }; + case "Baustellenlärm": + return new BannerState + { + title = "Frischluft, trotz hoher Außenlautstärke", + text = devices.WindowTarget == WindowState.Open + ? "CO₂ erfordert Lüften. Die Mehrheit wünscht das Fenster offen." + : "CO₂ erfordert Lüften. Der Lärmschutz hält die Fenster zu – Lüftungsanlage läuft.", + icon = "!", tone = ToneAmber, priority = 1 + }; + case "Sturm": + return new BannerState { title = "Sturm – Fenster nur gekippt", text = $"Wind {N(env.windSpeed * 3.6f, 0)} km/h. Die Kontext-Sperre begrenzt die Öffnung.", icon = "!", tone = ToneRed, priority = 2 }; + case "Hitze": + return new BannerState { title = "Zu warm – es wird gelüftet", text = $"{N(env.indoorTemp, 1)} °C im Raum, Ziel {N(Target, 1)} °C.", icon = "!", tone = ToneAmber, priority = 1 }; + case "Wintermorgen": + return new BannerState { title = "Raum wird aufgeheizt", text = $"{N(env.indoorTemp, 1)} °C im Raum. Zielwert {N(Target, 1)} °C aus {controller.wishes.Count} Stimmen.", icon = "i", tone = ToneBlue, priority = 3 }; + case "Pralle Sonne": + return new BannerState { title = "Sonnenschutz aktiv", text = "Starke Sonneneinstrahlung – die Jalousien fahren herunter.", icon = "i", tone = ToneBlue, priority = 4 }; + } + if (devices.BeamerOn) + return new BannerState { title = $"Vortragsmodus aktiv bis {Clock(beamerUntil)}", text = "Jalousien geschlossen, Raumautomatik bleibt im Hintergrund aktiv.", icon = "i", tone = ToneBlue, priority = 4 }; + return new BannerState { title = "Raumklima im Zielbereich", text = "Temperatur und Luftqualität sind stabil.", icon = "✓", tone = ToneGreen, priority = 4 }; + } + + static readonly string[] PriorityNames = { "", "Gesundheit", "Kontext", "Mehrheit", "Energie" }; + + static string N(float v, int dec) => v.ToString("N" + dec, De); + + static string Clock(double simMinutes) + { + if (double.IsInfinity(simMinutes)) return "–"; + var t = TimeSpan.FromMinutes(simMinutes % 1440.0); + return $"{t.Hours:00}:{t.Minutes:00}"; + } + + string Greeting() + { + int h = (int)(env.simMinutes % 1440.0 / 60.0); + return h < 11 ? "Guten Morgen" : h < 18 ? "Guten Tag" : "Guten Abend"; + } + + // ================================================================ OnGUI + void OnGUI() + { + if (env == null || devices == null || controller == null) return; + EnsureStyles(); + var e = Event.current; + if (e.type == EventType.KeyDown && GUIUtility.keyboardControl == 0) HandleKeys(e); + + popRect = settingsOpen ? V(RefW - 24f - 340f, 62f, 340f, SettingsHeight()) : Rect.zero; + if (settingsOpen && e.type == EventType.MouseDown && !popRect.Contains(e.mousePosition) && !statusPill.Contains(e.mousePosition)) + settingsOpen = false; + + // Bildschirmränder außerhalb der 1440×900-Fläche + Fill(new Rect(0, 0, Screen.width, Screen.height), Soft); + + var banner = Banner(); + DrawTopBar(); + DrawHeader(); + DrawBanner(banner); + DrawRoomCard(); + DrawMetrics(); + DrawDemos(); + if (lecturerView) + { + DrawLecturerCard(V(1016, 236, 400, 254)); + DrawMood(V(1016, 502, 400, 198), false); + } + else + { + DrawMood(V(1016, 236, 400, 234), true); + DrawPriorities(V(1016, 482, 400, 218), banner.priority); + } + DrawHistory(V(1016, 712, 400, 138)); + DrawFooter(); + if (settingsOpen) DrawSettings(); + + ForwardToCamera(e); + } + + void HandleKeys(Event e) + { + switch (e.keyCode) + { + case KeyCode.Alpha0: case KeyCode.R: FrontView(false); break; + case KeyCode.Alpha1: orbit?.Preset(0); break; + case KeyCode.Alpha2: orbit?.Preset(1); break; + case KeyCode.Alpha3: orbit?.Preset(2); break; + case KeyCode.Alpha4: orbit?.Preset(3); break; + case KeyCode.T: devices.door?.Toggle(); break; + case KeyCode.B: if (C == null) SetBeamer(!devices.BeamerOn); break; // mit Backend: Webinterface + case KeyCode.Space: controller.RunCycle(); break; + default: return; + } + e.Use(); + } + + void ForwardToCamera(Event e) + { + if (orbit == null || e.type == EventType.Used) return; + bool relevant = e.isMouse || e.type == EventType.ScrollWheel; + bool over = vpRect.Contains(e.mousePosition) && !(settingsOpen && popRect.Contains(e.mousePosition)); + if (relevant && (over || orbit.IsDragging)) orbit.HandleEvent(e); + } + + // ---------------------------------------------------------------- Kopfzeile + void DrawTopBar() + { + var bar = new Rect(0, 0, Screen.width, V(0, 0, 1, 60).yMax); + Fill(bar, Surface); + Fill(new Rect(0, bar.yMax - 1, Screen.width, 1), Line); + + Box(V(24, 12, 36, 36), Green, 9); + Text(V(24, 12, 36, 36), "≋", 20, Color.white, true, TextAnchor.MiddleCenter); + Text(V(70, 13, 300, 18), campus, 15, Ink, true); + Text(V(70, 32, 300, 16), $"{roomName} · {building}", 11, Muted); + + // Studierende / Dozent + var seg = V(RefW / 2 - 110, 12, 220, 36); + Box(seg, Soft, 10, Line); + var a = V(RefW / 2 - 106, 16, 106, 28); + var b = V(RefW / 2, 16, 106, 28); + var active = lecturerView ? b : a; + Shadow(active, 7); + Box(active, Surface, 7, Line); + Text(a, "Studierende", 12, lecturerView ? Muted : Ink, true, TextAnchor.MiddleCenter); + Text(b, "Dozent", 12, lecturerView ? Ink : Muted, true, TextAnchor.MiddleCenter); + if (Click(a)) lecturerView = false; + if (Click(b)) lecturerView = true; + + // Arduino-Status rechts (Klick → Einstellungen) + bool arduino = bridge != null && bridge.ArduinoConnected; + string status = arduino ? "Arduino verbunden" : "Arduino nicht verbunden"; + float w = TextWidth(status, 12, true) + 52f; + var pill = V(RefW - 24 - w, 14, w, 32); + statusPill = pill; + Box(pill, arduino ? GreenSoft : RedSoft, 8, settingsOpen || Hover(pill) ? (arduino ? Green2 : Red) : Color.Lerp(arduino ? GreenSoft : RedSoft, arduino ? Green : Red, 0.25f)); + Box(V(VX(pill) + 11, 26, 8, 8), arduino ? Green2 : Red, 4); + Text(V(VX(pill) + 25, 14, w - 25, 32), status + " ≡", 12, arduino ? Green : Red, true); + if (Click(pill)) settingsOpen = !settingsOpen; + + // Umschalter: Werte vom Arduino oder Beispielwerte der Simulation + if (bridge == null) return; + const float sw = 236f; + float sx = VX(pill) - 12 - sw; + Box(V(sx, 12, sw, 36), Soft, 10, Line); + var ar = V(sx + 4, 16, sw / 2 - 4, 28); + var si = V(sx + sw / 2, 16, sw / 2 - 4, 28); + bool useArduino = bridge.UseArduinoData; + var on = useArduino ? ar : si; + Shadow(on, 7); + Box(on, Surface, 7, Line); + Text(ar, "Arduino-Werte", 12, useArduino ? Ink : Muted, true, TextAnchor.MiddleCenter); + Text(si, "Simulation", 12, useArduino ? Muted : Ink, true, TextAnchor.MiddleCenter); + if (Click(ar) && !useArduino) bridge.UseArduinoData = true; + if (Click(si) && useArduino) bridge.UseArduinoData = false; + } + + Rect statusPill; + + // ---------------------------------------------------------------- Begrüßung + void DrawHeader() + { + Text(V(24, 74, 600, 16), roomLong.ToUpperInvariant(), 11, Green, true); + string title = lecturerView ? $"{Greeting()}, {lecturer}." : $"{Greeting()}."; + Text(V(22, 90, 900, 44), title, 34, Ink, false, TextAnchor.MiddleLeft, true); + Text(V(24, 134, 900, 18), lecturerView ? "Das Raumklima wird automatisch und fair gesteuert." + : "Wie fühlt sich der Raum für dich an? Deine Stimme zählt – anonym.", 13, Muted); + + // Außenwerte + string tOut = $"{N(env.outdoorTemp, 0)} °C außen"; + string wind = $"{N(env.windSpeed * 3.6f, 0)} km/h Wind"; + float w1 = TextWidth(tOut, 12, false) + 28f, w2 = TextWidth(wind, 12, false) + 28f; + float x = RefW - 24 - w1 - w2; + var r = V(x, 102, w1 + w2, 38); + Box(r, Surface, 10, Line); + Text(V(x, 102, w1, 38), tOut, 12, Ink, false, TextAnchor.MiddleCenter); + Fill(V(x + w1, 111, 1, 20), Line); + Text(V(x + w1, 102, w2, 38), wind, 12, Ink, false, TextAnchor.MiddleCenter); + } + + // ---------------------------------------------------------------- Hinweisband + void DrawBanner(BannerState s) + { + var r = V(24, 164, RefW - 48, 58); + Box(r, s.tone.bg, 12, Color.Lerp(s.tone.bg, s.tone.fg, 0.18f)); + Box(V(40, 175, 36, 36), Color.Lerp(s.tone.bg, Color.white, 0.55f), 9, Color.Lerp(s.tone.bg, s.tone.fg, 0.25f)); + Text(V(40, 175, 36, 36), s.icon, 16, s.tone.fg, true, TextAnchor.MiddleCenter); + Text(V(90, 174, 900, 20), s.title, 14, Ink, true); + Text(V(90, 194, 900, 18), s.text, 11.5f, Muted); + + string prio = $"Priorität {s.priority}: {s.priorityText ?? PriorityNames[s.priority]}"; + float w = TextWidth(prio, 11.5f, true) + 26f; + var chip = V(RefW - 40 - w, 178, w, 30); + Box(chip, Surface, 8, Color.Lerp(s.tone.bg, s.tone.fg, 0.2f)); + Text(chip, prio, 11.5f, s.tone.fg, true, TextAnchor.MiddleCenter); + } + + // ---------------------------------------------------------------- Raumstatus mit 3D-Ansicht + void DrawRoomCard() + { + var card = V(24, 236, 976, 312); + Card(card); + Text(V(42, 252, 400, 20), "Raumstatus", 15, Ink, true); + Text(V(42, 272, 400, 16), "Live-Ansicht der automatischen Steuerung", 11, Muted); + + string right; + var c = C; + if (bridge != null && !bridge.UseArduinoData) + right = "Simulation mit Beispielwerten · " + (bridge.ArduinoConnected ? "Arduino verbunden (nicht übernommen)" : "Arduino nicht verbunden"); + else if (env.AnyMeasured) + { + right = (c != null ? $"Prüfung in {c.pruefung.restSekunden / 60}:{c.pruefung.restSekunden % 60:00} · " : "") + $"Arduino live · vor {Mathf.Max(0f, Time.unscaledTime - bridge.LastPacketTime):0} s"; + if (env.IsMeasured("rh")) right += $" · Feuchte {N(env.indoorHumidity, 0)} %"; + if (env.IsMeasured("tvoc")) right += $" · TVOC {N(env.tvoc, 0)} ppb"; + if (env.IsMeasured("lightpct")) right += $" · Licht {N(env.lightPercent, 0)} %"; + } + else if (c != null && c.szenario != "live") right = "Zentrales Backend · Demo-Werte"; + else right = (bridge != null ? bridge.ArduinoDetail : "Simulation") + " – Simulation füllt die Lücken"; + float rw = TextWidth(right, 11, false); + Box(V(984 - rw - 14, 262.5f, 7, 7), env.AnyMeasured ? Green2 : Mint, 3.5f); + Text(V(984 - rw, 254, rw, 24), right, 11, Muted); + + // 3D-Ansicht + vpRect = V(38, 296, 948, 238); + UpdateRenderTexture(); + if (rt != null && Event.current.type == EventType.Repaint) GUI.DrawTexture(vpRect, rt, ScaleMode.StretchToFill, false); + Hole(vpRect, Surface, 10); + + // Overlays unten: Aktorzustände + float x = 50f, y = 498f; + x += Chip(x, y, $"Fenster: {devices.WindowLabel}", Ink, Surface) + 8; + if (devices.HeatingLevel > 0.02f) x += Chip(x, y, $"Heizung {devices.HeatingLevel * 100f:0} %", Amber, Surface) + 8; + if (devices.VentLevel > 0.02f) x += Chip(x, y, $"Lüftung {devices.VentLevel * 100f:0} %", Blue, Surface) + 8; + if (devices.LightLevel > 0.02f) x += Chip(x, y, $"Licht {devices.LightLevel * 100f:0} %", Ink, Surface) + 8; + bool noiseVeto = c != null ? c.vetos.laerm : env.outdoorNoise > controller.limits.noiseLimit; + if (noiseVeto) x += Chip(x, y, "Lärmschutz: Fenster gesperrt", Red, Surface) + 8; + bool manualBlinds = c != null ? c.manuell.jalousie >= 0 : controller.BlindOverrideActive; + string blinds = $"Jalousien: {devices.BlindPosition * 100f:0} %" + (manualBlinds ? " · manuell" : ""); + float bw = TextWidth(blinds, 11, true) + 22f; + Chip(974 - bw, y, blinds, Ink, Surface); + + // Ansicht zurücksetzen + var reset = V(974 - 104, 308, 104, 24); + if (Hover(reset)) Box(reset, Surface, 7, Line); else Box(reset, new Color(1, 1, 1, 0.82f), 7, Line); + Text(reset, "Frontansicht", 10.5f, Ink, true, TextAnchor.MiddleCenter); + if (Click(reset)) FrontView(false); + } + + void UpdateRenderTexture() + { + if (roomCamera == null || Event.current.type != EventType.Repaint) return; + int w = Mathf.Max(16, Mathf.RoundToInt(vpRect.width)), h = Mathf.Max(16, Mathf.RoundToInt(vpRect.height)); + if (rt != null && rt.width == w && rt.height == h) return; + if (rt != null) { roomCamera.targetTexture = null; rt.Release(); Destroy(rt); } + rt = new RenderTexture(w, h, 24) { antiAliasing = 4, name = "Raumansicht" }; + roomCamera.targetTexture = rt; + } + + // ---------------------------------------------------------------- Messwert-Kacheln + void DrawMetrics() + { + var L = controller.limits; + float w = (976f - 36f) / 4f, y = 560f; + float co2 = env.co2, t = env.indoorTemp, noise = env.outdoorNoise, kmh = env.windSpeed * 3.6f; + + Metric(24, y, w, "CO₂", "Luftqualität", env.IsMeasured("co2"), N(co2, 0), "ppm", co2 / (L.co2Limit * 1.6f), + co2 < 800f ? ("Gut", ToneGreen) : co2 <= L.co2Limit ? ("Mäßig", ToneAmber) : ("Zu hoch", ToneRed), + $"Grenzwert {N(L.co2Limit, 0)} ppm · fest"); + Metric(24 + (w + 12), y, w, "°C", "Temperatur", env.IsMeasured("t"), N(t, 1), "°C", Mathf.InverseLerp(14f, 32f, t), + t > L.tempHigh ? ("Zu warm", ToneAmber) : t < L.tempLow ? ("Zu kalt", ToneBlue) : ("Im Ziel", ToneGreen), + $"Zielbereich {N(L.tempLow, 0)}–{N(L.tempHigh, 0)} °C · Ziel {N(Target, 1)} °C"); + if (!bridge.MicrophoneOutdoor && env.IsMeasured("noise")) + { + // Mikrofon steht im Raum: Lärm im Raum zeigen, Außenlärm bleibt simuliert + float inside = env.indoorNoise; + Metric(24 + 2 * (w + 12), y, w, "dB", "Lärm im Raum", true, N(inside, 0), "dB", Mathf.InverseLerp(30f, 95f, inside), + inside <= 50f ? ("Ruhig", ToneGreen) : inside <= 65f ? ("Mäßig", ToneAmber) : ("Laut", ToneRed), + $"Außen {N(noise, 0)} dB (Simulation)"); + } + else + Metric(24 + 2 * (w + 12), y, w, "dB", "Außenlärm", env.IsMeasured("nout"), N(noise, 0), "dB", Mathf.InverseLerp(30f, 95f, noise), + noise <= 55f ? ("Ruhig", ToneGreen) : noise <= NoiseLimit ? ("Mäßig", ToneAmber) : ("Außen laut", ToneRed), + noise > NoiseLimit ? "Lärmschutz: Fenster gesperrt" : "Ab 70 dB Fenster gesperrt"); + float windLimitKmh = C != null ? C.grenzwerte.windKmh : L.windLimit * 3.6f; + Metric(24 + 3 * (w + 12), y, w, "≋", "Wind", env.IsMeasured("wind"), N(kmh, 0), "km/h", Mathf.InverseLerp(0f, 80f, kmh), + kmh <= 20f ? ("Leicht", ToneGreen) : kmh <= windLimitKmh ? ("Mäßig", ToneAmber) : ("Stark", ToneRed), + $"Außenluft AQI {env.outdoorAqi:0} · {N(env.outdoorTemp, 0)} °C"); + } + + float NoiseLimit => C != null ? C.grenzwerte.laermDb : controller.limits.noiseLimit; + + void Metric(float x, float y, float w, string icon, string label, bool measured, string value, string unit, float norm, + (string text, Tone tone) status, string foot) + { + var r = V(x, y, w, 128); + Card(r); + Box(V(x + 14, y + 14, 32, 32), GreenSoft, 8); + Text(V(x + 14, y + 14, 32, 32), icon, icon.Length > 2 ? 10 : 12, Green, true, TextAnchor.MiddleCenter); + float pw = TextWidth(status.text, 10, true) + 16f; + Box(V(x + w - 14 - pw, y + 18, pw, 22), status.tone.bg, 6); + Text(V(x + w - 14 - pw, y + 18, pw, 22), status.text, 10, status.tone.fg, true, TextAnchor.MiddleCenter); + + Text(V(x + 14, y + 54, w - 28, 16), measured ? $"{label} ● Sensor" : label, 11.5f, Muted); + Text(V(x + 14, y + 70, w - 28, 30), $"{value} {unit}", 24, Ink); + var track = V(x + 14, y + 104, w - 28, 4); + Box(track, Line, 2); + Box(V(x + 14, y + 104, Mathf.Max(4f, (w - 28) * Mathf.Clamp01(norm)), 4), status.tone.fg, 2); + Text(V(x + 14, y + 110, w - 28, 14), foot, 9.5f, Muted); + } + + // ---------------------------------------------------------------- Demo-Szenarien + void DrawDemos() + { + var card = V(24, 700, 976, 150); + Card(card); + Box(V(40, 712, 30, 30), GreenSoft, 8); + Text(V(40, 712, 30, 30), "✦", 13, Green, true, TextAnchor.MiddleCenter); + Text(V(80, 710, 400, 18), "Demo-Szenarien", 13.5f, Ink, true); + Text(V(80, 728, 500, 16), "Systemreaktionen direkt simulieren – Sensorwerte lösen sie automatisch aus", 10.5f, Muted); + + var c = C; + if (c != null && c.szenarien != null && c.szenarien.Length > 0) + { + DrawCentralDemos(c); + return; + } + string active = ActiveDemo(); + string pill = "Aktiv: " + (active ?? controller.Scenario) + (env.AnyMeasured ? " · Sensor" : ""); + float pw = TextWidth(pill, 10.5f, true) + 18f; + Box(V(984 - pw, 715, pw, 24), GreenSoft, 7); + Text(V(984 - pw, 715, pw, 24), pill, 10.5f, Green, true, TextAnchor.MiddleCenter); + + float tw = (976f - 32f - 3 * 8f) / 4f; + for (int i = 0; i < demos.Count; i++) + { + var d = demos[i]; + float x = 40 + (i % 4) * (tw + 8), y = 752 + (i / 4) * 46; + var r = V(x, y, tw, 40); + bool on = d.name == active; + bool hover = Hover(r); + Box(r, on ? GreenSoft : hover ? Soft : Surface, 9, on ? Color.Lerp(Green2, Mint, 0.4f) : Line); + Box(V(x + 10, y + 13, 14, 14), on ? Green2 : Surface, 7, on ? Green2 : Hex(0xb9c4bd)); + if (on) Text(V(x + 10, y + 13, 14, 14), "✓", 9, Color.white, true, TextAnchor.MiddleCenter); + Text(V(x + 32, y + 4, tw - 38, 17), d.name, 11.5f, Ink, true); + Text(V(x + 32, y + 20, tw - 38, 15), d.sub, 9.5f, Muted); + if (Click(r)) + { + d.apply(); + controller.RunCycle(); + } + } + } + + /// Demo-Szenarien des zentralen Backends – gelten für Webinterface und Unity gleichzeitig. + void DrawCentralDemos(CentralState c) + { + string activeText = c.szenario; + foreach (var s in c.szenarien) if (s.id == c.szenario) activeText = s.text; + string pill = "Aktiv: " + activeText + (c.sensorOnline && c.szenario == "live" ? " · Sensor" : ""); + float pw = TextWidth(pill, 10.5f, true) + 18f; + Box(V(984 - pw, 715, pw, 24), GreenSoft, 7); + Text(V(984 - pw, 715, pw, 24), pill, 10.5f, Green, true, TextAnchor.MiddleCenter); + + float tw = (976f - 32f - 3 * 8f) / 4f; + for (int i = 0; i < c.szenarien.Length && i < 8; i++) + { + var d = c.szenarien[i]; + float x = 40 + (i % 4) * (tw + 8), y = 752 + (i / 4) * 46; + var r = V(x, y, tw, 40); + bool on = d.id == c.szenario; + Box(r, on ? GreenSoft : Hover(r) ? Soft : Surface, 9, on ? Color.Lerp(Green2, Mint, 0.4f) : Line); + Box(V(x + 10, y + 13, 14, 14), on ? Green2 : Surface, 7, on ? Green2 : Hex(0xb9c4bd)); + if (on) Text(V(x + 10, y + 13, 14, 14), "✓", 9, Color.white, true, TextAnchor.MiddleCenter); + Text(V(x + 32, y + 4, tw - 38, 17), d.text, 11.5f, Ink, true); + Text(V(x + 32, y + 20, tw - 38, 15), d.beschreibung, 9.5f, Muted); + // Anzeige: Szenarien werden im Webinterface gewählt + } + } + + // ---------------------------------------------------------------- Dozentensteuerung + void DrawLecturerCard(Rect card) + { + Card(card); + float x = VX(card), y = VY(card), w = card.width / k; + var c = C; + Text(V(x + 18, y + 14, w - 36, 16), c != null ? "DOZENTENSTEUERUNG · ANZEIGE, BEDIENUNG IM WEBINTERFACE" : "DOZENTENSTEUERUNG", 10, Green, true); + + bool beamer = c != null ? c.vortrag.aktiv : devices.BeamerOn; + Text(V(x + 18, y + 38, 260, 20), "Beamer-Modus", 14, Ink, true); + string beamerText = !beamer ? "Jalousien schließen, Raum abdunkeln" + : c != null ? $"Aktiv · noch {c.vortrag.restMinuten} min" + : $"Aktiv bis {Clock(beamerUntil)} · noch {Mathf.Max(0f, (float)(beamerUntil - env.simMinutes)):0} min"; + Text(V(x + 18, y + 58, 300, 16), beamerText, 11, beamer ? Green2 : Muted); + bool sw = Switch(V(x + w - 18 - 46, y + 42, 46, 26), beamer, c == null); + if (sw != beamer) SetBeamer(sw); + + Text(V(x + 18, y + 84, 200, 16), "Dauer", 11, Ink, true); + float bw = (w - 36 - 2 * 8) / 3f; + for (int i = 0; i < beamerDurations.Length && i < 3; i++) + { + var r = V(x + 18 + i * (bw + 8), y + 102, bw, 30); + bool on = c != null ? Mathf.RoundToInt(beamerDurations[i]) == c.vortrag.dauerMinuten : i == beamerDurationIndex; + Box(r, on ? GreenSoft : Surface, 8, on ? Color.Lerp(Green2, Mint, 0.4f) : Line); + Text(r, $"{beamerDurations[i]:0} Min.", 11, on ? Green : Ink, on, TextAnchor.MiddleCenter); + if (c == null && Click(r)) + { + beamerDurationIndex = i; + if (devices.BeamerOn) beamerUntil = env.simMinutes + BeamerMinutes; + } + } + + Fill(V(x + 18, y + 144, w - 36, 1), Line); + Text(V(x + 18, y + 154, 260, 16), "Jalousien manuell fahren", 11, Ink, true); + bool paused = c != null ? c.manuell.aktiv : controller.BlindOverrideActive; + string pauseText = c != null + ? (paused ? $"Manuelle Einstellungen bis {c.manuell.bis}" : "Automatik aktiv") + : paused ? $"Automatik pausiert · noch {controller.BlindOverrideMinutesLeft:0} Min." : $"Pausiert die Automatik für {manualBlindMinutes:0} Min."; + Text(V(x + 18, y + 172, 280, 16), pauseText, 10.5f, paused ? Amber : Muted); + var up = V(x + w - 18 - 66, y + 154, 30, 30); + var down = V(x + w - 18 - 30, y + 154, 30, 30); + Box(up, Hover(up) ? Soft : Surface, 8, Line); + Box(down, Hover(down) ? Soft : Surface, 8, Line); + Text(up, "↑", 13, Ink, true, TextAnchor.MiddleCenter); + Text(down, "↓", 13, Ink, true, TextAnchor.MiddleCenter); + if (c == null && Click(up)) controller.OverrideBlinds(Mathf.Round((devices.BlindTarget - 0.25f) * 4f) / 4f, manualBlindMinutes); + if (c == null && Click(down)) controller.OverrideBlinds(Mathf.Round((devices.BlindTarget + 0.25f) * 4f) / 4f, manualBlindMinutes); + + var note = V(x + 18, y + 202, w - 36, 40); + Box(note, Soft, 8, Line); + Text(V(x + 28, y + 202, 20, 40), "ⓘ", 12, Muted, false, TextAnchor.MiddleCenter); + Text(V(x + 50, y + 204, w - 80, 36), "Schutzregeln bleiben aktiv. CO₂-Grenzwert und Kontext-Sperren können nicht überschrieben werden.", 9.5f, Muted, false, TextAnchor.MiddleLeft, false, true); + } + + // ---------------------------------------------------------------- Raumstimmung (Abstimmung) + void DrawMood(Rect card, bool student) + { + Card(card); + float x = VX(card), y = VY(card), w = card.width / k; + var wishes = controller.wishes; + if (wishes.Count == 0) wishes.Add(new UserWish("Du", 22f, false)); + var own = wishes[0]; + + int cool = 0, ok = 0, warm = 0; + foreach (var wsh in wishes) + { + if (wsh.temperature < 21.5f) cool++; + else if (wsh.temperature > 22.5f) warm++; + else ok++; + } + int ownVote = own.temperature < 21.5f ? 0 : own.temperature > 22.5f ? 2 : 1; + var c = C; + int votes = wishes.Count; + string subtitle = $"{votes} Stimmen · Ø Wunsch {N(controller.AverageWish, 1)} °C"; + if (c != null) + { + // Stimmen aller Clients (Webinterface + Unity) aus dem Backend + cool = c.stimmen.kuehler; ok = c.stimmen.angenehm; warm = c.stimmen.waermer; + votes = c.stimmen.gesamt; + ownVote = centralVote; + subtitle = $"{votes} Stimmen · Zielwert {N(c.zielTemperatur, 1)} °C"; + } + + Text(V(x + 18, y + 14, 260, 20), student ? "Deine Stimme" : "Raumstimmung", 15, Ink, true); + Text(V(x + 18, y + 34, 300, 16), subtitle, 11, Muted); + Text(V(x + w - 18 - 30, y + 14, 30, 30), "☺", 16, Muted, false, TextAnchor.MiddleCenter); + Text(V(x + 18, y + 58, w - 36, 18), "Wie fühlt sich der Raum für dich an?", 12, Ink, true); + + float bh = student ? 62f : 52f, bw = (w - 36 - 2 * 8) / 3f; + string[] icons = { "↓", "—", "↑" }; + string[] labels = { "Kühler", "Angenehm", "Wärmer" }; + int[] counts = { cool, ok, warm }; + float[] temps = { 21f, 22f, 23f }; + for (int i = 0; i < 3; i++) + { + var r = V(x + 18 + i * (bw + 8), y + 80, bw, bh); + bool mine = i == ownVote; + Box(r, mine ? GreenSoft : Hover(r) ? Soft : Surface, 9, mine ? Color.Lerp(Green2, Mint, 0.4f) : Line); + Text(V(x + 18 + i * (bw + 8), y + 84, bw, 16), icons[i], 12, mine ? Green : Ink, true, TextAnchor.MiddleCenter); + Text(V(x + 18 + i * (bw + 8), y + 100, bw, 14), labels[i], 10.5f, mine ? Green : Ink, mine, TextAnchor.MiddleCenter); + Text(V(x + 18 + i * (bw + 8), y + 114, bw, 14), counts[i].ToString(), 10.5f, Muted, false, TextAnchor.MiddleCenter); + if (c == null && Click(r)) // mit Backend wird im Webinterface abgestimmt + { + own.temperature = temps[i]; + controller.RunCycle(); + } + } + + // Verteilung + float by = y + 80 + bh + 10, total = Mathf.Max(1, cool + ok + warm), tw = w - 36, bx = x + 18; + float[] parts = { cool / total, ok / total, warm / total }; + Color[] cols = { CoolVote, Green, WarmVote }; + for (int i = 0; i < 3; i++) + { + float pw = tw * parts[i]; + if (pw > 0.5f) Box(V(bx, by, Mathf.Max(6f, pw - 3f), 6), cols[i], 3); + bx += pw; + } + Text(V(x + 18, by + 10, tw, 14), $"kühler · {cool}", 9.5f, Muted); + Text(V(x + 18, by + 10, tw, 14), $"angenehm · {ok}", 9.5f, Muted, false, TextAnchor.MiddleCenter); + Text(V(x + 18, by + 10, tw, 14), $"wärmer · {warm}", 9.5f, Muted, false, TextAnchor.MiddleRight); + + float ny = by + 30; + if (c != null) + Text(V(x + 18, ny, w - 36, 16), "ⓘ Zählt zusammen mit den Stimmen aus dem Webinterface, jede Stimme gleich.", 10, Muted); + else if (student) + { + Text(V(x + 18, ny, 260, 22), "Frische Luft (Fenster öffnen)", 11.5f, Ink, true); + bool wantWindow = Switch(V(x + w - 18 - 46, ny - 2, 46, 26), own.windowOpen); + if (wantWindow != own.windowOpen) + { + own.windowOpen = wantWindow; + controller.RunCycle(); + } + ny += 28; + Text(V(x + 18, ny, w - 36, 16), $"Fenster: {controller.WindowVotes} von {wishes.Count} dafür · Anonym, zählt wie jede andere Stimme.", 9.5f, Muted); + } + else Text(V(x + 18, ny, w - 36, 16), "ⓘ Die Stimme des Dozenten zählt wie jede andere.", 10, Muted); + } + + // ---------------------------------------------------------------- Prioritäten (Studierendenansicht) + void DrawPriorities(Rect card, int current) + { + Card(card); + float x = VX(card), y = VY(card), w = card.width / k; + Text(V(x + 18, y + 14, 300, 16), "SO ENTSCHEIDET DAS SYSTEM", 10, Green, true); + string[] subs = + { + $"CO₂-Grenzwert {N(controller.limits.co2Limit, 0)} ppm – kann nicht überstimmt werden", + "Lärm, Wind und Außenluft sperren ggf. das Fenster", + "Ø aller Temperaturwünsche wird zum Zielwert", + "Fenster offen → Heizung aus, Licht nach Tageslicht", + }; + for (int i = 0; i < 4; i++) + { + float ry = y + 38 + i * 44; + bool on = i + 1 == current; + var r = V(x + 12, ry, w - 24, 40); + if (on) Box(r, GreenSoft, 9, Color.Lerp(Green2, Mint, 0.4f)); + Box(V(x + 22, ry + 9, 22, 22), on ? Green : Soft, 11, on ? Green : Line); + Text(V(x + 22, ry + 9, 22, 22), (i + 1).ToString(), 10.5f, on ? Color.white : Muted, true, TextAnchor.MiddleCenter); + Text(V(x + 54, ry + 4, w - 80, 17), PriorityNames[i + 1] + (on ? " · gerade maßgeblich" : ""), 11.5f, Ink, true); + Text(V(x + 54, ry + 20, w - 80, 15), subs[i], 9.5f, Muted); + } + } + + // ---------------------------------------------------------------- Verlauf + void DrawHistory(Rect card) + { + Card(card); + float x = VX(card), y = VY(card), w = card.width / k; + Text(V(x + 18, y + 12, 260, 20), "Verlauf", 15, Ink, true); + Text(V(x + 18, y + 32, 300, 14), "Entscheidungen des Systems", 10.5f, Muted); + + var c = C; + var list = history; + if (c != null && c.verlauf != null) + { + list = new List(); + foreach (var v in c.verlauf) + list.Add(new Entry { time = v.uhrzeit, title = v.titel, text = v.grund, dot = ToneOf(v.ton).fg == Green ? Green2 : ToneOf(v.ton).fg }); + } + int n = Mathf.Min(3, list.Count); + for (int i = 0; i < n; i++) + { + var h = list[i]; + float ry = y + 52 + i * 28; + if (i < n - 1) Fill(V(x + 21.5f, ry + 10, 1, 26), Line); + Box(V(x + 18, ry + 3, 8, 8), h.dot, 4); + Text(V(x + 34, ry - 2, w - 110, 16), h.title, 11, Ink, true); + Text(V(x + w - 18 - 60, ry - 2, 60, 16), h.time, 9.5f, Muted, false, TextAnchor.MiddleRight); + Text(V(x + 34, ry + 12, w - 52, 14), h.text, 9.5f, Muted); + } + if (n == 0) Text(V(x + 18, y + 56, w - 36, 16), "Noch keine Entscheidungen.", 10.5f, Muted); + } + + // ---------------------------------------------------------------- Fußzeile + void DrawFooter() + { + Text(V(24, 860, 700, 20), "ⓘ Automatische Steuerung nach Gesundheit, Kontext, Mehrheit und Energie", 10.5f, Muted); + string src = bridge == null ? "Simulation" + : !bridge.UseArduinoData ? "Werte: Simulation (Beispielwerte)" + : C != null ? $"Steuerung: zentrales Backend {bridge.backendUrl}" + (C.sensorOnline ? " · Arduino live" : "") + : bridge.mode == LinkMode.Backend ? (env.AnyMeasured ? $"Sensorquelle: Arduino über {bridge.backendUrl}" : $"Sensorquelle: {bridge.backendUrl} (keine Werte)") + : bridge.mode == LinkMode.Simulation ? "Sensorquelle: Simulation" : $"Sensorquelle: {bridge.mode}"; + Text(V(RefW - 24 - 700, 860, 700, 20), $"{src} · Simulationszeit {env.ClockText}", 10.5f, Muted, false, TextAnchor.MiddleRight); + } + + // ---------------------------------------------------------------- Einstellungen (Klick auf Status oben rechts) + float SettingsHeight() + { + bool link = bridge != null && bridge.mode != LinkMode.Simulation; + bool backend = bridge != null && bridge.mode == LinkMode.Backend; + return 46 + 54 + (link ? 52 + 74 : 0) + (backend ? 34 : 0) + 14 + 34 + 34 + 20 + 34 + 16; + } + + void DrawSettings() + { + drawingPopover = true; + float x = VX(popRect), y = VY(popRect), w = popRect.width / k; + Shadow(popRect, 14); + Box(popRect, Surface, 14, Line); + Text(V(x + 18, y + 14, 300, 20), "Einstellungen", 14, Ink, true); + y += 46; + + // Sensorquelle + Text(V(x + 18, y, 300, 16), "Sensorquelle", 10.5f, Muted); + LinkMode[] modes = { LinkMode.Simulation, LinkMode.Backend, LinkMode.Udp, LinkMode.Serial }; + string[] names = { "Simulation", "Backend", "UDP", "Seriell" }; + float sw = (w - 36) / 4f; + Box(V(x + 18, y + 18, w - 36, 30), Soft, 8, Line); + for (int i = 0; i < 4; i++) + { + var r = V(x + 18 + i * sw + 2, y + 20, sw - 4, 26); + bool on = bridge.mode == modes[i]; + if (on) Box(r, Surface, 6, Line); + Text(r, names[i], 10.5f, on ? Ink : Muted, on, TextAnchor.MiddleCenter); + if (Click(r) && !on) + { + bridge.Disconnect(); + bridge.mode = modes[i]; + bridge.Disconnect(); // Statustext aktualisieren + fieldMode = (LinkMode)(-1); + } + } + y += 54; + + if (bridge.mode != LinkMode.Simulation) + { + string label = bridge.mode == LinkMode.Backend ? "Adresse von backend/server.py" + : bridge.mode == LinkMode.Udp ? "UDP-Empfangsport" : "Serieller Port"; + Text(V(x + 18, y, w - 36, 16), label, 10.5f, Muted); + if (fieldMode != bridge.mode) + { + fieldMode = bridge.mode; + fieldText = bridge.mode == LinkMode.Backend ? bridge.backendUrl + : bridge.mode == LinkMode.Udp ? bridge.udpListenPort.ToString() : bridge.serialPort; + } + var fr = V(x + 18, y + 18, w - 36, 30); + Box(fr, Surface, 8, Line); + fieldText = GUI.TextField(fr, fieldText ?? "", fieldStyle); + if (bridge.mode == LinkMode.Backend) bridge.backendUrl = fieldText.Trim(); + else if (bridge.mode == LinkMode.Udp && int.TryParse(fieldText, out var port)) bridge.udpListenPort = port; + else if (bridge.mode == LinkMode.Serial) bridge.serialPort = fieldText.Trim(); + y += 52; + + var btn = V(x + 18, y, 110, 30); + Box(btn, bridge.Connected ? Surface : Green, 8, bridge.Connected ? Line : Green); + Text(btn, bridge.Connected ? "Trennen" : "Verbinden", 11, bridge.Connected ? Ink : Color.white, true, TextAnchor.MiddleCenter); + if (Click(btn)) { if (bridge.Connected) bridge.Disconnect(); else bridge.Connect(); } + string packets = bridge.LastPacketTime >= 0f ? $"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s" : ""; + Text(V(x + 138, y, w - 156, 30), packets, 10, Muted); + Text(V(x + 18, y + 34, w - 36, 36), bridge.Status, 9.5f, Muted, false, TextAnchor.UpperLeft, false, true); + y += 74; + } + + if (bridge.mode == LinkMode.Backend) + { + Text(V(x + 18, y, 260, 26), "Mikrofon steht draußen", 11.5f, Ink); + bridge.MicrophoneOutdoor = Switch(V(x + w - 18 - 46, y, 46, 26), bridge.MicrophoneOutdoor); + y += 34; + } + + Fill(V(x + 18, y + 4, w - 36, 1), Line); + y += 14; + if (weather != null) + { + Text(V(x + 18, y, 260, 26), "Live-Wetter (Open-Meteo)", 11.5f, Ink); + bool live = Switch(V(x + w - 18 - 46, y, 46, 26), weather.useLiveWeather); + if (live != weather.useLiveWeather) weather.SetLive(live); + } + y += 34; + Text(V(x + 18, y, 260, 26), "Vorlesung läuft", 11.5f, Ink); + env.lectureRunning = Switch(V(x + w - 18 - 46, y, 46, 26), env.lectureRunning); + y += 34; + + Text(V(x + 18, y, 300, 16), "Zeitraffer (simulierte Minuten pro Sekunde)", 10.5f, Muted); + float[] speeds = { 0f, 1f, 5f, 20f }; + string[] speedNames = { "Pause", "1×", "5×", "20×" }; + Box(V(x + 18, y + 18, w - 36, 30), Soft, 8, Line); + for (int i = 0; i < 4; i++) + { + var r = V(x + 18 + i * sw + 2, y + 20, sw - 4, 26); + bool on = Mathf.Approximately(env.timeScale, speeds[i]); + if (on) Box(r, Surface, 6, Line); + Text(r, speedNames[i], 10.5f, on ? Ink : Muted, on, TextAnchor.MiddleCenter); + if (Click(r)) env.timeScale = speeds[i]; + } + drawingPopover = false; + } + + // ================================================================ Bausteine + Rect V(float x, float y, float w, float h) => new Rect(origin.x + x * k, origin.y + y * k, w * k, h * k); + float VX(Rect r) => (r.x - origin.x) / k; + float VY(Rect r) => (r.y - origin.y) / k; + int F(float size) => Mathf.Max(7, Mathf.RoundToInt(size * k)); + + bool Hover(Rect r) => r.Contains(Event.current.mousePosition) && !(settingsOpen && !drawingPopover && popRect.Contains(Event.current.mousePosition)); + + /// Unsichtbarer Knopf; unter dem offenen Einstellungsfenster gibt es keine Klicks. + bool Click(Rect r) + { + if (settingsOpen && !drawingPopover && popRect.Contains(Event.current.mousePosition)) return false; + return GUI.Button(r, GUIContent.none, GUIStyle.none); + } + + void Card(Rect r) + { + Shadow(r, 14); + Box(r, Surface, 14, Line); + } + + void Shadow(Rect r, float radius) + { + if (Event.current.type != EventType.Repaint) return; + for (int i = 1; i <= 3; i++) + { + float g = i * 2f * k; + var s = new Rect(r.x - g, r.y - g + 4f * k, r.width + 2 * g, r.height + 2 * g); + Box(s, new Color(0.118f, 0.2f, 0.16f, 0.022f), radius + i * 2f); + } + } + + void Fill(Rect r, Color c) + { + if (Event.current.type != EventType.Repaint) return; + var old = GUI.color; + GUI.color = c; + GUI.DrawTexture(r, Texture2D.whiteTexture); + GUI.color = old; + } + + /// Abgerundetes Rechteck (Radius in virtuellen Einheiten), optional mit 1-px-Rahmen. + void Box(Rect r, Color fill, float radius, Color? border = null) + { + if (Event.current.type != EventType.Repaint) return; + var old = GUI.color; + if (border.HasValue) + { + GUI.color = border.Value; + RoundStyle(radius).Draw(r, false, false, false, false); + float px = Mathf.Max(1f, Mathf.Round(k)); + r = new Rect(r.x + px, r.y + px, r.width - 2 * px, r.height - 2 * px); + radius = Mathf.Max(0f, radius - px / k); + } + GUI.color = fill; + RoundStyle(radius).Draw(r, false, false, false, false); + GUI.color = old; + } + + /// Rundet die Ecken der 3D-Ansicht ab (Ecken in Kartenfarbe übermalen). + void Hole(Rect r, Color c, float radius) + { + if (Event.current.type != EventType.Repaint) return; + int rp = Mathf.Max(2, Mathf.RoundToInt(radius * k)); + if (!holeStyles.TryGetValue(rp, out var st)) + { + var tex = RoundedTex(rp, true); + st = new GUIStyle { normal = { background = tex }, border = new RectOffset(rp + 1, rp + 1, rp + 1, rp + 1) }; + holeStyles[rp] = st; + } + var old = GUI.color; + GUI.color = c; + st.Draw(r, false, false, false, false); + GUI.color = old; + } + + GUIStyle RoundStyle(float radius) + { + int rp = Mathf.Max(1, Mathf.RoundToInt(radius * k)); + if (!roundStyles.TryGetValue(rp, out var st)) + { + var tex = RoundedTex(rp, false); + st = new GUIStyle { normal = { background = tex }, border = new RectOffset(rp + 1, rp + 1, rp + 1, rp + 1) }; + roundStyles[rp] = st; + } + return st; + } + + Texture2D RoundedTex(int r, bool hole) + { + int n = 2 * r + 4; + var t = new Texture2D(n, n, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, hideFlags = HideFlags.HideAndDontSave }; + var px = new Color[n * n]; + for (int y = 0; y < n; y++) + for (int x = 0; x < n; x++) + { + var p = new Vector2(x + 0.5f, y + 0.5f); + var q = new Vector2(Mathf.Clamp(p.x, r, n - r), Mathf.Clamp(p.y, r, n - r)); + float a = Mathf.Clamp01(r - Vector2.Distance(p, q) + 0.5f); + px[y * n + x] = new Color(1f, 1f, 1f, hole ? 1f - a : a); + } + t.SetPixels(px); + t.Apply(); + textures.Add(t); + return t; + } + + bool Switch(Rect r, bool on, bool interactive = true) + { + if (interactive && Click(r)) on = !on; + Box(r, on ? Green2 : Line, r.height / 2f / k); + float kn = r.height - 6f * k; + var knob = new Rect(on ? r.xMax - kn - 3f * k : r.x + 3f * k, r.y + 3f * k, kn, kn); + Box(knob, Surface, kn / 2f / k); + return on; + } + + float Chip(float x, float y, string text, Color fg, Color bg) + { + float w = TextWidth(text, 11, true) + 22f; + var r = V(x, y, w, 26); + Box(r, new Color(bg.r, bg.g, bg.b, 0.94f), 8, Line); + Text(r, text, 11, fg, true, TextAnchor.MiddleCenter); + return w; + } + + void Text(Rect r, string s, float size, Color c, bool bold = false, TextAnchor anchor = TextAnchor.MiddleLeft, bool useSerif = false, bool wrap = false) + => GUI.Label(r, s, TextStyle(size, c, bold, anchor, useSerif, wrap)); + + float TextWidth(string s, float size, bool bold) => TextStyle(size, Ink, bold, TextAnchor.MiddleLeft, false, false).CalcSize(new GUIContent(s)).x / k; + + GUIStyle TextStyle(float size, Color c, bool bold, TextAnchor anchor, bool useSerif, bool wrap) + { + string key = $"{size}|{ColorUtility.ToHtmlStringRGBA(c)}|{bold}|{anchor}|{useSerif}|{wrap}"; + if (textStyles.TryGetValue(key, out var st)) return st; + st = new GUIStyle + { + font = useSerif ? serif : sans, + fontSize = F(size), + fontStyle = bold ? FontStyle.Bold : FontStyle.Normal, + alignment = anchor, + wordWrap = wrap, + richText = true, + clipping = TextClipping.Overflow, + normal = { textColor = c }, + }; + textStyles[key] = st; + return st; + } + + /// Erste installierte Schrift aus der Liste (null = Unity-Standardschrift). + /// Nur einen vorhandenen Namen übergeben – mit fehlenden Namen rendert IMGUI in Unity 6 falsche Texte. + static Font OsFont(int size, params string[] names) + { + var installed = new HashSet(Font.GetOSInstalledFontNames()); + foreach (var n in names) + if (installed.Contains(n)) return Font.CreateDynamicFontFromOSFont(n, size); + return null; + } + + void EnsureStyles() + { + k = Mathf.Min(Screen.width / RefW, Screen.height / RefH); + origin = new Vector2(Mathf.Round((Screen.width - RefW * k) / 2f), Mathf.Round((Screen.height - RefH * k) / 2f)); + if (Mathf.Approximately(stylesFor, k) && sans != null) return; + stylesFor = k; + textStyles.Clear(); + roundStyles.Clear(); + holeStyles.Clear(); + foreach (var t in textures) if (t != null) Destroy(t); + textures.Clear(); + + // Systemschriften wie im Frontend (Sans + Serifen-Überschrift) + if (sans == null) sans = OsFont(14, "Inter", "Helvetica Neue", "Helvetica", "Segoe UI", "Arial"); + if (serif == null) serif = OsFont(32, "Georgia", "Charter", "Times New Roman", "Times"); + + fieldStyle = new GUIStyle + { + font = sans, + fontSize = F(11.5f), + alignment = TextAnchor.MiddleLeft, + padding = new RectOffset(F(10), F(10), 0, 0), + clipping = TextClipping.Clip, + normal = { textColor = Ink }, + focused = { textColor = Ink }, + hover = { textColor = Ink }, + }; + } + } +} diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/OrbitCamera.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/OrbitCamera.cs index 2daa64f..949df1c 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/OrbitCamera.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/OrbitCamera.cs @@ -22,6 +22,9 @@ namespace SmartRoom public bool IsDragging => dragging; + /// Optional: rechnet eine GUI-Position in einen Strahl um (wenn die Kamera in eine Textur rendert). + public System.Func rayProvider; + struct View { public Vector3 target; public float yaw, pitch, distance; @@ -49,6 +52,13 @@ namespace SmartRoom goalTarget = v.target; goalYaw = v.yaw; goalPitch = v.pitch; goalDistance = v.distance; } + /// Beliebige Ansicht anfahren (snap = sofort statt weich). + public void SetView(Vector3 viewTarget, float viewYaw, float viewPitch, float viewDistance, bool snap = false) + { + goalTarget = viewTarget; goalYaw = viewYaw; goalPitch = viewPitch; goalDistance = viewDistance; + if (snap) { target = viewTarget; yaw = viewYaw; pitch = viewPitch; distance = viewDistance; } + } + public void HandleEvent(Event e) { switch (e.type) @@ -89,7 +99,7 @@ namespace SmartRoom void Click(Vector2 guiPos) { - var ray = cam.ScreenPointToRay(new Vector3(guiPos.x, Screen.height - guiPos.y, 0f)); + var ray = rayProvider != null ? rayProvider(guiPos) : cam.ScreenPointToRay(new Vector3(guiPos.x, Screen.height - guiPos.y, 0f)); if (Physics.Raycast(ray, out var hit, 50f)) { var door = hit.collider.GetComponentInParent(); diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs index 18bfc73..328a007 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs @@ -8,8 +8,6 @@ namespace SmartRoom /// Schlichtes, dunkles Dashboard (IMGUI, keine Zusatzpakete nötig): /// links Raumklima + Außenwerte + Szenarien, rechts Steuerung / Nutzerwünsche / Verbindung, /// unten der zuletzt durchlaufene Pfad der Entscheidungslogik. - /// Ist das gemeinsame Backend verbunden, zeigt das HUD dessen Zustand und schickt Eingaben dorthin - /// (dieselben Endpunkte wie das Webinterface) – Website und Zwilling zeigen dann immer dasselbe. /// public class SmartRoomHUD : MonoBehaviour { @@ -17,7 +15,6 @@ namespace SmartRoom public RoomDevices devices; public ClimateController controller; public ArduinoBridge bridge; - public BackendLink backend; public WeatherService weather; public OrbitCamera orbit; public bool visible = true; @@ -37,30 +34,12 @@ namespace SmartRoom bool showBottom, logCollapsed; Vector2 leftScroll, rightScroll, logScroll; int tab; - string latField, lonField, udpField, urlField; + string latField, lonField, udpField, backendField; string[] foundPorts; static readonly string[] Tabs = { "Steuerung", "Wünsche", "Verbindung" }; static readonly string[] SpeedLabels = { "Pause", "1×", "5×", "20×" }; static readonly float[] Speeds = { 0f, 1f, 5f, 20f }; - static readonly string[] TempVotes = { "kuehler", "angenehm", "waermer" }; - static readonly string[] TempVoteLabels = { "Kühler", "Angenehm", "Wärmer" }; - static readonly string[] LightVotes = { "dunkler", "passt", "heller" }; - static readonly string[] LightVoteLabels = { "Dunkler", "Passt", "Heller" }; - static readonly int[] LectureMinutes = { 30, 60, 90 }; - static readonly string[] WindowVotes = { "auf", "zu" }; - static readonly string[] WindowVoteLabels = { "Auf", "Zu lassen" }; - // Manuelle Einstellungen: Index 0 = Automatik, Werte als JSON für /api/manuell - static readonly string[] ManualWindowCodes = { "", "closed", "tilted", "open" }; - static readonly string[] ManualWindowLabels = { "Auto", "Zu", "Kipp", "Auf" }; - static readonly int[] ManualPercent = { -1, 0, 50, 100 }; - static readonly string[] ManualBlindLabels = { "Auto", "Oben", "Halb", "Unten" }; - static readonly string[] ManualLightLabels = { "Auto", "Aus", "50 %", "100 %" }; - static readonly string[] ManualVentLabels = { "Auto", "Aus", "An" }; - - /// Backend verbunden: Es entscheidet, das HUD zeigt nur an und leitet Eingaben weiter. - bool Shared => backend != null && backend.Connected && backend.State != null; - BackendState B => backend.State; float S(float v) => v * scale; int I(float v) => Mathf.RoundToInt(v * scale); @@ -115,9 +94,8 @@ namespace SmartRoom case KeyCode.Alpha3: orbit?.Preset(2); break; case KeyCode.Alpha4: orbit?.Preset(3); break; case KeyCode.T: devices.door?.Toggle(); break; - case KeyCode.B: - if (Shared) backend.SetLecture(!B.vortrag.aktiv); // Beamer folgt dem Vortragsmodus des Backends - else if (devices.projector != null) devices.projector.beamerOn = !devices.projector.beamerOn; + case KeyCode.B: // mit Backend steuert das Webinterface den Beamer + if (devices.projector != null && (bridge == null || !bridge.CentralActive)) devices.projector.beamerOn = !devices.projector.beamerOn; break; case KeyCode.Space: controller.RunCycle(); break; default: return; @@ -139,11 +117,25 @@ namespace SmartRoom void DrawLeft() { GUILayout.Label("Smart Lecture Room", title); - string src = Shared ? "gemeinsames Backend" - : bridge.mode == LinkMode.Backend ? "Backend getrennt, lokale Logik" - : env.AnyMeasured ? "Arduino live" : "Simulation"; + string src = bridge != null && !bridge.UseArduinoData ? "Simulation" : env.AnyMeasured ? "Arduino live" : bridge != null && bridge.Connected ? "warte auf Arduino" : "Simulation"; GUILayout.Label($"Digitaler Zwilling · {env.ClockText} · {src}", dim); + // Arduino-Status und Umschalter Arduino-Werte ↔ Simulation (Beispielwerte) + if (bridge != null) + { + bool arduino = bridge.ArduinoConnected; + GUILayout.Space(S(6)); + GUILayout.BeginVertical(card); + GUILayout.BeginHorizontal(); + Tag(arduino ? "ARDUINO VERBUNDEN" : "ARDUINO NICHT VERBUNDEN", arduino ? Good : Bad); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.Label(bridge.ArduinoDetail, dim); + int src2 = GUILayout.Toolbar(bridge.UseArduinoData ? 0 : 1, new[] { "Arduino-Werte", "Simulation" }, seg); + if (src2 != (bridge.UseArduinoData ? 0 : 1)) bridge.UseArduinoData = src2 == 0; + GUILayout.EndVertical(); + } + GUILayout.Space(S(8)); GUILayout.BeginHorizontal(); GUILayout.Label("Vorlesung läuft", label); @@ -164,30 +156,44 @@ namespace SmartRoom env.IsMeasured("t")); Metric("CO2", $"{co2:0} ppm", Mathf.InverseLerp(400f, 2000f, co2), co2 < 800f ? Good : co2 <= controller.limits.co2Limit ? Warn : Bad, env.IsMeasured("co2")); - Metric("Helligkeit", $"{env.indoorLux:0} lx", Mathf.InverseLerp(0f, 1200f, env.indoorLux), Accent, env.IsMeasured("lux")); - Metric("Lärm", $"{env.indoorNoise:0} dB", Mathf.InverseLerp(30f, 90f, env.indoorNoise), + Metric("Helligkeit", env.IsMeasured("lightpct") ? $"{env.lightPercent:0} % (≈ {env.indoorLux:0} lx)" : $"{env.indoorLux:0} lx", + Mathf.InverseLerp(0f, 1200f, env.indoorLux), Accent, env.IsMeasured("lux")); + Metric("Lärm im Raum", $"{env.indoorNoise:0} dB", Mathf.InverseLerp(30f, 90f, env.indoorNoise), env.indoorNoise < 55f ? Good : env.indoorNoise < 70f ? Warn : Bad, env.IsMeasured("noise")); + // Luftfeuchte und TVOC werden nicht simuliert – nur anzeigen, wenn der Arduino sie liefert + if (env.IsMeasured("rh")) + Metric("Luftfeuchte", $"{env.indoorHumidity:0} %", env.indoorHumidity / 100f, + env.indoorHumidity >= 30f && env.indoorHumidity <= 60f ? Good : Warn, true); + if (env.IsMeasured("tvoc")) + Metric("TVOC", $"{env.tvoc:0} ppb", Mathf.InverseLerp(0f, 1000f, env.tvoc), + env.tvoc < 220f ? Good : env.tvoc < 660f ? Warn : Bad, true); env.occupants = Mathf.RoundToInt(SliderRow("Personen im Raum", env.occupants, 0f, 120f, "{0:0}", !env.IsMeasured("persons"))); - if (!env.IsMeasured("t")) + if (!env.IsProvided("t")) env.indoorTemp = SliderRow("Temperatur innen setzen", env.indoorTemp, 10f, 35f, "{0:0.0} °C"); - if (!env.IsMeasured("co2")) + if (!env.IsProvided("co2")) env.co2 = SliderRow("CO2 innen setzen", env.co2, 400f, 2500f, "{0:0} ppm"); Section(weather != null && weather.useLiveWeather ? "AUSSEN · OPEN-METEO" : "AUSSEN"); // Werte vom Backend/Arduino lassen sich nicht verschieben (würden sofort wieder überschrieben) - env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C", !env.IsMeasured("tout")); - env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}", !env.IsMeasured("aq")); - env.outdoorNoise = SliderRow("Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsMeasured("nout")); - env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s", !env.IsMeasured("wind")); - env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²", !env.IsMeasured("sun")); + env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C", !env.IsProvided("tout")); + env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}", !env.IsProvided("aq")); + env.outdoorNoise = SliderRow(env.IsMeasured("nout") ? "Lärm (Mikrofon draußen)" : "Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsProvided("nout")); + env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s", !env.IsProvided("wind")); + env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²", !env.IsProvided("sun")); Section("SZENARIEN"); - if (Shared) + if (bridge != null && bridge.CentralActive) { - DrawBackendScenarios(); + DrawCentralScenarios(bridge.Central); return; } + GUILayout.BeginHorizontal(); + GUILayout.Label("Erkannt", label); + GUILayout.FlexibleSpace(); + Tag(controller.Scenario, controller.Scenario == ClimateController.NormalScenario ? Good : Warn); + Tag(env.AnyMeasured ? "AUS SENSORDATEN" : "AUS SIMULATION", env.AnyMeasured ? Good : TextDim); + GUILayout.EndHorizontal(); ScenarioRow("Hitze 30 °C", () => { env.indoorTemp = 30f; env.outdoorTemp = 24f; env.solar = 750f; env.windSpeed = 2f; env.outdoorNoise = 55f; env.outdoorAqi = 25f; }, "Stickig + kalt", () => { env.co2 = 1600f; env.outdoorTemp = -2f; env.solar = 150f; }); ScenarioRow("Schlechte Außenluft", () => { env.co2 = 1450f; env.outdoorAqi = 85f; env.outdoorTemp = 15f; }, @@ -200,38 +206,48 @@ namespace SmartRoom env.indoorTemp = 22f; env.co2 = 650f; env.outdoorTemp = 14f; env.outdoorAqi = 25f; env.outdoorNoise = 55f; env.windSpeed = 3f; env.solar = 350f; }); - GUILayout.Label("Szenarien setzen Werte und lösen sofort einen Prüfzyklus aus. Mit Arduino werden gemessene Innenwerte überschrieben.", dim); + GUILayout.Label("Das passende Szenario wird aus den Werten erkannt (hervorgehoben) und löst sofort einen Prüfzyklus aus. Mit Arduino kommen Temperatur und CO2 vom Sensor – Knöpfe setzen dann nur noch die Außenwerte.", dim); GUILayout.Space(S(4)); GUILayout.Label("Maus: ziehen = drehen · Shift/rechts = schieben · Rad = Zoom · Tür anklicken\nTasten: 1–4 Ansichten · T Tür · B Beamer · Leertaste prüfen · H Dashboard", dim); } - void DrawBackendScenarios() + /// Zentrales Backend: Demo-Szenarien gelten für Webinterface und Unity gleichzeitig. + void DrawCentralScenarios(CentralState c) { - var list = B.szenarien; - for (int i = 0; i < list.Length; i += 2) + GUILayout.BeginHorizontal(); + GUILayout.Label("Backend", label); + GUILayout.FlexibleSpace(); + Tag(c.status ?? "", c.ton == "good" ? Good : c.ton == "danger" ? Bad : Warn); + GUILayout.EndHorizontal(); + for (int i = 0; i < c.szenarien.Length; i += 2) { GUILayout.BeginHorizontal(); - for (int k = i; k < Mathf.Min(i + 2, list.Length); k++) + for (int j = i; j < i + 2 && j < c.szenarien.Length; j++) { - var sc = list[k]; - bool on = sc.id == B.szenario; - if (GUILayout.Toggle(on, sc.text, button) && !on) backend.ChooseScenario(sc.id); + var s = c.szenarien[j]; + bool on = s.id == c.szenario; + GUILayout.Toggle(on, s.text, button); // Anzeige: Szenarien werden im Webinterface gewählt } GUILayout.EndHorizontal(); } - GUILayout.Label("Szenarien des Backends gelten auch im Webinterface. „Live“ nutzt nur echte Sensordaten und Stimmen.", dim); - GUILayout.Space(S(4)); - GUILayout.Label("Maus: ziehen = drehen · Shift/rechts = schieben · Rad = Zoom · Tür anklicken\nTasten: 1–4 Ansichten · T Tür · B Vortragsmodus · H Dashboard", dim); + GUILayout.Label($"Entschieden wird im Backend (server.js), Unity zeigt nur an. Szenarien wählt ihr im Webinterface. Nächste Prüfung in {c.pruefung.restSekunden / 60}:{c.pruefung.restSekunden % 60:00} (Zeitraffer {c.pruefung.zeitraffer}×).", dim); } void ScenarioRow(string a, Action fa, string b, Action fb) { GUILayout.BeginHorizontal(); - if (GUILayout.Button(a, button)) { fa(); controller.RunCycle(); } - if (GUILayout.Button(b, button)) { fb(); controller.RunCycle(); } + ScenarioButton(a, fa); + ScenarioButton(b, fb); GUILayout.EndHorizontal(); } + void ScenarioButton(string text, Action set) + { + // erkanntes Szenario wird wie ein aktiver Knopf dargestellt ("Hitze 30 °C" passt zu "Hitze") + bool active = text.StartsWith(controller.Scenario, StringComparison.Ordinal); + if (GUILayout.Toggle(active, text, button) != active) { set(); controller.RunCycle(); } + } + // ================================================================ Rechts: Tabs void DrawRight() { @@ -247,12 +263,13 @@ namespace SmartRoom void DrawControl() { - if (Shared) - { - DrawBackendControl(); - return; - } Section("BETRIEBSART"); + if (bridge != null && bridge.CentralActive) + { + var c = bridge.Central; + GUILayout.Label($"Zentrales Backend entscheidet: {c.status} · Priorität {c.prioritaetNummer}: {c.prioritaet}" + + (c.vetos.laerm ? " · Lärmschutz aktiv" : ""), dim); + } int mode = GUILayout.Toolbar(controller.autoMode ? 0 : 1, new[] { "Automatik", "Manuell" }, seg); bool auto = mode == 0; if (auto != controller.autoMode) @@ -314,88 +331,6 @@ namespace SmartRoom GUILayout.EndHorizontal(); } if (!manual) GUILayout.Label("Im Automatikmodus steuert die Logik Fenster, Jalousien, Heizung, Lüftung und Licht. Für Handsteuerung auf \"Manuell\" wechseln.", dim); - else GUILayout.Label($"Manuelle Einstellungen gelten noch {controller.ManualMinutesLeft:0} min. Bei Sturm öffnet das Fenster höchstens gekippt, bei zu hohem CO₂ läuft die Lüftungsanlage weiter.", dim); - } - - void DrawBackendControl() - { - Section("BETRIEBSART"); - GUILayout.BeginVertical(card); - GUILayout.BeginHorizontal(); - GUILayout.Label(B.status, label); - GUILayout.FlexibleSpace(); - Tag(B.prioritaet.ToUpperInvariant(), Accent); - GUILayout.EndHorizontal(); - GUILayout.Label(B.detail, dim); - GUILayout.EndVertical(); - GUILayout.Label($"Das Backend entscheidet für Webinterface und Zwilling. Zielwert {B.zielTemperatur:0.0} °C.", dim); - - Section("AKTOREN"); - GUILayout.BeginVertical(card); - GUILayout.BeginHorizontal(); - GUILayout.Label("Fenster (4×)", label); - GUILayout.FlexibleSpace(); - GUILayout.Label(devices.WindowLabel, valueRight); - GUILayout.EndHorizontal(); - Bar(devices.WindowAirflow, Accent); - GUILayout.EndVertical(); - DeviceRow("Jalousien", devices.BlindPosition > 0.5f ? "unten" : "oben", devices.BlindPosition, devices.BlindTarget, false); - DeviceRow("Heizung", null, devices.HeatingLevel, devices.HeatingTarget, false, new Color(1f, 0.55f, 0.35f)); - DeviceRow("Lüftungsanlage", null, devices.VentLevel, devices.VentTarget, false); - DeviceRow("Licht", null, devices.LightLevel, devices.LightTarget, false, new Color(1f, 0.9f, 0.6f)); - - Section("DOZENT"); - GUILayout.BeginVertical(card); - GUILayout.BeginHorizontal(); - GUILayout.Label("Vortragsmodus (Beamer, Jalousie zu)", label); - GUILayout.FlexibleSpace(); - bool lecture = Switch(B.vortrag.aktiv); - GUILayout.EndHorizontal(); - if (lecture != B.vortrag.aktiv) backend.SetLecture(lecture); - int di = Array.IndexOf(LectureMinutes, B.vortrag.dauerMinuten); - int ndi = GUILayout.Toolbar(di, new[] { "30 min", "60 min", "90 min" }, seg); - if (ndi != di && ndi >= 0) backend.SetLectureDuration(LectureMinutes[ndi]); - if (B.vortrag.aktiv) GUILayout.Label($"Noch {B.vortrag.restMinuten} min", dim); - GUILayout.EndVertical(); - - var m = B.manuell; - GUILayout.BeginVertical(card); - GUILayout.BeginHorizontal(); - GUILayout.Label("Manuelle Einstellungen", label); - GUILayout.FlexibleSpace(); - if (m.aktiv && GUILayout.Button("Automatik", button, GUILayout.Width(S(90)))) backend.ResetManual(); - GUILayout.EndHorizontal(); - GUILayout.Label("Fenster", dim); - int wi = Mathf.Max(0, Array.IndexOf(ManualWindowCodes, m.fenster)); - int nwi = GUILayout.Toolbar(wi, ManualWindowLabels, seg); - if (nwi != wi) backend.SetManual("fenster", nwi == 0 ? "\"auto\"" : $"\"{ManualWindowCodes[nwi]}\""); - ManualPercentRow("Jalousie", "jalousie", m.jalousie, ManualBlindLabels); - ManualPercentRow("Licht", "licht", m.licht, ManualLightLabels); - GUILayout.Label("Lüftungsanlage", dim); - int vi = m.lueftung + 1; // -1 Auto, 0 aus, 1 an - int nvi = GUILayout.Toolbar(vi, ManualVentLabels, seg); - if (nvi != vi) backend.SetManual("lueftung", nvi == 0 ? "\"auto\"" : nvi == 1 ? "\"aus\"" : "\"an\""); - GUILayout.Label(m.aktiv ? $"Manuell bis {m.bis} (90 min), dann wieder Automatik." : "Manuelle Werte haben Vorrang und gelten 90 min.", dim); - GUILayout.EndVertical(); - - if (devices.door != null) - { - Section("ZUGANG"); - GUILayout.BeginHorizontal(card); - GUILayout.Label("Tür offen (nur im Zwilling)", label); - GUILayout.FlexibleSpace(); - devices.door.open = Switch(devices.door.open); - GUILayout.EndHorizontal(); - } - GUILayout.Label("Schutzregeln bleiben: Bei zu hohem CO₂ läuft die Lüftungsanlage weiter, bei Sturm öffnen die Fenster höchstens gekippt.", dim); - } - - void ManualPercentRow(string title, string field, int current, string[] labels) - { - GUILayout.Label(title, dim); - int i = Mathf.Max(0, Array.IndexOf(ManualPercent, current)); - int ni = GUILayout.Toolbar(i, labels, seg); - if (ni != i) backend.SetManual(field, ni == 0 ? "\"auto\"" : ManualPercent[ni].ToString()); } float DeviceRow(string name, string state, float current, float target, bool editable, Color? color = null) @@ -415,12 +350,13 @@ namespace SmartRoom void DrawWishes() { - if (Shared) - { - DrawBackendWishes(); - return; - } Section("DEIN WUNSCH"); + if (bridge != null && bridge.CentralActive) + { + var v = bridge.Central.stimmen; + GUILayout.Label($"Stimmen im Backend: kühler {v.kuehler} · angenehm {v.angenehm} · wärmer {v.waermer} → Zielwert {bridge.Central.zielTemperatur:0.0} °C", dim); + GUILayout.Label("Abgestimmt wird im Webinterface (jeder Browser-Tab ist eine Person). Die lokalen Wünsche unten gelten nur im Modus „Simulation“.", dim); + } if (controller.wishes.Count == 0) controller.wishes.Add(new UserWish("Du", 22f, false)); var own = controller.wishes[0]; own.temperature = SliderRow("Wunschtemperatur", own.temperature, 18f, 26f, "{0:0.0} °C"); @@ -460,54 +396,6 @@ namespace SmartRoom GUILayout.Label("Die Wünsche werden gemittelt (Aggregation) und fließen beim nächsten Prüfzyklus in Heizung und Fenstersteuerung ein.", dim); } - void DrawBackendWishes() - { - var v = B.stimmen; - Section("DEINE STIMME"); - GUILayout.Label("Temperatur", dim); - int ti = Array.IndexOf(TempVotes, v.eigeneTemperatur); - int nti = GUILayout.Toolbar(ti, TempVoteLabels, seg); - if (nti != ti && nti >= 0) backend.VoteTemperature(TempVotes[nti]); - GUILayout.Label("Licht", dim); - int li = Array.IndexOf(LightVotes, v.eigeneLicht); - int nli = GUILayout.Toolbar(li, LightVoteLabels, seg); - if (nli != li && nli >= 0) backend.VoteLight(LightVotes[nli]); - GUILayout.Label("Fenster öffnen?", dim); - int fi = Array.IndexOf(WindowVotes, v.eigeneFenster); - int nfi = GUILayout.Toolbar(fi, WindowVoteLabels, seg); - if (nfi != fi && nfi >= 0) backend.VoteWindow(WindowVotes[nfi]); - GUILayout.Label("Eine Stimme pro Gerät, wie im Webinterface. Sie verfällt nach 30 min.", dim); - - Section("ALLE EINGABEN"); - GUILayout.BeginVertical(card); - GUILayout.BeginHorizontal(); - GUILayout.Label($"Ziel {B.zielTemperatur:0.0} °C", bigValue); - GUILayout.FlexibleSpace(); - GUILayout.Label($"{v.gesamt} Stimmen", valueRight); - GUILayout.EndHorizontal(); - GUILayout.EndVertical(); - VoteRow("Kühler", v.kuehler); - VoteRow("Angenehm", v.angenehm); - VoteRow("Wärmer", v.waermer); - GUILayout.Space(S(4)); - VoteRow("Licht dunkler", v.dunkler); - VoteRow("Licht passt", v.passt); - VoteRow("Licht heller", v.heller); - GUILayout.Space(S(4)); - VoteRow("Fenster auf", v.auf); - VoteRow("Fenster zu lassen", v.zu); - GUILayout.Label("Temperatur und Licht: Durchschnitt aller Stimmen aus Webinterface und Zwilling. Fenster: Mehrheit, bei Außenlärm öffnet es nur auf Wunsch. Gegen den CO₂-Grenzwert kommen Stimmen nicht an.", dim); - } - - void VoteRow(string name, int count) - { - GUILayout.BeginHorizontal(); - GUILayout.Label(name, label); - GUILayout.FlexibleSpace(); - GUILayout.Label(count.ToString(), valueRight); - GUILayout.EndHorizontal(); - } - void DrawConnection() { Section("SENSORQUELLE"); @@ -542,13 +430,20 @@ namespace SmartRoom udpField = GUILayout.TextField(udpField, field); if (int.TryParse(udpField, out var port)) bridge.udpListenPort = port; } - else if (bridge.mode == LinkMode.Backend && backend != null) + else if (bridge.mode == LinkMode.Backend) { - GUILayout.Label("Server-URL des gemeinsamen Backends (backend/server.js)", dim); - if (urlField == null) urlField = backend.serverUrl; - urlField = GUILayout.TextField(urlField, field); - backend.serverUrl = urlField.Trim(); - GUILayout.Label("Anderer Laptop im Hotspot: http://:3000. Nach Änderung neu verbinden.", dim); + GUILayout.Label("Adresse von backend/server.py (Arduino → ESP-01 → Server → Unity)", dim); + if (backendField == null) backendField = bridge.backendUrl; + backendField = GUILayout.TextField(backendField, field); + bridge.backendUrl = backendField.Trim(); + GUILayout.Label($"Fragt alle {bridge.backendPollSeconds:0.#} s GET /api/messwerte ab (Temperatur, Luftfeuchte, eCO2, TVOC, Lautstärke, Helligkeit) und meldet die Steuerbefehle per POST /api/steuerung zurück.", dim); + GUILayout.BeginHorizontal(); + GUILayout.Label("Mikrofon steht draußen", label); + GUILayout.FlexibleSpace(); + bridge.MicrophoneOutdoor = Switch(bridge.MicrophoneOutdoor); + GUILayout.EndHorizontal(); + GUILayout.Label(bridge.MicrophoneOutdoor ? "Lautstärke zählt als Außenlärm: über 70 dB wird die Fensteröffnung gesperrt." + : "Lautstärke zählt als Lärm im Raum (nur Anzeige).", dim); } if (bridge.mode != LinkMode.Simulation) @@ -558,49 +453,27 @@ namespace SmartRoom { if (bridge.Connected) bridge.Disconnect(); else bridge.Connect(); } - if (bridge.mode != LinkMode.Backend) - { - GUILayout.BeginHorizontal(); - GUILayout.Label("Steuerbefehle senden", label); - GUILayout.FlexibleSpace(); - bridge.sendCommands = Switch(bridge.sendCommands); - GUILayout.EndHorizontal(); - } + GUILayout.BeginHorizontal(); + GUILayout.Label("Steuerbefehle senden", label); + GUILayout.FlexibleSpace(); + bridge.sendCommands = Switch(bridge.sendCommands); + GUILayout.EndHorizontal(); } GUILayout.BeginVertical(card); - if (bridge.mode == LinkMode.Backend && backend != null) - { - GUILayout.BeginHorizontal(); - Tag(backend.Connected ? "VERBUNDEN" : backend.Active ? "KEINE ANTWORT" : "GETRENNT", backend.Connected ? Good : Warn); - GUILayout.FlexibleSpace(); - if (backend.LastPacketTime >= 0f) - GUILayout.Label($"{backend.PacketCount} Abfragen · vor {Time.unscaledTime - backend.LastPacketTime:0} s", valueRight); - GUILayout.EndHorizontal(); - GUILayout.Label(backend.Status, dim); - GUILayout.Label("Kennung: " + backend.ClientId, dim); - } - else - { - GUILayout.BeginHorizontal(); - Tag(bridge.Connected ? "VERBUNDEN" : bridge.mode == LinkMode.Simulation ? "SIMULATION" : "GETRENNT", - bridge.Connected ? Good : TextDim); - GUILayout.FlexibleSpace(); - if (bridge.LastPacketTime >= 0f) - GUILayout.Label($"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s", valueRight); - GUILayout.EndHorizontal(); - GUILayout.Label(bridge.Status, dim); - if (!string.IsNullOrEmpty(bridge.LastLine)) GUILayout.Label("← " + bridge.LastLine, dim); - if (bridge.Connected && !string.IsNullOrEmpty(bridge.LastSent)) GUILayout.Label("→ " + bridge.LastSent, dim); - } + GUILayout.BeginHorizontal(); + Tag(bridge.Connected ? "VERBUNDEN" : bridge.mode == LinkMode.Simulation ? "SIMULATION" : "GETRENNT", + bridge.Connected ? Good : TextDim); + GUILayout.FlexibleSpace(); + if (bridge.LastPacketTime >= 0f) + GUILayout.Label($"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s", valueRight); + GUILayout.EndHorizontal(); + GUILayout.Label(bridge.Status, dim); + if (!string.IsNullOrEmpty(bridge.LastLine)) GUILayout.Label("← " + bridge.LastLine, dim); + if (bridge.Connected && !string.IsNullOrEmpty(bridge.LastSent)) GUILayout.Label("→ " + bridge.LastSent, dim); GUILayout.EndVertical(); - if (Shared) - { - Section("WETTERDATEN (EXTERN)"); - GUILayout.Label("Kommen vom Backend (Open-Meteo, Mannheim), damit Webinterface und Zwilling dieselben Werte nutzen.", dim); - } - else if (weather != null) + if (weather != null) { Section("WETTERDATEN (EXTERN)"); GUILayout.BeginHorizontal(); @@ -628,7 +501,7 @@ namespace SmartRoom } Section("PROTOKOLL"); - GUILayout.Label("Arduino → Unity (eine JSON-Zeile, alle Felder optional):\n{\"t\":30.2,\"co2\":1250,\"lux\":320,\"noise\":48,\"tout\":12,\"aq\":30,\"nout\":55,\"wind\":3.5,\"sun\":420,\"persons\":40}\n\nUnity → Arduino:\n{\"window\":\"open|tilted|closed\",\"blind\":1.00,\"heat\":0.50,\"vent\":0.80,\"light\":0.40,\"beamer\":0}", dim); + GUILayout.Label("Arduino → Unity (eine JSON-Zeile, alle Felder optional):\n{\"t\":30.2,\"co2\":1250,\"rh\":45,\"tvoc\":30,\"lux\":320,\"noise\":48,\"tout\":12,\"aq\":30,\"nout\":55,\"wind\":3.5,\"sun\":420,\"persons\":40}\n\nBackend (server.py): {\"temperatur\":22.5,\"luftfeuchte\":45,\"eco2\":612,\"tvoc\":30,\"lautstaerke\":48.5,\"helligkeit\":60}\n\nUnity → Arduino:\n{\"window\":\"open|tilted|closed\",\"blind\":1.00,\"heat\":0.50,\"vent\":0.80,\"light\":0.40,\"beamer\":0}", dim); } // ================================================================ Unten: Entscheidungslogik @@ -636,12 +509,6 @@ namespace SmartRoom { GUI.Box(bottomRect, GUIContent.none, panel); GUILayout.BeginArea(new Rect(bottomRect.x + S(16), bottomRect.y + S(10), bottomRect.width - S(32), bottomRect.height - S(18))); - if (Shared) - { - DrawBackendDecision(); - GUILayout.EndArea(); - return; - } var d = controller.Last; GUILayout.BeginHorizontal(); GUILayout.Label("ENTSCHEIDUNGSLOGIK" + (d != null ? " · " + d.time : ""), header); @@ -669,28 +536,6 @@ namespace SmartRoom GUILayout.EndArea(); } - void DrawBackendDecision() - { - var c = B.steuerung; - GUILayout.BeginHorizontal(); - GUILayout.Label("ENTSCHEIDUNG BACKEND · " + B.prioritaet, header); - GUILayout.FlexibleSpace(); - Tag($"Fenster {devices.WindowTarget.Label()}", Accent); - Tag($"Lüftung {c.vent * 100:0} %", Accent); - Tag($"Heizung {c.heat * 100:0} %", new Color(1f, 0.55f, 0.35f)); - Tag($"Jalousie {c.blind * 100:0} %", TextDim); - if (GUILayout.Button(logCollapsed ? "+" : "–", button, GUILayout.Width(S(30)))) logCollapsed = !logCollapsed; - GUILayout.EndHorizontal(); - if (logCollapsed) return; - - logScroll = GUILayout.BeginScrollView(logScroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none); - GUILayout.Label(B.status, logLineStrong); - GUILayout.Label(B.detail, logLine); - for (int i = 0; i < B.pfad.Length; i++) - GUILayout.Label($"{i + 1,2}. {B.pfad[i]}", B.pfad[i].Contains("→") ? logLineStrong : logLine); - GUILayout.EndScrollView(); - } - // ================================================================ Bausteine void Section(string text) { @@ -704,7 +549,7 @@ namespace SmartRoom GUILayout.BeginHorizontal(); GUILayout.Label(name, dim); GUILayout.FlexibleSpace(); - Tag(measured ? (Shared ? "BACKEND" : "SENSOR") : "SIM", measured ? Good : TextDim); + Tag(measured ? "SENSOR" : "SIM", measured ? Good : TextDim); GUILayout.EndHorizontal(); GUILayout.Label(value, bigValue); Bar(norm, status); diff --git a/frontend/SmartLectureRoom/README.md b/frontend/SmartLectureRoom/README.md index 4012462..6b9d506 100644 --- a/frontend/SmartLectureRoom/README.md +++ b/frontend/SmartLectureRoom/README.md @@ -7,12 +7,30 @@ Ein 3D-Vorlesungsraum als digitaler Zwilling für ein Smart-Home-Projekt. Er ste 1. **Unity Hub → Add → Add project from disk** und den Ordner `frontend/SmartLectureRoom` wählen. Ausgelegt ist das Projekt für **Unity 6 (6000.0 LTS)**. Unity 2022.3 LTS funktioniert ebenfalls. Fragt der Hub nach einer Version, eine installierte wählen. 2. Beim ersten Öffnen wird automatisch die Szene `Assets/Scenes/SmartRoom.unity` angelegt und geöffnet. Falls nicht: Menü **Smart Room → Szene öffnen**. -3. Das gemeinsame Backend starten (`backend/start.bat` bzw. `node backend/server.js`, siehe unten). -4. **Play** drücken. +3. **Play** drücken. Der ganze Raum wird beim Start per Code erzeugt (`RoomBuilder.cs`), es gibt also keine Modelle oder Prefabs, die fehlen könnten. Wenn du in einer beliebigen anderen Szene Play drückst, entsteht der Raum dort ebenfalls. Das Projekt läuft mit der Built-in Render Pipeline und mit URP. +## Zwei Szenen: Classic und Ambient + +| Szene | Optik | +|---|---| +| `Assets/Scenes/SmartRoom.unity` | Ursprünglicher Zwilling: dunkles Dashboard links/rechts, Raum bildschirmfüllend | +| `Assets/Scenes/SmartRoomAmbient.unity` | Look des Web-Frontends **Ambient²**: hell, Salbei/Grün, Karten. Der Raum erscheint als Frontansicht in der Karte „Raumstatus“ | + +Beide Szenen nutzen dieselbe Logik (Simulation, Entscheidungslogik, Arduino/Backend, Wetter); umgeschaltet wird nur über das Feld **Style** am `SmartRoom`-Objekt. Öffnen: Menü **Smart Room → Ambient-Szene öffnen** (wird beim ersten Mal angelegt). + +**Ambient-Dashboard:** +- **Kopfzeile:** Umschalter *Studierende / Dozent*; der Status oben rechts („System aktiv“ / „Arduino live“) öffnet die **Einstellungen** (Sensorquelle inkl. Backend-Adresse, Live-Wetter, Vorlesung läuft, Zeitraffer). +- **Hinweisband:** aktueller Zustand mit Priorität (1 Gesundheit, 2 Kontext, 3 Mehrheit, 4 Energie). +- **Raumstatus:** 3D-Raum (ziehen = drehen, Mausrad = Zoom, Tür anklicken), Chips für Fenster/Heizung/Lüftung/Licht/Jalousien; „⟲ Frontansicht“ setzt die Ansicht zurück. +- **Kacheln:** Luftqualität (CO2), Temperatur, Außenlärm, Wind – „● Sensor“, wenn der Wert vom Arduino kommt. +- **Dozentensteuerung:** Beamer-Modus mit Dauer 30/60/90 min (endet automatisch), Jalousien ↑/↓ (pausiert die Jalousie-Automatik für 30 min; Schutzregeln bleiben aktiv). +- **Raumstimmung:** Kühler / Angenehm / Wärmer setzt deinen Temperaturwunsch (21 / 22 / 23 °C), alle Wünsche werden gemittelt. Wünsche außerhalb 18–26 °C werden vorher begrenzt („Ausreißer-Stimme“). Studierende können zusätzlich „Frische Luft“ wünschen. +- **Verlauf:** die letzten Entscheidungen der Steuerung. **Demo-Szenarien:** Normal, CO₂ zu hoch, CO₂ + Außenlärm, Sturm, Vortragsmodus, Ausreißer-Stimme, Hitze, Kalter Morgen – das aus den Messwerten erkannte Szenario ist markiert. +- Tasten: `0`/`R` Frontansicht, `1`–`4` Ansichten, `B` Beamer, `T` Tür, Leertaste prüfen. + ## Bedienung | Eingabe | Wirkung | @@ -22,53 +40,98 @@ Das Projekt läuft mit der Built-in Render Pipeline und mit URP. | Mausrad | Zoom | | Tür anklicken / `T` | Tür öffnen/schließen | | `1` – `4` | Ansichten: Gesamt, Fensterfront, Leinwand & Tür, Decke & Lüftung | -| `B` | Beamer (Leinwand fährt herunter, Bild blendet ein); mit Backend: Vortragsmodus an/aus | -| Leertaste | sofort einen Prüfzyklus ausführen (nur ohne Backend) | +| `B` | Beamer (Leinwand fährt herunter, Bild blendet ein) | +| Leertaste | sofort einen Prüfzyklus ausführen | | `H` | Dashboard ein-/ausblenden | **Dashboard links:** Innenwerte (Temperatur, CO2, Licht, Lärm) mit „SIM“/„SENSOR“-Kennzeichnung, Außenwerte als Schieberegler, Zeitraffer und **Szenarien** (z. B. „Hitze 30 °C“: Fenster öffnet, Jalousie fährt runter; „Stickig + kalt“: Fenster bleibt zu, Lüftung läuft). **Dashboard rechts:** Automatik/Manuell, Aktorzustände, Nutzerwünsche (Wunschtemperatur, Fenster ja/nein), Verbindung zu Arduino und Live-Wetter. **Unten:** der Pfad, den die Logik im letzten Zyklus durch das Aktivitätsdiagramm genommen hat. -## Gemeinsames Backend (Standard) +## Logik (Aktivitätsdiagramm → `ClimateController.cs`) -Der Zwilling startet im Modus **Verbindung → Backend** und verbindet sich mit `http://localhost:3000` (`backend/server.js`). Das ist dasselbe Backend, das auch das Webinterface nutzt. Es entscheidet für beide. Der Zwilling zeigt nur an und animiert: +Alle 10 simulierten Minuten läuft ein Prüfzyklus. Wird ein Grenzwert neu überschritten, läuft er sofort. -- Sensorwerte (Arduino über ESP, Wetter, Demo-Szenario) und Steuerbefehle kommen jede Sekunde von `GET /api/unity` (`IO/BackendLink.cs`). Werte vom Backend tragen im Dashboard das Kennzeichen „BACKEND“, alle anderen simuliert Unity weiter („SIM“). -- **Wünsche:** Stimme Kühler/Angenehm/Wärmer, Dunkler/Passt/Heller und „Fenster öffnen? Auf/Zu lassen“ wie im Webinterface. Der Zwilling zählt als ein Gerät. -- **Steuerung:** Status und Priorität des Backends, dazu die Dozentenfunktionen Vortragsmodus (30/60/90 min) und manuelle Einstellungen für Fenster, Jalousie, Licht und Lüftungsanlage (gelten 90 min, „Automatik“ setzt zurück). Bei zu hohem CO₂ bleibt die Lüftungsanlage trotzdem an, bei Sturm öffnet das Fenster höchstens gekippt. -- **Szenarien:** die Demo-Szenarien des Backends (Live, Normal, CO₂ zu hoch, CO₂ + Außenlärm, Sturm, Vortragsmodus, Ausreißer-Stimme, Lärm + Fensterwunsch). Ein Wechsel gilt auch im Webinterface. - -Läuft das Backend auf einem anderen Laptop, unter **Verbindung** die URL ändern (z. B. `http://172.20.10.2:3000`) und neu verbinden. Antwortet das Backend länger als 5 s nicht, übernimmt die lokale Logik unten. Das Dashboard zeigt dann „Backend getrennt, lokale Logik“. - -## Lokale Logik (Aktivitätsdiagramm → `ClimateController.cs`) - -Nur aktiv in den Modi Simulation, Seriell und UDP oder wenn das Backend nicht erreichbar ist. - -Die Regeln und Grenzwerte entsprechen dem Backend (`backend/logik.js`), damit der Zwilling ohne Backend genauso entscheidet. Alle 10 simulierten Minuten läuft ein Prüfzyklus. Wird ein Grenzwert neu überschritten, läuft er sofort. - -1. Sensordaten, Fensterzustand und Nutzerwünsche erfassen. Zielwert = Ø-Wunschtemperatur, begrenzt auf 20–24 °C. Fenster gewünscht, wenn mehr als die Hälfte es will. -2. **CO2 > 1000 ppm** → Lüftung erforderlich. Sonst **Temperatur**: unter Ziel − 0,5 °C heizen, über Ziel + 1 °C (und draußen kühler) Lüftung erforderlich. +1. Sensordaten, Fensterzustand und Nutzerwünsche erfassen. Die Wünsche werden gemittelt (Aggregation). +2. **CO2 > 1000 ppm** → Lüftung erforderlich. Sonst **Temperatur**: unter 20 °C heizen, 20–25 °C Komfortbereich, über 25 °C Lüftung erforderlich. 3. Ist Lüftung erforderlich: - - **Außenluft schlecht (AQI > 60) oder draußen zu kalt (< 5 °C)**: Fenster zu, Lüftungsanlage an - - **Extremer Außenlärm (> 70 dB)**: Fensteröffnung gesperrt. Will die Mehrheit trotzdem lüften, öffnet das Fenster, sonst läuft die Lüftungsanlage. + - **Außenluft schlecht (AQI > 60) oder draußen zu kalt (< 5 °C)**: Fenster zu, Lüftungsanlage an (deine Vorgabe) + - **Extremer Außenlärm (> 70 dB)**: Fensteröffnung gesperrt. Wollen die Nutzer trotzdem lüften, öffnet das Fenster, sonst läuft die alternative Lüftung. + - **Starker Wind (> 10 m/s)**: Fenster gekippt - sonst: Fenster offen -4. Ohne Lüftungsbedarf entscheidet der Mehrheitswunsch über das Fenster. -5. **Starker Wind (> 16,7 m/s = 60 km/h)**: Fenster höchstens gekippt, auch bei manueller Einstellung. Bei zu hohem CO₂ läuft die Lüftungsanlage, solange das Fenster nicht offen ist. -6. Geheizt wird auf den Zielwert, bei offenem Fenster ist die Heizung aus. Dann Soll- und Ist-Zustand des Fensters vergleichen. -7. **Beamer an** → Licht aus, Jalousie runter. Sonst **Sonneneinstrahlung > 500 W/m²** → Jalousie runter, Licht an; sonst Jalousie hoch. Das Licht ergänzt das Tageslicht auf 500 lx. -8. **Manuell:** Die Handeinstellungen haben Vorrang, die Schutzregeln aus Schritt 5 gelten weiter. Nach 90 simulierten Minuten werden sie gelöscht und die Automatik übernimmt. -9. Die virtuellen Aktoren werden angesteuert. Nach 10 Minuten wird erneut geprüft. -10. Läuft keine Vorlesung, werden die gespeicherten Einstellungen gelöscht und der Raum geht in den Energiesparmodus. +4. Ohne Lüftungsbedarf entscheidet der Nutzerwunsch über das Fenster. Geheizt wird auf die Ø-Wunschtemperatur, bei offenem Fenster ist die Heizung aus. +5. Soll- und Ist-Zustand des Fensters vergleichen, dann beibehalten oder anpassen. +6. **Sonneneinstrahlung > 500 W/m²** → Jalousie runter, sonst hoch. Als Erweiterung fährt die Jalousie auch bei laufendem Beamer runter. +7. Als Erweiterung wird das Licht auf 500 lx ergänzt und für den Beamer gedimmt. +8. Die virtuellen Aktoren werden angesteuert. Nach 10 Minuten wird erneut geprüft. +9. Läuft keine Vorlesung, geht der Raum in den Energiesparmodus. Alle Grenzwerte lassen sich im Inspector am `SmartRoom`-Objekt unter **Climate Controller → Limits** einstellen. ## Arduino anbinden (Architekturdiagramm: Physische Umgebung → Backend) +### Gemeinsames Backend: Arduino → `server.js` ← Webinterface, → Unity + +Das Node-Backend (`node backend/server.js`) ist das **eine** Backend für Webinterface und Unity. Es nimmt die Messwerte des ESP-01 an, aggregiert die Stimmen und entscheidet alle 2 Minuten nach Gesundheit, Kontext, Mehrheit und Energie (Übersicht: `docs/regeln.md`). **Bedient wird im Webinterface.** Unity fragt jede Sekunde `GET /api/unity` ab und **zeigt nur, was die Entscheidung im Raum auslöst**: + +``` +DHT11 + CCS811 + MAX9814 + LDR ─▶ Arduino Uno ─▶ ESP-01 ─WLAN─▶ server.js :3000 ◀──▶ Webinterface (Ambient², Bedienung) + │ + GET /api/unity ▼ + Unity-Zwilling (nur Anzeige) +``` + +- **Plug & Play:** Modus **Backend** ist Standard, Adresse `http://localhost:3000`. Unity erkennt selbst, welches Backend läuft: `server.js` (zentral, Unity führt aus) oder `server.py` (nur Messwerte, Unity entscheidet selbst, siehe unten). Ohne Server läuft die Simulation. +- **Alle Sensoren:** Temperatur, eCO₂, Luftfeuchte, TVOC, Helligkeit und Lautstärke. „● Sensor“ steht nur an echten Sensorwerten; Wetter- und Demo-Werte ersetzen die Simulation ebenfalls, aber ohne diese Kennzeichnung. +- **Lautstärkesensor:** zählt als Außenlärm. Über 70 dB sperrt das Backend die Fenster, die Lüftungsanlage übernimmt (nur wenn die Mehrheit im Webinterface „Fenster auf“ wählt, wird trotzdem gelüftet). Im 3D-Raum: Schallwellen vor der Fensterfront (ab dem Grenzwert rot), Pegelschild an der Fassade, Chip „Lärmschutz: Fenster gesperrt“. +- **Status und Umschalter:** Oben rechts steht „● Arduino verbunden“ (grün) bzw. „● Arduino nicht verbunden“ (rot, mit Grund im Raumstatus, z. B. „Backend nicht erreichbar“). Der Umschalter **Arduino-Werte | Simulation** wechselt zwischen den echten Werten (und Entscheidungen des Backends) und den Beispielwerten der Simulation, bei der Unity selbst entscheidet. Der Status bleibt auch im Simulationsmodus aktuell. Im Classic-Dashboard sitzt beides links unter dem Titel. +- **Nur Anzeige:** Mit Backend zeigen Dozentensteuerung, Raumstimmung und Demo-Szenarien in Unity den Zustand aus dem Webinterface; Klicks darauf bewirken nichts. Ebenfalls angezeigt: nächste Prüfung (Prüfzyklus 2 min, Zeitraffer aus dem Webinterface). +- **WebGL:** Die Abfrage läuft über `UnityWebRequest`, der Zwilling funktioniert also auch als WebGL-Build im Browser und übernimmt dort die Adresse der Seite als Backend (Anleitung in `backend/README.md`, „Live-Demo im Browser“). + +### Älteres Backend: Arduino Uno + ESP-01 → `server.py` → Unity (Modus „Backend“) + +Der Sensor-Arduino aus dem GruppeC-Repo (`firmware/dht11_lcd`, DHT11 + CCS811) schickt seine Messwerte per ESP-01 als HTTP-POST an `backend/server.py` auf dem Laptop. Unity holt sie dort jede Sekunde ab, die Website läuft parallel weiter: + +``` +DHT11 + CCS811 ─▶ Arduino Uno ─▶ ESP-01 ─WLAN─▶ server.py :3000 ─GET /api/messwerte─▶ Unity-Zwilling + ▲ │ + └──────── POST /api/steuerung ─────────┘ +``` + +| Backend-Feld | Unity | Wirkung in der Simulation | +|---|---|---| +| `temperatur` | Temperatur innen | ersetzt das Wärmemodell → Heizen (< 20 °C) / Lüften (> 25 °C) | +| `eco2` | CO2 innen | ersetzt das CO2-Modell → Lüften ab 1000 ppm (Hard-Constraint) | +| `luftfeuchte` | Luftfeuchte | nur Anzeige im Dashboard | +| `tvoc` | TVOC | nur Anzeige im Dashboard | +| `lautstaerke` | Lärm (MAX9814) | Schalter **„Mikrofon steht draußen“** (Verbindung → Backend bzw. Einstellungen): aus = Lärm im Raum (Anzeige), an = Außenlärm → über 70 dB Sensor-Veto, Fenster bleiben zu | +| `helligkeit` | Helligkeit (Fotowiderstand, %) | grob in lx umgerechnet (100 % ≈ 1000 lx, `luxPerLightPercent`); die Lichtsteuerung rechnet dann mit dem gemessenen statt dem geschätzten Tageslicht | + +So läuft es: +1. `python backend/server.py` starten (GruppeC-Repo, bzw. `start.bat`). +2. Unity: **Play** → Dashboard rechts **Verbindung → Backend** → Adresse prüfen (`http://localhost:3000`, läuft Unity auf einem anderen Rechner: `http://:3000`) → **Verbinden**. +3. Sobald Messwerte kommen, stehen Temperatur und CO2 auf **SENSOR**, links oben „Arduino live“. + +Was dann automatisch passiert: +- **Szenario-Erkennung:** Aus den Messwerten (plus Außenwerten) wird das passende Szenario erkannt und im Dashboard hervorgehoben, z. B. „Hitze“, „Stickige Luft“, „Stickig + kalt“, „Wintermorgen“. Es steht auch auf der Beamer-Leinwand und im Entscheidungspfad. +- **Sofortige Reaktion:** Wechselt das Szenario (z. B. CO2 steigt über 1000 ppm) oder kommen die ersten Arduino-Werte an, läuft sofort ein Prüfzyklus. Fenster, Lüftung, Heizung, Jalousie und Licht werden ohne Klick angesteuert. +- **Rückkanal:** Unity meldet die Aktor-Sollwerte und das erkannte Szenario per `POST /api/steuerung` an den Server (`GET /api/steuerung` zeigt den letzten Stand, das Serverfenster gibt ihn aus). +- Kommen 25 s lang keine neuen Messwerte (die Station sendet ca. alle 7–8 s), übernimmt wieder die Simulation. Messwerte, die beim Verbinden schon älter als 30 s sind, werden ignoriert. + +**Ohne Arduino testen** (Server muss laufen): +```bash +python backend/simulator.py --szenario demo +``` +`demo` läuft nacheinander normal → stickig → laerm → normal → hitze → dunkel → kalt durch (je ca. 1 min). Einzeln: `--szenario normal|hitze|stickig|kalt|laerm|dunkel`. + +Die Szenario-Knöpfe im Dashboard funktionieren weiter; mit Arduino überschreibt der nächste Messwert aber Temperatur und CO2 innen, wirksam bleiben dann die Außenwerte (Wind, Lärm, Luftqualität, Sonne). + +### Eigenes JSON-Protokoll (USB-Seriell / UDP) + Unity empfängt pro Zeile ein JSON-Objekt. Alle Felder sind optional, gesendete Felder überschreiben die Simulation: ```json -{"t":30.2,"co2":1250,"lux":320,"noise":48,"tout":12,"aq":30,"nout":55,"wind":3.5,"sun":420,"persons":40} +{"t":30.2,"co2":1250,"rh":45,"tvoc":30,"lux":320,"noise":48,"tout":12,"aq":30,"nout":55,"wind":3.5,"sun":420,"persons":40} ``` Unity sendet die Steuerbefehle zurück, sobald sie sich ändern: @@ -97,8 +160,9 @@ Assets/SmartRoom/Scripts Actuators/* Animationen: Fenster (Dreh-Kipp), Jalousie, Heizung, Lüftung, Licht, Beamer, Tür Simulation/RoomEnvironment.cs Raumklima-Modell (CO2, Wärme, Licht, Lärm) + Messwertübernahme Control/ClimateController.cs Entscheidungslogik - IO/ArduinoBridge.cs Seriell/UDP, JSON-Protokoll, Moduswahl - IO/BackendLink.cs gemeinsames Backend (GET /api/unity, Stimmen, Szenarien, Dozentenfunktionen) + IO/ArduinoBridge.cs Seriell/UDP/Backend (HTTP), JSON-Protokoll IO/WeatherService.cs Open-Meteo - UI/SmartRoomHUD.cs, UI/OrbitCamera.cs + UI/SmartRoomHUD.cs Dashboard Classic + UI/AmbientHUD.cs Dashboard im Look des Web-Frontends (Ambient²) + UI/OrbitCamera.cs ``` diff --git a/frontend/ambient-v1/index.html b/frontend/ambient-v1/index.html new file mode 100644 index 0000000..2f3ee5b --- /dev/null +++ b/frontend/ambient-v1/index.html @@ -0,0 +1,16853 @@ + + + + + + Ambient² + + + + + +
+ + diff --git a/frontend/ambient/ambient.css b/frontend/ambient/ambient.css new file mode 100644 index 0000000..7ebe717 --- /dev/null +++ b/frontend/ambient/ambient.css @@ -0,0 +1,2 @@ +/* Unveraendertes CSS aus dem Figma-Export Ambient2_v2.html (Branch Figma_Prototyp). Ergaenzungen stehen in ergaenzungen.css. */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.border-collapse{border-collapse:collapse}.transform{transform:var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.resize{resize:both}.flex-wrap{flex-wrap:wrap}.border{border-style:var(--tw-border-style);border-width:1px}.underline{text-decoration-line:underline}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.filter{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.filter\!{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )!important}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur, ) var(--tw-backdrop-brightness, ) var(--tw-backdrop-contrast, ) var(--tw-backdrop-grayscale, ) var(--tw-backdrop-hue-rotate, ) var(--tw-backdrop-invert, ) var(--tw-backdrop-opacity, ) var(--tw-backdrop-saturate, ) var(--tw-backdrop-sepia, );backdrop-filter:var(--tw-backdrop-blur, ) var(--tw-backdrop-brightness, ) var(--tw-backdrop-contrast, ) var(--tw-backdrop-grayscale, ) var(--tw-backdrop-hue-rotate, ) var(--tw-backdrop-invert, ) var(--tw-backdrop-opacity, ) var(--tw-backdrop-saturate, ) var(--tw-backdrop-sepia, )}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}}:root{color:#0e1a14;font-synthesis:none;--ink:#0e1a14;--muted:#45524b;--line:#c4cfc8;--line-strong:#9fb0a6;--surface:#fff;--soft:#f1f5f2;--green:#0c5238;--green-2:#137049;--green-soft:#dcefe4;--mint:#a9d6bd;--amber:#7a4300;--amber-2:#c27a12;--amber-soft:#fdebc8;--red:#8f2018;--red-2:#c0392b;--red-soft:#fbdcd7;--blue:#164e68;--blue-soft:#d9ebf2;--grey:#3d4741;--grey-soft:#e3e7e4;--shadow:0 10px 30px #0e281c17;background:#e6ece8;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}*{box-sizing:border-box}body{background:#e6ece8;min-width:320px;min-height:100vh;margin:0}button{font:inherit}h2{margin:0}.icon{fill:none;stroke:currentColor;stroke-width:2px;stroke-linecap:round;stroke-linejoin:round;flex:none;display:block}.skip-link{z-index:50;background:var(--ink);color:#fff;border-radius:8px;padding:10px 14px;font-size:14px;position:absolute;top:-60px;left:12px}.skip-link:focus{top:12px}.app-shell{min-height:100vh}.topbar{border-bottom:1px solid var(--line);z-index:20;background:#fff;grid-template-columns:1fr auto 1fr;align-items:center;height:56px;padding:0 max(24px,50vw - 720px);display:grid;position:sticky;top:0}.brand-group{align-items:center;gap:12px;display:flex}.brand-mark{color:#fff;background:var(--green);border-radius:12px;place-items:center;width:34px;height:34px;display:grid}.brand-name{letter-spacing:-.02em;font-size:17px;font-weight:800}.brand-subtitle{color:var(--muted);margin-top:2px;font-size:12px}.role-switch{border:1px solid var(--line);background:#dde5e0;border-radius:12px;padding:4px;display:flex}.role-option{min-height:36px;color:var(--muted);cursor:pointer;background:0 0;border:0;border-radius:9px;padding:6px 18px;font-size:14px;font-weight:700}.role-option.active{color:#fff;background:var(--green);box-shadow:0 2px 8px #0c523840}.live-status{color:var(--green);justify-self:end;align-items:center;gap:8px;font-size:13px;font-weight:600;display:flex}.live-status.is-offline{color:var(--grey);background:var(--grey-soft);border-radius:8px;padding:6px 10px}.live-dot{background:#1f9d63;border-radius:50%;width:8px;height:8px;box-shadow:0 0 0 4px #cdeedc}.page{max-width:1440px;margin:auto;padding:10px 24px 24px}.context-bar{justify-content:space-between;align-items:center;gap:16px;margin-bottom:8px;display:flex}.greeting{flex-wrap:wrap;align-items:baseline;gap:4px 12px;font-size:15px;display:flex}.greeting b{font-weight:750}.greeting span{color:var(--muted);font-size:13px}.outside-chip{border:1px solid var(--line);color:var(--muted);background:#fff;border-radius:10px;align-items:center;gap:8px;padding:5px 10px;font-size:13px;display:flex}.outside-chip b{color:var(--ink)}.outside-chip .divider{background:var(--line);width:1px;height:18px;margin:0 4px}.student-banner{background:var(--blue);color:#fff;box-shadow:var(--shadow);border-radius:14px;align-items:center;gap:12px;margin-bottom:12px;padding:12px 16px;font-size:14px;display:flex}.student-banner .banner-icon{background:#ffffff2e;border-radius:9px;place-items:center;width:32px;height:32px;display:grid}.student-banner span{color:#ffffffe0}.countdown-small{font-variant-numeric:tabular-nums;align-items:center;gap:7px;margin-left:auto;font-weight:700;display:flex}.status-banner{border:1px solid;border-left-width:6px;border-radius:14px;align-items:center;gap:12px;margin-bottom:10px;padding:9px 14px;display:flex}.status-symbol{border-radius:12px;flex:none;place-items:center;width:34px;height:34px;display:grid}.status-copy{flex:1}.status-title{letter-spacing:-.01em;font-size:16px;font-weight:800}.status-detail{margin-top:1px;font-size:13px;line-height:1.4}.tone-good{color:var(--green);border-color:var(--green-2);background:var(--green-soft)}.tone-good .status-symbol{background:var(--green);color:#fff}.tone-good .status-detail{color:#1d4c39}.tone-info{color:var(--blue);border-color:var(--blue);background:var(--blue-soft)}.tone-info .status-symbol{background:var(--blue);color:#fff}.tone-warning{color:var(--amber);border-color:var(--amber-2);background:var(--amber-soft)}.tone-warning .status-symbol{background:var(--amber-2);color:#fff}.tone-danger{color:#fff;border-color:var(--red);background:var(--red-2)}.tone-danger .status-symbol{color:var(--red-2);background:#fff}.tone-danger .priority-chip{color:#fff;background:#fff3}.countdown-chip{font-variant-numeric:tabular-nums}.tone-neutral{color:var(--grey);border-color:var(--grey);background:var(--grey-soft)}.tone-neutral .status-symbol{background:var(--grey);color:#fff}.priority-chip{white-space:nowrap;background:#ffffffbf;border-radius:9px;align-items:center;gap:7px;padding:6px 10px;font-size:13px;font-weight:750;display:flex}.banner-action{color:#fff;background:var(--grey);cursor:pointer;white-space:nowrap;border:0;border-radius:10px;align-items:center;gap:8px;min-height:34px;padding:0 16px;font-size:14px;font-weight:700;display:flex}.banner-action:hover{background:var(--ink)}.toast{color:#fff;background:var(--green);border-radius:10px;align-items:center;gap:8px;margin:-2px 0 10px;padding:8px 14px;font-size:14px;font-weight:600;display:flex}.content-grid{grid-template-columns:minmax(0,1.68fr) minmax(340px,.72fr);align-items:start;gap:12px;display:grid}.main-column,.side-column{flex-direction:column;gap:12px;min-width:0;display:flex}.card{background:var(--surface);border:1px solid var(--line);box-shadow:var(--shadow);border-radius:16px}.status-card{outline:none;padding:12px 14px}.room-card{padding:10px;position:relative}.room-card .section-header{z-index:6;background:#ffffffeb;border-radius:8px;margin:0;padding:4px 10px;position:absolute;top:18px;left:18px}.room-card .section-title{font-size:13px}.room-card .section-subtitle{display:none}.status-card .section-header{margin-bottom:10px}.status-card .section-subtitle{display:none}.section-header{justify-content:space-between;align-items:center;gap:10px;margin-bottom:14px;display:flex}.section-header.compact{margin-bottom:12px}.section-title{letter-spacing:-.01em;font-size:17px;font-weight:800}.section-subtitle{color:var(--muted);margin-top:3px;font-size:13px;line-height:1.45}.updated{color:var(--green);white-space:nowrap;align-items:center;gap:8px;font-size:13px;font-weight:650;display:flex}.updated.stale{color:var(--grey);background:var(--grey-soft);border-radius:8px;padding:6px 10px}.measure-grid{grid-template-columns:repeat(4,1fr);gap:10px;display:grid}.metric-card{background:var(--soft);border:1px solid var(--line);border-radius:12px;grid-template-columns:auto 1fr auto;align-items:center;column-gap:8px;min-width:0;padding:10px 12px;display:grid}.metric-top{display:contents}.metric-icon{grid-area:1/1}.metric-state{grid-area:1/3}.metric-label{grid-area:1/2}.metric-value,.metric-bar,.metric-foot{grid-column:1/-1}.metric-icon{color:#fff;background:var(--green-2);border-radius:9px;place-items:center;width:28px;height:28px;display:grid}.metric-state{color:var(--green);background:var(--green-soft);border:1px solid var(--mint);white-space:nowrap;border-radius:20px;padding:2px 7px;font-size:12px;font-weight:800}.metric-label{color:var(--muted);text-overflow:ellipsis;white-space:nowrap;min-width:0;font-size:13px;font-weight:650;overflow:hidden}.metric-value{letter-spacing:-.03em;font-variant-numeric:tabular-nums;margin-top:6px;font-size:26px;font-weight:800;line-height:1.1}.metric-value small{color:var(--muted);letter-spacing:0;font-size:14px;font-weight:650}.metric-bar{background:#d3dcd6;border-radius:6px;height:5px;margin:8px 0 6px;position:relative}.metric-bar i{border-radius:inherit;background:var(--green-2);max-width:100%;height:100%;display:block}.metric-bar em{background:var(--ink);border-radius:1px;width:2px;height:14px;position:absolute;top:-4px}.metric-foot{white-space:nowrap;text-overflow:ellipsis;min-height:16px;color:var(--muted);align-items:center;gap:5px;font-size:12px;display:flex;overflow:hidden}.metric-foot b{color:var(--ink)}.metric-alert{border-color:var(--red-2);background:#fff4f2}.metric-alert .metric-icon{background:var(--red-2)}.metric-alert .metric-state{color:#fff;background:var(--red-2);border-color:var(--red-2)}.metric-alert .metric-bar i{background:var(--red-2)}.metric-warning{border-color:var(--amber-2);background:#fff8ea}.metric-warning .metric-icon{background:var(--amber-2)}.metric-warning .metric-state{color:var(--amber);background:var(--amber-soft);border-color:var(--amber-2)}.metric-warning .metric-bar i{background:var(--amber-2)}.measure-grid.is-stale .metric-card{border-style:dashed;border-color:var(--line-strong);background:#eef0ee}.measure-grid.is-stale .metric-icon{background:#8a948e}.measure-grid.is-stale .metric-state{color:var(--grey);background:var(--grey-soft);border-color:var(--line-strong)}.measure-grid.is-stale .metric-value{color:#59645e}.measure-grid.is-stale .metric-bar i{background:#8a948e}.device-row{grid-template-columns:repeat(4,1fr);gap:8px;margin-top:10px;display:grid}.device{border:1px solid var(--line);color:var(--green);background:#fff;border-radius:11px;align-items:center;gap:10px;padding:6px 10px;display:flex}.device span{color:var(--muted);flex-direction:column;min-width:0;font-size:12px;font-weight:600;display:flex}.device b{color:var(--ink);font-size:13px;font-weight:750}.device.locked,.device.manual{color:var(--amber);border-color:var(--amber-2);background:#fff8ea}.device.unknown{color:var(--grey);border-style:dashed;border-color:var(--line-strong);background:#eef0ee}.room-visual{border:1px solid var(--line);background:#dfe9e3;border-radius:12px;overflow:hidden}.room-wall{perspective:700px;background:linear-gradient(#e8eee9,#dbe5de 69%,#cad4cd 70%,#b8c5bc);height:clamp(150px,100vh - 470px,340px);position:relative;overflow:hidden;container-type:size}.room-wall:after{content:"";background:#5b6f6333;height:2px;position:absolute;top:69%;left:0;right:0}.ceiling-light{background:#fff;width:22%;height:4px;position:absolute;top:9%;transform:skew(-25deg);box-shadow:0 0 18px 6px #ffffff8c}.ceiling-light.one{left:14%}.ceiling-light.two{right:14%}.screen{z-index:2;background:#f7faf8;border:7px solid #3e4c44;border-width:7px 5px;flex-direction:column;justify-content:center;align-items:center;width:32%;height:40%;display:flex;position:absolute;top:12%;left:34%;box-shadow:0 9px 14px #283b3126}.screen-title{letter-spacing:.18em;color:var(--green-2);font-size:clamp(7px,4.2cqh,10px);font-weight:800}.screen-temp{color:#1f3a2e;margin:1px 0;font-size:clamp(16px,11cqh,34px);font-weight:800;line-height:1.05}.screen-note{color:#4f5d55;font-size:clamp(7px,4.2cqh,11px)}.window-unit{background:#99b6ba;border:6px solid #f4f6f4;width:20%;height:45%;position:absolute;top:14%;overflow:hidden;box-shadow:inset 0 0 0 2px #a9b7b0}.left-window{left:4%}.right-window{right:4%}.window-panel{background:linear-gradient(145deg,#a9c2c3,#d6dfd9);grid-template-columns:repeat(3,1fr);transition:transform .4s;display:grid;position:absolute;inset:0}.window-panel.open-yes{transform-origin:0;background:linear-gradient(145deg,#8fb0b4,#c4d4ce);transform:perspective(200px)rotateY(-28deg)}.window-panel span{border-right:3px solid #eff2ef}.blind-overlay{z-index:2;opacity:.95;background:repeating-linear-gradient(#5d685f 0,#6c776e 5px,#3d4941 6px 7px);transition:height .45s;position:absolute;top:0;left:0;right:0}.airflow{z-index:4;color:#137049;gap:17px;font-size:24px;animation:1.5s ease-in-out infinite breathe;display:flex;position:absolute;top:28%;left:22%}@keyframes breathe{50%{opacity:.5;transform:translate(12px)}}.room-floor{background:repeating-linear-gradient(90deg,#0000 0 54px,#53655b14 55px),#b9c5bd;height:54%;position:absolute;bottom:-30%;left:-10%;right:-10%;transform:rotateX(58deg)}.desk{z-index:3;background:#7d8c82;border-radius:2px;width:17%;height:8%;position:absolute;box-shadow:0 5px #56655c}.desk:after,.desk:before{content:"";background:#66746b;width:4px;height:30px;position:absolute;top:100%}.desk:before{left:9px}.desk:after{right:9px}.desk i{background:#4a5a50;border-radius:50% 50% 4px 4px;width:16px;height:20px;position:absolute;bottom:10px}.desk i:first-child{left:24%}.desk i:last-child{right:24%}.desk-one{bottom:14%;left:9%}.desk-two{bottom:14%;left:41.5%}.desk-three{bottom:14%;right:9%}.teacher-desk{z-index:3;background:#66776c;width:20%;height:5%;position:absolute;top:60%;left:40%;box-shadow:0 5px #46564c}.room-label{z-index:5;color:var(--ink);background:#fff;border-radius:8px;align-items:center;gap:6px;padding:7px 10px;font-size:12px;font-weight:700;display:flex;position:absolute;bottom:10px;box-shadow:0 3px 12px #1e322826}.window-label{left:10px}.blind-label{right:10px}.presentation-card{padding:18px}.presentation-card.is-active{border-color:var(--green-2);border-width:2px}.card-kicker{color:var(--green-2);text-transform:uppercase;letter-spacing:.1em;align-items:center;gap:7px;margin-bottom:12px;font-size:12px;font-weight:800;display:flex}.presentation-heading{justify-content:space-between;align-items:center;gap:10px;display:flex}.switch-wrap{align-items:center;gap:8px;display:flex}.switch-text{min-width:26px;color:var(--muted);text-align:right;font-size:14px;font-weight:800}.big-switch{cursor:pointer;background:#9aa69f;border:0;border-radius:20px;width:62px;height:34px;padding:4px;transition:background .2s}.big-switch span{background:#fff;border-radius:50%;width:26px;height:26px;transition:transform .2s;display:block;box-shadow:0 2px 6px #1e282340}.big-switch.on{background:var(--green-2)}.big-switch.on span{transform:translate(28px)}.duration-label{color:var(--ink);margin-top:14px;font-size:14px;font-weight:750}.duration-group{grid-template-columns:repeat(3,1fr);gap:6px;margin-top:8px;display:grid}.duration-button{min-height:44px;color:var(--ink);background:var(--soft);border:1px solid var(--line);cursor:pointer;border-radius:9px;padding:8px 4px;font-size:14px;font-weight:650}.duration-button:hover{border-color:var(--green-2)}.duration-button.active{color:#fff;background:var(--green);border-color:var(--green)}.countdown-box{color:var(--blue);background:var(--blue-soft);border-radius:11px;align-items:center;gap:10px;margin-top:12px;padding:11px;display:flex}.countdown-icon{background:#fff;border-radius:8px;place-items:center;width:32px;height:32px;display:grid}.countdown-box span{font-size:12px;display:block}.countdown-box b{font-variant-numeric:tabular-nums;margin-top:1px;font-size:20px;display:block}.countdown-box .until{margin-left:auto;font-size:13px;font-weight:650}.blind-controls{border-top:1px solid var(--line);justify-content:space-between;align-items:center;gap:10px;margin-top:14px;padding-top:14px;display:flex}.blind-controls .duration-label{margin:0}.blind-buttons{gap:6px;display:flex}.icon-button{min-width:64px;height:44px;color:var(--green);border:1px solid var(--line-strong);cursor:pointer;white-space:nowrap;background:#fff;border-radius:9px;padding:0 10px;font-size:14px;font-weight:750}.icon-button:hover{background:var(--green-soft);border-color:var(--green-2)}.pause-note{color:var(--amber);border:1px solid var(--amber-2);background:var(--amber-soft);border-radius:10px;flex-direction:column;gap:8px;margin-top:10px;padding:10px 12px;font-size:13px;font-weight:700;display:flex}.pause-note>span:first-child{align-items:center;gap:6px;display:flex}.pause-actions{flex-wrap:wrap;gap:6px;display:flex}.text-button{min-height:36px;color:var(--ink);border:1px solid var(--amber-2);cursor:pointer;background:#fff;border-radius:8px;align-items:center;gap:5px;padding:0 12px;font-size:13px;font-weight:700;display:inline-flex}.text-button:hover{background:#fff8ea}.guard-note{color:var(--muted);background:var(--soft);border-radius:9px;align-items:flex-start;gap:8px;margin-top:12px;padding:10px;font-size:13px;line-height:1.45;display:flex}.guard-note b{color:var(--ink)}.wish-card,.history-card{padding:18px}.stepper{background:var(--soft);border:1px solid var(--line);border-radius:14px;grid-template-columns:56px 1fr 56px;align-items:center;gap:10px;padding:10px;display:grid}.step-button{color:#fff;background:var(--green);cursor:pointer;border:0;border-radius:12px;place-items:center;width:56px;height:56px;display:grid}.step-button:hover:not(:disabled){background:var(--ink)}.step-button:disabled{background:#9aa69f}.step-value{text-align:center}.step-value b{letter-spacing:-.03em;font-variant-numeric:tabular-nums;font-size:40px;font-weight:800}.step-value span{color:var(--muted);margin-left:3px;font-size:18px;font-weight:700}.step-value small{color:var(--muted);margin-top:1px;font-size:12px;display:block}.wish-actions{gap:8px;margin-top:10px;display:flex}.primary-button{color:#fff;background:var(--green);cursor:pointer;border:0;border-radius:10px;flex:1;min-height:46px;font-size:15px;font-weight:750}.primary-button:hover:not(:disabled){background:var(--ink)}.primary-button:disabled{color:var(--green);background:var(--green-soft);border:1px solid var(--mint)}.secondary-button{min-height:46px;color:var(--ink);border:1px solid var(--line-strong);cursor:pointer;background:#fff;border-radius:10px;align-items:center;gap:6px;padding:0 14px;font-size:14px;font-weight:700;display:inline-flex}.secondary-button:hover{background:var(--soft)}.my-wish{color:var(--blue);background:var(--blue-soft);border-radius:10px;align-items:flex-start;gap:8px;margin-top:10px;padding:9px 12px;font-size:13px;display:flex}.my-wish .icon{margin-top:2px}.my-wish b{color:var(--ink)}.my-wish small{color:var(--muted);margin-top:2px;font-size:12px;display:block}.wish-offline{color:var(--grey);align-items:center;gap:6px;margin-top:8px;font-size:13px;display:flex}.distribution{grid-template-columns:repeat(7,1fr);align-items:end;gap:6px;height:92px;margin-top:16px;display:grid}.bucket{flex-direction:column;justify-content:flex-end;align-items:center;height:100%;display:flex}.bucket i{background:#b4c3ba;border-radius:5px 5px 2px 2px;width:100%;min-height:3px;display:block}.bucket-count{color:var(--muted);margin-bottom:2px;font-size:12px;font-weight:700}.bucket-label{color:var(--muted);margin-top:4px;font-size:12px}.bucket.is-target i{background:var(--green)}.bucket.is-target .bucket-label,.bucket.is-target .bucket-count{color:var(--green);font-weight:800}.wish-summary{color:var(--muted);margin-top:10px;font-size:13px;line-height:1.45}.wish-summary b{color:var(--ink)}.fairness-note{border-top:1px solid var(--line);color:var(--muted);align-items:flex-start;gap:6px;margin-top:12px;padding-top:11px;font-size:12px;line-height:1.45;display:flex}.timeline{position:relative}.timeline:before{content:"";background:var(--line);width:2px;position:absolute;top:6px;bottom:8px;left:5px}.timeline-row{grid-template-columns:12px 1fr;gap:10px;padding-bottom:12px;display:grid;position:relative}.timeline-row:last-child{padding-bottom:0}.timeline-dot{z-index:1;background:var(--green-2);width:12px;height:12px;box-shadow:0 0 0 1px var(--line-strong);border:2px solid #fff;border-radius:50%;margin-top:4px}.timeline-dot.warning{background:var(--amber-2)}.timeline-dot.danger{background:var(--red-2)}.timeline-dot.info{background:var(--blue)}.timeline-dot.neutral{background:var(--grey)}.timeline-content>div{justify-content:space-between;gap:8px;font-size:14px;display:flex}.timeline-content time{color:var(--muted);font-variant-numeric:tabular-nums;font-size:12px}.timeline-content p{color:var(--muted);margin:3px 0 0;font-size:13px;line-height:1.4}.demo-panel{background:var(--surface);border:1px solid var(--line);box-shadow:var(--shadow);border-radius:16px;margin-top:16px;overflow:hidden}.demo-header{text-align:left;cursor:pointer;background:#fff;border:0;grid-template-columns:1fr auto auto;align-items:center;gap:15px;width:100%;padding:12px 18px;display:grid}.demo-title{align-items:center;gap:10px;display:flex}.demo-title>span:last-child{flex-direction:column;display:flex}.demo-title b{font-size:15px}.demo-title small{color:var(--muted);margin-top:2px;font-size:13px}.demo-spark{color:#fff;background:var(--green-2);border-radius:9px;place-items:center;width:32px;height:32px;display:grid}.demo-current{color:var(--green);background:var(--green-soft);border-radius:7px;padding:6px 10px;font-size:13px;font-weight:750}.chevron{color:var(--muted);transition:transform .2s}.chevron.up{transform:rotate(180deg)}.scenario-grid{border-top:1px solid var(--line);grid-template-columns:repeat(7,1fr);gap:8px;padding:12px 14px 14px;display:grid}.scenario-button{text-align:left;min-height:64px;color:var(--ink);background:var(--soft);border:1px solid var(--line);cursor:pointer;border-radius:10px;grid-template-columns:18px 1fr;gap:8px;padding:10px;display:grid}.scenario-button:hover{border-color:var(--green-2)}.scenario-button.active{background:var(--green-soft);border-color:var(--green);border-width:2px;padding:9px}.scenario-check{border:2px solid var(--line-strong);color:#fff;border-radius:50%;place-items:center;width:18px;height:18px;margin-top:1px;display:grid}.scenario-button.active .scenario-check{background:var(--green);border-color:var(--green)}.scenario-button b{font-size:13px;display:block}.scenario-button small{color:var(--muted);margin-top:3px;font-size:12px;line-height:1.35;display:block}footer{color:var(--muted);justify-content:space-between;align-items:flex-start;gap:16px;padding:16px 4px 0;font-size:12px;display:flex}footer>div:first-child{align-items:center;gap:5px;display:flex}.data-info{max-width:460px}.data-info summary{cursor:pointer;color:var(--green);text-underline-offset:3px;font-weight:700;text-decoration:underline}.data-info p{color:var(--ink);border:1px solid var(--line);background:#fff;border-radius:10px;margin:6px 0 0;padding:10px 12px;line-height:1.5}button:focus-visible,summary:focus-visible,a:focus-visible{outline-offset:2px;outline:3px solid #1f6feb}button:disabled{cursor:not-allowed}@media(prefers-reduced-motion:reduce){*,:before,:after{transition:none!important;animation:none!important}}@media(max-width:1180px){.scenario-grid{grid-template-columns:repeat(4,1fr)}.device-row{grid-template-columns:repeat(2,1fr)}}@media(max-width:1100px){.content-grid{grid-template-columns:1fr}.side-column{grid-template-columns:repeat(2,1fr);align-items:start;display:grid}.presentation-card{grid-row:span 2}}@media(max-width:760px){.topbar{grid-template-columns:1fr auto;height:auto;min-height:64px;padding:10px 16px}.live-status,.brand-subtitle{display:none}.role-option{padding:8px 12px}.page{padding:14px 14px 18px}.outside-chip,.greeting span{display:none}.status-banner{flex-wrap:wrap}.priority-chip{display:none}.measure-grid{grid-template-columns:repeat(2,1fr)}.side-column{display:flex}.room-wall{height:220px}.desk i{display:none}.scenario-grid{grid-template-columns:repeat(2,1fr)}.demo-current{display:none}.demo-header{grid-template-columns:1fr auto}footer{flex-direction:column}}@media(max-width:470px){.brand-name{font-size:15px}.brand-mark{width:34px;height:34px}.role-option{padding:8px 10px;font-size:13px}.student-banner{flex-wrap:wrap;align-items:flex-start}.countdown-small{width:100%;margin-left:44px}.screen{width:40%;left:30%}.desk,.blind-label{display:none}.metric-card{padding:12px}.metric-value{font-size:24px}.device-row,.scenario-grid{grid-template-columns:1fr}.demo-title small{display:none}}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false} \ No newline at end of file diff --git a/frontend/ambient/app.js b/frontend/ambient/app.js new file mode 100644 index 0000000..0cc941c --- /dev/null +++ b/frontend/ambient/app.js @@ -0,0 +1,525 @@ +// Webinterface Ambient² im Figma-Design v2 (frontend/figma/Ambient2_v2.html), angebunden an backend/server.js. +// Die Seite entscheidet nichts selbst: Sie zeigt, was GET /api/zustand liefert, und schickt Eingaben an +// dieselben Endpunkte wie der Unity-Zwilling. Kein Framework, kein Build-Schritt. +"use strict"; + +const ABFRAGE_MS = 1000; + +// Jeder Browser-Tab ist ein eigener Teilnehmer: sessionStorage gilt pro Tab, ein neuer Tab bekommt eine neue Kennung. +const CLIENT = (() => { + const neu = () => "tab-" + Math.random().toString(36).slice(2, 10); + try { + let id = sessionStorage.getItem("ambient-client"); + if (!id) { + id = neu(); + sessionStorage.setItem("ambient-client", id); + } + return id; + } catch { + return neu(); + } +})(); + +const ui = { + rolle: lies("ambient-rolle") || "dozent", + wunsch: null, // Wert im Stepper (noch nicht gesendet) + demoOffen: true, + datenOffen: false, + toast: "", + toastBis: 0, +}; +let zustand = null; +let verbunden = false; +let antwortZeit = 0; // Zeitpunkt der letzten Antwort (fuer Countdowns zwischen zwei Abfragen) +let letzterSchluessel = ""; +let zeigerUnten = false; // waehrend eines Klicks nicht neu zeichnen, sonst geht der Klick verloren + +function lies(schluessel) { + try { return sessionStorage.getItem(schluessel); } catch { return null; } +} +function merke(schluessel, wert) { + try { sessionStorage.setItem(schluessel, wert); } catch { /* privates Fenster: egal */ } +} + +// ---------------------------------------------------------------- Formatierung + +const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); +const zahl = (w, stellen = 1) => + w === null || w === undefined ? "–" : Number(w).toLocaleString("de-DE", { minimumFractionDigits: stellen, maximumFractionDigits: stellen }); +const uhr = (d) => new Date(d).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" }); +const mmss = (ms) => { + const s = Math.max(0, Math.round(ms / 1000)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +}; +const gruss = () => { + const h = new Date().getHours(); + return h < 11 ? "Guten Morgen" : h < 18 ? "Guten Tag" : "Guten Abend"; +}; +const QUELLE_TEXT = { sensor: "Arduino", wetter: "Wetter", demo: "Demo" }; +const quelle = (eingabe) => + eingabe && eingabe.quelle ? `${QUELLE_TEXT[eingabe.quelle] || esc(eingabe.quelle)}` : `kein Wert`; + +// Icons aus dem Figma-Export (Komponente "W") +const ICONS = { + air: '', + blinds: '', + check: '', + chevron: '', + clock: '', + energy: '', + history: '', + info: '', + lock: '', + people: '', + presentation: '', + shield: '', + spark: '', + temperature: '', + volume: '', + wind: '', + undo: '', + refresh: '', + offline: '', + minus: '', + plus: '', +}; +const icon = (name, size = 20) => + ``; + +// ---------------------------------------------------------------- Backend + +async function holen() { + try { + const r = await fetch(`/api/zustand?client=${encodeURIComponent(CLIENT)}`, { cache: "no-store" }); + if (!r.ok) throw new Error("HTTP " + r.status); + zustand = await r.json(); + verbunden = true; + antwortZeit = Date.now(); + } catch { + verbunden = false; + } + zeichne(); +} + +async function senden(pfad, daten, meldung) { + try { + const r = await fetch(pfad, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(daten) }); + const antwort = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(antwort.fehler || "HTTP " + r.status); + if (meldung) zeigeToast(meldung); + } catch (fehler) { + zeigeToast("Nicht gesendet: " + fehler.message); + } + await holen(); +} + +function zeigeToast(text) { + ui.toast = text; + ui.toastBis = Date.now() + 6000; + zeichne(true); +} + +// ---------------------------------------------------------------- Zeichnen + +/** Neu zeichnen nur, wenn sich Daten oder Bedienzustand geaendert haben (sonst gehen Klicks verloren). */ +function zeichne(erzwingen = false) { + if (zeigerUnten && !erzwingen) return ticke(); + if (ui.toast && Date.now() > ui.toastBis) ui.toast = ""; + const fluechtig = zustand + ? { ...zustand, jetzt: null, pruefung: { ...zustand.pruefung, restSekunden: null }, vortrag: { ...zustand.vortrag, restMs: null } } + : null; + const schluessel = JSON.stringify([fluechtig, ui, verbunden]); + if (erzwingen || schluessel !== letzterSchluessel) { + letzterSchluessel = schluessel; + document.getElementById("root").innerHTML = seite(); + } + ticke(); +} + +/** Uhrzeit und Countdowns jede Sekunde aktualisieren, ohne die Seite neu aufzubauen. */ +function ticke() { + const vergangen = Date.now() - antwortZeit; + document.querySelectorAll("[data-tick]").forEach((el) => { + const art = el.dataset.tick; + if (art === "uhr") el.textContent = uhr(Date.now()); + else if (art === "pruefung" && zustand) el.textContent = mmss(zustand.pruefung.restSekunden * 1000 - vergangen); + else if (art === "vortrag" && zustand) el.textContent = mmss(zustand.vortrag.restMs - vergangen); + }); +} + +function seite() { + if (!zustand) { + return `
${kopf(null)}
${verbindungsBanner()}
`; + } + const z = zustand; + const dozent = ui.rolle === "dozent"; + return `
+ + ${kopf(z)} +
+ ${kontext(z)} + ${verbunden ? banner(z) : verbindungsBanner()} + ${ui.toast ? `
${icon("check", 16)} ${esc(ui.toast)}
` : ""} +
+
${raumstatus(z)}${raumansicht(z)}
+ +
+ ${demos(z)} + ${fuss(z)} +
+
`; +} + +function kopf(z) { + const rolle = (name, text) => + ``; + let status; + if (!z || !verbunden) status = `
${icon("offline", 16)} Backend nicht erreichbar
`; + else if (z.szenario !== "live") status = `
Demo-Szenario
`; + else if (z.sensorOnline) status = `
Arduino verbunden
`; + else status = `
${icon("offline", 16)} Arduino nicht verbunden
`; + return `
+
${icon("wind", 22)}
+
KlimaCampus
Raum 2.14 · Gebäude West
+
${rolle("studierende", "Studierende")}${rolle("dozent", "Dozent")}
+ ${status} +
`; +} + +function kontext(z) { + const w = z.werte; + return `
+
${gruss()}, ${ui.rolle === "dozent" ? "Herr Weber" : "zusammen"}. + Seminarraum 2.14 · Raumklima wird automatisch und fair gesteuert
+
${icon("temperature", 17)}${zahl(w.aussenTemperatur.wert, 0)} °C außen + ${icon("wind", 17)}${zahl(w.wind.wert, 0)} km/h Wind
+
`; +} + +function verbindungsBanner() { + return `
+
${icon("offline", 24)}
+
Backend nicht erreichbar
+
Läuft node backend/server.js? Die Seite versucht es jede Sekunde erneut.
+
`; +} + +function banner(z) { + const e = z.entscheidung; + const offline = z.szenario === "offline"; + const ton = offline ? "neutral" : e.status.ton; + const symbol = offline ? "offline" : ton === "good" ? "check" : ton === "info" ? "presentation" : "info"; + const vortragTitel = z.vortrag.aktiv && !e.vetos.co2 && !e.vetos.wind && !offline; + const titel = offline ? "Sensor offline – sicherer Zustand" : vortragTitel ? `Vortragsmodus aktiv bis ${uhr(z.vortrag.ende)}` : e.status.titel; + const detail = offline ? "Es kommen keine aktuellen Messwerte. Die Automatik hält die letzten sicheren Einstellungen." : e.status.detail; + let rechts; + if (offline) rechts = ``; + else if (ui.rolle === "studierende" && z.vortrag.aktiv) + rechts = `
${icon("clock", 16)} noch
`; + else rechts = `
${icon(e.prioritaet.icon, 16)} Priorität ${e.prioritaet.nummer}: ${esc(e.prioritaet.text)}
`; + return `
+
${icon(symbol, 24)}
+
${esc(titel)}
${esc(detail)}
+ ${rechts} +
`; +} + +function raumstatus(z) { + const w = z.werte, e = z.entscheidung, g = z.grenzwerte; + const offline = z.szenario === "offline"; + const soll = e.zielTemperatur; + const ist = w.temperatur.wert; + const zustandText = (wert, normal) => (offline ? "Veraltet" : wert === null ? "Kein Wert" : normal); + + const co2 = w.eco2.wert; + const co2Hoch = co2 !== null && co2 > g.co2Ppm; + const abw = ist === null ? 0 : ist - soll; + const tempText = Math.abs(abw) <= 0.5 ? "Im Ziel" : abw > 0 ? "Über Soll" : "Unter Soll"; + const laerm = w.laerm.wert; + const laut = laerm !== null && laerm > g.laermDb; + const wind = w.wind.wert; + const sturm = wind !== null && wind > g.windKmh; + + const karte = (klasse, iconName, status, label, wert, einheit, balken, fuss, eingabe) => ` +
+
${icon(iconName)}${status}
+
${label}
+
${wert} ${einheit}
+ ${balken} +
${fuss}
+
`; + const balken = (breite, marke, neutral = false) => + `
`; + + const p = z.pruefung; + const geraet = (klasse, iconName, name, wert) => `
${icon(iconName, 18)}${name}${wert}
`; + const manuell = z.manuell; + const automatik = offline ? "Eingeschränkt" : manuell.aktiv ? `Manuell bis ${uhr(manuell.bis)}` : z.vortrag.aktiv ? "Vortragsmodus" : "Aktiv"; + const fensterText = e.fenster.text + (e.fenster.oeffnung > 0 ? ` · ${e.fenster.oeffnung} %` : ""); + const fensterKlasse = e.fenster.text === "Gesperrt" ? "locked" : manuell.fenster ? "manual" : ""; + + const s = z.letzterMesswert; + const chip = (name, eingabe, einheit, stellen = 0) => + `${name} ${zahl(eingabe.wert, stellen)}${eingabe.wert === null ? "" : " " + einheit} ${quelle(eingabe)}`; + + return `
+
+

Raumstatus

Messwerte und Gerätezustand in Raum 2.14
+
${ + offline ? `${icon("offline", 14)} Sensor offline · veraltet` + : z.sensorOnline ? ` Live · Uhr` + : `${icon("offline", 14)} Kein Arduino${s ? " · letzte Messung " + uhr(s.zeit) : ""}`}
+
+
+ ${icon("clock", 16)}Nächste Prüfung in + · alle ${p.abstandSekunden >= 60 ? zahl(p.abstandSekunden / 60, 0) + " min" : p.abstandSekunden + " s"}${p.letzteUhrzeit ? " · zuletzt " + esc(p.letzteUhrzeit) : ""} + + + Zeitraffer + ${[1, 5, 10].map((f) => ``).join("")} + +
+
+ ${karte(co2Hoch ? "metric-alert" : "", "air", zustandText(co2, co2Hoch ? "Zu hoch" : "Gut"), "Luft (CO₂)", co2 === null ? "–" : co2.toLocaleString("de-DE"), "ppm", + balken((co2 ?? 0) / 15, g.co2Ppm / 15), `${icon("lock", 13)} Grenzwert ${g.co2Ppm.toLocaleString("de-DE")} ppm`, w.eco2)} + ${karte(tempText !== "Im Ziel" ? "metric-warning" : "", "temperature", zustandText(ist, tempText), "Temperatur", zahl(ist), "°C Ist", + balken((((ist ?? 18) - 18) / 8) * 100, ((soll - 18) / 8) * 100, true), `Soll ${zahl(soll)} °C · ${g.zielMinC}–${g.zielMaxC} °C`, w.temperatur)} + ${karte(laut ? "metric-warning" : "", "volume", zustandText(laerm, laut ? "Außen laut" : "Ruhig"), "Außenlärm", zahl(laerm, 0), "dB", + balken(laerm ?? 0, g.laermDb), `${icon("shield", 13)} Ab ${g.laermDb} dB Fenster gesperrt`, w.laerm)} + ${karte(sturm ? "metric-warning" : "", "wind", zustandText(wind, sturm ? "Sturm" : "Leicht"), "Wind", zahl(wind, 0), "km/h", + balken(wind ?? 0, g.windKmh), `Feinstaub ${zahl(w.feinstaub.wert, 0)} µg/m³`, w.wind)} +
+
+ ${z.sensorOnline ? `Arduino live · ${uhr(s.zeit)}` : "Arduino nicht verbunden"} + ${chip("Luftfeuchte", w.luftfeuchte, "%")}${chip("TVOC", w.tvoc, "ppb")}${chip("Helligkeit", w.helligkeit, "%")} +
+
+ ${geraet(fensterKlasse, e.fenster.text === "Gesperrt" ? "lock" : "air", "Fenster", esc(fensterText))} + ${geraet(manuell.jalousie !== null ? "manual" : "", "blinds", "Jalousien", `${Math.round(e.jalousie)} % geschlossen${manuell.jalousie !== null ? " · manuell" : ""}`)} + ${geraet(offline ? "unknown" : manuell.aktiv ? "manual" : "", "spark", "Automatik", esc(automatik))} + ${geraet("", "people", "Sollwert", `${zahl(soll)} °C · ${z.stimmen.gesamt} Wünsche`)} +
+
+ ${geraet(manuell.lueftung ? "manual" : "", "air", "Lüftungsanlage", e.lueftung > 0 ? `An · ${Math.round(e.lueftung * 100)} %` : "Aus")} + ${geraet("", "temperature", "Heizung", e.heizung > 0 ? `${Math.round(e.heizung * 100)} %` : "Aus")} + ${geraet(manuell.licht !== null ? "manual" : "", "energy", "Licht", `${Math.round(e.licht * 100)} %`)} + ${geraet("", "presentation", "Beamer", e.beamer ? "An" : "Aus")} +
+
`; +} + +function raumansicht(z) { + const e = z.entscheidung; + const offen = e.fenster.oeffnung > 0; + const fenster = (seite) => `
+
+
`; + const fensterIcon = e.fenster.text === "Gesperrt" ? "lock" : "air"; + return `
+

Raumansicht

+
Visualisierung von Fenstern und Jalousien
+ +
`; +} + +function dozentensteuerung(z) { + const v = z.vortrag, m = z.manuell; + return `
+
${icon("presentation", 17)} Dozentensteuerung
+
+

Beamer-Modus

Beamer an, Licht aus, Jalousien schließen
+
${v.aktiv ? "An" : "Aus"} +
+
+
Dauer
+
+ ${[30, 60, 90].map((d) => ``).join("")} +
+ ${v.aktiv ? `
${icon("clock")}
+
Verbleibende Zeit
bis ${uhr(v.ende)}
` : ""} +
+
Jalousien manuell
Übersteuert die Automatik für 90 Min.
+
+ + +
+
+ ${m.aktiv ? `
${icon("clock", 15)} Automatik pausiert bis ${uhr(m.bis)} +
` : ""} +
${icon("shield", 17)}Schutzregeln bleiben aktiv. CO₂-Grenzwert und Sturm-Sperre können nicht überschrieben werden.
+
`; +} + +function wunschkarte(z) { + const e = z.entscheidung, g = z.grenzwerte, st = z.stimmen; + const eigene = st.eigene; + const eigenerWunsch = eigene ? eigene.temperaturWunsch : null; + const offline = z.szenario === "offline"; + if (ui.wunsch === null) ui.wunsch = eigenerWunsch ?? e.zielTemperatur ?? 22; + const wert = ui.wunsch; + const geaendert = eigenerWunsch === null || eigenerWunsch !== wert; + const knopf = eigenerWunsch === null ? "Wunsch senden" : geaendert ? "Wunsch aktualisieren" : "Wunsch gezählt ✓"; + const ausserhalb = wert < g.zielMinC || wert > g.zielMaxC; + + const grade = [19, 20, 21, 22, 23, 24, 25]; + const verteilung = st.verteilung || {}; + const max = Math.max(1, ...grade.map((d) => verteilung[d] || 0)); + const agg = e.aggregation.temperatur; + const fenster = st.fenster || { auf: 0, zu: 0 }; + const fensterWahl = eigene ? eigene.fenster : null; + + return `
+

Dein Temperaturwunsch

+
Ist ${zahl(z.werte.temperatur.wert)} °C · Soll ${zahl(e.zielTemperatur)} °C
${icon("temperature")}
+
+ +
${zahl(wert)}°C + ${ausserhalb ? `außerhalb ${g.zielMinC}–${g.zielMaxC} °C – wird begrenzt` : "in 0,5 °C-Schritten"}
+ +
+
+ + ${eigene ? `` : ""} +
+ ${eigenerWunsch !== null ? `
${icon("lock", 15)} Dein Wunsch: ${zahl(eigenerWunsch)} °C · gesendet ${uhr(eigene.zeit)} Uhr + Nur für dich sichtbar – nicht im gemeinsamen Verlauf.
` : ""} + ${offline ? `
${icon("offline", 15)} Senden ist möglich, sobald der Sensor wieder verbunden ist.
` : ""} +
+
Fenster öffnen? Auf ${fenster.auf} : Zu ${fenster.zu} – bei Außenlärm öffnet nur die Mehrheit
+
+ + +
+
+
+ ${grade.map((d) => `
${verteilung[d] || 0} + ${d === 19 ? "≤19" : d === 25 ? "≥25" : d}°
`).join("")} +
+
Sollwert ${zahl(e.zielTemperatur)} °C = Durchschnitt aus ${agg.gesamt} Wünschen${agg.begrenzt ? `, auf ${g.zielMinC}–${g.zielMaxC} °C begrenzt` : ""}.${ + agg.ausreisser ? " Einzelne Ausreißer verschieben den Wert nicht." : ""}${ + st.zielNachPruefung !== e.zielTemperatur ? ` Nach der nächsten Prüfung: ${zahl(st.zielNachPruefung)} °C (${st.gesamt} Wünsche).` : ""}
+
${icon("info", 16)} Anonym – gespeichert wird nur der Wert. Jeder Browser-Tab zählt als eigene Person + (Kennung ${esc(CLIENT.slice(4))}). Die Stimme des Dozenten zählt wie jede andere.
+
`; +} + +function verlauf(z) { + return `
+

Verlauf

+
Was das System getan hat – und warum. Keine einzelnen Wünsche.
${icon("history")}
+
${z.verlauf.slice(0, 4).map((v) => `
+
${esc(v.titel)}

${esc(v.grund)}

`).join("")}
+
`; +} + +function demos(z) { + const aktiv = z.szenarien.find((s) => s.id === z.szenario); + return `
+ + ${ui.demoOffen ? `
${z.szenarien.map((s) => ` + `).join("")}
` : ""} +
`; +} + +function fuss(z) { + return `
+
${icon("shield", 15)} Reihenfolge: Gesundheit → Kontext → Dozent/Mehrheit → Energie
+
Welche Daten werden erfasst? +

CO₂, TVOC, Temperatur, Luftfeuchte, Helligkeit und Lautstärke vom Arduino im Raum, Wind, Außentemperatur und Feinstaub vom Wetterdienst. + Lärm nur als Pegel in dB – keine Mikrofonaufnahmen, keine Kameras. Temperaturwünsche anonym, ohne Namen – deinen eigenen Wunsch siehst nur du, + im gemeinsamen Verlauf erscheinen nur Entscheidungen. Alles liegt nur im Arbeitsspeicher des Backends und ist nach einem Neustart weg; Wünsche verfallen nach 30 Minuten.

+
${z.sensorOnline ? "Arduino verbunden" : "Arduino nicht verbunden"} · Prüfung alle ${zahl(z.pruefung.intervallSekunden / 60, 0)} min
+
`; +} + +// ---------------------------------------------------------------- Bedienung + +document.getElementById("root").addEventListener("click", (ereignis) => { + const ziel = ereignis.target.closest("[data-action]"); + if (!ziel || ziel.disabled || !zustand) return; + const [aktion, wert] = ziel.dataset.action.split(":"); + const z = zustand; + switch (aktion) { + case "rolle": + ui.rolle = wert; + merke("ambient-rolle", wert); + zeichne(true); + break; + case "minus": + ui.wunsch = Math.max(z.grenzwerte.wunschMinC, ui.wunsch - 0.5); + zeichne(true); + break; + case "plus": + ui.wunsch = Math.min(z.grenzwerte.wunschMaxC, ui.wunsch + 0.5); + zeichne(true); + break; + case "senden": + senden("/api/stimme", { client: CLIENT, rolle: ui.rolle, temperaturWunsch: ui.wunsch }, + `Dein Wunsch von ${zahl(ui.wunsch)} °C wurde gezählt. Er wirkt bei der nächsten Prüfung.`); + break; + case "zurueck": + ui.wunsch = null; + senden("/api/stimme", { client: CLIENT, zuruecknehmen: true }, "Deine Stimme wurde zurückgezogen."); + break; + case "fenster": + senden("/api/stimme", { client: CLIENT, rolle: ui.rolle, fenster: wert }, `Fensterwunsch „${wert === "auf" ? "Auf" : "Zu"}“ gezählt.`); + break; + case "beamer": + senden("/api/vortragsmodus", { rolle: "dozent", aktiv: !z.vortrag.aktiv, dauerMinuten: z.vortrag.dauerMinuten }); + break; + case "dauer": + senden("/api/vortragsmodus", { rolle: "dozent", dauerMinuten: Number(wert) }); + break; + case "jalousie": + senden("/api/jalousie", { rolle: "dozent", position: Number(wert) }, Number(wert) ? "Jalousien manuell geschlossen." : "Jalousien manuell geöffnet."); + break; + case "automatik": + senden("/api/manuell", { rolle: "dozent", zuruecksetzen: true }, "Automatik fortgesetzt."); + break; + case "pruefen": + senden("/api/pruefen", {}, "Prüfung ausgeführt – Entscheidung ist aktuell."); + break; + case "raffer": + senden("/api/zeitraffer", { faktor: Number(wert) }, `Zeitraffer ${wert}×: Prüfung alle ${Math.round(z.pruefung.intervallSekunden / Number(wert))} s.`); + break; + case "demo": + ui.demoOffen = !ui.demoOffen; + zeichne(true); + break; + case "szenario": + senden("/api/szenario", { id: wert }); + break; + } +}); + +document.addEventListener("pointerdown", () => { zeigerUnten = true; }, true); +document.addEventListener("pointerup", () => { + zeigerUnten = false; + setTimeout(() => zeichne(), 0); // nach dem Klick-Ereignis nachholen +}, true); + +document.getElementById("root").addEventListener("toggle", (ereignis) => { + if (ereignis.target.dataset && ereignis.target.dataset.details === "daten") ui.datenOffen = ereignis.target.open; +}, true); + +holen(); +setInterval(holen, ABFRAGE_MS); +setInterval(ticke, 1000); diff --git a/frontend/ambient/ergaenzungen.css b/frontend/ambient/ergaenzungen.css new file mode 100644 index 0000000..430b79d --- /dev/null +++ b/frontend/ambient/ergaenzungen.css @@ -0,0 +1,44 @@ +/* Ergaenzungen zum Figma-Design (ambient.css bleibt unveraendert): + Pruefzyklus mit "Jetzt pruefen" und Zeitraffer, weitere Arduino-Werte, Fensterwunsch, Teilnehmerkennung. */ + +.loading { padding: 40px 0; color: var(--muted); font-size: 15px; } + +/* Pruefzyklus: Leiste unter der Kopfzeile des Raumstatus */ +.check-bar { + display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; + margin: 10px 0 2px; padding: 8px 10px; + border: 1px solid var(--line); border-radius: 11px; background: var(--soft); + font-size: 13px; color: var(--muted); +} +.check-bar b { color: var(--ink); font-variant-numeric: tabular-nums; } +.check-bar .spacer { flex: 1; } +.check-bar .icon-button { height: 34px; min-width: 0; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; } +.speed-group { display: inline-flex; gap: 4px; align-items: center; } +.speed-group .duration-button { min-height: 34px; padding: 4px 10px; font-size: 13px; } +.duration-button.active, .vote-row .duration-button.active { + color: #fff; background: var(--green); border-color: var(--green); +} + +/* Weitere Arduino-Werte (Luftfeuchte, TVOC, Helligkeit) und Herkunft */ +.sensor-strip { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } +.sensor-chip { + display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; + border: 1px solid var(--line); border-radius: 999px; background: #fff; + font-size: 13px; color: var(--muted); +} +.sensor-chip b { color: var(--ink); } +.sensor-chip.is-off { color: var(--grey, #6b7280); background: var(--soft); } +.source-tag { font-size: 11px; font-weight: 700; letter-spacing: .02em; color: var(--green-2); text-transform: uppercase; } +.source-tag.demo { color: var(--amber); } +.source-tag.wetter { color: var(--blue); } +.source-tag.fehlt { color: var(--grey, #6b7280); } + +/* zweite Geraetezeile: Lueftungsanlage, Heizung, Licht, Beamer */ +.device-row + .device-row { margin-top: 6px; } + +/* Fensterwunsch (Mehrheit oeffnet trotz Laerm) */ +.vote-row { margin-top: 12px; } +.vote-row .duration-group { grid-template-columns: repeat(2, 1fr); } +.vote-row .duration-button { min-height: 38px; } +.next-target { color: var(--blue); } +.client-id { font-variant-numeric: tabular-nums; } diff --git a/frontend/ambient/index.html b/frontend/ambient/index.html index 2f3ee5b..e199b0c 100644 --- a/frontend/ambient/index.html +++ b/frontend/ambient/index.html @@ -1,16853 +1,15 @@ - + Ambient² - - - - + + + + -
- +

Verbinde mit dem Backend …

+ + diff --git a/frontend/figma/Ambient2_v2.html b/frontend/figma/Ambient2_v2.html new file mode 100644 index 0000000..4d5c2af --- /dev/null +++ b/frontend/figma/Ambient2_v2.html @@ -0,0 +1,22 @@ + + + + + + Ambient² + + + + + +
+ +