diff --git a/README.md b/README.md index e052185..eb656c4 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ DHT11 + CCS811 ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Hand └──▶ Unity-Zwilling (SmartLectureRoom) ``` -Der Unity-Zwilling (eigenes Repo `SmartLectureRoom`) holt im Modus **Verbindung → Backend** jede Sekunde `GET /api/messwerte` ab. Temperatur und eCO₂ vom Arduino ersetzen dann die simulierten Werte, das passende Szenario (Hitze, stickige Luft, Wintermorgen …) wird erkannt und Fenster, Lüftung, Heizung, Jalousie und Licht werden automatisch angesteuert. Die Entscheidung meldet Unity per `POST /api/steuerung` zurück. Details: README im Unity-Projekt, Abschnitt „Arduino anbinden“. +Der Unity-Zwilling (eigenes Repo `SmartLectureRoom`) holt im Modus **Verbindung → Backend** jede Sekunde `GET /api/messwerte` ab. Alle Sensorwerte erscheinen dort live: Temperatur, eCO₂ und Helligkeit ersetzen die simulierten Werte, Luftfeuchte und TVOC werden angezeigt. Die Lautstärke zählt je nach Schalter „Mikrofon steht draußen“ als Lärm im Raum (Anzeige) oder als Außenlärm (über 70 dB wird die Fensteröffnung gesperrt). Dann wird das passende Szenario (Hitze, stickige Luft, Baustellenlärm, Wintermorgen …) erkannt und Fenster, Lüftung, Heizung, Jalousie und Licht werden automatisch angesteuert. Die Entscheidung meldet Unity per `POST /api/steuerung` zurück. Details: README im Unity-Projekt, Abschnitt „Arduino anbinden“. ## Repo-Struktur | Ordner | Inhalt | @@ -25,7 +25,7 @@ Der Unity-Zwilling (eigenes Repo `SmartLectureRoom`) holt im Modus **Verbindung | `frontend/` | Responsive Webinterface (Live-Werte, Präferenz-Slider) und 3D-Raum | ## 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 an `backend/server.py`; die Website (`frontend/`) zeigt sie live mit Verlauf und CO₂-Alarm. Der Unity-Zwilling ist an den Server angebunden (mit `simulator.py` vorbereitet, mit dem echten Arduino noch nicht getestet). Aggregation/Präferenzen im Backend fehlen noch (siehe [docs/offene-punkte.md](docs/offene-punkte.md)). +Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂, TVOC, Lautstärke und Helligkeit, zeigt sie auf dem LCD und sendet sie per ESP-01 an `backend/server.py`; die Website (`frontend/`) zeigt sie live mit Verlauf und CO₂-Alarm. Der Unity-Zwilling ist an den Server angebunden und zeigt alle Sensorwerte; Lautstärke und Helligkeit sind bisher nur mit `simulator.py` getestet. Aggregation/Präferenzen im Backend fehlen noch (siehe [docs/offene-punkte.md](docs/offene-punkte.md)). ## Komponenten und ihre Aufgabe @@ -35,7 +35,9 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e | **Arduino Uno** (Haupt-Uno) | Herz der Messstation: liest alle 2 s die Sensoren, zeigt die Werte auf dem LCD und gibt sie an den ESP weiter. | | **DHT11** | Misst **Temperatur** (°C) und **Luftfeuchte** (%). Langsam, braucht ca. 2 s zwischen zwei Messungen. | | **CCS811 / CJMCU-811** | Misst die Luftqualität: **eCO₂** (ppm) und **TVOC** (ppb, flüchtige organische Stoffe). eCO₂ ist ein aus den Gasen *geschätzter* CO₂-Wert, keine echte CO₂-Messung. Temperatur und Feuchte vom DHT11 bekommt er zur Korrektur. In den ersten ~20 min nach dem Einschalten oft 400 ppm / 0 ppb. | -| **LCD 16×2** | Zeigt die Werte direkt an der Station. Nur 2 Zeilen, daher Wechsel zwischen Temp/Luft und CO2/TVOC. Beim Start zeigt es den WLAN-Status („WLAN OK“ oder „Fehler E1“ …). | +| **Fotowiderstand (LDR)** | Misst die **Helligkeit** als relativen Wert (0–100 %, keine Lux). Wird auf dem LCD angezeigt und als `helligkeit` ans Backend gesendet (Unity rechnet grob 100 % ≈ 1000 lx). | +| **MAX9814 (Mikrofon)** | Misst die **Lautstärke** in dB (steht derzeit im Raum, soll später nach draußen; in Unity per Schalter „Mikrofon steht draußen“ umstellbar). Der Uno wertet dafür 2 s lang den Ausschlag des Mikrofonsignals aus (Mittelwert über 50-ms-Fenster). Nur ein Näherungswert: Die automatische Verstärkungsregelung des Moduls dämpft laute Geräusche (ab ca. 70 dB). Abgleich über `LAUT_DB_OFFSET` im Sketch, z. B. mit einer Schallpegel-App. | +| **LCD 16×2** | Zeigt die Werte direkt an der Station. Nur 2 Zeilen, daher Wechsel zwischen Temp/Luft, CO2/TVOC und Licht/Lautstärke. Beim Start zeigt es den WLAN-Status („WLAN OK“ oder „Fehler E1“ …). | | **Potentiometer** | Stellt den Kontrast des LCD ein. | | **ESP-01 (ESP8266)** | WLAN-Modul, da der Uno selbst kein WLAN hat. Der Uno schickt ihm Textbefehle („AT-Befehle“), der ESP verbindet sich mit dem Hotspot und schickt die Werte an den Laptop. | | **Zweiter Uno** | Liefert dem ESP nur Strom (3,3 V), weil der Haupt-Uno zu wenig Strom für den ESP hat. Braucht **gemeinsame Masse** (GND) mit dem Haupt-Uno. | @@ -51,13 +53,13 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e | `backend/server.py` | **Server** auf dem Laptop (Port 3000): nimmt die Messwerte vom ESP an, merkt sich die letzten 100, liefert die Website aus und stellt die Werte dem Unity-Zwilling bereit (dessen Steuerbefehle kommen per `POST /api/steuerung` zurück). | | `backend/start.bat` | Startet den Server per Doppelklick und prüft, ob die Laptop-IP zu `wifi_config.h` passt. | | `backend/firewall_freigeben.bat` | Gibt Port 3000 in der Windows-Firewall frei, damit der ESP den Laptop erreicht. | -| `backend/simulator.py` | Schickt erfundene Werte – zum Testen ohne Arduino. Mit `--szenario hitze/stickig/kalt/normal/demo` gezielt Szenarien für den Unity-Zwilling auslösen. | +| `backend/simulator.py` | Schickt erfundene Werte – zum Testen ohne Arduino. Mit `--szenario hitze/stickig/kalt/laerm/dunkel/normal/demo` gezielt Szenarien für den Unity-Zwilling auslösen. | | `frontend/` | **Website**: fragt alle 2 s beim Server die neuesten Werte ab und zeigt Kacheln, Verlaufsdiagramm und CO₂-Alarm ab 1000 ppm. | | `firmware/esp_test`, `firmware/ccs811_test`, `firmware/ccs811_diagnose` | Testprogramme zur Fehlersuche, im normalen Betrieb nicht nötig. | ### Ablauf einer Messung -1. Der **Uno** liest **DHT11** und **CCS811** aus und zeigt die Werte auf dem **LCD**. -2. Etwa alle 4 s schickt er sie über Pin 0/1 an den **ESP-01**. +1. Der **Uno** liest **DHT11**, **CCS811** und **MAX9814** aus und zeigt die Werte auf dem **LCD**. +2. Etwa alle 7–8 s schickt er DHT11-, CCS811-, Lautstärke- und Helligkeitswerte über Pin 0/1 an den **ESP-01**. 3. Der ESP sendet sie über den **Hotspot** an den **Laptop** (`server.py`, Port 3000). 4. Der **Browser** fragt den Server alle 2 s nach den neuesten Werten und zeigt sie auf der Website. @@ -67,6 +69,8 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e | DHT11 | Daten → Pin 2 | | LCD 16×2 | RS 7, E 8, D4–D7 → 9–12, RW → GND, V0 → Poti | | CCS811 (CJMCU-811) | VCC → 3,3 V, GND, SDA → A4, SCL → A5, WAK → GND, ADD → GND (Adresse 0x5A) | +| LDR | Ein Bein → 5 V, anderes Bein → A0 und über 10 kΩ → GND | +| MAX9814 (Mikrofon) | VDD → 5 V, GND → GND, OUT → A1; Gain und AR offen (60 dB Verstärkung) | | ESP-01 | **TX → Pin 0, RX → Pin 1 (gekreuzt!)**, VCC + EN → 3,3 V, GND; RST, GPIO0, GPIO2 frei | 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. diff --git a/backend/README.md b/backend/README.md index 013bd08..506c2aa 100644 --- a/backend/README.md +++ b/backend/README.md @@ -15,7 +15,7 @@ python backend/server.py # Port 3000 (oder: python backend/server.py 80 python backend/simulator.py # optional: Fake-Sensordaten ohne Hardware python backend/simulator.py --szenario demo # Szenarien nacheinander: normal, stickig, normal, hitze, kalt ``` -Szenarien des Simulators: `wechsel` (Standard, Werte schwanken), `normal`, `hitze` (→ ca. 30 °C), `stickig` (→ ca. 1600 ppm), `kalt` (→ ca. 17 °C), `demo`. Die Werte ändern sich langsam wie in echt, damit man im Unity-Zwilling sieht, wann die Steuerung umschaltet. +Szenarien des Simulators: `wechsel` (Standard, Werte schwanken), `normal`, `hitze` (→ ca. 30 °C), `stickig` (→ ca. 1600 ppm), `kalt` (→ ca. 17 °C), `laerm` (CO₂ hoch, ca. 80 dB), `dunkel` (Helligkeit → ca. 10 %), `demo` (alles nacheinander). Die Werte ändern sich langsam wie in echt, damit man im Unity-Zwilling sieht, wann die Steuerung umschaltet. Frontend: http://localhost:3000, im Hotspot von anderen Geräten: `http://:3000` Beim Start zeigt der Server die IP-Adressen des Laptops und prüft, ob `SERVER_IP` in `firmware/dht11_lcd/wifi_config.h` dazu passt („OK“ bzw. „ACHTUNG“). Jeder empfangene Messwert erscheint mit Absender-IP im Fenster (`127.0.0.1` = Simulator, `172.20.10.x` = ESP im Hotspot). @@ -27,7 +27,7 @@ Windows stuft den Handy-Hotspot meist als „öffentliches Netz“ ein und block `POST /api/messwerte`, `Content-Type: application/json`, reines HTTP (kein TLS): ```json -{"temperatur": 22.5, "luftfeuchte": 45.0, "eco2": 612, "tvoc": 30} +{"temperatur": 22.5, "luftfeuchte": 45.0, "eco2": 612, "tvoc": 30, "lautstaerke": 48.5, "helligkeit": 60} ``` | Feld | Einheit | Quelle | @@ -36,6 +36,8 @@ Windows stuft den Handy-Hotspot meist als „öffentliches Netz“ ein und block | `luftfeuchte` | % | DHT11 | | `eco2` | ppm | CCS811 | | `tvoc` | ppb | CCS811 | +| `lautstaerke` | dB | MAX9814 (Näherungswert) | +| `helligkeit` | % (relativ) | Fotowiderstand an A0 | Alle Felder sind Zahlen; ein Feld darf fehlen oder `null` sein (z. B. CCS811 noch nicht bereit). Den Zeitstempel setzt der Server beim Empfang. diff --git a/backend/server.py b/backend/server.py index 958bc02..20698a7 100644 --- a/backend/server.py +++ b/backend/server.py @@ -19,9 +19,9 @@ MAX_VERLAUF = 100 MAX_BODY_BYTES = 1024 # Erlaubte Felder des Datenvertrags (so sendet esp_wifi.h) -FELDER = ["temperatur", "luftfeuchte", "eco2", "tvoc"] +FELDER = ["temperatur", "luftfeuchte", "eco2", "tvoc", "lautstaerke", "helligkeit"] -verlauf = deque(maxlen=MAX_VERLAUF) # { zeit: ISO-String, temperatur, luftfeuchte, eco2, tvoc } +verlauf = deque(maxlen=MAX_VERLAUF) # { zeit: ISO-String, temperatur, luftfeuchte, eco2, tvoc, lautstaerke, helligkeit } # Steuerbefehle des Unity-Zwillings, z. B. {"window":"open","blind":1.0,"heat":0,"vent":0,"light":0.4,"beamer":0,"szenario":"Hitze"} STEUER_TEXTFELDER = {"window", "szenario"} diff --git a/backend/simulator.py b/backend/simulator.py index 885f1be..0e8dec0 100644 --- a/backend/simulator.py +++ b/backend/simulator.py @@ -3,11 +3,13 @@ # # Szenarien (fuer die Vorfuehrung mit dem Unity-Zwilling, Modus "Backend"): # 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 -> Unity oeffnet die Fenster # stickig CO2 steigt langsam auf ca. 1600 ppm -> Unity lueftet (Fenster oder Lueftungsanlage) # kalt Temperatur faellt auf ca. 17 °C -> Unity heizt -# demo laeuft nacheinander normal -> stickig -> normal -> hitze -> kalt durch (je ca. 1 min) +# laerm CO2 hoch und Lautstaerke ca. 80 dB -> mit "Mikrofon draussen" sperrt Unity die Fenster +# dunkel Helligkeit faellt auf ca. 10 % -> Unity schaltet das Licht hoch +# 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,26 +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(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/firmware/dht11_lcd/dht11_lcd.ino b/firmware/dht11_lcd/dht11_lcd.ino index e7c36fe..15d8424 100644 --- a/firmware/dht11_lcd/dht11_lcd.ino +++ b/firmware/dht11_lcd/dht11_lcd.ino @@ -21,6 +21,52 @@ DHT dht(DHTPIN, DHTTYPE); Adafruit_CCS811 ccs; bool ccsOk = false; +// --- Fotowiderstand (LDR) Setup --- +// Spannungsteiler: 5V -> LDR -> A0 -> 10 kOhm -> GND. Heller = höherer Wert. +#define LDR_PIN A0 + +// Helligkeit in Prozent des Messbereichs (relativer Wert, keine Lux) +int lichtProzent() { + return map(analogRead(LDR_PIN), 0, 1023, 0, 100); +} + +// --- MAX9814 Mikrofon Setup --- +// VDD -> 5 V, GND -> GND, OUT -> A1. Gain offen = 60 dB Verstärkung, AR offen. +// Der Ausgang schwingt um ca. 1,25 V, lauter = größerer Ausschlag (max. ca. 2 V Spitze-Spitze). +#define MIKROFON_PIN A1 +const unsigned long LAUT_FENSTER_MS = 50; // ein Messfenster, lang genug für Töne ab 20 Hz + +// Umrechnung Spitze-Spitze-Spannung -> Schalldruckpegel: dB = 20 * log10(Vpp) + LAUT_DB_OFFSET. +// 69 dB folgen aus Mikrofon-Empfindlichkeit (-44 dBV/Pa) und 60 dB Verstärkung (94 dB SPL ~ 17,8 Vpp). +// Nur ein Näherungswert: Die automatische Verstärkungsregelung (AGC) des MAX9814 dämpft laute +// Geräusche (ab ca. 70 dB), dort zeigt der Sensor zu wenig an. Zum Abgleich neben eine +// Schallpegel-App halten und die Differenz hier addieren. +const float LAUT_DB_OFFSET = 69.0; +float lautstaerkeDb = NAN; + +// Misst dauerMs lang die Lautstärke in 50-ms-Fenstern und liefert den energetischen +// Mittelwert in dB (wie ein Schallpegelmesser, kurze Knackser zählen nicht übermäßig). +// Ersetzt zugleich die Pause, die der DHT11 zwischen zwei Messungen braucht. +float lautstaerkeMessen(unsigned long dauerMs) { + float summeQuadrate = 0; + uint16_t fenster = 0; + unsigned long start = millis(); + while (millis() - start < dauerMs) { + int minimum = 1023; + int maximum = 0; + unsigned long fensterStart = millis(); + while (millis() - fensterStart < LAUT_FENSTER_MS) { + int wert = analogRead(MIKROFON_PIN); + if (wert < minimum) minimum = wert; + if (wert > maximum) maximum = wert; + } + float vpp = max(maximum - minimum, 1) * 5.0 / 1023.0; // mind. 1 ADC-Schritt, sonst log10(0) + summeQuadrate += vpp * vpp; + fenster++; + } + return 10.0 * log10(summeQuadrate / fenster) + LAUT_DB_OFFSET; +} + // --- CCS811-Baseline im EEPROM --- // Die Baseline ist der Kalibrierwert des Sensors. Wird sie nach einem Neustart // wieder gesetzt, ist der eCO2/TVOC-Wert sofort deutlich stabiler. @@ -70,8 +116,9 @@ void ccsStarten() { } } -// Anzeige wechselt zwischen zwei Seiten, da das LCD nur 2 Zeilen hat -bool zeigeLuftqualitaet = false; +// Anzeige wechselt zwischen drei Seiten, da das LCD nur 2 Zeilen hat +enum Seite { SEITE_KLIMA, SEITE_LUFTQUALITAET, SEITE_LICHT_LAUTSTAERKE }; +uint8_t seite = SEITE_KLIMA; void setup() { // Serial gehoert dem ESP8266 (wird in wifiVerbinden() gestartet), kein Serial-Monitor moeglich @@ -110,7 +157,8 @@ void setup() { void loop() { // WICHTIG: Der DHT11 ist ein langsamer Sensor. // Er benötigt ca. 2 Sekunden Pause zwischen den Messungen. - delay(2000); + // Diese Zeit wird zum Messen der Lautstärke genutzt. + lautstaerkeDb = lautstaerkeMessen(2000); // Werte für Luftfeuchtigkeit und Temperatur auslesen float h = dht.readHumidity(); @@ -124,9 +172,26 @@ void loop() { return; // Loop hier abbrechen und von vorne starten } + // --- Seite 3: Helligkeit (LDR) und Lautstärke (MAX9814) --- + if (seite == SEITE_LICHT_LAUTSTAERKE) { + seite = SEITE_KLIMA; + + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Licht: "); + lcd.print(lichtProzent()); + lcd.print(" %"); + + lcd.setCursor(0, 1); + lcd.print("Laerm: "); + lcd.print(lautstaerkeDb, 1); + lcd.print(" dB"); + return; + } + // --- Seite 2: CO2 und TVOC vom CCS811 --- - if (zeigeLuftqualitaet) { - zeigeLuftqualitaet = false; + if (seite == SEITE_LUFTQUALITAET) { + seite = SEITE_LICHT_LAUTSTAERKE; lcd.clear(); if (!ccsOk) { @@ -153,7 +218,7 @@ void loop() { lcd.print(" ppb"); // Vollständigen Messwertsatz ans Backend schicken (blockiert ca. 1-2 s) - sendeMesswerte(t, h, ccs.geteCO2(), ccs.getTVOC()); + sendeMesswerte(t, h, ccs.geteCO2(), ccs.getTVOC(), lautstaerkeDb, lichtProzent()); // Baseline regelmäßig sichern (Vergleich überlaufsicher für millis()) if ((long)(millis() - naechsteBaselineSicherung) >= 0) { @@ -168,7 +233,7 @@ void loop() { } // --- Seite 1: Ausgabe auf dem LCD Display --- - zeigeLuftqualitaet = true; + seite = SEITE_LUFTQUALITAET; // Zeile 1: Temperatur lcd.setCursor(0, 0); // Spalte 0, Zeile 0 diff --git a/firmware/dht11_lcd/esp_wifi.h b/firmware/dht11_lcd/esp_wifi.h index 5dea8f4..04b5b78 100644 --- a/firmware/dht11_lcd/esp_wifi.h +++ b/firmware/dht11_lcd/esp_wifi.h @@ -101,23 +101,25 @@ bool wifiVerbinden() { } // Schickt einen Messwertsatz per HTTP-POST an das Backend. true, wenn der Server mit 200 antwortet. -bool sendeMesswerte(float temperatur, float luftfeuchte, uint16_t eco2, uint16_t tvoc) { +bool sendeMesswerte(float temperatur, float luftfeuchte, uint16_t eco2, uint16_t tvoc, float lautstaerke, int helligkeit) { if (!wifiOk) { if (millis() - letzterWifiVersuch < WIFI_NEUVERSUCH_MS || !wifiVerbinden()) { return false; } } - char temp[8], feuchte[8]; + char temp[8], feuchte[8], laut[8]; dtostrf(temperatur, 1, 1, temp); dtostrf(luftfeuchte, 1, 1, feuchte); + dtostrf(lautstaerke, 1, 1, laut); - char body[72]; + // laengster Body ca. 103 Zeichen, z. B. {"temperatur":-12.3,...,"lautstaerke":123.4,"helligkeit":100} + char body[120]; snprintf_P(body, sizeof(body), - PSTR("{\"temperatur\":%s,\"luftfeuchte\":%s,\"eco2\":%u,\"tvoc\":%u}"), - temp, feuchte, eco2, tvoc); + PSTR("{\"temperatur\":%s,\"luftfeuchte\":%s,\"eco2\":%u,\"tvoc\":%u,\"lautstaerke\":%s,\"helligkeit\":%d}"), + temp, feuchte, eco2, tvoc, laut, helligkeit); - char anfrage[200]; + char anfrage[260]; int laenge = snprintf_P(anfrage, sizeof(anfrage), PSTR("POST /api/messwerte HTTP/1.1\r\nHost: %s:%u\r\n" "Content-Type: application/json\r\nContent-Length: %u\r\n" 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 3f37fc8..5c3c85f 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs @@ -30,6 +30,7 @@ namespace SmartRoom [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 – zulässiger Bereich für Temperaturwünsche (Ausreißer werden begrenzt)")] public float wishMin = 18f, wishMax = 26f; } /// Ergebnis eines Prüfzyklus inkl. durchlaufenem Pfad im Aktivitätsdiagramm. @@ -38,6 +39,7 @@ 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(); } @@ -70,21 +72,46 @@ namespace SmartRoom public event Action Decided; double nextCheckAt = double.NegativeInfinity; - bool wasCritical, wasRunning = true; + bool wasCritical, wasRunning = true, wasMeasured; + string lastScenario; + + public const string NormalScenario = "Normalbetrieb"; + + /// Aktuell 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)); + /// Ø aller Temperaturwünsche; jeder Wunsch wird vorher auf den zulässigen Bereich begrenzt. 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 zulässigen Bereichs. + public int ClampedWishes => wishes.FindAll(w => w.temperature < limits.wishMin || w.temperature > limits.wishMax).Count; + + // Manuelle Jalousiesteuerung pausiert die Jalousie-Automatik für eine Weile (Schutzregeln bleiben aktiv) + 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); + } + public int WindowVotes => wishes.FindAll(w => w.windowOpen).Count; public bool WindowWanted => wishes.Count > 0 && WindowVotes * 2 > wishes.Count; @@ -101,10 +128,37 @@ namespace SmartRoom if (!wasRunning) nextCheckAt = double.NegativeInfinity; // Vorlesung beginnt -> sofort prüfen wasRunning = true; + // Szenarien werden aus den Messwerten erkannt: Kommt ein neues Szenario hinzu (z. B. Arduino meldet + // CO2 > 1000 ppm) oder liefert der Arduino erstmals Werte, wird sofort geprüft statt erst nach 10 min. + Scenario = DetectScenario(); bool critical = env.co2 > limits.co2Limit || env.indoorTemp > limits.tempHigh || env.indoorTemp < limits.tempLow; - if (env.simMinutes >= nextCheckAt || (reactImmediately && critical && !wasCritical)) + bool newScenario = Scenario != lastScenario && Scenario != NormalScenario; + bool measured = env.AnyMeasured; + if (env.simMinutes >= nextCheckAt || + (reactImmediately && ((critical && !wasCritical) || newScenario || (measured && !wasMeasured)))) RunCycle(); wasCritical = critical; + wasMeasured = measured; + lastScenario = Scenario; + } + + /// + /// Ordnet die aktuellen Werte einem Szenario zu. Reihenfolge = Priorität (Lüftungsbedarf zuerst, dann Temperatur, dann Sonne). + /// + public string DetectScenario() + { + var L = limits; + bool co2High = env.co2 > L.co2Limit; + bool ventNeeded = co2High || env.indoorTemp > L.tempHigh; + 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 > L.tempHigh) return "Hitze"; + if (env.indoorTemp < L.tempLow) return "Wintermorgen"; + if (env.solar > L.sunLimit) return "Pralle Sonne"; + return NormalScenario; } /// Einen kompletten Prüfzyklus ausführen (auch per HUD "Jetzt prüfen"). @@ -126,14 +180,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 avgWish = AverageWish; 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: Ø {avgWish:0.0} °C, Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})"); + if (ClampedWishes > 0) + p.Add($"Temperaturwunsch begrenzt: {ClampedWishes} Wunsch außerhalb {limits.wishMin:0}–{limits.wishMax:0} °C"); // --- CO2 / Temperatur bool ventilationNeeded = false, heat = false; @@ -228,7 +285,12 @@ namespace SmartRoom : $"Fensterzustand {current.Label()} ≠ Soll {d.window.Label()} → anpassen"); // --- Sonne / Jalousie - if (env.solar > L.sunLimit) + if (BlindOverrideActive) + { + d.blinds = blindOverride; + p.Add($"Jalousien manuell auf {blindOverride * 100:0} % (Automatik pausiert, noch {BlindOverrideMinutesLeft:0} min)"); + } + else if (env.solar > L.sunLimit) { d.blinds = 1f; p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Jalousie nach unten"); @@ -245,13 +307,26 @@ namespace SmartRoom } // --- Licht (Erweiterung: Tageslicht ergänzen) - float daylight = env.DaylightLux(d.blinds); + // Mit Lichtsensor: gemessene Helligkeit minus eigenes Kunstlicht = Tageslicht, sonst Schätzung aus Sonne + Jalousie + bool luxMeasured = env.IsMeasured("lux"); + float daylight = luxMeasured ? Mathf.Max(0f, env.indoorLux - devices.LightLevel * 520f) : env.DaylightLux(d.blinds); d.lights = Mathf.Clamp01((L.targetLux - daylight) / 520f); if (devices.BeamerOn) d.lights = Mathf.Min(d.lights, 0.3f); - p.Add($"Tageslicht ≈ {daylight:0} lx → Licht {d.lights * 100:0} %{(devices.BeamerOn ? " (gedimmt für Beamer)" : "")}"); + p.Add($"Tageslicht ≈ {daylight:0} lx{(luxMeasured ? " (Lichtsensor)" : "")} → Licht {d.lights * 100:0} %{(devices.BeamerOn ? " (gedimmt für Beamer)" : "")}"); 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("lux")) 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); + } + public void Apply(Decision d) { devices.SetWindows(d.window); diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs index c7f470b..bd30cdf 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/ArduinoBridge.cs @@ -4,10 +4,13 @@ #endif using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Net; using System.Net.Sockets; using System.Text; +using System.Text.RegularExpressions; using System.Threading; using UnityEngine; #if SMARTROOM_SERIAL @@ -33,25 +36,46 @@ 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) } - public enum LinkMode { Simulation, Serial, Udp } + /// + /// Backend = GruppeC-Aufbau: Arduino Uno + ESP-01 schicken per HTTP-POST an backend/server.py, + /// Unity holt die Werte dort per GET /api/messwerte ab. + /// + 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. + /// oder fragt sie beim Backend (ESP-01 → server.py) ab und sendet die Steuerbefehle der virtuellen Aktoren zurück. /// public class ArduinoBridge : MonoBehaviour { - public LinkMode mode = LinkMode.Simulation; + [Tooltip("Backend = Werte vom Arduino über backend/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"; public int baudRate = 115200; public int udpListenPort = 5005; [Tooltip("Port, an den Steuerbefehle an den Absender zurückgeschickt werden")] public int udpReplyPort = 5006; + [Tooltip("Adresse von backend/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; @@ -62,6 +86,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 @@ -81,6 +116,11 @@ namespace SmartRoom UdpClient udp; IPEndPoint remote; float nextSend; + string pendingCommand; // vom Hauptthread gesetzt, vom Backend-Thread per POST verschickt + string lastBackendTime; + const string HttpPrefix = "!HTTP "; + 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 @@ -108,6 +148,7 @@ namespace SmartRoom { case LinkMode.Serial: OpenSerial(); break; case LinkMode.Udp: OpenUdp(); break; + case LinkMode.Backend: OpenBackend(); break; default: Status = "Simulation aktiv"; break; } } @@ -137,6 +178,14 @@ namespace SmartRoom Status = $"Lausche auf UDP-Port {udpListenPort}"; } + void OpenBackend() + { + lastBackendTime = null; + pendingCommand = null; + StartWorker(BackendLoop); + Status = "Frage " + backendUrl + " ab …"; + } + void StartWorker(ThreadStart loop) { running = true; @@ -204,6 +253,111 @@ namespace SmartRoom } } + // ---------------------------------------------------------------- Backend (HTTP) + void BackendLoop() + { + string baseUrl = backendUrl.Trim().TrimEnd('/'); + while (running) + { + try + { + string body = Http("GET", baseUrl + "/api/messwerte", null); + if (running) inbox.Enqueue(HttpPrefix + body); + } + catch (Exception ex) + { + if (running) inbox.Enqueue("!ERR Backend nicht erreichbar (" + ex.Message + ") – läuft backend/server.py?"); + } + + string cmd = Interlocked.Exchange(ref pendingCommand, null); + if (cmd != null) + { + try { Http("POST", baseUrl + "/api/steuerung", cmd); } + catch (Exception ex) { if (running) inbox.Enqueue("!ERR Steuerbefehl nicht angenommen: " + ex.Message); } + } + + // in kleinen Schritten schlafen, damit "Trennen" sofort greift + for (int ms = 0; running && ms < backendPollSeconds * 1000f; ms += 50) Thread.Sleep(50); + } + } + + static string Http(string method, string url, string body) + { + var req = (HttpWebRequest)WebRequest.Create(url); + req.Method = method; + req.Timeout = 3000; + req.ReadWriteTimeout = 3000; + req.Proxy = null; + if (body != null) + { + byte[] bytes = Encoding.UTF8.GetBytes(body); + req.ContentType = "application/json"; + req.ContentLength = bytes.Length; + using (var s = req.GetRequestStream()) s.Write(bytes, 0, bytes.Length); + } + using (var res = (HttpWebResponse)req.GetResponse()) + using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) + return reader.ReadToEnd(); + } + + /// + /// 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) + { + 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; + env.ApplyMeasurement(p); + LastPacketTime = Time.unscaledTime; + PacketCount++; + 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)) @@ -213,6 +367,11 @@ namespace SmartRoom Status = "Verbindungsfehler: " + line.Substring(4).Trim(); continue; } + if (line.StartsWith(HttpPrefix)) + { + ApplyBackend(line.Substring(HttpPrefix.Length)); + continue; + } LastLine = line; if (!line.StartsWith("{")) continue; // Debug-Ausgaben des Arduino ignorieren try @@ -251,6 +410,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(); } @@ -263,6 +425,7 @@ namespace SmartRoom #if SMARTROOM_SERIAL if (mode == LinkMode.Serial && port != null && port.IsOpen) port.WriteLine(json); #endif + if (mode == LinkMode.Backend) Interlocked.Exchange(ref pendingCommand, json); if (mode == LinkMode.Udp && udp != null) { IPEndPoint target; 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/RoomEnvironment.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Simulation/RoomEnvironment.cs index cab5991..525b39c 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,7 +42,7 @@ 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; @@ -77,8 +83,14 @@ 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); } + /// Kanal sofort wieder simulieren (z. B. wenn das Mikrofon von innen nach außen wechselt). + public void Forget(string channel) => measuredAt.Remove(channel); + void Set(string channel, float v, Action apply) { if (float.IsNaN(v)) return; diff --git a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs index 242553e..834a6cf 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/SmartRoomApp.cs @@ -10,11 +10,14 @@ 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; @@ -30,9 +33,17 @@ namespace SmartRoom var controller = GetOrAdd(); controller.env = env; controller.devices = Devices; + bridge.scenarioProvider = () => controller.Scenario; 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; @@ -45,9 +56,32 @@ namespace SmartRoom 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..4bee84b --- /dev/null +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/AmbientHUD.cs @@ -0,0 +1,1114 @@ +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; public Tone tone; public int priority; } + + 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; + // 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 => Mathf.Clamp(controller.AverageWish, 18f, 26f); + + BannerState Banner() + { + 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) && !V(RefW - 300f, 10f, 276f, 40f).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: SetBeamer(!devices.BeamerOn); break; + 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; + + // Status rechts → Einstellungen + bool live = env.AnyMeasured; + string status = !env.lectureRunning ? "Energiesparmodus" : live ? "Arduino live" : bridge != null && bridge.Connected ? "Warte auf Arduino" : "System aktiv"; + float w = TextWidth(status, 12, false) + 52f; + var pill = V(RefW - 24 - w, 16, w, 28); + if (settingsOpen || Hover(pill)) Box(pill, Soft, 8, Line); + Box(V(VX(pill) + 10, 26.5f, 8, 8), env.lectureRunning ? Green2 : Muted, 4); + Text(V(VX(pill) + 24, 16, w - 24, 28), status + " ≡", 12, Ink); + if (Click(pill)) settingsOpen = !settingsOpen; + } + + // ---------------------------------------------------------------- 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}: {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; + if (env.AnyMeasured) + { + right = $"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 right = env.lectureRunning ? $"Simulation · nächste Prüfung in {controller.MinutesUntilNextCheck:0} min" : "Simulation"; + 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; + string blinds = $"Jalousien: {devices.BlindPosition * 100f:0} %" + (controller.BlindOverrideActive ? " · 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 <= L.noiseLimit ? ("Mäßig", ToneAmber) : ("Außen laut", ToneAmber), + noise > L.noiseLimit ? "Fensteröffnung gesperrt" : "Öffnung wird ggf. begrenzt"); + Metric(24 + 3 * (w + 12), y, w, "≋", "Wind", false, N(kmh, 0), "km/h", Mathf.InverseLerp(0f, 70f, kmh), + kmh <= 20f ? ("Leicht", ToneGreen) : env.windSpeed <= L.windLimit ? ("Mäßig", ToneAmber) : ("Stark", ToneRed), + $"Außenluft AQI {env.outdoorAqi:0} · {N(env.outdoorTemp, 0)} °C"); + } + + 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); + + 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(); + } + } + } + + // ---------------------------------------------------------------- Dozentensteuerung + void DrawLecturerCard(Rect card) + { + Card(card); + float x = VX(card), y = VY(card), w = card.width / k; + Text(V(x + 18, y + 14, 300, 16), "DOZENTENSTEUERUNG", 10, Green, true); + + bool beamer = devices.BeamerOn; + Text(V(x + 18, y + 38, 260, 20), "Beamer-Modus", 14, Ink, true); + Text(V(x + 18, y + 58, 300, 16), beamer + ? $"Aktiv bis {Clock(beamerUntil)} · noch {Mathf.Max(0f, (float)(beamerUntil - env.simMinutes)):0} min" + : "Jalousien schließen, Raum abdunkeln", 11, beamer ? Green2 : Muted); + bool sw = Switch(V(x + w - 18 - 46, y + 42, 46, 26), beamer); + 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 = 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 (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); + Text(V(x + 18, y + 172, 280, 16), controller.BlindOverrideActive + ? $"Automatik pausiert · noch {controller.BlindOverrideMinutesLeft:0} Min." + : $"Pausiert die Automatik für {manualBlindMinutes:0} Min.", 10.5f, controller.BlindOverrideActive ? 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 (Click(up)) controller.OverrideBlinds(Mathf.Round((devices.BlindTarget - 0.25f) * 4f) / 4f, manualBlindMinutes); + if (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; + + Text(V(x + 18, y + 14, 260, 20), student ? "Deine Stimme" : "Raumstimmung", 15, Ink, true); + Text(V(x + 18, y + 34, 300, 16), $"{wishes.Count} Stimmen · Ø Wunsch {N(controller.AverageWish, 1)} °C", 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 (Click(r)) + { + own.temperature = temps[i]; + controller.RunCycle(); + } + } + + // Verteilung + float by = y + 80 + bh + 10, total = Mathf.Max(1, wishes.Count), 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 (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); + + int n = Mathf.Min(3, history.Count); + for (int i = 0; i < n; i++) + { + var h = history[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.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) + { + if (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 74a6507..2afdeae 100644 --- a/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs +++ b/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs @@ -34,7 +34,7 @@ namespace SmartRoom bool showBottom, logCollapsed; Vector2 leftScroll, rightScroll, logScroll; int tab; - string latField, lonField, udpField; + string latField, lonField, udpField, backendField; string[] foundPorts; static readonly string[] Tabs = { "Steuerung", "Wünsche", "Verbindung" }; @@ -115,7 +115,7 @@ namespace SmartRoom void DrawLeft() { GUILayout.Label("Smart Lecture Room", title); - string src = env.AnyMeasured ? "Arduino live" : "Simulation"; + string src = env.AnyMeasured ? "Arduino live" : bridge != null && bridge.Connected ? "warte auf Arduino" : "Simulation"; GUILayout.Label($"Digitaler Zwilling · {env.ClockText} · {src}", dim); GUILayout.Space(S(8)); @@ -138,9 +138,17 @@ 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")) @@ -151,11 +159,17 @@ namespace SmartRoom Section(weather != null && weather.useLiveWeather ? "AUSSEN · OPEN-METEO" : "AUSSEN"); env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C"); env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}"); - env.outdoorNoise = SliderRow("Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB"); + env.outdoorNoise = SliderRow(env.IsMeasured("nout") ? "Lärm (Mikrofon draußen)" : "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.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²"); Section("SZENARIEN"); + 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; }, @@ -168,7 +182,7 @@ 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); } @@ -176,11 +190,18 @@ namespace SmartRoom 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() { @@ -320,7 +341,7 @@ namespace SmartRoom void DrawConnection() { Section("SENSORQUELLE"); - int m = GUILayout.Toolbar((int)bridge.mode, new[] { "Simulation", "Seriell", "UDP / WLAN" }, seg); + int m = GUILayout.Toolbar((int)bridge.mode, new[] { "Simulation", "Seriell", "UDP", "Backend" }, seg); if (m != (int)bridge.mode) { bridge.Disconnect(); @@ -351,6 +372,21 @@ namespace SmartRoom udpField = GUILayout.TextField(udpField, field); if (int.TryParse(udpField, out var port)) bridge.udpListenPort = port; } + else if (bridge.mode == LinkMode.Backend) + { + 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) { @@ -407,7 +443,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 diff --git a/frontend/SmartLectureRoom/README.md b/frontend/SmartLectureRoom/README.md index 33ea2cd..320cc40 100644 --- a/frontend/SmartLectureRoom/README.md +++ b/frontend/SmartLectureRoom/README.md @@ -12,6 +12,25 @@ Ein 3D-Vorlesungsraum als digitaler Zwilling für ein Smart-Home-Projekt. Er ste 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 | @@ -51,10 +70,50 @@ Alle Grenzwerte lassen sich im Inspector am `SmartRoom`-Objekt unter **Climate C ## Arduino anbinden (Architekturdiagramm: Physische Umgebung → Backend) +### Unser Aufbau: 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: @@ -83,7 +142,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 + 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/app.js b/frontend/app.js index 7106fbf..4affa9b 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -1,7 +1,7 @@ // Fragt alle paar Sekunden die Messwerte vom Backend ab und zeigt sie an. const API_URL = "/api/messwerte"; const ABFRAGE_INTERVALL_MS = 2000; -const VERALTET_NACH_MS = 10000; +const VERALTET_NACH_MS = 20000; // Station sendet etwa alle 7-8 s, faellt eine Sendung aus ca. alle 15 s const CO2_GRENZWERT_PPM = 1000; // Hard-Constraint laut Konzept (Standard 1000 ppm) const el = (id) => document.getElementById(id); @@ -21,6 +21,8 @@ function zeigeWerte(aktuell, veraltet) { el("wert-luftfeuchte").textContent = formatiere(aktuell && aktuell.luftfeuchte, 1); el("wert-eco2").textContent = formatiere(aktuell && aktuell.eco2, 0); el("wert-tvoc").textContent = formatiere(aktuell && aktuell.tvoc, 0); + el("wert-lautstaerke").textContent = formatiere(aktuell && aktuell.lautstaerke, 0); + el("wert-helligkeit").textContent = formatiere(aktuell && aktuell.helligkeit, 0); for (const kachel of document.querySelectorAll(".kachel")) { kachel.classList.toggle("veraltet", veraltet); diff --git a/frontend/index.html b/frontend/index.html index 6f892c8..cba3f10 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -31,6 +31,14 @@

TVOC

– ppb

+
+

Lautstärke

+

– dB

+
+
+

Helligkeit

+

– %

+