Gesamtstand Phase 2: Figma-Frontend v2 angebunden, Pruefzyklus, Mehrbenutzer, Unity nur Anzeige
- Webinterface frontend/ambient: Figma-Design Ambient2_v2 (Branch Figma_Prototyp) als HTML/CSS/JS ohne Build, zeigt alle Arduino-Werte, Bedienung ueber das Backend; jeder Browser-Tab ist eine eigene Person; Originalexport unveraendert in frontend/figma, alte angebundene Fassung in frontend/ambient-v1 - Backend: Entscheidung im Pruefzyklus alle 2 min (PRUEF_SEKUNDEN), POST /api/pruefen (Jetzt pruefen), POST /api/zeitraffer (1/5/10x), sofort bei Demo-Szenario, Dozentenbefehl und erster Messung nach Ausfall; Zahlenwuensche in °C werden gemittelt (Durchschnitt statt Median), Stimme zuruecknehmen, Szenario "Sensor offline"; /api/unity mit Quellen, Vetos, Pruefzyklus und Verlauf; Tests 23/23 - Unity-Zwilling: zeigt nur an (Bedienung im Webinterface), UnityWebRequest statt Threads (WebGL-faehig), Ambient-Szene, Laermsensor als Schallwellen im 3D-Raum, Arduino-Status und Umschalter Arduino/Simulation, Ersatzlogik wie im Backend (Licht- und Laermregeln, manuelle Einstellungen, Schutzregeln) - Simulator mit Lautstaerke, Helligkeit und Szenarien laerm/dunkel/demo - Doku: ANLEITUNG.md (Starten mit und ohne Arduino), docs/regeln.md (wer entscheidet wo, wann, was)phase2-gesamt
parent
cc5ce175bb
commit
fc956903f3
|
|
@ -0,0 +1,90 @@
|
|||
# Anleitung: Lernklima-System starten
|
||||
|
||||
Alles liegt in diesem Ordner: Firmware (`firmware/`), Backend (`backend/`), Webinterface (`frontend/ambient`) und Unity-Zwilling (`frontend/SmartLectureRoom`). Wie und wann entschieden wird: [docs/regeln.md](docs/regeln.md).
|
||||
|
||||
```
|
||||
Arduino + ESP-01 ──WLAN──▶ backend/server.js :3000 ◀──▶ Webinterface (Bedienung, beliebig viele Tabs/Geräte)
|
||||
│
|
||||
└──▶ Unity-Zwilling (zeigt, was die Werte im Raum auslösen)
|
||||
```
|
||||
|
||||
## 1. Was man braucht
|
||||
|
||||
| Programm | wofür | Hinweis |
|
||||
|---|---|---|
|
||||
| **Node.js ≥ 18** | Backend | kein `npm install` nötig |
|
||||
| Python 3 | nur für den Simulator (Test ohne Arduino) | |
|
||||
| Unity 6 (6000.x) | nur für den 3D-Zwilling | Projekt `frontend/SmartLectureRoom` |
|
||||
| Arduino IDE | nur zum Hochladen der Firmware | Bibliotheken: DHT sensor library, Adafruit CCS811, LiquidCrystal |
|
||||
|
||||
## 2. Schnellstart ohne Arduino (zum Ausprobieren)
|
||||
|
||||
Im Ordner dieses Repos, jeweils in einem eigenen Terminal:
|
||||
|
||||
```bash
|
||||
node backend/server.js
|
||||
```
|
||||
```bash
|
||||
python3 backend/simulator.py --szenario demo
|
||||
```
|
||||
|
||||
- **Webinterface:** http://localhost:3000 im Browser öffnen.
|
||||
- **Unity:** Unity Hub → *Add project from disk* → `frontend/SmartLectureRoom` → Menü **Smart Room → Ambient-Szene öffnen** → **Play**.
|
||||
|
||||
`--szenario demo` spielt nacheinander normal → stickig → Lärm → normal → Hitze → dunkel → kalt durch (je ca. 1 min). Einzeln: `--szenario normal|hitze|stickig|kalt|laerm|dunkel`.
|
||||
Ohne Internet: `WETTER=aus node backend/server.js` (dann fehlen nur Wind und Außentemperatur).
|
||||
|
||||
## 3. Mit dem Arduino
|
||||
|
||||
1. **Hotspot:** iPhone-Hotspot mit „Maximale Kompatibilität“ (2,4 GHz) einschalten, Laptop verbinden.
|
||||
- **Mac:** Systemeinstellungen → WLAN → Details (beim Hotspot) → TCP/IP → *IPv6 konfigurieren: Nur Link-lokal*. Sonst bekommt der Mac nur `192.0.0.2` und der ESP erreicht ihn nicht. Nach der Vorführung wieder auf „Automatisch“.
|
||||
- **Windows:** einmalig `backend/firewall_freigeben.bat` als Administrator ausführen.
|
||||
2. **Backend starten:** `node backend/server.js` (Windows: Doppelklick auf `backend/start.bat`).
|
||||
Es muss „**OK: SERVER_IP … passt**“ melden. Bei „ACHTUNG“: die angezeigte IP in `firmware/dht11_lcd/wifi_config.h` als `SERVER_IP` eintragen und Firmware neu hochladen.
|
||||
3. **Firmware** (nur wenn nötig, z. B. neue IP): `wifi_config.example.h` als `wifi_config.h` kopieren und Hotspot, Passwort, Laptop-IP eintragen (nicht committen!). **ESP-Kabel an Pin 0/1 abziehen**, `firmware/dht11_lcd` hochladen, Kabel wieder anstecken (ESP TX → Pin 0, ESP RX → Pin 1), Reset.
|
||||
4. LCD zeigt „WLAN OK“. Im Backend-Fenster erscheint alle ~7 s eine Zeile mit den Messwerten (Absender `172.20.10.x`).
|
||||
5. Webinterface oben rechts: „**Arduino verbunden**“. Demo-Szenario auf **Live** lassen, sonst werden Beispielwerte gezeigt.
|
||||
|
||||
## 4. Webinterface bedienen (http://localhost:3000)
|
||||
|
||||
| Bereich | Funktion |
|
||||
|---|---|
|
||||
| Studierende / Dozent | Ansicht wechseln; die Dozentensteuerung gibt es nur in „Dozent“ |
|
||||
| Raumstatus | alle Arduino-Werte (CO₂, Temperatur, Lärm, Luftfeuchte, TVOC, Helligkeit), Wind vom Wetterdienst, Zustand von Fenster, Jalousie, Lüftung, Heizung, Licht, Beamer |
|
||||
| **Nächste Prüfung in m:ss** | das Backend entscheidet alle 2 min |
|
||||
| **Jetzt prüfen** | sofort entscheiden |
|
||||
| **Zeitraffer 1× / 5× / 10×** | Prüfung alle 2 min / 24 s / 12 s |
|
||||
| Dein Temperaturwunsch | mit − / + in 0,5-°C-Schritten einstellen, **Wunsch senden**; „Rückgängig“ zieht ihn zurück |
|
||||
| Fenster öffnen? Auf / Zu | Mehrheit „Auf“ öffnet das Fenster auch bei Außenlärm |
|
||||
| Dozentensteuerung | Beamer-Modus (30/60/90 min), Jalousien ↑/↓ (manuell, 90 min), „Automatik fortsetzen“ |
|
||||
| Demo-Szenarien | Beispielwerte für Vorführungen (gelten auch in Unity); **Live** = echte Werte |
|
||||
|
||||
**Mehrere Personen:** Jeder Browser-Tab ist eine eigene Person (eigene Kennung unten im Wunsch-Kasten). Andere Geräte im selben Hotspot öffnen `http://<Laptop-IP>:3000` (die IP zeigt das Backend beim Start). Neue Stimmen erscheinen sofort, wirken aber erst bei der nächsten Prüfung (Hinweis „Nach der nächsten Prüfung: …“). Stimmen verfallen nach 30 min.
|
||||
|
||||
## 5. Unity-Zwilling
|
||||
|
||||
- Startet automatisch im Modus **Backend** (`http://localhost:3000`) und **zeigt nur an**: Fenster, Jalousie, Heizung, Lüftung, Licht und Beamer bewegen sich so, wie das Backend entscheidet. Bedient wird im Webinterface.
|
||||
- Oben rechts: **„Arduino verbunden / nicht verbunden“** und der Umschalter **Arduino-Werte | Simulation**. „Simulation“ stellt Beispielwerte her und lässt Unity selbst rechnen (zum Ausprobieren mit den Unity-eigenen Szenarien).
|
||||
- Lärm wird sichtbar: Schallwellen vor der Fensterfront, ab 70 dB rot, Schild „Fenster gesperrt“.
|
||||
- Ohne Backend rechnet Unity mit derselben Logik selbst (Ersatzlogik), bis das Backend wieder antwortet.
|
||||
- Für die Vorführung im Browser (WebGL) siehe [backend/README.md](backend/README.md#live-demo-im-browser-webinterface--zwilling-für-alle).
|
||||
|
||||
## 6. Prüfen, ob alles stimmt
|
||||
|
||||
```bash
|
||||
node --test backend/test
|
||||
```
|
||||
Erwartet: alle Tests bestanden.
|
||||
|
||||
## 7. Fehlerbehebung
|
||||
|
||||
| Problem | Lösung |
|
||||
|---|---|
|
||||
| Webinterface: „Backend nicht erreichbar“ | `node backend/server.js` läuft nicht oder auf einem anderen Port |
|
||||
| „Arduino nicht verbunden“, LCD „WLAN OK“ | Backend meldet „ACHTUNG“? → Laptop-IP stimmt nicht mit `SERVER_IP` überein. Mac: IPv6 auf „Nur Link-lokal“. Windows: Firewall freigeben |
|
||||
| LCD „WLAN Fehler E1“ | ESP antwortet nicht: Kabel gekreuzt? (TX→0, RX→1), gemeinsame Masse, lose Kabel; siehe README |
|
||||
| LCD „WLAN Fehler E3“ | Hotspot nicht gefunden: SSID/Passwort, „Maximale Kompatibilität“, Hotspot-Seite am iPhone offen lassen |
|
||||
| Werte ändern sich, Entscheidung nicht | gewollt: erst bei der nächsten Prüfung → „Jetzt prüfen“ oder Zeitraffer |
|
||||
| Webinterface zeigt Beispielwerte statt Arduino | Demo-Szenario steht nicht auf **Live** |
|
||||
| Unity zeigt „Simulation“ | Umschalter oben rechts auf **Arduino-Werte** stellen; Backend muss laufen |
|
||||
| Wind/Außentemperatur „–“ | kein Internet oder `WETTER=aus` |
|
||||
10
CLAUDE.md
10
CLAUDE.md
|
|
@ -7,8 +7,10 @@ UCPS-Projekt (Gruppe C): Lernklima-Aggregation für Vorlesungsräume. Konzept: `
|
|||
|
||||
## Architektur
|
||||
Sensoren (Uno + ESP-01) ➔ `backend/server.js` (Node, Port 3000) ➔ Webinterface (`frontend/ambient`) und Unity-Zwilling (`frontend/SmartLectureRoom`).
|
||||
- **Die gesamte Logik liegt im Backend** (`backend/logik.js`, reine Funktionen; Zustand in `raum.js`; Wetter in `wetter.js`). Webinterface und Unity rechnen nichts selbst, sie holen Entscheidungen über `/api/zustand` bzw. `/api/unity` und schicken Stimmen/Einstellungen an dieselben Endpunkte.
|
||||
- Regeländerungen gehören nach `logik.js` (Grenzwerte in `GRENZWERTE`) und müssen mit `docs/aktivitaetsdiagramm.png` und den Tests übereinstimmen. Die Ersatzlogik in Unity (`ClimateController`) muss gleich bleiben, sie springt nur ein, wenn das Backend > 5 s nicht antwortet.
|
||||
- **Die gesamte Logik liegt im Backend** (`backend/logik.js`, reine Funktionen; Zustand in `raum.js`; Wetter in `wetter.js`). Entschieden wird im **Prüfzyklus alle 2 min** (`PRUEF_SEKUNDEN`), dazu „Jetzt prüfen“ (`POST /api/pruefen`), Zeitraffer 1/5/10× (`POST /api/zeitraffer`) und sofort bei Demo-Szenario, Vortragsmodus, manuellen Einstellungen und der ersten Messung nach einem Sensorausfall. Messwerte und Stimmen werden sofort angezeigt.
|
||||
- **Webinterface** (`frontend/ambient`: `index.html`, `app.js`, `ambient.css` = unverändertes CSS aus `frontend/figma/Ambient2_v2.html`, `ergaenzungen.css`) ist die Bedienoberfläche, ohne Framework/Build. Jeder Browser-Tab ist ein eigener Client (`sessionStorage`). Es rechnet nichts selbst.
|
||||
- **Unity-Zwilling** zeigt nur an (`/api/unity`), Bedienung nur im Webinterface. Regeln, Ablauf und Auslöser: `docs/regeln.md`.
|
||||
- Regeländerungen gehören nach `logik.js` (Grenzwerte in `GRENZWERTE`) und müssen mit `docs/aktivitaetsdiagramm.png`, `docs/regeln.md` und den Tests übereinstimmen. Die Ersatzlogik in Unity (`ClimateController`) muss gleich bleiben, sie springt nur ein, wenn das Backend > 5 s nicht antwortet oder im Unity-Umschalter „Simulation“ gewählt ist.
|
||||
- `backend/server.py` ist veraltet (nur Messwerte, keine Logik); nicht weiterentwickeln.
|
||||
- API-Referenz und Datenformate: `backend/README.md`. Hardware, Verkabelung, Fehlerbehebung: `README.md`.
|
||||
|
||||
|
|
@ -16,7 +18,7 @@ Sensoren (Uno + ESP-01) ➔ `backend/server.js` (Node, Port 3000) ➔ Webinterfa
|
|||
```bash
|
||||
node backend/server.js # Backend starten, http://localhost:3000 (oder backend/start.bat)
|
||||
node --test backend/test # Tests der Logik
|
||||
python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario hitze|stickig|kalt|normal|demo)
|
||||
python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario hitze|stickig|kalt|laerm|dunkel|normal|demo)
|
||||
```
|
||||
- Node.js ≥ 18, keine Abhängigkeiten, kein `npm install`. `WETTER=aus` schaltet den Open-Meteo-Abruf ab.
|
||||
- Firmware (`firmware/dht11_lcd`) wird in der Arduino IDE hochgeladen, nicht über die CLI. `wifi_config.h` (Hotspot-Zugang) ist lokal und nicht im Repo; Vorlage `wifi_config.example.h`. Nie Zugangsdaten committen.
|
||||
|
|
@ -27,7 +29,7 @@ python backend/simulator.py # Fake-Sensordaten ohne Hardware (--szenario h
|
|||
- Änderungen an Regeln oder API in `backend/README.md` und ggf. `docs/aggregationskonzept.md` nachziehen.
|
||||
|
||||
## Fachliche Kernregeln (nicht verletzen)
|
||||
- Temperatur/Licht: Durchschnitt aller Live-Eingaben.
|
||||
- Temperatur/Licht: Durchschnitt aller Live-Eingaben (auch die Zahlenwünsche des Webinterfaces; der Figma-Text „Median“ wurde deshalb in „Durchschnitt“ geändert).
|
||||
- CO2 ist Hard-Constraint (Standard 1000 ppm): Nutzer können nicht überschreiben.
|
||||
- Sensor-Veto: extremer Außenlärm sperrt das automatische Öffnen (Lüftungsanlage statt Fenster), nur ein Mehrheitswunsch „Fenster auf“ öffnet trotzdem (Aktivitätsdiagramm `docs/aktivitaetsdiagramm.png`); extremer Wind ➔ max. gekippt, auch manuell.
|
||||
- Manuelle Dozenteneinstellungen haben Vorrang, gelten 90 min; CO₂ hält die Lüftungsanlage trotzdem an.
|
||||
|
|
|
|||
12
README.md
12
README.md
|
|
@ -4,17 +4,19 @@ Dynamische, kontextsensitive Steuerung des Lernklimas im Vorlesungsraum: Sensord
|
|||
|
||||
Das vollständige Konzept steht in [docs/aggregationskonzept.md](docs/aggregationskonzept.md).
|
||||
|
||||
**Starten:** [ANLEITUNG.md](ANLEITUNG.md) · **Regeln (wer entscheidet wo, wann, was):** [docs/regeln.md](docs/regeln.md)
|
||||
|
||||
## Datenfluss
|
||||
Sensoren (Arduino UNO) ➔ WiFi/Bluetooth ➔ Backend (Aggregation & Regeln) ➔ Frontend (Webinterface + 3D-Zwilling)
|
||||
|
||||
Aktuell umgesetzt:
|
||||
```
|
||||
DHT11 + CCS811 ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Handy-Hotspot)─▶ Laptop: backend/server.js :3000 ◀──▶ Browser (Ambient²-Webinterface)
|
||||
DHT11 + CCS811 + MAX9814 + LDR ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Handy-Hotspot)─▶ Laptop: backend/server.js :3000 ◀──▶ Browser (Ambient²-Webinterface)
|
||||
▲
|
||||
└──▶ Unity-Zwilling (frontend/SmartLectureRoom)
|
||||
```
|
||||
|
||||
Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind-Veto, Vortragsmodus) läuft im **gemeinsamen Node-Backend** `backend/server.js`. Webinterface und Unity-Zwilling holen Werte und Entscheidungen nur dort ab (`/api/zustand` bzw. `/api/unity`) und schicken Stimmen, Szenario, Vortragsmodus und Jalousie an dieselben Endpunkte. So zeigen beide immer denselben Zustand. API und Regeln: [backend/README.md](backend/README.md), Zwilling: [frontend/SmartLectureRoom/README.md](frontend/SmartLectureRoom/README.md).
|
||||
Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind-Veto, Vortragsmodus) läuft im **gemeinsamen Node-Backend** `backend/server.js` und wird **alle 2 Minuten** geprüft („Jetzt prüfen“ und Zeitraffer 5×/10× im Webinterface). Das **Webinterface** (`frontend/ambient`, Figma-Design Ambient² v2) ist die Bedienoberfläche: Es zeigt alle Arduino-Werte und nimmt Stimmen (jeder Browser-Tab = eine Person), Fensterwunsch, Vortragsmodus, Jalousie und Demo-Szenarien an. Der **Unity-Zwilling** zeigt nur, was die Entscheidung im Raum auslöst (`/api/unity`). API und Regeln: [backend/README.md](backend/README.md), Zwilling: [frontend/SmartLectureRoom/README.md](frontend/SmartLectureRoom/README.md).
|
||||
|
||||
## Repo-Struktur
|
||||
| Ordner | Inhalt |
|
||||
|
|
@ -22,10 +24,10 @@ Die gesamte Logik (Durchschnitt der Stimmen, CO₂-Hard-Constraint, Lärm-/Wind-
|
|||
| `docs/` | Konzept, Architektur- und Entscheidungsdokumente |
|
||||
| `firmware/` | Arduino-Sketches für Sensorik und Übertragung |
|
||||
| `backend/` | Aggregationslogik (Durchschnitt, CO2-Hard-Constraint, Kontext-Sperren), API, Wetterdaten |
|
||||
| `frontend/` | Responsive Webinterface (Live-Werte, Präferenz-Slider) und 3D-Raum |
|
||||
| `frontend/` | `ambient/` Webinterface (Figma v2, angebunden), `figma/` unveränderter Figma-Export, `ambient-v1/` ältere angebundene Fassung, `SmartLectureRoom/` Unity-Zwilling, `index.html` einfache Messwert-Seite |
|
||||
|
||||
## Status
|
||||
Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂ und TVOC, zeigt sie auf dem LCD und sendet sie per ESP-01 ans Backend. Das Node-Backend aggregiert Stimmen und entscheidet. Webinterface (Figma-Prototyp `frontend/ambient`, http://localhost:3000) und Unity-Zwilling (`frontend/SmartLectureRoom`) sind beide daran angebunden. Mit dem echten Arduino ist der Zwilling noch nicht getestet. Offene Punkte: [docs/offene-punkte.md](docs/offene-punkte.md).
|
||||
Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂ und TVOC, zeigt sie auf dem LCD und sendet sie per ESP-01 ans Backend. Das Node-Backend aggregiert Stimmen und entscheidet. Webinterface (Figma-Prototyp v2 `frontend/ambient`, http://localhost:3000) und Unity-Zwilling (`frontend/SmartLectureRoom`) sind beide daran angebunden, mit Simulator getestet; Lautstärke und Helligkeit kamen am echten Aufbau bis Unity an (vor der Umstellung auf das Node-Backend). Offene Punkte: [docs/offene-punkte.md](docs/offene-punkte.md).
|
||||
|
||||
## Komponenten und ihre Aufgabe
|
||||
|
||||
|
|
@ -79,6 +81,8 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e
|
|||
Der 3,3-V-Pin des Uno liefert nur ca. 150 mA, der ESP-01 braucht beim Start kurz bis zu 300 mA. Wir versorgen den ESP deshalb aus einer eigenen 3,3-V-Quelle (zweiter Uno); deren **GND muss mit dem GND des Haupt-Uno verbunden** sein.
|
||||
|
||||
## Starten
|
||||
Ausführlich mit Test ohne Arduino, Webinterface, Unity und Fehlerbehebung: [ANLEITUNG.md](ANLEITUNG.md). Kurzfassung:
|
||||
|
||||
1. `firmware/dht11_lcd/wifi_config.example.h` als `wifi_config.h` kopieren und Hotspot-Name, Passwort und Laptop-IP eintragen (die Datei ist in `.gitignore`).
|
||||
2. iPhone-Hotspot mit **„Maximale Kompatibilität“** einschalten (ESP-01 kann nur 2,4 GHz), Laptop verbinden.
|
||||
3. Einmalig `backend/firewall_freigeben.bat` als Administrator ausführen.
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ Nur Node-Bordmittel, kein `npm install` nötig. Voraussetzung: **Node.js ≥ 18*
|
|||
```
|
||||
ESP8266 ─────────POST /api/messwerte─────────▶ ┐
|
||||
Open-Meteo ◀──────── alle 10 min ───────────── │ server.js
|
||||
Webinterface ── GET /api/zustand, POST /api/stimme, /api/vortragsmodus, /api/jalousie, /api/szenario
|
||||
Unity-Zwilling ─ GET /api/unity (Werte + Steuerbefehl), POST wie das Webinterface
|
||||
Webinterface ── GET /api/zustand, POST /api/stimme, /api/vortragsmodus, /api/jalousie, /api/manuell, /api/szenario, /api/pruefen, /api/zeitraffer
|
||||
Unity-Zwilling ─ GET /api/unity (Werte + Steuerbefehl), nur Anzeige
|
||||
```
|
||||
|
||||
```bash
|
||||
|
|
@ -23,7 +23,10 @@ node backend/server.js # oder Doppelklick auf backend/start.bat
|
|||
node --test backend/test # Tests der Logik
|
||||
python backend/simulator.py # optional: Fake-Sensordaten ohne Hardware (funktioniert mit beiden Servern)
|
||||
```
|
||||
Webinterface: http://localhost:3000 (Figma-Prototyp Ambient², angebunden). Die alte einfache Messwert-Seite liegt unter http://localhost:3000/index.html.
|
||||
Webinterface: http://localhost:3000 (leitet auf `/ambient/` um: Figma-Prototyp Ambient² v2, angebunden). Ältere Fassung: `/ambient-v1/`, einfache Messwert-Seite: `/index.html`.
|
||||
|
||||
### Prüfzyklus
|
||||
Entschieden wird **alle 2 Minuten** (`PRUEF_SEKUNDEN=…` zum Ändern). Neue Messwerte und Stimmen erscheinen sofort im Webinterface, wirken aber erst bei der nächsten Prüfung. Sofort geprüft wird bei „Jetzt prüfen“ (`POST /api/pruefen`), Demo-Szenario, Vortragsmodus, manuellen Einstellungen, ablaufenden Modi und bei der ersten Messung nach Start oder Sensorausfall. Zeitraffer (`POST /api/zeitraffer`, 1/5/10×) verkürzt den Abstand auf 2 min / 24 s / 12 s. Übersicht mit Diagramm: [../docs/regeln.md](../docs/regeln.md).
|
||||
Ohne Internet (Hotspot ohne Daten) fehlen nur die Wetterwerte; mit `WETTER=aus` wird der Abruf abgeschaltet.
|
||||
|
||||
| Datei | Aufgabe |
|
||||
|
|
@ -40,7 +43,7 @@ Ohne Internet (Hotspot ohne Daten) fehlen nur die Wetterwerte; mit `WETTER=aus`
|
|||
| 1 Gesundheit | eCO₂ > **1000 ppm** ➔ Lüften erzwungen (Fenster offen). Nutzerstimmen können das nicht verhindern. Ist die Außenluft belastet (PM10 > 50 µg/m³) oder draußen < 5 °C, läuft stattdessen die Lüftungsanlage. Auch bei manuell geschlossenem Fenster bleibt die Lüftungsanlage an. |
|
||||
| 2 Kontext-Veto | Außenlärm > **70 dB** ➔ Fensteröffnung gesperrt, Lüftungsanlage statt Fenster. **Nur wenn die Mehrheit „Fenster auf“ stimmt, öffnet es trotzdem.** Wind > **60 km/h** ➔ Fenster höchstens gekippt (auch manuell), Lüftungsanlage unterstützt. |
|
||||
| 3 Dozent | Manuelle Einstellungen (Fenster, Jalousie, Licht, Lüftungsanlage) haben Vorrang vor der Automatik und werden nach **90 min** gelöscht. |
|
||||
| 3 Mehrheit | Temperaturwunsch = **Durchschnitt aller Stimmen** (kühler −1, angenehm 0, wärmer +1) × 1,5 °C um 22 °C, begrenzt auf 20–24 °C. Liegt der Durchschnitt unter ±0,2, bleibt der Zielwert (Ausreißer). Licht ebenso: Durchschnitt aus dunkler/passt/heller. Fenster: offen, wenn mehr Stimmen für „auf“ als für „zu“. |
|
||||
| 3 Mehrheit | Temperaturwunsch = **Durchschnitt aller Stimmen**: Zahlenwünsche aus dem Webinterface (18–26 °C, je Wunsch begrenzt) und Kategorien (kühler −1, angenehm 0, wärmer +1, je 1,5 °C um 22 °C) werden gemeinsam gemittelt, begrenzt auf 20–24 °C. Liegt der Durchschnitt unter ±0,2, bleibt der Zielwert (Ausreißer). Licht ebenso: Durchschnitt aus dunkler/passt/heller. Fenster: offen, wenn mehr Stimmen für „auf“ als für „zu“. |
|
||||
| 4 Energie | Sonst Zielwerte halten: heizen unter Ziel − 0,5 °C, lüften über Ziel + 1 °C (wenn draußen kühler). |
|
||||
|
||||
Jalousie und Licht: Beamermodus (= Vortragsmodus) ➔ Beamer an, Licht aus, Jalousie unten. Sonst zu hell (Lichtsensor `helligkeit` > **80 %**, ohne Sensor Sonne > 500 W/m²) ➔ Jalousie unten, Licht an; sonst Jalousie oben. Zu dunkel (< **30 %**) ➔ Licht heller. Manuelle Werte gehen vor. Alle Grenzwerte stehen oben in `logik.js` (`GRENZWERTE`); die Lichtschwellen sind relative Werte des Fotowiderstands und müssen am Aufbau abgeglichen werden.
|
||||
|
|
@ -51,27 +54,32 @@ Demo-Szenarien (aus dem Figma-Prototyp: Normal, CO₂ zu hoch, CO₂ + Außenlä
|
|||
| Methode & Pfad | Inhalt |
|
||||
|---|---|
|
||||
| `POST /api/messwerte` | ESP8266: `{"temperatur":22.5,"luftfeuchte":45,"eco2":612,"tvoc":30,"lautstaerke":48,"helligkeit":55}` – alle Felder optional. `lautstaerke` (Mikrofon, dB) gilt als Außenlärm, `helligkeit` ist der Fotowiderstand in % (relativ). |
|
||||
| `GET /api/zustand?client=<id>` | Alles fürs Webinterface: `werte` (je Feld `wert` + `quelle`: sensor/wetter/demo), `entscheidung` (Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Zielwert, Priorität, Status), `stimmen` (Temperatur, Licht, Fenster), `vortrag`, `manuell`, `verlauf`, `szenarien`. |
|
||||
| `POST /api/stimme` | `{"client":"<id>","rolle":"studierende","temperatur":"kuehler\|angenehm\|waermer","licht":"dunkler\|passt\|heller","fenster":"auf\|zu"}` – eine Stimme pro Client, Felder einzeln überschreibbar. |
|
||||
| `GET /api/zustand?client=<id>` | Alles fürs Webinterface: `werte` (je Feld `wert` + `quelle`: sensor/wetter/demo), `entscheidung` (Stand der letzten Prüfung: Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Zielwert, Priorität, Status), `pruefung` (Intervall, Zeitraffer, `restSekunden`), `stimmen` (live: Kategorien, `verteilung` je Grad, `durchschnittC`, `zielNachPruefung`, eigene Stimme), `vortrag`, `manuell`, `verlauf`, `szenarien`. |
|
||||
| `POST /api/stimme` | `{"client":"<id>","rolle":"studierende","temperaturWunsch":22.5}` (Webinterface, °C in 0,5er-Schritten) oder `"temperatur":"kuehler\|angenehm\|waermer"`, dazu `"licht":"dunkler\|passt\|heller"`, `"fenster":"auf\|zu"` – eine Stimme pro Client (Webinterface: pro Browser-Tab), Felder einzeln überschreibbar. `{"client":"<id>","zuruecknehmen":true}` löscht die Stimme. |
|
||||
| `POST /api/pruefen` | `{}` – sofort prüfen, der 2-min-Zyklus beginnt neu |
|
||||
| `POST /api/zeitraffer` | `{"faktor":1\|5\|10}` – Prüfung alle 2 min / 24 s / 12 s |
|
||||
| `POST /api/vortragsmodus` | `{"rolle":"dozent","aktiv":true,"dauerMinuten":60}` (30/60/90) |
|
||||
| `POST /api/manuell` | `{"rolle":"dozent","fenster":"closed\|tilted\|open\|auto","jalousie":0…100\|"auto","licht":0…100\|"auto","lueftung":"an\|aus\|auto"}` – fehlende Felder bleiben, gilt 90 min. `{"rolle":"dozent","zuruecksetzen":true}` löscht alles. |
|
||||
| `POST /api/jalousie` | `{"rolle":"dozent","position":100}` (0 = offen, 100 = zu), Kurzform von `/api/manuell` |
|
||||
| `POST /api/szenario` | `{"id":"live\|normal\|co2\|noise\|storm\|presentation\|outlier\|noisewish"}` |
|
||||
| `POST /api/szenario` | `{"id":"live\|normal\|co2\|noise\|storm\|presentation\|outlier\|noisewish\|offline"}` |
|
||||
| `GET /api/unity` | Für den Unity-Zwilling, siehe unten |
|
||||
| `GET /api/messwerte`, `GET /api/steuerung` | kompatibel zu `server.py` |
|
||||
|
||||
Die Rolle wird nicht geprüft (keine Anmeldung, siehe `docs/offene-punkte.md`).
|
||||
|
||||
### Unity-Zwilling anbinden
|
||||
Der Zwilling (`frontend/SmartLectureRoom`) startet im Modus **Verbindung → Backend** (`BackendLink.cs`). Er fragt jede Sekunde `GET /api/unity?client=<id>` ab und **führt nur aus**. Seine eigene `ClimateController`-Logik ruht, solange das Backend antwortet. Bei mehr als 5 s ohne Antwort springt sie als Fallback ein.
|
||||
|
||||
Eingaben im Unity-HUD gehen an **dieselben Endpunkte wie beim Webinterface**: Stimme (`/api/stimme`, Kennung `unity-…`), Szenario, Vortragsmodus, manuelle Einstellungen. Website und Zwilling zeigen daher immer denselben Zustand. Die eigene Handsteuerung des Zwillings ist dann aus; manuelle Werte laufen über `/api/manuell`, damit die Schutzregeln greifen.
|
||||
Der Zwilling (`frontend/SmartLectureRoom`, Verbindung **Backend**, Klasse `ArduinoBridge`) fragt jede Sekunde `GET /api/unity` ab und **zeigt nur an**: Er übernimmt die Werte (nur echte Sensorwerte gelten als „Sensor“, siehe `quellen`) und führt den Steuerbefehl aus. Bedient wird ausschließlich im Webinterface. Antwortet das Backend länger als 5 s nicht oder steht der Unity-Umschalter auf „Simulation“, rechnet die Ersatzlogik (`ClimateController`) mit denselben Regeln. Die Abfrage nutzt `UnityWebRequest` und läuft deshalb auch als WebGL im Browser.
|
||||
|
||||
```json
|
||||
{
|
||||
"szenario": "noise",
|
||||
"sensor": {"t":22.5,"co2":1374,"nout":86,"tout":14,"wind":2.2,"sun":200},
|
||||
"sensorFelder": ["t","co2","nout","tout","wind","sun"],
|
||||
"sensorFelder": ["t","co2","rh","tvoc","lightpct","nout","tout","wind","sun"],
|
||||
"quellen": {"t":"sensor","co2":"sensor","nout":"sensor","tout":"wetter","…":"…"},
|
||||
"sensorOnline": true, "ton": "warning", "prioritaetNummer": 1, "fensterGesperrt": true,
|
||||
"vetos": {"co2":true,"laerm":true,"wind":false,"aussenluft":false},
|
||||
"pruefung": {"intervallSekunden":120,"zeitraffer":1,"abstandSekunden":120,"restSekunden":84,"letzteUhrzeit":"11:06"},
|
||||
"verlauf": [{"uhrzeit":"11:06","titel":"Lüftungsanlage gestartet","grund":"…","ton":"warning"}],
|
||||
"steuerung": {"window":"tilted","blind":0.32,"heat":0,"vent":1,"light":0.6,"beamer":0},
|
||||
"status": "Frischluft, trotz hoher Außenlautstärke",
|
||||
"detail": "CO₂ erfordert Lüften. Der Lärmschutz begrenzt die Öffnung.",
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ const GRENZWERTE = {
|
|||
totzone: 0.2, // |Durchschnitt| darunter: Zielwert bleibt (Ausreisser)
|
||||
heizenAbC: 0.5, // unter Ziel - 0,5 °C wird geheizt
|
||||
kuehlenAbC: 1, // ueber Ziel + 1 °C wird gelueftet (Zielbereich im Webinterface: Ziel ± 1 °C)
|
||||
wunschMinC: 18, // Eingabebereich fuer Zahlenwuensche im Webinterface (Schritte von 0,5 °C)
|
||||
wunschMaxC: 26,
|
||||
};
|
||||
|
||||
const STIMME_WERT = { kuehler: -1, angenehm: 0, waermer: 1, dunkler: -1, passt: 0, heller: 1 };
|
||||
|
|
@ -67,13 +69,39 @@ function zaehle(stimmen, feld, namen) {
|
|||
return { anzahl, gesamt, durchschnitt: gesamt ? summe / gesamt : 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Temperaturstimmen: entweder Zahlenwunsch in °C (`wunschC`, Webinterface) oder kuehler/angenehm/waermer.
|
||||
* Beide werden in Stufen um die Baseline umgerechnet (1 Stufe = gradProStimme °C) und gemittelt.
|
||||
* `anzahl` ordnet Zahlenwuensche den drei Kategorien zu, `verteilung` zaehlt sie je ganzes Grad (≤19 … ≥25).
|
||||
*/
|
||||
function temperaturStimmen(stimmen, g) {
|
||||
const anzahl = { kuehler: 0, angenehm: 0, waermer: 0 };
|
||||
const verteilung = { "19": 0, "20": 0, "21": 0, "22": 0, "23": 0, "24": 0, "25": 0 };
|
||||
let summe = 0;
|
||||
let gesamt = 0;
|
||||
for (const s of stimmen) {
|
||||
let stufe;
|
||||
if (typeof s.wunschC === "number" && Number.isFinite(s.wunschC)) {
|
||||
stufe = (begrenze(s.wunschC, g.wunschMinC, g.wunschMaxC) - g.basisTemperaturC) / g.gradProStimme;
|
||||
} else if (s.temperatur in anzahl) {
|
||||
stufe = STIMME_WERT[s.temperatur];
|
||||
} else continue;
|
||||
anzahl[stufe < -1 / 3 ? "kuehler" : stufe > 1 / 3 ? "waermer" : "angenehm"] += 1;
|
||||
const grad = Math.round(g.basisTemperaturC + stufe * g.gradProStimme);
|
||||
verteilung[String(begrenze(grad, 19, 25))] += 1;
|
||||
summe += stufe;
|
||||
gesamt += 1;
|
||||
}
|
||||
return { anzahl, verteilung, gesamt, durchschnitt: gesamt ? summe / gesamt : 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Temperatur und Licht: Durchschnitt aller Live-Eingaben (jede Stimme zaehlt gleich, auch die des Dozenten).
|
||||
* Liegt der Durchschnitt in der Totzone, bleibt der Zielwert (Ausreisser veraendern ihn nicht).
|
||||
* Fenster: gewuenscht, wenn mehr Stimmen fuer "auf" als fuer "zu" abgegeben wurden.
|
||||
*/
|
||||
function aggregiere(stimmen, g = GRENZWERTE) {
|
||||
const temp = zaehle(stimmen, "temperatur", ["kuehler", "angenehm", "waermer"]);
|
||||
const temp = temperaturStimmen(stimmen, g);
|
||||
const licht = zaehle(stimmen, "licht", ["dunkler", "passt", "heller"]);
|
||||
const fenster = zaehle(stimmen, "fenster", ["auf", "zu"]);
|
||||
|
||||
|
|
@ -84,7 +112,10 @@ function aggregiere(stimmen, g = GRENZWERTE) {
|
|||
const begrenzt = wunsch < g.zielMinC || wunsch > g.zielMaxC;
|
||||
|
||||
return {
|
||||
temperatur: { ...temp, durchschnitt: runde(temp.durchschnitt, 2), zielTemperatur, ausreisser, begrenzt },
|
||||
temperatur: {
|
||||
...temp, durchschnitt: runde(temp.durchschnitt, 2), zielTemperatur, ausreisser, begrenzt,
|
||||
durchschnittC: temp.gesamt ? runde(g.basisTemperaturC + temp.durchschnitt * g.gradProStimme, 1) : null,
|
||||
},
|
||||
licht: { ...licht, durchschnitt: runde(licht.durchschnitt, 2) },
|
||||
fenster: { anzahl: fenster.anzahl, gesamt: fenster.gesamt, gewuenscht: fenster.anzahl.auf > fenster.anzahl.zu },
|
||||
};
|
||||
|
|
|
|||
148
backend/raum.js
148
backend/raum.js
|
|
@ -1,6 +1,6 @@
|
|||
// Zustand des Raums im Speicher: Messwerte, Wetter, Stimmen, Dozentenvorgaben, Demo-Szenario und Verlauf.
|
||||
// Die Zeit wird als Parameter `jetzt` (ms) uebergeben, damit sich alles ohne Warten testen laesst.
|
||||
const { GRENZWERTE, KEIN_MANUELL, entscheide, unityBefehl } = require("./logik");
|
||||
const { GRENZWERTE, KEIN_MANUELL, aggregiere, entscheide, unityBefehl } = require("./logik");
|
||||
|
||||
const MESSWERT_FELDER = ["temperatur", "luftfeuchte", "eco2", "tvoc", "lautstaerke", "helligkeit"];
|
||||
const MAX_MESSWERTE = 100;
|
||||
|
|
@ -11,6 +11,7 @@ const MANUELL_GUELTIG_MS = 90 * 60 * 1000; // manuelle Einstellungen gelten eine
|
|||
const FENSTER_CODES = ["closed", "tilted", "open"];
|
||||
const STIMMEN_FELD = { kuehler: "temperatur", angenehm: "temperatur", waermer: "temperatur", dunkler: "licht", passt: "licht", heller: "licht", auf: "fenster", zu: "fenster" };
|
||||
const VORTRAG_DAUERN_MIN = [30, 60, 90];
|
||||
const ZEITRAFFER_FAKTOREN = [1, 5, 10];
|
||||
|
||||
// Demo-Szenarien aus dem Figma-Prototyp. Sie ueberschreiben die Sensorwerte, solange sie aktiv sind.
|
||||
// "live" nutzt nur echte Sensordaten, echtes Wetter und echte Stimmen.
|
||||
|
|
@ -51,6 +52,10 @@ const SZENARIEN = [
|
|||
innen: { temperatur: 22.5, eco2: 1374 }, aussen: { laerm: 86, wind: 8, feinstaub: 9 },
|
||||
stimmen: { kuehler: 1, angenehm: 7, waermer: 1, auf: 6, zu: 3 },
|
||||
},
|
||||
{
|
||||
id: "offline", text: "Sensor offline", beschreibung: "Ehrlicher Fehlerzustand", offline: true,
|
||||
stimmen: { kuehler: 1, angenehm: 7, waermer: 1 },
|
||||
},
|
||||
];
|
||||
const DEMO_AUSSEN = { temperatur: 14, sonne: 200 };
|
||||
|
||||
|
|
@ -70,7 +75,17 @@ function ohneLichtUndJalousie(manuell) {
|
|||
}
|
||||
|
||||
class Raum {
|
||||
constructor(jetzt = Date.now()) {
|
||||
/**
|
||||
* @param {number} jetzt
|
||||
* @param {{pruefIntervallMs?: number}} optionen pruefIntervallMs: Abstand der Pruefzyklen (0 = bei jeder Abfrage,
|
||||
* so arbeiten die Tests; server.js nutzt 2 Minuten). Messwerte und Stimmen werden sofort angezeigt,
|
||||
* entschieden wird erst bei der naechsten Pruefung.
|
||||
*/
|
||||
constructor(jetzt = Date.now(), { pruefIntervallMs = 0 } = {}) {
|
||||
this.pruefIntervallMs = pruefIntervallMs;
|
||||
this.zeitraffer = 1;
|
||||
this.letztePruefung = null;
|
||||
this.naechstePruefung = jetzt; // erste Entscheidung sofort
|
||||
this.messwerte = []; // { zeit, temperatur, luftfeuchte, eco2, tvoc, lautstaerke, helligkeit }
|
||||
this.wetter = null; // { zeit, temperatur, wind, sonne, feinstaub, aqi }
|
||||
this.stimmen = new Map(); // client -> { rolle, temperatur, licht, zeit }
|
||||
|
|
@ -88,6 +103,7 @@ class Raum {
|
|||
|
||||
/** Messwertsatz vom ESP8266. Wirft einen Fehler mit Meldung, wenn ein Feld keine Zahl ist. */
|
||||
messwertEmpfangen(daten, jetzt = Date.now()) {
|
||||
const warOffline = this.aktuellerMesswert(jetzt) === null && !this.szenario.offline;
|
||||
const eintrag = { zeit: new Date(jetzt).toISOString() };
|
||||
for (const feld of MESSWERT_FELDER) {
|
||||
const wert = daten[feld];
|
||||
|
|
@ -97,7 +113,11 @@ class Raum {
|
|||
}
|
||||
this.messwerte.push(eintrag);
|
||||
if (this.messwerte.length > MAX_MESSWERTE) this.messwerte.shift();
|
||||
this.aktualisiere(jetzt);
|
||||
// Erste Messung nach Start oder Ausfall: sofort pruefen, statt bis zu 2 min mit alten Annahmen zu warten
|
||||
if (warOffline) {
|
||||
this.protokolliere(jetzt, "Sensor verbunden", "Der Arduino liefert wieder Messwerte. Die Steuerung prüft sofort.", "good");
|
||||
this.pruefe(jetzt);
|
||||
} else this.aktualisiere(jetzt);
|
||||
return eintrag;
|
||||
}
|
||||
|
||||
|
|
@ -106,8 +126,21 @@ class Raum {
|
|||
this.aktualisiere(jetzt);
|
||||
}
|
||||
|
||||
stimmeAbgeben({ client, rolle, temperatur, licht, fenster }, jetzt = Date.now()) {
|
||||
/**
|
||||
* Stimme eines Clients (Browser-Tab, Geraet oder Unity). temperaturWunsch: Zahl in °C (Webinterface, wird auf
|
||||
* 0,5 °C gerundet und auf 18–26 °C begrenzt) oder temperatur kuehler|angenehm|waermer. `zuruecknehmen: true`
|
||||
* loescht die Stimme. Die Entscheidung folgt beim naechsten Pruefzyklus.
|
||||
*/
|
||||
stimmeAbgeben({ client, rolle, temperatur, temperaturWunsch, licht, fenster, zuruecknehmen }, jetzt = Date.now()) {
|
||||
if (typeof client !== "string" || client.length < 4 || client.length > 64) throw new Error("Feld 'client' fehlt");
|
||||
if (zuruecknehmen === true) {
|
||||
this.stimmen.delete(client);
|
||||
this.aktualisiere(jetzt);
|
||||
return;
|
||||
}
|
||||
if (temperaturWunsch !== undefined && (typeof temperaturWunsch !== "number" || !Number.isFinite(temperaturWunsch))) {
|
||||
throw new Error("Feld 'temperaturWunsch' muss eine Zahl in °C sein");
|
||||
}
|
||||
if (temperatur !== undefined && !["kuehler", "angenehm", "waermer"].includes(temperatur)) {
|
||||
throw new Error("Feld 'temperatur' muss kuehler, angenehm oder waermer sein");
|
||||
}
|
||||
|
|
@ -116,9 +149,13 @@ class Raum {
|
|||
}
|
||||
if (fenster !== undefined && !["auf", "zu"].includes(fenster)) throw new Error("Feld 'fenster' muss auf oder zu sein");
|
||||
const alt = this.stimmen.get(client) || {};
|
||||
const wunschC = temperaturWunsch !== undefined
|
||||
? Math.round(Math.min(GRENZWERTE.wunschMaxC, Math.max(GRENZWERTE.wunschMinC, temperaturWunsch)) * 2) / 2
|
||||
: temperatur !== undefined ? undefined : alt.wunschC; // eine Temperaturmeinung pro Client
|
||||
this.stimmen.set(client, {
|
||||
rolle: rolle === "dozent" ? "dozent" : "studierende",
|
||||
temperatur: temperatur ?? alt.temperatur,
|
||||
wunschC,
|
||||
temperatur: temperaturWunsch !== undefined ? undefined : temperatur ?? alt.temperatur,
|
||||
licht: licht ?? alt.licht,
|
||||
fenster: fenster ?? alt.fenster,
|
||||
zeit: jetzt,
|
||||
|
|
@ -142,7 +179,7 @@ class Raum {
|
|||
this.manuell = ohneLichtUndJalousie(this.manuell);
|
||||
this.protokolliere(jetzt, "Vortragsmodus beendet", "Die reguläre Raumautomatik ist wieder aktiv.", "info");
|
||||
}
|
||||
this.aktualisiere(jetzt);
|
||||
this.pruefe(jetzt); // Befehl des Dozenten wirkt sofort
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -176,7 +213,7 @@ class Raum {
|
|||
aktiv ? `Gültig bis ${uhrzeit(this.manuell.bis)}. CO₂-Grenzwert und Sturmschutz bleiben aktiv.` : "Alle manuellen Einstellungen wurden zurückgesetzt.",
|
||||
aktiv ? "warning" : "info",
|
||||
);
|
||||
this.aktualisiere(jetzt);
|
||||
this.pruefe(jetzt); // Befehl des Dozenten wirkt sofort
|
||||
}
|
||||
|
||||
/** Jalousie manuell fahren (0 = offen, 100 = zu), wie im Webinterface. Kurzform von manuellSetzen. */
|
||||
|
|
@ -193,9 +230,27 @@ class Raum {
|
|||
if (szenario.vortrag) this.vortragEnde = jetzt + this.vortragDauer * 60000;
|
||||
else this.vortragEnde = null;
|
||||
this.letzteAktion = null; // Entscheidung des neuen Szenarios immer protokollieren
|
||||
this.pruefe(jetzt); // Demo-Szenario wirkt sofort
|
||||
}
|
||||
|
||||
/** "Jetzt pruefen": Entscheidung sofort neu berechnen statt auf den naechsten Pruefzyklus zu warten. */
|
||||
jetztPruefen(jetzt = Date.now()) {
|
||||
return this.pruefe(jetzt);
|
||||
}
|
||||
|
||||
/** Zeitraffer 1×, 5× oder 10×: Pruefzyklen entsprechend oefter (2 min → 24 s → 12 s). */
|
||||
zeitrafferSetzen(faktor, jetzt = Date.now()) {
|
||||
if (!ZEITRAFFER_FAKTOREN.includes(faktor)) throw new Error("Zeitraffer muss 1, 5 oder 10 sein");
|
||||
this.zeitraffer = faktor;
|
||||
const basis = this.letztePruefung ?? jetzt;
|
||||
this.naechstePruefung = Math.min(this.naechstePruefung, basis + this.pruefAbstandMs());
|
||||
this.aktualisiere(jetzt);
|
||||
}
|
||||
|
||||
pruefAbstandMs() {
|
||||
return this.pruefIntervallMs / this.zeitraffer;
|
||||
}
|
||||
|
||||
// ---------- Auswertung ----------
|
||||
|
||||
vortragAktiv(jetzt) {
|
||||
|
|
@ -203,6 +258,7 @@ class Raum {
|
|||
}
|
||||
|
||||
aktuellerMesswert(jetzt) {
|
||||
if (this.szenario.offline) return null; // Demo "Sensor offline"
|
||||
const letzter = this.messwerte[this.messwerte.length - 1];
|
||||
if (!letzter || jetzt - Date.parse(letzter.zeit) > MESSWERT_VERALTET_MS) return null;
|
||||
return letzter;
|
||||
|
|
@ -247,18 +303,29 @@ class Raum {
|
|||
};
|
||||
}
|
||||
|
||||
/** Rechnet die Entscheidung neu, beendet abgelaufene Modi und schreibt Aenderungen in den Verlauf. */
|
||||
/**
|
||||
* Haelt den Zustand aktuell: Messwerte fuer die Anzeige immer, die Entscheidung nur zum Pruefzyklus
|
||||
* (alle 2 min, mit Zeitraffer oefter) oder wenn ein Vortragsmodus bzw. manuelle Einstellungen ablaufen.
|
||||
*/
|
||||
aktualisiere(jetzt = Date.now()) {
|
||||
let faellig = this.entscheidung === undefined || jetzt >= this.naechstePruefung;
|
||||
if (this.vortragEnde !== null && this.vortragEnde <= jetzt) {
|
||||
this.vortragEnde = null;
|
||||
if (this.szenario.vortrag) this.szenario = SZENARIEN.find((s) => s.id === "normal");
|
||||
this.protokolliere(jetzt, "Vortragsmodus beendet", "Die eingestellte Dauer ist abgelaufen. Die reguläre Raumautomatik übernimmt.", "info");
|
||||
faellig = true;
|
||||
}
|
||||
if (this.manuell.bis !== null && this.manuell.bis <= jetzt) {
|
||||
this.manuell = { ...KEIN_MANUELL, bis: null };
|
||||
this.protokolliere(jetzt, "Manuelle Einstellungen gelöscht", "Nach 90 Minuten übernimmt wieder die Automatik.", "info");
|
||||
faellig = true;
|
||||
}
|
||||
this.eingabeWerte = this.eingaben(jetzt);
|
||||
return faellig ? this.pruefe(jetzt) : this.entscheidung;
|
||||
}
|
||||
|
||||
/** Pruefzyklus: Entscheidung aus den aktuellen Eingaben berechnen und Aenderungen protokollieren. */
|
||||
pruefe(jetzt = Date.now()) {
|
||||
const e = this.eingaben(jetzt);
|
||||
const entscheidung = entscheide({
|
||||
innen: { temperatur: e.temperatur.wert, eco2: e.eco2.wert, helligkeit: e.helligkeit.wert },
|
||||
|
|
@ -274,9 +341,23 @@ class Raum {
|
|||
}
|
||||
this.entscheidung = entscheidung;
|
||||
this.eingabeWerte = e;
|
||||
this.letztePruefung = jetzt;
|
||||
this.naechstePruefung = jetzt + this.pruefAbstandMs();
|
||||
return entscheidung;
|
||||
}
|
||||
|
||||
/** Stand der Pruefzyklen fuer Webinterface und Unity. */
|
||||
pruefungInfo(jetzt) {
|
||||
return {
|
||||
intervallSekunden: Math.round(this.pruefIntervallMs / 1000),
|
||||
zeitraffer: this.zeitraffer,
|
||||
abstandSekunden: Math.round(this.pruefAbstandMs() / 1000),
|
||||
letzte: this.letztePruefung === null ? null : new Date(this.letztePruefung).toISOString(),
|
||||
letzteUhrzeit: this.letztePruefung === null ? "" : uhrzeit(this.letztePruefung),
|
||||
restSekunden: Math.max(0, Math.ceil((this.naechstePruefung - jetzt) / 1000)),
|
||||
};
|
||||
}
|
||||
|
||||
protokolliere(jetzt, titel, grund, ton) {
|
||||
this.verlauf.unshift({ zeit: new Date(jetzt).toISOString(), uhrzeit: uhrzeit(jetzt), titel, grund, ton });
|
||||
if (this.verlauf.length > MAX_VERLAUF) this.verlauf.pop();
|
||||
|
|
@ -289,8 +370,12 @@ class Raum {
|
|||
const d = this.aktualisiere(jetzt);
|
||||
const eigene = client ? this.stimmen.get(client) : null;
|
||||
const sensor = this.aktuellerMesswert(jetzt);
|
||||
// Stimmen sofort anzeigen; der Zielwert daraus gilt erst nach der naechsten Pruefung
|
||||
const liveAgg = aggregiere(this.gueltigeStimmen(jetzt));
|
||||
const live = liveAgg.temperatur;
|
||||
return {
|
||||
jetzt: new Date(jetzt).toISOString(),
|
||||
pruefung: this.pruefungInfo(jetzt),
|
||||
szenario: this.szenario.id,
|
||||
szenarien: SZENARIEN.map(({ id, text, beschreibung }) => ({ id, text, beschreibung })),
|
||||
sensorOnline: sensor !== null,
|
||||
|
|
@ -313,11 +398,16 @@ class Raum {
|
|||
bis: this.manuell.bis === null ? null : new Date(this.manuell.bis).toISOString(),
|
||||
},
|
||||
stimmen: {
|
||||
temperatur: d.aggregation.temperatur.anzahl,
|
||||
licht: d.aggregation.licht.anzahl,
|
||||
fenster: d.aggregation.fenster.anzahl,
|
||||
gesamt: d.aggregation.temperatur.gesamt,
|
||||
eigene: eigene ? { temperatur: eigene.temperatur ?? null, licht: eigene.licht ?? null, fenster: eigene.fenster ?? null } : null,
|
||||
temperatur: live.anzahl,
|
||||
verteilung: live.verteilung,
|
||||
durchschnittC: live.durchschnittC,
|
||||
zielNachPruefung: live.zielTemperatur,
|
||||
licht: liveAgg.licht.anzahl,
|
||||
fenster: liveAgg.fenster.anzahl,
|
||||
gesamt: live.gesamt,
|
||||
eigene: eigene
|
||||
? { temperatur: eigene.temperatur ?? null, temperaturWunsch: eigene.wunschC ?? null, licht: eigene.licht ?? null, fenster: eigene.fenster ?? null, zeit: new Date(eigene.zeit).toISOString() }
|
||||
: null,
|
||||
},
|
||||
verlauf: this.verlauf,
|
||||
};
|
||||
|
|
@ -334,13 +424,22 @@ class Raum {
|
|||
const setze = (feld, wert) => {
|
||||
if (wert !== null) sensor[feld] = wert;
|
||||
};
|
||||
setze("t", e.temperatur.wert);
|
||||
setze("co2", e.eco2.wert);
|
||||
setze("nout", e.laerm.wert);
|
||||
setze("tout", e.aussenTemperatur.wert);
|
||||
setze("wind", e.wind.wert === null ? null : Math.round((e.wind.wert / 3.6) * 10) / 10); // km/h -> m/s
|
||||
setze("sun", e.sonne.wert);
|
||||
setze("aq", e.aqi.wert);
|
||||
const quellen = {};
|
||||
const mit = (feld, eingabe, umrechnen = (w) => w) => {
|
||||
if (eingabe.wert === null) return;
|
||||
setze(feld, umrechnen(eingabe.wert));
|
||||
quellen[feld] = eingabe.quelle;
|
||||
};
|
||||
mit("t", e.temperatur);
|
||||
mit("co2", e.eco2);
|
||||
mit("rh", e.luftfeuchte);
|
||||
mit("tvoc", e.tvoc);
|
||||
mit("lightpct", e.helligkeit);
|
||||
mit("nout", e.laerm); // Mikrofon MAX9814 = Aussenlaerm
|
||||
mit("tout", e.aussenTemperatur);
|
||||
mit("wind", e.wind, (w) => Math.round((w / 3.6) * 10) / 10); // km/h -> m/s
|
||||
mit("sun", e.sonne);
|
||||
mit("aq", e.aqi);
|
||||
const eigene = client ? this.stimmen.get(client) : null;
|
||||
const vortrag = this.vortragAktiv(jetzt);
|
||||
return {
|
||||
|
|
@ -348,10 +447,19 @@ class Raum {
|
|||
szenario: this.szenario.id,
|
||||
sensor,
|
||||
sensorFelder: Object.keys(sensor), // JsonUtility kennt kein "fehlt" – Unity simuliert die uebrigen Felder
|
||||
quellen, // je Feld sensor | wetter | demo
|
||||
sensorOnline: this.aktuellerMesswert(jetzt) !== null,
|
||||
steuerung: unityBefehl(d),
|
||||
status: d.status.titel,
|
||||
detail: d.status.detail,
|
||||
ton: d.status.ton,
|
||||
prioritaet: d.prioritaet.text,
|
||||
prioritaetNummer: d.prioritaet.nummer,
|
||||
vetos: d.vetos,
|
||||
fensterGesperrt: d.fenster.gesperrt,
|
||||
grenzwerte: { co2Ppm: GRENZWERTE.co2Ppm, laermDb: GRENZWERTE.laermDb, windKmh: GRENZWERTE.windKmh },
|
||||
pruefung: this.pruefungInfo(jetzt),
|
||||
verlauf: this.verlauf.slice(0, 5).map(({ uhrzeit: zeit, titel, grund, ton }) => ({ uhrzeit: zeit, titel, grund, ton })),
|
||||
pfad: d.pfad,
|
||||
zielTemperatur: d.zielTemperatur,
|
||||
stimmen: {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ const { holeWetter } = require("./wetter");
|
|||
|
||||
const PORT = Number(process.argv[2] || process.env.PORT || 3000);
|
||||
const FRONTEND_DIR = path.resolve(__dirname, "..", "frontend");
|
||||
const STARTSEITE = path.join(FRONTEND_DIR, "ambient", "index.html");
|
||||
const WIFI_CONFIG = path.resolve(__dirname, "..", "firmware", "dht11_lcd", "wifi_config.h");
|
||||
const MAX_BODY_BYTES = 1024;
|
||||
const WETTER_INTERVALL_MS = 10 * 60 * 1000;
|
||||
|
|
@ -37,7 +36,9 @@ const MIME = {
|
|||
".data": "application/octet-stream",
|
||||
};
|
||||
|
||||
const raum = new Raum();
|
||||
// Pruefzyklus: alle 2 Minuten wird entschieden (PRUEF_SEKUNDEN=… zum Aendern), "Jetzt pruefen" und Zeitraffer im Webinterface
|
||||
const PRUEF_SEKUNDEN = Number(process.env.PRUEF_SEKUNDEN || 120);
|
||||
const raum = new Raum(Date.now(), { pruefIntervallMs: PRUEF_SEKUNDEN * 1000 });
|
||||
|
||||
function zeitstempel() {
|
||||
return new Date().toLocaleTimeString("de-DE");
|
||||
|
|
@ -117,6 +118,14 @@ const POST_ROUTEN = {
|
|||
"/api/vortragsmodus": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.vortragsmodus(daten)),
|
||||
"/api/jalousie": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.jalousieFahren(daten.position)),
|
||||
"/api/manuell": (res, daten) => nurDozent(res, daten) && aendere(res, () => raum.manuellSetzen(daten)),
|
||||
"/api/pruefen": (res) => aendere(res, () => {
|
||||
raum.jetztPruefen();
|
||||
console.log(zeitstempel(), "Pruefung von Hand ausgeloest");
|
||||
}),
|
||||
"/api/zeitraffer": (res, daten) => aendere(res, () => {
|
||||
raum.zeitrafferSetzen(daten.faktor);
|
||||
console.log(zeitstempel(), `Zeitraffer ${daten.faktor}x (Pruefung alle ${raum.pruefAbstandMs() / 1000} s)`);
|
||||
}),
|
||||
"/api/szenario": (res, daten) => aendere(res, () => {
|
||||
raum.szenarioWaehlen(daten.id);
|
||||
console.log(zeitstempel(), "Szenario:", daten.id);
|
||||
|
|
@ -143,7 +152,12 @@ const GET_ROUTEN = {
|
|||
};
|
||||
|
||||
function sendeDatei(res, pfad) {
|
||||
const datei = pfad === "/" ? STARTSEITE : path.resolve(FRONTEND_DIR, "." + decodeURIComponent(pfad));
|
||||
if (pfad === "/") {
|
||||
// Startseite = Webinterface; Weiterleitung, damit relative Pfade (ambient.css, app.js) stimmen
|
||||
res.writeHead(302, { Location: "/ambient/" });
|
||||
return res.end();
|
||||
}
|
||||
const datei = path.resolve(FRONTEND_DIR, "." + decodeURIComponent(pfad));
|
||||
if (!datei.startsWith(FRONTEND_DIR + path.sep)) return sendeJson(res, 403, { fehler: "Verboten" });
|
||||
const ziel = fs.existsSync(datei) && fs.statSync(datei).isDirectory() ? path.join(datei, "index.html") : datei;
|
||||
fs.readFile(ziel, (fehler, inhalt) => {
|
||||
|
|
@ -212,6 +226,7 @@ function ipHinweis() {
|
|||
// 0.0.0.0, damit der ESP8266 im WLAN/Hotspot den Server erreicht
|
||||
server.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Backend laeuft auf Port ${PORT} (Webinterface: http://localhost:${PORT})`);
|
||||
console.log(`Pruefzyklus alle ${PRUEF_SEKUNDEN} s (Zeitraffer und "Jetzt pruefen" im Webinterface)`);
|
||||
ipHinweis();
|
||||
console.log("Beenden mit Strg+C\n");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,13 +1,15 @@
|
|||
# Simuliert den ESP8266: schickt alle 2 s Fantasiewerte an den Server (Entwicklung ohne Hardware).
|
||||
# Start: python simulator.py [Server-URL] [--szenario NAME] z. B. http://localhost:3000 --szenario hitze
|
||||
#
|
||||
# Szenarien (fuer Vorfuehrungen; das Backend entscheidet, Website und Unity-Zwilling zeigen es):
|
||||
# Szenarien (fuer Vorfuehrungen; das Backend entscheidet, Webinterface und Unity-Zwilling zeigen es):
|
||||
# wechsel (Standard) Temperatur und CO2 schwanken, CO2 ueberschreitet zeitweise 1000 ppm
|
||||
# normal angenehmes Raumklima (22 °C, ca. 650 ppm)
|
||||
# normal angenehmes Raumklima (22 °C, ca. 650 ppm, ca. 45 dB)
|
||||
# hitze Temperatur steigt langsam auf ca. 30 °C -> Fenster oeffnen
|
||||
# stickig CO2 steigt langsam auf ca. 1600 ppm -> Lueften (Fenster oder Lueftungsanlage)
|
||||
# kalt Temperatur faellt auf ca. 17 °C -> Heizen
|
||||
# demo laeuft nacheinander normal -> stickig -> normal -> hitze -> kalt durch (je ca. 1 min)
|
||||
# kalt Temperatur faellt auf ca. 17 °C -> Heizung
|
||||
# laerm CO2 hoch und Lautstaerke ca. 80 dB -> Laerm-Veto: Fenster zu, Lueftungsanlage (ausser Mehrheit will lueften)
|
||||
# dunkel Helligkeit faellt auf ca. 10 % -> Licht heller
|
||||
# demo laeuft nacheinander normal -> stickig -> laerm -> normal -> hitze -> dunkel -> kalt durch (je ca. 1 min)
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
|
|
@ -16,19 +18,27 @@ import urllib.request
|
|||
|
||||
parser = argparse.ArgumentParser(description="Fake-Messwerte wie vom ESP8266")
|
||||
parser.add_argument("basis", nargs="?", default="http://localhost:3000", help="Server-URL")
|
||||
parser.add_argument("--szenario", default="wechsel", choices=["wechsel", "normal", "hitze", "stickig", "kalt", "demo"])
|
||||
parser.add_argument("--szenario", default="wechsel",
|
||||
choices=["wechsel", "normal", "hitze", "stickig", "kalt", "laerm", "dunkel", "demo"])
|
||||
args = parser.parse_args()
|
||||
|
||||
ZIELE = { # Zielwerte (Temperatur °C, eCO2 ppm), auf die sich die Werte langsam zubewegen
|
||||
"normal": (22.0, 650),
|
||||
"hitze": (30.0, 750),
|
||||
"stickig": (23.0, 1600),
|
||||
"kalt": (17.0, 600),
|
||||
ZIELE = { # Zielwerte (Temperatur °C, eCO2 ppm, Lautstaerke dB, Helligkeit %), auf die sich die Werte langsam zubewegen
|
||||
"normal": (22.0, 650, 45.0, 60),
|
||||
"hitze": (30.0, 750, 48.0, 85),
|
||||
"stickig": (23.0, 1600, 52.0, 60),
|
||||
"kalt": (17.0, 600, 42.0, 35),
|
||||
"laerm": (23.0, 1400, 80.0, 60),
|
||||
"dunkel": (22.0, 700, 44.0, 10),
|
||||
}
|
||||
DEMO_ABLAUF = ["normal", "stickig", "normal", "hitze", "kalt"]
|
||||
DEMO_ABLAUF = ["normal", "stickig", "laerm", "normal", "hitze", "dunkel", "kalt"]
|
||||
DEMO_SCHRITTE = 30 # 30 x 2 s = 1 min je Abschnitt
|
||||
|
||||
temperatur, eco2 = 22.0, 650.0
|
||||
|
||||
def naeher(wert, ziel, schritt):
|
||||
return wert + max(-schritt, min(schritt, ziel - wert))
|
||||
|
||||
|
||||
temperatur, eco2, lautstaerke, helligkeit = 22.0, 650.0, 45.0, 60.0
|
||||
schritt = 0
|
||||
|
||||
while True:
|
||||
|
|
@ -36,28 +46,32 @@ while True:
|
|||
if args.szenario == "wechsel":
|
||||
temperatur = 22 + 2 * math.sin(schritt / 20)
|
||||
eco2 = 800 + 400 * math.sin(schritt / 25) # ueberschreitet zeitweise 1000 ppm
|
||||
lautstaerke = 50 + 10 * math.sin(schritt / 7)
|
||||
helligkeit = 55 + 30 * math.sin(schritt / 30)
|
||||
aktiv = "wechsel"
|
||||
else:
|
||||
aktiv = args.szenario
|
||||
if aktiv == "demo":
|
||||
aktiv = DEMO_ABLAUF[(schritt // DEMO_SCHRITTE) % len(DEMO_ABLAUF)]
|
||||
ziel_t, ziel_co2 = ZIELE[aktiv]
|
||||
temperatur += max(-0.4, min(0.4, ziel_t - temperatur))
|
||||
eco2 += max(-60.0, min(60.0, ziel_co2 - eco2))
|
||||
ziel_t, ziel_co2, ziel_laut, ziel_licht = ZIELE[aktiv]
|
||||
temperatur = naeher(temperatur, ziel_t, 0.4)
|
||||
eco2 = naeher(eco2, ziel_co2, 60.0)
|
||||
lautstaerke = naeher(lautstaerke, ziel_laut, 4.0)
|
||||
helligkeit = naeher(helligkeit, ziel_licht, 6.0)
|
||||
|
||||
messwert = {
|
||||
"temperatur": round(temperatur + 0.1 * math.sin(schritt), 1),
|
||||
"luftfeuchte": round(45 + 5 * math.sin(schritt / 15), 1),
|
||||
"eco2": round(eco2 + 10 * math.sin(schritt / 3)),
|
||||
"tvoc": round(70 + 30 * math.sin(schritt / 10) + max(0.0, eco2 - 800) / 10),
|
||||
"lautstaerke": round(50 + 10 * math.sin(schritt / 7), 1), # Mikrofon, gilt im Backend als Aussenlaerm
|
||||
"helligkeit": round(55 + 30 * math.sin(schritt / 30)), # Fotowiderstand in %, zeitweise zu hell
|
||||
"lautstaerke": round(lautstaerke + 1.5 * math.sin(schritt / 2), 1),
|
||||
"helligkeit": max(0, min(100, round(helligkeit + 2 * math.sin(schritt / 4)))),
|
||||
}
|
||||
anfrage = urllib.request.Request(args.basis + "/api/messwerte", data=json.dumps(messwert).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
urllib.request.urlopen(anfrage, timeout=3).read()
|
||||
print(f"gesendet [{aktiv}]", json.dumps(messwert))
|
||||
print(f"gesendet [{aktiv}]", json.dumps(messwert), flush=True)
|
||||
except OSError as fehler:
|
||||
print("Server nicht erreichbar:", fehler)
|
||||
print("Server nicht erreichbar:", fehler, flush=True)
|
||||
time.sleep(2)
|
||||
|
|
|
|||
|
|
@ -240,3 +240,79 @@ test("Unity und Webinterface sehen denselben Zustand", () => {
|
|||
// Keine null-Werte: Unitys JsonUtility kann sie nicht lesen
|
||||
assert.ok(!JSON.stringify(v).includes("null"));
|
||||
});
|
||||
|
||||
test("Pruefzyklus: Messwerte sofort sichtbar, Entscheidung erst zur Pruefung, Jetzt pruefen und Zeitraffer", () => {
|
||||
const t0 = Date.parse("2026-11-24T09:00:00Z");
|
||||
const raum = new Raum(t0, { pruefIntervallMs: 120000 });
|
||||
raum.messwertEmpfangen({ temperatur: 22, eco2: 600, lautstaerke: 45 }, t0);
|
||||
raum.jetztPruefen(t0);
|
||||
assert.equal(raum.zustand(t0).entscheidung.fenster.code, "closed");
|
||||
|
||||
raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + 10000);
|
||||
let z = raum.zustand(t0 + 10000);
|
||||
assert.equal(z.werte.eco2.wert, 1400); // Anzeige sofort
|
||||
assert.equal(z.entscheidung.fenster.code, "closed"); // Entscheidung noch alt
|
||||
assert.equal(z.pruefung.restSekunden, 110);
|
||||
|
||||
for (let t = 20000; t <= 115000; t += 5000) raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + t); // Station sendet laufend
|
||||
assert.equal(raum.zustand(t0 + 115000).entscheidung.fenster.code, "closed");
|
||||
assert.equal(raum.zustand(t0 + 120000).entscheidung.fenster.code, "open"); // naechster Zyklus
|
||||
|
||||
raum.messwertEmpfangen({ temperatur: 22, eco2: 600, lautstaerke: 45 }, t0 + 125000);
|
||||
raum.jetztPruefen(t0 + 125000); // Knopf "Jetzt pruefen"
|
||||
assert.equal(raum.zustand(t0 + 125000).entscheidung.fenster.code, "closed");
|
||||
|
||||
raum.zeitrafferSetzen(10, t0 + 125000);
|
||||
assert.equal(raum.zustand(t0 + 125000).pruefung.restSekunden, 12);
|
||||
assert.throws(() => raum.zeitrafferSetzen(3, t0));
|
||||
});
|
||||
|
||||
test("Zahlenwuensche (Webinterface) werden gemittelt, eine Stimme pro Client, zuruecknehmen moeglich", () => {
|
||||
const t0 = Date.parse("2026-11-24T09:00:00Z");
|
||||
const raum = new Raum(t0);
|
||||
raum.stimmeAbgeben({ client: "tab-aaaa", temperaturWunsch: 23.5 }, t0);
|
||||
raum.stimmeAbgeben({ client: "tab-bbbb", temperaturWunsch: 23.5 }, t0);
|
||||
raum.stimmeAbgeben({ client: "tab-cccc", temperaturWunsch: 23 }, t0);
|
||||
let z = raum.zustand(t0, "tab-aaaa");
|
||||
assert.equal(z.stimmen.gesamt, 3);
|
||||
assert.equal(z.stimmen.durchschnittC, 23.3);
|
||||
assert.equal(z.entscheidung.zielTemperatur, 23.5);
|
||||
assert.equal(z.stimmen.eigene.temperaturWunsch, 23.5);
|
||||
assert.equal(z.stimmen.verteilung["24"], 2); // 23,5 °C rundet auf 24
|
||||
|
||||
raum.stimmeAbgeben({ client: "tab-aaaa", temperaturWunsch: 30 }, t0); // Ueberschreiben, auf 26 °C begrenzt
|
||||
assert.equal(raum.zustand(t0, "tab-aaaa").stimmen.eigene.temperaturWunsch, 26);
|
||||
assert.equal(raum.zustand(t0).stimmen.gesamt, 3);
|
||||
|
||||
raum.stimmeAbgeben({ client: "tab-aaaa", zuruecknehmen: true }, t0);
|
||||
z = raum.zustand(t0, "tab-aaaa");
|
||||
assert.equal(z.stimmen.gesamt, 2);
|
||||
assert.equal(z.stimmen.eigene, null);
|
||||
});
|
||||
|
||||
test("Unity bekommt alle Sensorwerte mit Quelle; Szenario Sensor offline", () => {
|
||||
const t0 = Date.parse("2026-11-24T09:00:00Z");
|
||||
const raum = new Raum(t0);
|
||||
raum.messwertEmpfangen({ temperatur: 23, luftfeuchte: 44, eco2: 1300, tvoc: 200, lautstaerke: 82, helligkeit: 48 }, t0);
|
||||
let u = raum.unity(t0);
|
||||
assert.deepEqual([u.sensor.rh, u.sensor.tvoc, u.sensor.lightpct, u.sensor.nout], [44, 200, 48, 82]);
|
||||
assert.equal(u.quellen.nout, "sensor");
|
||||
assert.equal(u.sensorOnline, true);
|
||||
assert.equal(u.vetos.laerm, true);
|
||||
assert.equal(u.steuerung.window, "closed"); // Laerm sperrt, keine Mehrheit fuer "auf" -> Lueftungsanlage
|
||||
assert.equal(u.steuerung.vent, 1);
|
||||
|
||||
raum.szenarioWaehlen("offline", t0);
|
||||
u = raum.unity(t0);
|
||||
assert.equal(u.sensorOnline, false);
|
||||
assert.equal(u.sensor.co2, undefined);
|
||||
});
|
||||
|
||||
test("Pruefzyklus: erste Messung nach Start oder Ausfall wird sofort geprueft", () => {
|
||||
const t0 = Date.parse("2026-11-24T09:00:00Z");
|
||||
const raum = new Raum(t0, { pruefIntervallMs: 120000 });
|
||||
assert.equal(raum.zustand(t0).sensorOnline, false);
|
||||
raum.messwertEmpfangen({ temperatur: 22, eco2: 1400, lautstaerke: 45 }, t0 + 5000);
|
||||
assert.equal(raum.zustand(t0 + 5000).entscheidung.fenster.code, "open"); // nicht erst nach 2 min
|
||||
assert.ok(raum.verlauf.some((e) => e.titel === "Sensor verbunden"));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,107 @@
|
|||
# Regeln: Wer entscheidet wo, wann und was wird ausgelöst
|
||||
|
||||
Kurzfassung: **Entschieden wird nur im Backend** (`backend/logik.js`), und zwar **alle 2 Minuten** (Prüfzyklus). Das Webinterface ist die Bedienoberfläche (Anzeige + Eingaben), der Unity-Zwilling zeigt nur, was die Entscheidung im Raum bewirkt. Der Ablauf folgt dem Aktivitätsdiagramm [`aktivitaetsdiagramm.png`](aktivitaetsdiagramm.png).
|
||||
|
||||
## 1. Wo wird entschieden?
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Raum["Raum 2.14"]
|
||||
A["Arduino Uno<br/>DHT11 · CCS811 · MAX9814 · LDR"] -->|seriell| E["ESP-01"]
|
||||
end
|
||||
E -->|"POST /api/messwerte<br/>alle ~7 s"| B
|
||||
W["Open-Meteo<br/>Wetter, Feinstaub"] -->|alle 10 min| B
|
||||
subgraph Laptop
|
||||
B["backend/server.js<br/>raum.js + logik.js<br/><b>entscheidet</b>"]
|
||||
end
|
||||
B -->|"GET /api/zustand (1 s)"| F["Webinterface Ambient²<br/>Anzeige + Bedienung<br/>(jeder Tab = 1 Person)"]
|
||||
F -->|"POST Stimme, Vortragsmodus,<br/>Jalousie, Szenario,<br/>Jetzt prüfen, Zeitraffer"| B
|
||||
B -->|"GET /api/unity (1 s)"| U["Unity-Zwilling<br/>nur Anzeige:<br/>3D-Raum führt aus"]
|
||||
```
|
||||
|
||||
| Teil | Aufgabe | Entscheidet? |
|
||||
|---|---|---|
|
||||
| Arduino + ESP-01 (`firmware/dht11_lcd`) | misst Temperatur, Luftfeuchte, eCO₂, TVOC, Lautstärke, Helligkeit; sendet ca. alle 7–8 s | nein |
|
||||
| Backend (`backend/server.js`, `raum.js`, `logik.js`) | sammelt Messwerte, Wetter und Stimmen, prüft alle 2 min, merkt sich den Verlauf | **ja, nur hier** |
|
||||
| Webinterface (`frontend/ambient`) | zeigt Werte und Entscheidung, nimmt Stimmen und Dozentenbefehle an | nein |
|
||||
| Unity-Zwilling (`frontend/SmartLectureRoom`) | zeigt im 3D-Raum, was die Entscheidung auslöst (Fenster, Jalousie, Heizung, Lüftung, Licht, Beamer, Schallwellen bei Lärm) | nein (nur im Modus „Simulation“ oder ohne Backend rechnet er mit derselben Logik selbst) |
|
||||
|
||||
## 2. Wann wird entschieden?
|
||||
|
||||
| Auslöser | Wirkung |
|
||||
|---|---|
|
||||
| **Prüfzyklus alle 2 min** | Entscheidung aus den aktuellen Messwerten und Stimmen neu berechnen |
|
||||
| **„Jetzt prüfen“** (Webinterface) | sofort prüfen, Zyklus beginnt neu |
|
||||
| **Zeitraffer 1× / 5× / 10×** (Webinterface) | Prüfung alle 2 min / 24 s / 12 s |
|
||||
| Erste Messung nach Start oder Ausfall des Arduino | sofort prüfen („Sensor verbunden“) |
|
||||
| Demo-Szenario, Vortragsmodus, manuelle Dozenteneinstellung | sofort prüfen (ausdrücklicher Befehl) |
|
||||
| Vortragsmodus oder manuelle Einstellung läuft ab | sofort prüfen |
|
||||
| neuer Messwert, neue Stimme | **wird sofort angezeigt**, wirkt aber erst bei der nächsten Prüfung („Nach der nächsten Prüfung: 23,0 °C“) |
|
||||
|
||||
Einstellbar: `PRUEF_SEKUNDEN=60 node backend/server.js` (Standard 120).
|
||||
|
||||
## 3. Was wird ausgelöst? (Ablauf eines Prüfzyklus)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S([Prüfzyklus]) --> D[Eingaben sammeln:<br/>Arduino, Wetter, Stimmen,<br/>Vortragsmodus, manuelle Einstellungen]
|
||||
D --> AG["Zielwert = Ø aller Wünsche<br/>(begrenzt auf 20–24 °C)"]
|
||||
AG --> C{"CO₂ > 1000 ppm<br/>oder T > Ziel + 1 °C<br/>(draußen kühler)?"}
|
||||
C -- nein --> FW{"Mehrheit will<br/>Fenster auf?"}
|
||||
FW -- ja --> FO[Fenster offen]
|
||||
FW -- nein --> FZ[Fenster zu]
|
||||
C -- ja: Lüften nötig --> L1{"Außenluft belastet<br/>(PM10 > 50) oder<br/>draußen < 5 °C?"}
|
||||
L1 -- ja --> LA[Lüftungsanlage an,<br/>Fenster zu]
|
||||
L1 -- nein --> L2{"Außenlärm > 70 dB?<br/>(Mikrofon)"}
|
||||
L2 -- nein --> FO2[Fenster offen]
|
||||
L2 -- ja --> L3{"Mehrheit will<br/>Fenster auf?"}
|
||||
L3 -- ja --> FO3[Fenster offen<br/>trotz Lärm]
|
||||
L3 -- nein --> LA2[Lüftungsanlage an,<br/>Fenster gesperrt]
|
||||
FO & FZ & LA & FO2 & FO3 & LA2 --> M[Manuelle Dozenteneinstellungen<br/>überschreiben – 90 min]
|
||||
M --> SR{"Schutzregeln"}
|
||||
SR --> W1["Wind > 60 km/h → höchstens gekippt"]
|
||||
SR --> W2["CO₂ zu hoch und Fenster nicht offen<br/>→ Lüftungsanlage bleibt an"]
|
||||
W1 & W2 --> H{"T < Ziel − 0,5 °C<br/>und Fenster nicht offen?"}
|
||||
H -- ja --> HZ[Heizung an]
|
||||
H -- nein --> HA[Heizung aus]
|
||||
HZ & HA --> J{"Beamer-Modus?"}
|
||||
J -- ja --> JB[Beamer an, Licht aus,<br/>Jalousie unten]
|
||||
J -- nein --> J2{"Lichtsensor > 80 %<br/>(ohne Sensor: Sonne > 500 W/m²)"}
|
||||
J2 -- ja --> JH[Jalousie unten, Licht an]
|
||||
J2 -- nein --> J3{"Lichtsensor < 30 %?"}
|
||||
J3 -- ja --> JD[Jalousie oben, Licht heller]
|
||||
J3 -- nein --> JN[Jalousie oben]
|
||||
JB & JH & JD & JN --> O([Ausgabe an Webinterface und Unity,<br/>Eintrag im Verlauf])
|
||||
```
|
||||
|
||||
### Regeln als Tabelle
|
||||
|
||||
| Priorität | Bedingung | Wird ausgelöst | Kann ein Nutzer das überstimmen? |
|
||||
|---|---|---|---|
|
||||
| 1 Gesundheit | eCO₂ > **1000 ppm** | Lüften: Fenster offen; bei belasteter Außenluft (PM10 > 50 µg/m³) oder < 5 °C draußen stattdessen Lüftungsanlage | **Nein** (Hard-Constraint). Auch bei manuell geschlossenem Fenster bleibt die Lüftungsanlage an. |
|
||||
| 2 Kontext-Veto | Außenlärm > **70 dB** (Mikrofon MAX9814) | automatisches Öffnen gesperrt → Lüftungsanlage statt Fenster | nur die **Mehrheit** („Fenster auf“ > „zu“) öffnet trotzdem |
|
||||
| 2 Kontext-Veto | Wind > **60 km/h** (Wetterdienst) | Fenster höchstens gekippt, Lüftungsanlage hilft | **Nein**, auch manuell nur gekippt |
|
||||
| 3 Dozent | manuelle Einstellung (Fenster, Jalousie, Licht, Lüftung) | hat Vorrang vor der Automatik, gilt **90 min** | Schutzregeln (CO₂, Wind) gelten trotzdem |
|
||||
| 3 Mehrheit | Temperaturwünsche | Zielwert = **Durchschnitt** aller Wünsche (jeder Wunsch auf 18–26 °C begrenzt), Ergebnis auf 20–24 °C begrenzt, auf 0,5 °C gerundet; Abweichung < 0,3 °C von 22 °C zählt als Ausreißer (Ziel bleibt) | jede Stimme zählt gleich, auch die des Dozenten |
|
||||
| 4 Energie | T < Ziel − 0,5 °C | Heizung an (bei offenem Fenster aus) | – |
|
||||
| 4 Energie | T > Ziel + 1 °C und draußen kühler | Lüften zum Kühlen | – |
|
||||
| – | Beamer-Modus (30/60/90 min) | Beamer an, Licht aus, Jalousie unten | Dozent schaltet ihn |
|
||||
| – | Lichtsensor > 80 % (ohne Sensor: Sonne > 500 W/m²) | Jalousie unten, Licht an | Lichtwunsch verschiebt das Licht |
|
||||
| – | Lichtsensor < 30 % | Licht heller | – |
|
||||
|
||||
Alle Grenzwerte stehen oben in [`backend/logik.js`](../backend/logik.js) (`GRENZWERTE`). Die Ersatzlogik in Unity (`ClimateController`) verwendet dieselben Werte.
|
||||
|
||||
## 4. Welche Eingabe wirkt wie?
|
||||
|
||||
| Eingabe | Quelle | wirkt auf |
|
||||
|---|---|---|
|
||||
| eCO₂ | Arduino (CCS811) | Lüften (Priorität 1) |
|
||||
| Temperatur | Arduino (DHT11) | Heizen / Kühlen |
|
||||
| Lautstärke | Arduino (MAX9814), gilt als **Außenlärm** | Fenster-Sperre ab 70 dB |
|
||||
| Helligkeit | Arduino (Fotowiderstand, %) | Jalousie, Licht |
|
||||
| Luftfeuchte, TVOC | Arduino | nur Anzeige |
|
||||
| Wind, Außentemperatur, Feinstaub, Sonne | Open-Meteo (ohne Internet: fehlen) | Wind-Veto, Lüftungsanlage statt Fenster, Jalousie ohne Lichtsensor |
|
||||
| Temperaturwunsch (°C) | Webinterface, **eine Stimme pro Browser-Tab**, verfällt nach 30 min | Zielwert (Durchschnitt) |
|
||||
| Fensterwunsch auf/zu | Webinterface | öffnet trotz Lärm, wenn Mehrheit „auf“ |
|
||||
| Beamer-Modus, Jalousie ↑/↓ | Webinterface (Dozent) | Jalousie/Licht/Beamer, manuelle Phase 90 min |
|
||||
| Demo-Szenario | Webinterface | ersetzt Messwerte durch Beispielwerte (auch in Unity); „Live“ = echte Werte |
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<SmartRoomApp>();
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(ScenePath));
|
||||
EditorSceneManager.SaveScene(scene, ScenePath);
|
||||
EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(ScenePath, true) };
|
||||
new GameObject("SmartRoom").AddComponent<SmartRoomApp>().style = style;
|
||||
Save(scene, path);
|
||||
Debug.Log("[Smart Room] Szene erstellt: " + path + " – Play drücken, um den Raum zu simulieren.");
|
||||
}
|
||||
|
||||
/// <summary>Szene anlegen, ohne die gerade geöffnete Szene zu wechseln.</summary>
|
||||
static void CreateInBackground(string path, RoomStyle style)
|
||||
{
|
||||
var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive);
|
||||
var go = new GameObject("SmartRoom");
|
||||
go.AddComponent<SmartRoomApp>().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<EditorBuildSettingsScene>(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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ namespace SmartRoom
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Grenzwerte wie GRENZWERTE in backend/logik.js, damit Fallback und Backend gleich entscheiden.</summary>
|
||||
/// <summary>Grenzwerte wie GRENZWERTE in backend/logik.js, damit Ersatzlogik und Backend gleich entscheiden.</summary>
|
||||
[Serializable]
|
||||
public class ClimateThresholds
|
||||
{
|
||||
|
|
@ -29,10 +29,13 @@ namespace SmartRoom
|
|||
[Tooltip("°C – über Ziel plus diesem Wert wird gelüftet")] public float coolAbove = 1f;
|
||||
[Tooltip("dB(A) – extremer Außenlärm")] public float noiseLimit = 70f;
|
||||
[Tooltip("m/s – extremer Wind (60 km/h)")] public float windLimit = 16.7f;
|
||||
[Tooltip("W/m² – Sonneneinstrahlung zu hoch")] public float sunLimit = 500f;
|
||||
[Tooltip("W/m² – Sonneneinstrahlung zu hoch (nur ohne Lichtsensor)")] public float sunLimit = 500f;
|
||||
[Tooltip("% – Lichtsensor: darüber zu hell (Jalousie runter)")] public float brightPercent = 80f;
|
||||
[Tooltip("% – Lichtsensor: darunter zu dunkel (Licht heller)")] public float darkPercent = 30f;
|
||||
[Tooltip("°C – draußen zu kalt zum Lüften per Fenster")] public float outdoorColdLimit = 5f;
|
||||
[Tooltip("European AQI – Außenluft schlecht")] public float outdoorAqiLimit = 60f;
|
||||
[Tooltip("lx – Zielbeleuchtung")] public float targetLux = 500f;
|
||||
[Tooltip("°C – Eingabebereich eines einzelnen Wunschs (Ausreißer werden begrenzt)")] public float wishMin = 18f, wishMax = 26f;
|
||||
}
|
||||
|
||||
/// <summary>Ergebnis eines Prüfzyklus inkl. durchlaufenem Pfad im Aktivitätsdiagramm.</summary>
|
||||
|
|
@ -41,17 +44,16 @@ namespace SmartRoom
|
|||
public WindowState window = WindowState.Closed;
|
||||
public float blinds, heating, ventilation, lights;
|
||||
public string time;
|
||||
public string scenario;
|
||||
public bool applied;
|
||||
public readonly List<string> path = new List<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Automatische Steuerentscheidung nach dem Aktivitätsdiagramm:
|
||||
/// Datenerfassung → Aggregation (Nutzerwünsche) → CO2/Temperatur → Lüftung/Fenster → Heizung
|
||||
/// → Soll/Ist-Abgleich Fenster → Jalousie → Licht → virtuelle Aktoren ansteuern → nach 10 min erneut prüfen.
|
||||
/// Ist das gemeinsame Backend verbunden, entscheidet dieses und die lokale Logik ruht (nur Fallback ohne Backend).
|
||||
/// Die Regeln entsprechen backend/logik.js: Lärm sperrt das Fenster außer auf Mehrheitswunsch, Wind max. gekippt,
|
||||
/// Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang, gelten 90 min, CO2 hält die Lüftung an.
|
||||
/// Steuerung des Raums. Im Normalfall entscheidet das gemeinsame Backend (backend/logik.js) und Unity führt
|
||||
/// nur aus (<see cref="ApplyRemote"/>). Ohne Backend oder im Modus „Simulation“ entscheidet diese Ersatzlogik
|
||||
/// nach denselben Regeln (Aktivitätsdiagramm): CO2 → Lüftung, Lärm sperrt das Fenster außer auf Mehrheitswunsch,
|
||||
/// Wind max. gekippt, Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang (90 min).
|
||||
/// </summary>
|
||||
public class ClimateController : MonoBehaviour
|
||||
{
|
||||
|
|
@ -73,10 +75,6 @@ namespace SmartRoom
|
|||
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
public BackendLink backend;
|
||||
|
||||
/// <summary>true, solange das Backend entscheidet.</summary>
|
||||
public bool External => backend != null && backend.Connected;
|
||||
|
||||
public Decision Last { get; private set; }
|
||||
public event Action<Decision> Decided;
|
||||
|
|
@ -84,6 +82,12 @@ namespace SmartRoom
|
|||
double nextCheckAt = double.NegativeInfinity;
|
||||
double manualSince;
|
||||
bool wasCritical, wasRunning = true, wasAuto = true;
|
||||
string lastScenario;
|
||||
|
||||
public const string NormalScenario = "Normalbetrieb";
|
||||
|
||||
/// <summary>Erkanntes Szenario (aus Sensor- bzw. Simulationswerten), Namen wie die Szenario-Knöpfe im HUD.</summary>
|
||||
public string Scenario { get; private set; } = NormalScenario;
|
||||
|
||||
public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes));
|
||||
public float ManualMinutesLeft => autoMode ? 0f : Mathf.Max(0f, (float)(manualSince + manualMinutes - env.simMinutes));
|
||||
|
|
@ -91,25 +95,93 @@ namespace SmartRoom
|
|||
/// <summary>Zielwert = Ø-Wunschtemperatur, begrenzt auf den zulässigen Bereich.</summary>
|
||||
public float TargetTemp => Mathf.Clamp(AverageWish, limits.tempLow, limits.tempHigh);
|
||||
|
||||
/// <summary>Ø aller Temperaturwünsche; jeder Wunsch wird vorher auf den Eingabebereich begrenzt (wie im Backend).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Anzahl der Wünsche außerhalb des Eingabebereichs.</summary>
|
||||
public int ClampedWishes => wishes.FindAll(w => w.temperature < limits.wishMin || w.temperature > limits.wishMax).Count;
|
||||
|
||||
public int WindowVotes => wishes.FindAll(w => w.windowOpen).Count;
|
||||
public bool WindowWanted => wishes.Count > 0 && WindowVotes * 2 > wishes.Count;
|
||||
|
||||
// ---------------------------------------------------------------- Jalousie von Hand (Simulation)
|
||||
double blindOverrideUntil = double.NegativeInfinity;
|
||||
float blindOverride;
|
||||
|
||||
public bool BlindOverrideActive => env != null && env.simMinutes < blindOverrideUntil;
|
||||
public float BlindOverrideMinutesLeft => BlindOverrideActive ? (float)(blindOverrideUntil - env.simMinutes) : 0f;
|
||||
|
||||
/// <summary>Jalousien von Hand fahren; die Automatik übernimmt nach <paramref name="minutes"/> simulierten Minuten wieder.</summary>
|
||||
public void OverrideBlinds(float position, float minutes = 30f)
|
||||
{
|
||||
blindOverride = Mathf.Clamp01(position);
|
||||
blindOverrideUntil = env.simMinutes + minutes;
|
||||
devices.SetBlinds(blindOverride);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Gemeinsames Backend
|
||||
float remoteUntil = -1f;
|
||||
CentralCommand lastRemote;
|
||||
string lastRemoteStatus;
|
||||
|
||||
/// <summary>Das Backend entscheidet gerade (Unity führt nur aus, die Ersatzlogik ruht).</summary>
|
||||
public bool RemoteActive => Time.unscaledTime < remoteUntil;
|
||||
|
||||
/// <summary>Entscheidung des Backends ausführen (GET /api/unity, ca. jede Sekunde).</summary>
|
||||
public void ApplyRemote(CentralState s)
|
||||
{
|
||||
remoteUntil = Time.unscaledTime + 5f;
|
||||
var c = s.steuerung ?? new CentralCommand();
|
||||
bool changed = lastRemote == null || lastRemote.window != c.window || !Same(lastRemote.blind, c.blind) ||
|
||||
!Same(lastRemote.heat, c.heat) || !Same(lastRemote.vent, c.vent) || !Same(lastRemote.light, c.light) ||
|
||||
lastRemote.beamer != c.beamer || lastRemoteStatus != s.status;
|
||||
lastRemote = c;
|
||||
lastRemoteStatus = s.status;
|
||||
|
||||
var d = new Decision
|
||||
{
|
||||
time = env.ClockText,
|
||||
scenario = s.status,
|
||||
window = c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed,
|
||||
blinds = c.blind, heating = c.heat, ventilation = c.vent, lights = c.light,
|
||||
};
|
||||
d.path.Add($"Backend: {s.status} (Priorität {s.prioritaetNummer}: {s.prioritaet})");
|
||||
if (s.pfad != null) d.path.AddRange(s.pfad);
|
||||
if (s.vetos != null && s.vetos.laerm) d.path.Add("Lärmsensor: Außenlärm über dem Grenzwert → Fenster gesperrt");
|
||||
Apply(d);
|
||||
if (devices.projector != null) devices.projector.beamerOn = c.beamer == 1;
|
||||
d.path.Add("Unity führt nur aus: virtuelle Aktoren angesteuert");
|
||||
Last = d;
|
||||
if (changed) Decided?.Invoke(d);
|
||||
}
|
||||
|
||||
/// <summary>Zurück zur Ersatzlogik (Umschalter „Simulation“), sofort neu prüfen.</summary>
|
||||
public void ReleaseRemote()
|
||||
{
|
||||
remoteUntil = -1f;
|
||||
lastRemote = null;
|
||||
lastRemoteStatus = null;
|
||||
nextCheckAt = double.NegativeInfinity;
|
||||
}
|
||||
|
||||
static bool Same(float a, float b) => Mathf.Abs(a - b) < 0.005f;
|
||||
|
||||
// ---------------------------------------------------------------- Ersatzlogik
|
||||
void Update()
|
||||
{
|
||||
if (env == null || devices == null) return;
|
||||
if (External)
|
||||
if (RemoteActive)
|
||||
{
|
||||
Scenario = DetectScenario(); // nur zur Anzeige, entschieden wird im Backend
|
||||
nextCheckAt = double.NegativeInfinity; // fällt das Backend aus, sofort selbst prüfen
|
||||
return;
|
||||
}
|
||||
|
|
@ -133,17 +205,39 @@ namespace SmartRoom
|
|||
}
|
||||
if (!autoMode) EnforceSafety(null);
|
||||
|
||||
// Szenarien werden aus den Messwerten erkannt: Kommt ein neues hinzu, wird sofort geprüft
|
||||
Scenario = DetectScenario();
|
||||
float target = TargetTemp;
|
||||
bool critical = env.co2 > limits.co2Limit || env.indoorTemp > target + limits.coolAbove || env.indoorTemp < target - limits.heatBelow;
|
||||
if (env.simMinutes >= nextCheckAt || (reactImmediately && critical && !wasCritical))
|
||||
bool newScenario = Scenario != lastScenario && Scenario != NormalScenario;
|
||||
if (env.simMinutes >= nextCheckAt || (reactImmediately && ((critical && !wasCritical) || newScenario)))
|
||||
RunCycle();
|
||||
wasCritical = critical;
|
||||
lastScenario = Scenario;
|
||||
}
|
||||
|
||||
/// <summary>Einen kompletten Prüfzyklus ausführen (auch per HUD "Jetzt prüfen").</summary>
|
||||
/// <summary>Ordnet die aktuellen Werte einem Szenario zu (Anzeige und Demo-Knöpfe). Reihenfolge = Priorität.</summary>
|
||||
public string DetectScenario()
|
||||
{
|
||||
var L = limits;
|
||||
float target = TargetTemp;
|
||||
bool co2High = env.co2 > L.co2Limit;
|
||||
bool ventNeeded = co2High || env.indoorTemp > target + L.coolAbove;
|
||||
if (ventNeeded && env.outdoorAqi > L.outdoorAqiLimit) return "Schlechte Außenluft";
|
||||
if (ventNeeded && env.outdoorTemp < L.outdoorColdLimit) return "Stickig + kalt";
|
||||
if (ventNeeded && env.outdoorNoise > L.noiseLimit) return "Baustellenlärm";
|
||||
if (ventNeeded && env.windSpeed > L.windLimit) return "Sturm";
|
||||
if (co2High) return "Stickige Luft";
|
||||
if (env.indoorTemp > target + L.coolAbove) return "Hitze";
|
||||
if (env.indoorTemp < target - L.heatBelow) return "Wintermorgen";
|
||||
if (env.solar > L.sunLimit) return "Pralle Sonne";
|
||||
return NormalScenario;
|
||||
}
|
||||
|
||||
/// <summary>Einen kompletten Prüfzyklus der Ersatzlogik ausführen (auch per HUD "Jetzt prüfen").</summary>
|
||||
public void RunCycle()
|
||||
{
|
||||
if (External) return;
|
||||
if (RemoteActive) return;
|
||||
var d = Evaluate();
|
||||
if (autoMode)
|
||||
{
|
||||
|
|
@ -164,14 +258,17 @@ namespace SmartRoom
|
|||
public Decision Evaluate()
|
||||
{
|
||||
var L = limits;
|
||||
var d = new Decision { time = env.ClockText };
|
||||
var d = new Decision { time = env.ClockText, scenario = DetectScenario() };
|
||||
var p = d.path;
|
||||
float t = env.indoorTemp, co2 = env.co2;
|
||||
float target = TargetTemp;
|
||||
bool wantWindow = WindowWanted;
|
||||
|
||||
p.Add($"Sensordaten: {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx");
|
||||
p.Add($"Sensordaten ({SourceText()}): {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx");
|
||||
p.Add($"Erkanntes Szenario: {d.scenario}");
|
||||
p.Add($"Nutzerwünsche: Ziel {target:0.0} °C (Ø {AverageWish:0.0} °C), Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})");
|
||||
if (ClampedWishes > 0)
|
||||
p.Add($"Temperaturwunsch begrenzt: {ClampedWishes} Wunsch außerhalb {L.wishMin:0}–{L.wishMax:0} °C");
|
||||
|
||||
// --- CO2 / Temperatur
|
||||
bool co2High = co2 > L.co2Limit;
|
||||
|
|
@ -251,28 +348,51 @@ namespace SmartRoom
|
|||
? $"Aktueller Fensterzustand = Sollzustand ({d.window.Label()}) → beibehalten"
|
||||
: $"Fensterzustand {current.Label()} ≠ Soll {d.window.Label()} → anpassen");
|
||||
|
||||
// --- Beamer / Sonne → Jalousie und Licht
|
||||
// --- Beamer / Helligkeit → Jalousie und Licht (wie im Backend: Lichtsensor vor Sonnenstand)
|
||||
bool lightSensor = env.IsMeasured("lightpct");
|
||||
bool tooBright = lightSensor ? env.lightPercent > L.brightPercent : env.solar > L.sunLimit;
|
||||
bool tooDark = lightSensor && env.lightPercent < L.darkPercent;
|
||||
if (devices.BeamerOn)
|
||||
{
|
||||
d.blinds = 1f;
|
||||
d.lights = 0f;
|
||||
p.Add("Beamermodus aktiv → Lichter aus, Jalousie nach unten");
|
||||
}
|
||||
else if (env.solar > L.sunLimit)
|
||||
else if (tooBright)
|
||||
{
|
||||
d.blinds = 1f;
|
||||
d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f);
|
||||
p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten");
|
||||
d.lights = lightSensor ? 0.6f : Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f);
|
||||
p.Add(lightSensor
|
||||
? $"Lichtsensor {env.lightPercent:0} % > {L.brightPercent:0} % → zu hell, Jalousie unten, Licht an"
|
||||
: $"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten");
|
||||
}
|
||||
else
|
||||
{
|
||||
d.blinds = 0f;
|
||||
d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f);
|
||||
p.Add($"Sonneneinstrahlung ok ({env.solar:0} W/m²) → Jalousie nach oben, Licht {d.lights * 100:0} %");
|
||||
d.lights = lightSensor ? (tooDark ? 0.8f : 0.4f) : Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f);
|
||||
p.Add(tooDark
|
||||
? $"Lichtsensor {env.lightPercent:0} % < {L.darkPercent:0} % → zu dunkel, Licht heller"
|
||||
: $"Helligkeit ok → Jalousie nach oben, Licht {d.lights * 100:0} %");
|
||||
}
|
||||
if (BlindOverrideActive)
|
||||
{
|
||||
d.blinds = blindOverride;
|
||||
p.Add($"Jalousien manuell auf {blindOverride * 100:0} % (Automatik pausiert, noch {BlindOverrideMinutesLeft:0} min)");
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
string SourceText()
|
||||
{
|
||||
var measured = new List<string>();
|
||||
if (env.IsMeasured("t")) measured.Add("Temperatur");
|
||||
if (env.IsMeasured("co2")) measured.Add("CO2");
|
||||
if (env.IsMeasured("lightpct")) measured.Add("Licht");
|
||||
if (env.IsMeasured("noise")) measured.Add("Lärm innen");
|
||||
if (env.IsMeasured("nout")) measured.Add("Außenlärm");
|
||||
return measured.Count == 0 ? "Simulation" : "Arduino: " + string.Join(", ", measured);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schutzregeln, die auch manuelle Einstellungen nicht aufheben (wie im Backend):
|
||||
/// bei Sturm höchstens gekippt, bei zu hohem CO2 läuft die Lüftungsanlage, solange das Fenster nicht offen ist.
|
||||
|
|
|
|||
|
|
@ -3,13 +3,17 @@
|
|||
#define SMARTROOM_SERIAL
|
||||
#endif
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
#if SMARTROOM_SERIAL
|
||||
using System.IO.Ports;
|
||||
#endif
|
||||
|
|
@ -33,17 +37,26 @@ namespace SmartRoom
|
|||
public float wind = float.NaN; // Wind m/s
|
||||
public float sun = float.NaN; // Sonneneinstrahlung W/m²
|
||||
public float persons = float.NaN; // Personen im Raum
|
||||
public float rh = float.NaN; // Luftfeuchte innen %
|
||||
public float tvoc = float.NaN; // TVOC innen ppb
|
||||
public float lightpct = float.NaN; // Helligkeit innen % (Fotowiderstand, relativ)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Backend = GruppeC-Aufbau: Arduino Uno + ESP-01 schicken per HTTP-POST an das Backend auf dem Laptop.
|
||||
/// Zentrales Node-Backend (server.js): Unity holt Werte und Entscheidung per GET /api/unity und führt nur aus.
|
||||
/// Älteres server.py (ohne /api/unity): Unity holt die Messwerte per GET /api/messwerte und entscheidet selbst.
|
||||
/// </summary>
|
||||
public enum LinkMode { Simulation, Serial, Udp, Backend }
|
||||
|
||||
/// <summary>
|
||||
/// Verbindung zum Arduino: empfängt Sensordaten (JSON-Zeilen) per USB-Seriell oder UDP (WLAN, z. B. ESP32)
|
||||
/// und sendet die Steuerbefehle der virtuellen Aktoren zurück.
|
||||
/// Im Modus Backend (Standard) kommen Sensorwerte und Entscheidungen vom gemeinsamen Backend, siehe <see cref="BackendLink"/>.
|
||||
/// Verbindung zu den Messwerten. Standard ist das gemeinsame Backend (backend/server.js): Unity holt jede Sekunde
|
||||
/// GET /api/unity und zeigt nur an, was das Backend entscheidet (Bedienung läuft über das Webinterface).
|
||||
/// Läuft UnityWebRequest-basiert, also auch als WebGL im Browser. Daneben USB-Seriell und UDP für eigene Aufbauten.
|
||||
/// </summary>
|
||||
public class ArduinoBridge : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Backend = Werte und Entscheidungen vom Backend (server.js, sonst server.py); ohne laufenden Server bleibt die Simulation aktiv")]
|
||||
public LinkMode mode = LinkMode.Backend;
|
||||
[Tooltip("macOS: /dev/cu.usbmodem… · Windows: COM3")]
|
||||
public string serialPort = "/dev/cu.usbmodem101";
|
||||
|
|
@ -51,11 +64,85 @@ namespace SmartRoom
|
|||
public int udpListenPort = 5005;
|
||||
[Tooltip("Port, an den Steuerbefehle an den Absender zurückgeschickt werden")]
|
||||
public int udpReplyPort = 5006;
|
||||
[Tooltip("Adresse des Backends (server.js oder server.py) – dort kommen die Messwerte des ESP-01 an")]
|
||||
public string backendUrl = "http://localhost:3000";
|
||||
[Tooltip("Abfrageintervall beim Backend in Sekunden")]
|
||||
public float backendPollSeconds = 1f;
|
||||
[Tooltip("Ältere Messwerte im Backend gelten als veraltet und werden ignoriert (Sekunden)")]
|
||||
public float backendMaxAge = 30f;
|
||||
[Tooltip("MAX9814: an = Mikrofon steht draußen (Außenlärm, Sensor-Veto für Fenster), aus = Lärm im Raum")]
|
||||
[SerializeField] bool microphoneOutdoor;
|
||||
[Tooltip("Umrechnung Fotowiderstand % → lx (grob, 100 % ≈ 1000 lx)")]
|
||||
public float luxPerLightPercent = 10f;
|
||||
public bool sendCommands = true;
|
||||
|
||||
/// <summary>Optional: Name des erkannten Szenarios, wird mit den Steuerbefehlen ans Backend gemeldet.</summary>
|
||||
public Func<string> scenarioProvider;
|
||||
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
public BackendLink backend;
|
||||
public ClimateController controller;
|
||||
|
||||
/// <summary>Letzter Zustand des zentralen Backends (null bei server.py oder ohne Verbindung).</summary>
|
||||
public CentralState Central { get; private set; }
|
||||
/// <summary>Das zentrale Backend antwortet gerade (letzte Antwort jünger als 5 s).</summary>
|
||||
public bool CentralActive => useArduinoData && CentralFresh;
|
||||
bool CentralFresh => Central != null && Connected && Time.unscaledTime - centralAt < 5f;
|
||||
float centralAt = -100f;
|
||||
|
||||
[Tooltip("an = Werte vom Arduino übernehmen, aus = Beispielwerte der Simulation (die Verbindung bleibt für die Statusanzeige bestehen)")]
|
||||
[SerializeField] bool useArduinoData = true;
|
||||
float arduinoSeenAt = -100f; // letzte Messung vom Arduino (auch wenn sie gerade nicht übernommen wird)
|
||||
float backendReplyAt = -100f; // letzte Antwort des Backends
|
||||
|
||||
/// <summary>
|
||||
/// Umschalter Arduino-Werte ↔ Simulation. Aus: Beispielwerte wiederherstellen, Unity entscheidet selbst.
|
||||
/// An: Werte (und beim zentralen Backend auch die Entscheidungen) wieder vom Arduino bzw. Backend übernehmen.
|
||||
/// </summary>
|
||||
public bool UseArduinoData
|
||||
{
|
||||
get => useArduinoData;
|
||||
set
|
||||
{
|
||||
if (value == useArduinoData) return;
|
||||
useArduinoData = value;
|
||||
if (!value)
|
||||
{
|
||||
env?.ResetToExampleValues();
|
||||
controller?.ReleaseRemote();
|
||||
return;
|
||||
}
|
||||
if (mode == LinkMode.Simulation) mode = LinkMode.Backend;
|
||||
if (!Connected) Connect();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Kommen gerade Messwerte vom Arduino an (egal ob sie übernommen werden)?</summary>
|
||||
public bool ArduinoConnected
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!Connected) return false;
|
||||
if (CentralFresh) return Central.sensorOnline;
|
||||
return Time.unscaledTime - arduinoSeenAt < (env != null ? env.measurementTimeout : 25f);
|
||||
}
|
||||
}
|
||||
|
||||
public bool BackendReachable => Connected && Time.unscaledTime - backendReplyAt < 5f;
|
||||
|
||||
/// <summary>Statuszeile zum Arduino für die Dashboards.</summary>
|
||||
public string ArduinoDetail
|
||||
{
|
||||
get
|
||||
{
|
||||
if (ArduinoConnected)
|
||||
return $"Arduino verbunden · letzte Messung vor {Mathf.Max(0f, Time.unscaledTime - arduinoSeenAt):0} s";
|
||||
if (!Connected) return "Arduino nicht verbunden · keine Verbindung eingestellt";
|
||||
if (mode == LinkMode.Backend && !BackendReachable) return "Arduino nicht verbunden · Backend nicht erreichbar (läuft server.js?)";
|
||||
if (mode == LinkMode.Backend) return "Arduino nicht verbunden · Backend läuft, aber keine Messwerte";
|
||||
return "Arduino nicht verbunden · keine Messwerte";
|
||||
}
|
||||
}
|
||||
|
||||
public string Status { get; private set; } = "Simulation aktiv";
|
||||
public bool Connected { get; private set; }
|
||||
|
|
@ -64,6 +151,17 @@ namespace SmartRoom
|
|||
public float LastPacketTime { get; private set; } = -1f;
|
||||
public int PacketCount { get; private set; }
|
||||
|
||||
public bool MicrophoneOutdoor
|
||||
{
|
||||
get => microphoneOutdoor;
|
||||
set
|
||||
{
|
||||
if (value == microphoneOutdoor) return;
|
||||
microphoneOutdoor = value;
|
||||
env?.Forget(value ? "noise" : "nout"); // alter Kanal soll nicht noch als "Sensor" gelten
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SerialSupported
|
||||
{
|
||||
get
|
||||
|
|
@ -83,6 +181,13 @@ namespace SmartRoom
|
|||
UdpClient udp;
|
||||
IPEndPoint remote;
|
||||
float nextSend;
|
||||
string pendingCommand; // Rueckmeldung an server.py (veraltet), server.js braucht keine
|
||||
string lastBackendTime;
|
||||
const string HttpPrefix = "!HTTP ";
|
||||
const string CentralPrefix = "!UNITY ";
|
||||
Coroutine backendLoop;
|
||||
static readonly Regex AktuellRx = new Regex("\"aktuell\"\\s*:\\s*(null|\\{[^{}]*\\})");
|
||||
static readonly Regex FieldRx = new Regex("\"(\\w+)\"\\s*:\\s*(\"[^\"]*\"|[^,}\\s]+)");
|
||||
#if SMARTROOM_SERIAL
|
||||
SerialPort port;
|
||||
#endif
|
||||
|
|
@ -96,6 +201,15 @@ namespace SmartRoom
|
|||
#endif
|
||||
}
|
||||
|
||||
void Awake()
|
||||
{
|
||||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||||
// Im Browser läuft der Zwilling auf der Seite des Backends: dessen Adresse übernehmen, nicht "localhost"
|
||||
if (Application.absoluteURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
|
||||
backendUrl = new Uri(Application.absoluteURL).GetLeftPart(UriPartial.Authority);
|
||||
#endif
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (mode != LinkMode.Simulation) Connect();
|
||||
|
|
@ -110,11 +224,7 @@ namespace SmartRoom
|
|||
{
|
||||
case LinkMode.Serial: OpenSerial(); break;
|
||||
case LinkMode.Udp: OpenUdp(); break;
|
||||
case LinkMode.Backend:
|
||||
backend.Begin();
|
||||
Connected = true;
|
||||
Status = "Gemeinsames Backend " + backend.serverUrl;
|
||||
break;
|
||||
case LinkMode.Backend: OpenBackend(); break;
|
||||
default: Status = "Simulation aktiv"; break;
|
||||
}
|
||||
}
|
||||
|
|
@ -141,11 +251,22 @@ namespace SmartRoom
|
|||
{
|
||||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||||
Status = "UDP im Browser nicht verfügbar: Verbindung → Backend nutzen";
|
||||
#else
|
||||
return;
|
||||
#endif
|
||||
udp = new UdpClient(udpListenPort);
|
||||
StartWorker(UdpLoop);
|
||||
Status = $"Lausche auf UDP-Port {udpListenPort}";
|
||||
#endif
|
||||
}
|
||||
|
||||
void OpenBackend()
|
||||
{
|
||||
lastBackendTime = null;
|
||||
pendingCommand = null;
|
||||
Central = null;
|
||||
running = true;
|
||||
Connected = true;
|
||||
backendLoop = StartCoroutine(BackendPoll());
|
||||
Status = "Frage " + backendUrl + " ab …";
|
||||
}
|
||||
|
||||
void StartWorker(ThreadStart loop)
|
||||
|
|
@ -166,8 +287,9 @@ namespace SmartRoom
|
|||
port = null;
|
||||
#endif
|
||||
try { udp?.Close(); } catch { }
|
||||
if (backend != null) backend.End();
|
||||
udp = null;
|
||||
if (backendLoop != null) StopCoroutine(backendLoop);
|
||||
backendLoop = null;
|
||||
if (worker != null && worker.IsAlive) worker.Join(800);
|
||||
worker = null;
|
||||
lock (remoteLock) remote = null;
|
||||
|
|
@ -216,6 +338,173 @@ namespace SmartRoom
|
|||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Backend (HTTP, auch WebGL)
|
||||
IEnumerator BackendPoll()
|
||||
{
|
||||
string baseUrl = backendUrl.Trim().TrimEnd('/');
|
||||
bool legacy = false; // true: altes server.py ohne /api/unity
|
||||
while (running)
|
||||
{
|
||||
if (!legacy)
|
||||
{
|
||||
using (var req = UnityWebRequest.Get(baseUrl + "/api/unity"))
|
||||
{
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
if (!running) yield break;
|
||||
if (req.result == UnityWebRequest.Result.Success) ApplyCentral(req.downloadHandler.text);
|
||||
else if (req.responseCode == 404) legacy = true; // server.py: Messwerte holen und selbst entscheiden
|
||||
else Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ") – läuft backend/server.js?";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var req = UnityWebRequest.Get(baseUrl + "/api/messwerte"))
|
||||
{
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
if (!running) yield break;
|
||||
if (req.result == UnityWebRequest.Result.Success) ApplyBackend(req.downloadHandler.text);
|
||||
else
|
||||
{
|
||||
Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ")";
|
||||
legacy = false; // evtl. wurde inzwischen server.js gestartet
|
||||
}
|
||||
}
|
||||
if (pendingCommand != null)
|
||||
{
|
||||
string cmd = pendingCommand;
|
||||
pendingCommand = null;
|
||||
using (var req = new UnityWebRequest(baseUrl + "/api/steuerung", UnityWebRequest.kHttpVerbPOST))
|
||||
{
|
||||
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(cmd));
|
||||
req.downloadHandler = new DownloadHandlerBuffer();
|
||||
req.SetRequestHeader("Content-Type", "application/json");
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
yield return new WaitForSecondsRealtime(backendPollSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wertet GET /api/unity des zentralen Backends aus: Sensorwerte (mit Quelle) übernehmen, Entscheidung ausführen.
|
||||
/// </summary>
|
||||
void ApplyCentral(string json)
|
||||
{
|
||||
CentralState s;
|
||||
try { s = JsonUtility.FromJson<CentralState>(json); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status = "Antwort des Backends nicht lesbar: " + ex.Message;
|
||||
return;
|
||||
}
|
||||
if (s == null) return;
|
||||
|
||||
var p = new SensorPacket();
|
||||
string sensorJson = JsonObject(json, "sensor");
|
||||
if (sensorJson != null) JsonUtility.FromJsonOverwrite(sensorJson, p);
|
||||
if (!float.IsNaN(p.lightpct)) p.lux = p.lightpct * luxPerLightPercent;
|
||||
|
||||
Central = s;
|
||||
centralAt = backendReplyAt = Time.unscaledTime;
|
||||
PacketCount++;
|
||||
if (s.sensorOnline) LastPacketTime = arduinoSeenAt = Time.unscaledTime;
|
||||
LastLine = sensorJson ?? "";
|
||||
if (!useArduinoData)
|
||||
{
|
||||
Status = "Zentrales Backend (server.js) erreichbar · Simulation aktiv, Werte werden nicht übernommen";
|
||||
return;
|
||||
}
|
||||
env.ApplyRemote(p, channel => s.SourceOf(channel) == "sensor");
|
||||
controller?.ApplyRemote(s);
|
||||
Status = s.sensorOnline ? "Zentrales Backend (server.js) · Arduino live"
|
||||
: s.szenario != null && s.szenario != "live" ? $"Zentrales Backend (server.js) · Demo-Szenario „{s.szenario}“"
|
||||
: "Zentrales Backend (server.js) · kein Arduino (Werte aus Wetter/Simulation)";
|
||||
}
|
||||
|
||||
/// <summary>Unterobjekt <c>"key":{…}</c> aus einem JSON-Text (für Felder, die NaN-Vorgaben brauchen).</summary>
|
||||
static string JsonObject(string json, string key)
|
||||
{
|
||||
int i = json.IndexOf("\"" + key + "\"", StringComparison.Ordinal);
|
||||
if (i < 0) return null;
|
||||
i = json.IndexOf('{', i);
|
||||
if (i < 0) return null;
|
||||
int depth = 0;
|
||||
for (int j = i; j < json.Length; j++)
|
||||
{
|
||||
if (json[j] == '{') depth++;
|
||||
else if (json[j] == '}' && --depth == 0) return json.Substring(i, j - i + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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":[…]}
|
||||
/// </summary>
|
||||
void ApplyBackend(string json)
|
||||
{
|
||||
backendReplyAt = Time.unscaledTime;
|
||||
var m = AktuellRx.Match(json);
|
||||
if (!m.Success || m.Groups[1].Value == "null")
|
||||
{
|
||||
Status = "Backend erreichbar · noch keine Messwerte vom Arduino";
|
||||
return;
|
||||
}
|
||||
|
||||
var f = new Dictionary<string, string>();
|
||||
foreach (Match fm in FieldRx.Matches(m.Groups[1].Value))
|
||||
f[fm.Groups[1].Value] = fm.Groups[2].Value.Trim('"');
|
||||
f.TryGetValue("zeit", out var zeit);
|
||||
|
||||
if (zeit != null && zeit == lastBackendTime)
|
||||
{
|
||||
// kein neuer Messwert seit der letzten Abfrage
|
||||
if (LastPacketTime < 0f || Time.unscaledTime - LastPacketTime > env.measurementTimeout)
|
||||
Status = "Backend erreichbar · keine neuen Messwerte (Arduino/ESP aus?)";
|
||||
return;
|
||||
}
|
||||
lastBackendTime = zeit;
|
||||
|
||||
if (zeit != null && DateTime.TryParse(zeit, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var ts))
|
||||
{
|
||||
double age = (DateTime.UtcNow - ts.ToUniversalTime()).TotalSeconds;
|
||||
if (age > backendMaxAge)
|
||||
{
|
||||
Status = $"Letzter Messwert im Backend ist {age:0} s alt – Arduino sendet gerade nicht";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
float laut = Num(f, "lautstaerke"), licht = Num(f, "helligkeit");
|
||||
var p = new SensorPacket
|
||||
{
|
||||
t = Num(f, "temperatur"),
|
||||
rh = Num(f, "luftfeuchte"),
|
||||
co2 = Num(f, "eco2"),
|
||||
tvoc = Num(f, "tvoc"),
|
||||
lightpct = licht,
|
||||
lux = licht * luxPerLightPercent, // NaN bleibt NaN
|
||||
};
|
||||
if (microphoneOutdoor) p.nout = laut; else p.noise = laut;
|
||||
LastLine = m.Groups[1].Value;
|
||||
LastPacketTime = arduinoSeenAt = Time.unscaledTime;
|
||||
PacketCount++;
|
||||
if (!useArduinoData)
|
||||
{
|
||||
Status = "Backend verbunden · Simulation aktiv, Arduino-Werte werden nicht übernommen";
|
||||
return;
|
||||
}
|
||||
env.ApplyMeasurement(p);
|
||||
Status = "Backend verbunden · Messwerte vom Arduino (ESP-01)";
|
||||
}
|
||||
|
||||
static float Num(Dictionary<string, string> f, string key)
|
||||
=> f.TryGetValue(key, out var s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : float.NaN;
|
||||
|
||||
void Update()
|
||||
{
|
||||
while (inbox.TryDequeue(out var line))
|
||||
|
|
@ -225,14 +514,24 @@ namespace SmartRoom
|
|||
Status = "Verbindungsfehler: " + line.Substring(4).Trim();
|
||||
continue;
|
||||
}
|
||||
if (line.StartsWith(HttpPrefix))
|
||||
{
|
||||
ApplyBackend(line.Substring(HttpPrefix.Length));
|
||||
continue;
|
||||
}
|
||||
if (line.StartsWith(CentralPrefix))
|
||||
{
|
||||
ApplyCentral(line.Substring(CentralPrefix.Length));
|
||||
continue;
|
||||
}
|
||||
LastLine = line;
|
||||
if (!line.StartsWith("{")) continue; // Debug-Ausgaben des Arduino ignorieren
|
||||
try
|
||||
{
|
||||
var p = new SensorPacket();
|
||||
JsonUtility.FromJsonOverwrite(line, p);
|
||||
env.ApplyMeasurement(p);
|
||||
LastPacketTime = Time.unscaledTime;
|
||||
if (useArduinoData) env.ApplyMeasurement(p);
|
||||
LastPacketTime = arduinoSeenAt = Time.unscaledTime;
|
||||
PacketCount++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -242,8 +541,7 @@ namespace SmartRoom
|
|||
}
|
||||
|
||||
// Steuerbefehle senden, sobald sie sich ändern (spätestens alle 10 s als Heartbeat)
|
||||
// Im Backend-Modus entscheidet das Backend; Unity schickt keine eigenen Befehle
|
||||
if (Connected && sendCommands && devices != null && mode != LinkMode.Backend)
|
||||
if (Connected && sendCommands && useArduinoData && devices != null && !CentralFresh) // das zentrale Backend braucht keine Rückmeldung
|
||||
{
|
||||
string cmd = BuildCommand();
|
||||
if (cmd != LastSent || Time.unscaledTime >= nextSend)
|
||||
|
|
@ -264,6 +562,9 @@ namespace SmartRoom
|
|||
sb.Append(",\"vent\":").Append(devices.VentTarget.ToString("0.00", ci));
|
||||
sb.Append(",\"light\":").Append(devices.LightTarget.ToString("0.00", ci));
|
||||
sb.Append(",\"beamer\":").Append(devices.BeamerOn ? 1 : 0);
|
||||
string scenario = scenarioProvider?.Invoke();
|
||||
if (mode == LinkMode.Backend && !string.IsNullOrEmpty(scenario))
|
||||
sb.Append(",\"szenario\":\"").Append(scenario.Replace("\"", "'")).Append('"');
|
||||
sb.Append('}');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
|
@ -276,6 +577,7 @@ namespace SmartRoom
|
|||
#if SMARTROOM_SERIAL
|
||||
if (mode == LinkMode.Serial && port != null && port.IsOpen) port.WriteLine(json);
|
||||
#endif
|
||||
if (mode == LinkMode.Backend) pendingCommand = json; // nur fuer server.py, server.js entscheidet selbst
|
||||
if (mode == LinkMode.Udp && udp != null)
|
||||
{
|
||||
IPEndPoint target;
|
||||
|
|
|
|||
|
|
@ -1,201 +0,0 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
// Antwort von GET /api/unity (backend/raum.js → unity()). Das Backend liefert keine null-Werte.
|
||||
[Serializable] public class BackendCommand { public string window = "closed"; public float blind, heat, vent, light; public int beamer; }
|
||||
[Serializable] public class BackendVotes
|
||||
{
|
||||
public int kuehler, angenehm, waermer, dunkler, passt, heller, auf, zu, gesamt;
|
||||
public string eigeneTemperatur = "", eigeneLicht = "", eigeneFenster = "";
|
||||
}
|
||||
[Serializable] public class BackendLecture { public bool aktiv; public int restMinuten, dauerMinuten = 60; }
|
||||
/// <summary>Manuelle Einstellungen des Dozenten: -1 bzw. "" = Automatik.</summary>
|
||||
[Serializable] public class BackendManual
|
||||
{
|
||||
public bool aktiv;
|
||||
public string fenster = "", bis = "";
|
||||
public int jalousie = -1, licht = -1, lueftung = -1;
|
||||
}
|
||||
[Serializable] public class BackendScenario { public string id, text, beschreibung; }
|
||||
[Serializable] public class BackendState
|
||||
{
|
||||
public string zeit, szenario, status, detail, prioritaet;
|
||||
public SensorPacket sensor = new SensorPacket();
|
||||
public string[] sensorFelder = new string[0];
|
||||
public BackendCommand steuerung = new BackendCommand();
|
||||
public string[] pfad = new string[0];
|
||||
public float zielTemperatur = 22f;
|
||||
public BackendVotes stimmen = new BackendVotes();
|
||||
public BackendLecture vortrag = new BackendLecture();
|
||||
public BackendManual manuell = new BackendManual();
|
||||
public BackendScenario[] szenarien = new BackendScenario[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gemeinsames Backend (backend/server.js): Es entscheidet für Webinterface und Zwilling gleichermaßen.
|
||||
/// Holt jede Sekunde GET /api/unity, übernimmt Sensorwerte und führt den Steuerbefehl nur aus.
|
||||
/// Stimmen, Szenario, Vortragsmodus und Jalousie aus dem HUD gehen an dieselben Endpunkte wie beim Webinterface.
|
||||
/// </summary>
|
||||
public class BackendLink : MonoBehaviour
|
||||
{
|
||||
public string serverUrl = "http://localhost:3000";
|
||||
[Tooltip("Abfrageintervall in Sekunden")] public float pollSeconds = 1f;
|
||||
[Tooltip("So lange ohne Antwort gilt das Backend als getrennt; dann übernimmt die lokale Logik")]
|
||||
public float timeoutSeconds = 5f;
|
||||
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
|
||||
public bool Active { get; private set; }
|
||||
public bool Connected => Active && LastPacketTime >= 0f && Time.unscaledTime - LastPacketTime < timeoutSeconds;
|
||||
public string Status { get; private set; } = "aus";
|
||||
public BackendState State { get; private set; }
|
||||
public float LastPacketTime { get; private set; } = -1f;
|
||||
public int PacketCount { get; private set; }
|
||||
|
||||
/// <summary>Eigene Kennung als "Client" – wie ein Browser im Webinterface, eine Stimme pro Zwilling.</summary>
|
||||
public string ClientId { get; private set; }
|
||||
|
||||
Coroutine loop;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
string id = SystemInfo.deviceUniqueIdentifier;
|
||||
if (string.IsNullOrEmpty(id) || id == SystemInfo.unsupportedIdentifier) id = Guid.NewGuid().ToString("N");
|
||||
ClientId = "unity-" + id.Substring(0, Mathf.Min(12, id.Length));
|
||||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||||
// Im Browser läuft der Zwilling auf der Seite des Backends: dessen Adresse übernehmen, nicht "localhost".
|
||||
// Nur bei http(s); beim Öffnen per file:// bleibt die eingestellte URL.
|
||||
if (Application.absoluteURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
|
||||
serverUrl = new Uri(Application.absoluteURL).GetLeftPart(UriPartial.Authority);
|
||||
#endif
|
||||
}
|
||||
|
||||
string Base => serverUrl.TrimEnd('/');
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
End();
|
||||
Active = true;
|
||||
Status = "Verbinde mit " + Base + " …";
|
||||
loop = StartCoroutine(Poll());
|
||||
}
|
||||
|
||||
public void End()
|
||||
{
|
||||
if (loop != null) StopCoroutine(loop);
|
||||
loop = null;
|
||||
Active = false;
|
||||
Status = "aus";
|
||||
}
|
||||
|
||||
IEnumerator Poll()
|
||||
{
|
||||
while (Active)
|
||||
{
|
||||
using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId)))
|
||||
{
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text);
|
||||
else Status = $"Backend nicht erreichbar ({req.error}) – lokale Logik aktiv";
|
||||
}
|
||||
yield return new WaitForSecondsRealtime(pollSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
void Receive(string json)
|
||||
{
|
||||
BackendState s;
|
||||
try { s = JsonUtility.FromJson<BackendState>(json); }
|
||||
catch (Exception ex) { Status = "Ungültige Antwort: " + ex.Message; return; }
|
||||
if (s == null) return;
|
||||
|
||||
// Nur Felder übernehmen, die das Backend wirklich kennt – der Rest bleibt simuliert
|
||||
var p = new SensorPacket();
|
||||
foreach (var f in s.sensorFelder)
|
||||
{
|
||||
switch (f)
|
||||
{
|
||||
case "t": p.t = s.sensor.t; break;
|
||||
case "co2": p.co2 = s.sensor.co2; break;
|
||||
case "lux": p.lux = s.sensor.lux; break;
|
||||
case "noise": p.noise = s.sensor.noise; break;
|
||||
case "tout": p.tout = s.sensor.tout; break;
|
||||
case "aq": p.aq = s.sensor.aq; break;
|
||||
case "nout": p.nout = s.sensor.nout; break;
|
||||
case "wind": p.wind = s.sensor.wind; break;
|
||||
case "sun": p.sun = s.sensor.sun; break;
|
||||
case "persons": p.persons = s.sensor.persons; break;
|
||||
}
|
||||
}
|
||||
env.ApplyMeasurement(p);
|
||||
|
||||
var c = s.steuerung;
|
||||
devices.SetWindows(c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed);
|
||||
devices.SetBlinds(c.blind);
|
||||
devices.SetHeating(c.heat);
|
||||
devices.SetVentilation(c.vent);
|
||||
devices.SetLights(c.light);
|
||||
if (devices.projector != null) devices.projector.beamerOn = c.beamer != 0;
|
||||
|
||||
State = s;
|
||||
LastPacketTime = Time.unscaledTime;
|
||||
PacketCount++;
|
||||
Status = $"Verbunden mit {Base} · Szenario {s.szenario}";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Eingaben ans Backend
|
||||
// Werte wie im Webinterface: temperatur kuehler|angenehm|waermer, licht dunkler|passt|heller
|
||||
|
||||
public void VoteTemperature(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"temperatur\":\"{wert}\"}}");
|
||||
public void VoteLight(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"licht\":\"{wert}\"}}");
|
||||
/// <summary>auf | zu</summary>
|
||||
public void VoteWindow(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"fenster\":\"{wert}\"}}");
|
||||
public void ChooseScenario(string id) => Post("/api/szenario", $"{{\"id\":\"{id}\"}}");
|
||||
public void SetLecture(bool aktiv) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"aktiv\":{(aktiv ? "true" : "false")}}}");
|
||||
public void SetLectureDuration(int minuten) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"dauerMinuten\":{minuten}}}");
|
||||
/// <summary>
|
||||
/// Manuelle Einstellung (gilt 90 min): feld fenster|jalousie|licht|lueftung, wert als JSON,
|
||||
/// z. B. "\"open\"", "100", "\"an\"" oder "\"auto\"" für Automatik.
|
||||
/// </summary>
|
||||
public void SetManual(string feld, string jsonWert) => Post("/api/manuell", $"{{\"rolle\":\"dozent\",\"{feld}\":{jsonWert}}}");
|
||||
public void ResetManual() => Post("/api/manuell", "{\"rolle\":\"dozent\",\"zuruecksetzen\":true}");
|
||||
|
||||
void Post(string path, string json)
|
||||
{
|
||||
if (Active) StartCoroutine(PostRoutine(path, json));
|
||||
}
|
||||
|
||||
IEnumerator PostRoutine(string path, string json)
|
||||
{
|
||||
using (var req = new UnityWebRequest(Base + path, UnityWebRequest.kHttpVerbPOST))
|
||||
{
|
||||
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
|
||||
req.downloadHandler = new DownloadHandlerBuffer();
|
||||
req.SetRequestHeader("Content-Type", "application/json");
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
if (req.result != UnityWebRequest.Result.Success)
|
||||
{
|
||||
Status = $"{path} fehlgeschlagen: {req.error} {req.downloadHandler.text}";
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
// Ergebnis sofort abholen statt bis zur nächsten Abfrage zu warten
|
||||
using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId)))
|
||||
{
|
||||
req.timeout = 3;
|
||||
yield return req.SendWebRequest();
|
||||
if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text);
|
||||
}
|
||||
}
|
||||
|
||||
void OnDisable() => End();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
using System;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Antwort von GET /api/unity des gemeinsamen Backends (backend/raum.js → unity()).
|
||||
/// Das Backend entscheidet für Webinterface und Unity gemeinsam; Unity zeigt nur an und führt aus.
|
||||
/// Das Backend liefert keine null-Werte (in "manuell" bedeutet -1 bzw. "" Automatik).
|
||||
/// Die Sensorwerte ("sensor") liest <see cref="ArduinoBridge"/> separat in ein <see cref="SensorPacket"/>.
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class CentralState
|
||||
{
|
||||
public string zeit, szenario, status, detail, ton, prioritaet;
|
||||
public int prioritaetNummer;
|
||||
public float zielTemperatur;
|
||||
public bool sensorOnline, fensterGesperrt;
|
||||
public CentralCommand steuerung = new CentralCommand();
|
||||
public CentralSources quellen = new CentralSources();
|
||||
public CentralVetos vetos = new CentralVetos();
|
||||
public CentralLimits grenzwerte = new CentralLimits();
|
||||
public CentralVotes stimmen = new CentralVotes();
|
||||
public CentralTimer vortrag = new CentralTimer();
|
||||
public CentralManual manuell = new CentralManual();
|
||||
public CentralCheck pruefung = new CentralCheck();
|
||||
public string[] pfad = new string[0];
|
||||
public CentralEntry[] verlauf = new CentralEntry[0];
|
||||
public CentralScenario[] szenarien = new CentralScenario[0];
|
||||
|
||||
/// <summary>Quelle eines Sensorkanals: "sensor", "wetter", "demo" oder null.</summary>
|
||||
public string SourceOf(string channel)
|
||||
{
|
||||
switch (channel)
|
||||
{
|
||||
case "t": return quellen.t;
|
||||
case "co2": return quellen.co2;
|
||||
case "rh": return quellen.rh;
|
||||
case "tvoc": return quellen.tvoc;
|
||||
case "lightpct":
|
||||
case "lux": return quellen.lightpct;
|
||||
case "nout": return quellen.nout;
|
||||
case "tout": return quellen.tout;
|
||||
case "wind": return quellen.wind;
|
||||
case "sun": return quellen.sun;
|
||||
case "aq": return quellen.aq;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Steuerbefehl, gleiches Format wie <see cref="ArduinoBridge.BuildCommand"/>.</summary>
|
||||
[Serializable]
|
||||
public class CentralCommand
|
||||
{
|
||||
public string window = "closed";
|
||||
public float blind, heat, vent, light;
|
||||
public int beamer;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralSources
|
||||
{
|
||||
public string t, co2, rh, tvoc, lightpct, nout, tout, wind, sun, aq;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralVetos
|
||||
{
|
||||
public bool co2, laerm, wind, aussenluft;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralLimits
|
||||
{
|
||||
public float co2Ppm = 1000f, laermDb = 70f, windKmh = 60f;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralVotes
|
||||
{
|
||||
public int kuehler, angenehm, waermer, auf, zu, gesamt;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralTimer
|
||||
{
|
||||
public bool aktiv;
|
||||
public int restMinuten, dauerMinuten;
|
||||
}
|
||||
|
||||
/// <summary>Manuelle Dozenteneinstellungen aus dem Webinterface (-1 bzw. "" = Automatik).</summary>
|
||||
[Serializable]
|
||||
public class CentralManual
|
||||
{
|
||||
public bool aktiv;
|
||||
public string fenster = "", bis = "";
|
||||
public int jalousie = -1, licht = -1, lueftung = -1;
|
||||
}
|
||||
|
||||
/// <summary>Prüfzyklus des Backends (alle 2 min, Zeitraffer 1×/5×/10×).</summary>
|
||||
[Serializable]
|
||||
public class CentralCheck
|
||||
{
|
||||
public int intervallSekunden = 120, zeitraffer = 1, abstandSekunden = 120, restSekunden;
|
||||
public string letzteUhrzeit = "";
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralEntry
|
||||
{
|
||||
public string uhrzeit, titel, grund, ton;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class CentralScenario
|
||||
{
|
||||
public string id, text, beschreibung;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,9 @@ using UnityEngine;
|
|||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Optik des Raums: Classic = ursprünglicher Zwilling, Ambient = Look des Web-Frontends (Ambient²).</summary>
|
||||
public enum RoomStyle { Classic, Ambient }
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
/// <summary>Grün des Ambient-Frontends (--green #175c45).</summary>
|
||||
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<RoomDevices>();
|
||||
if (devices == null) devices = root.gameObject.AddComponent<RoomDevices>();
|
||||
|
||||
|
|
@ -70,6 +75,36 @@ namespace SmartRoom
|
|||
slideAccent = Mat.Emissive(Accent, Accent);
|
||||
}
|
||||
|
||||
/// <summary>Helle, matte Salbei-/Grüntöne wie in der Raumansicht des Web-Frontends.</summary>
|
||||
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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,142 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Macht den Außenlärm (Lautstärkesensor MAX9814 bzw. Simulation) im 3D-Raum sichtbar: Schallwellen-Ringe
|
||||
/// vor der Fensterfront, je lauter, desto mehr, größer und schneller. Über dem Grenzwert (Standard 70 dB) werden
|
||||
/// sie rot – dann gilt das Sensor-Veto: Fenster gesperrt, Lüftungsanlage statt Fenster (außer die Mehrheit will lüften). Ein Schild an der Fassade zeigt den Pegel.
|
||||
/// </summary>
|
||||
public class NoiseVisualizer : MonoBehaviour
|
||||
{
|
||||
public RoomEnvironment env;
|
||||
public ClimateController controller;
|
||||
public ArduinoBridge bridge;
|
||||
[Tooltip("Unterhalb dieses Pegels keine Wellen (dB)")] public float quietDb = 55f;
|
||||
|
||||
static readonly Color Calm = new Color(0.55f, 0.72f, 0.64f, 0.55f);
|
||||
static readonly Color Loud = new Color(0.66f, 0.25f, 0.21f, 0.8f);
|
||||
|
||||
ParticleSystem waves;
|
||||
TextMesh label;
|
||||
Material ringMat;
|
||||
Texture2D ringTex;
|
||||
|
||||
void Start()
|
||||
{
|
||||
// Wellen kommen von der Straße links vor der Fensterfront (x < 0) und laufen auf den Raum zu
|
||||
var go = new GameObject("Schallwellen");
|
||||
go.transform.SetParent(transform, false);
|
||||
go.transform.localPosition = new Vector3(-RoomBuilder.W / 2f - 2.2f, 1.7f, 0f);
|
||||
waves = go.AddComponent<ParticleSystem>();
|
||||
waves.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
||||
|
||||
var main = waves.main;
|
||||
main.loop = true;
|
||||
main.startLifetime = 2.2f;
|
||||
main.startSpeed = 0f;
|
||||
main.startSize = 0.4f;
|
||||
main.maxParticles = 80;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.playOnAwake = true;
|
||||
|
||||
var shape = waves.shape;
|
||||
shape.shapeType = ParticleSystemShapeType.Box;
|
||||
shape.scale = new Vector3(0.2f, 1.2f, RoomBuilder.D * 0.8f);
|
||||
|
||||
var vel = waves.velocityOverLifetime;
|
||||
vel.enabled = true;
|
||||
vel.space = ParticleSystemSimulationSpace.World;
|
||||
vel.x = new ParticleSystem.MinMaxCurve(0.6f);
|
||||
vel.y = new ParticleSystem.MinMaxCurve(0f);
|
||||
vel.z = new ParticleSystem.MinMaxCurve(0f);
|
||||
|
||||
var size = waves.sizeOverLifetime;
|
||||
size.enabled = true;
|
||||
size.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.Linear(0f, 0.3f, 1f, 3.2f));
|
||||
|
||||
var col = waves.colorOverLifetime;
|
||||
col.enabled = true;
|
||||
var g = new Gradient();
|
||||
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
|
||||
new[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(1f, 0.15f), new GradientAlphaKey(0f, 1f) });
|
||||
col.color = g;
|
||||
|
||||
ringTex = RingTexture(64);
|
||||
ringMat = new Material(Shader.Find("Sprites/Default")) { mainTexture = ringTex };
|
||||
var r = go.GetComponent<ParticleSystemRenderer>();
|
||||
r.material = ringMat;
|
||||
r.renderMode = ParticleSystemRenderMode.Billboard;
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
r.receiveShadows = false;
|
||||
|
||||
var emission = waves.emission;
|
||||
emission.rateOverTime = 0f;
|
||||
waves.Play();
|
||||
|
||||
// Pegelanzeige an der Fassade (von innen durch die Fenster lesbar)
|
||||
var sign = new GameObject("Pegelanzeige");
|
||||
sign.transform.SetParent(transform, false);
|
||||
sign.transform.localPosition = new Vector3(-RoomBuilder.W / 2f - 0.6f, RoomBuilder.WinTopY + 0.32f, 0f);
|
||||
sign.transform.localRotation = Quaternion.Euler(0f, -90f, 0f);
|
||||
label = sign.AddComponent<TextMesh>();
|
||||
label.anchor = TextAnchor.MiddleCenter;
|
||||
label.alignment = TextAlignment.Center;
|
||||
label.characterSize = 0.05f;
|
||||
label.fontSize = 64;
|
||||
var font = Prim.BuiltinFont();
|
||||
if (font != null)
|
||||
{
|
||||
label.font = font;
|
||||
sign.GetComponent<MeshRenderer>().sharedMaterial = font.material;
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (env == null || waves == null) return;
|
||||
float db = env.outdoorNoise;
|
||||
float limit = bridge != null && bridge.CentralActive ? bridge.Central.grenzwerte.laermDb
|
||||
: controller != null ? controller.limits.noiseLimit : 70f;
|
||||
bool veto = db > limit;
|
||||
float k = Mathf.InverseLerp(quietDb, 95f, db); // 0 = ruhig, 1 = sehr laut
|
||||
|
||||
var emission = waves.emission;
|
||||
emission.rateOverTime = db <= quietDb ? 0f : Mathf.Lerp(2f, 22f, k);
|
||||
var main = waves.main;
|
||||
main.startColor = veto ? Loud : Color.Lerp(Calm, new Color(0.85f, 0.6f, 0.25f, 0.65f), k);
|
||||
main.startSize = Mathf.Lerp(0.35f, 0.9f, k);
|
||||
var vel = waves.velocityOverLifetime;
|
||||
vel.x = new ParticleSystem.MinMaxCurve(Mathf.Lerp(0.4f, 1.6f, k));
|
||||
|
||||
if (label != null)
|
||||
{
|
||||
bool sensor = env.IsMeasured("nout");
|
||||
label.text = $"Außenlärm {db:0} dB{(sensor ? " · Sensor" : "")}{(veto ? "\nFenster gesperrt" : "")}";
|
||||
label.color = veto ? new Color(0.75f, 0.2f, 0.15f) : new Color(0.25f, 0.33f, 0.3f);
|
||||
}
|
||||
}
|
||||
|
||||
static Texture2D RingTexture(int n)
|
||||
{
|
||||
var t = new Texture2D(n, n, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, hideFlags = HideFlags.HideAndDontSave };
|
||||
var px = new Color[n * n];
|
||||
for (int y = 0; y < n; y++)
|
||||
for (int x = 0; x < n; x++)
|
||||
{
|
||||
float d = Vector2.Distance(new Vector2(x + 0.5f, y + 0.5f), new Vector2(n / 2f, n / 2f)) / (n / 2f);
|
||||
float a = Mathf.Clamp01(1f - Mathf.Abs(d - 0.82f) / 0.12f); // Ring bei 82 % des Radius
|
||||
px[y * n + x] = new Color(1f, 1f, 1f, a * a);
|
||||
}
|
||||
t.SetPixels(px);
|
||||
t.Apply();
|
||||
return t;
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (ringMat != null) Destroy(ringMat);
|
||||
if (ringTex != null) Destroy(ringTex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +27,12 @@ namespace SmartRoom
|
|||
public float co2 = 650f; // ppm
|
||||
public float indoorLux = 300f; // lx
|
||||
public float indoorNoise = 42f; // dB(A)
|
||||
[Tooltip("Nur gemessen (DHT11), wird nicht simuliert")]
|
||||
public float indoorHumidity = 45f; // %
|
||||
[Tooltip("Nur gemessen (CCS811), wird nicht simuliert")]
|
||||
public float tvoc = 0f; // ppb
|
||||
[Tooltip("Nur gemessen (Fotowiderstand), relativ 0–100 %")]
|
||||
public float lightPercent = 0f;
|
||||
|
||||
[Header("Außen (Wetterdaten / Sensoren / manuell)")]
|
||||
public float outdoorTemp = 14f; // °C
|
||||
|
|
@ -36,11 +42,12 @@ namespace SmartRoom
|
|||
public float solar = 350f; // W/m² Globalstrahlung
|
||||
|
||||
[Tooltip("Sekunden, die ein Messwert als 'live' gilt")]
|
||||
public float measurementTimeout = 15f;
|
||||
public float measurementTimeout = 25f; // Station sendet ca. alle 7–8 s, fällt eine Sendung aus ca. alle 15 s
|
||||
|
||||
public RoomDevices devices;
|
||||
|
||||
readonly Dictionary<string, float> measuredAt = new Dictionary<string, float>();
|
||||
readonly Dictionary<string, float> measuredAt = new Dictionary<string, float>(); // echter Sensorwert
|
||||
readonly Dictionary<string, float> providedAt = new Dictionary<string, float>(); // von außen vorgegeben (Sensor, Wetter, Demo)
|
||||
|
||||
public string ClockText
|
||||
{
|
||||
|
|
@ -51,9 +58,34 @@ namespace SmartRoom
|
|||
}
|
||||
}
|
||||
|
||||
// Beispielwerte beim Start (Umschalter "Simulation" stellt sie wieder her)
|
||||
float[] example;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
example = new[] { indoorTemp, co2, indoorLux, indoorNoise, indoorHumidity, tvoc, lightPercent,
|
||||
outdoorTemp, outdoorAqi, outdoorNoise, windSpeed, solar, occupants };
|
||||
}
|
||||
|
||||
/// <summary>Zurück zu den Beispielwerten der Simulation; alle Arduino-/Backend-Werte werden verworfen.</summary>
|
||||
public void ResetToExampleValues()
|
||||
{
|
||||
measuredAt.Clear();
|
||||
providedAt.Clear();
|
||||
if (example == null) return;
|
||||
indoorTemp = example[0]; co2 = example[1]; indoorLux = example[2]; indoorNoise = example[3];
|
||||
indoorHumidity = example[4]; tvoc = example[5]; lightPercent = example[6];
|
||||
outdoorTemp = example[7]; outdoorAqi = example[8]; outdoorNoise = example[9];
|
||||
windSpeed = example[10]; solar = example[11]; occupants = Mathf.RoundToInt(example[12]);
|
||||
}
|
||||
|
||||
public bool IsMeasured(string channel)
|
||||
=> measuredAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout;
|
||||
|
||||
/// <summary>Wert kommt von außen (Arduino oder zentrales Backend) und wird nicht simuliert.</summary>
|
||||
public bool IsProvided(string channel)
|
||||
=> providedAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout;
|
||||
|
||||
public bool AnyMeasured
|
||||
{
|
||||
get
|
||||
|
|
@ -65,8 +97,25 @@ namespace SmartRoom
|
|||
}
|
||||
|
||||
/// <summary>Übernimmt ein Datenpaket vom Arduino. Fehlende Felder (NaN) werden ignoriert.</summary>
|
||||
public void ApplyMeasurement(SensorPacket p)
|
||||
public void ApplyMeasurement(SensorPacket p) => Apply(p, _ => true);
|
||||
|
||||
/// <summary>
|
||||
/// Übernimmt Werte des zentralen Backends. Alle gesendeten Werte ersetzen die Simulation,
|
||||
/// als "Sensor" gelten aber nur die, für die <paramref name="isSensor"/> true liefert (nicht Wetter/Demo).
|
||||
/// </summary>
|
||||
public void ApplyRemote(SensorPacket p, Func<string, bool> isSensor) => Apply(p, isSensor);
|
||||
|
||||
void Apply(SensorPacket p, Func<string, bool> isSensor)
|
||||
{
|
||||
void Set(string channel, float v, Action<float> apply)
|
||||
{
|
||||
if (float.IsNaN(v)) return;
|
||||
apply(v);
|
||||
providedAt[channel] = Time.unscaledTime;
|
||||
if (isSensor(channel)) measuredAt[channel] = Time.unscaledTime;
|
||||
else measuredAt.Remove(channel);
|
||||
}
|
||||
|
||||
Set("t", p.t, v => indoorTemp = v);
|
||||
Set("co2", p.co2, v => co2 = v);
|
||||
Set("lux", p.lux, v => indoorLux = v);
|
||||
|
|
@ -77,13 +126,16 @@ namespace SmartRoom
|
|||
Set("wind", p.wind, v => windSpeed = v);
|
||||
Set("sun", p.sun, v => solar = v);
|
||||
Set("persons", p.persons, v => occupants = Mathf.RoundToInt(v));
|
||||
Set("rh", p.rh, v => indoorHumidity = v);
|
||||
Set("tvoc", p.tvoc, v => tvoc = v);
|
||||
Set("lightpct", p.lightpct, v => lightPercent = v);
|
||||
}
|
||||
|
||||
void Set(string channel, float v, Action<float> apply)
|
||||
/// <summary>Kanal sofort wieder simulieren (z. B. wenn das Mikrofon von innen nach außen wechselt).</summary>
|
||||
public void Forget(string channel)
|
||||
{
|
||||
if (float.IsNaN(v)) return;
|
||||
apply(v);
|
||||
measuredAt[channel] = Time.unscaledTime;
|
||||
measuredAt.Remove(channel);
|
||||
providedAt.Remove(channel);
|
||||
}
|
||||
|
||||
/// <summary>Geschätzte Tageslicht-Beleuchtungsstärke im Raum bei gegebener Jalousie-Abschirmung.</summary>
|
||||
|
|
@ -101,9 +153,9 @@ namespace SmartRoom
|
|||
for (int i = 0; i < steps; i++) Integrate(h);
|
||||
|
||||
float win = devices.WindowAirflow;
|
||||
if (!IsMeasured("lux"))
|
||||
if (!IsProvided("lux"))
|
||||
indoorLux = DaylightLux(devices.BlindClosure) + devices.LightLevel * 520f;
|
||||
if (!IsMeasured("noise"))
|
||||
if (!IsProvided("noise"))
|
||||
{
|
||||
float people = lectureRunning ? 45f : 30f;
|
||||
float outside = outdoorNoise - Mathf.Lerp(32f, 8f, win);
|
||||
|
|
@ -120,14 +172,14 @@ namespace SmartRoom
|
|||
float achVent = vent * 6f;
|
||||
int persons = lectureRunning ? occupants : 0;
|
||||
|
||||
if (!IsMeasured("co2"))
|
||||
if (!IsProvided("co2"))
|
||||
{
|
||||
float gen = persons * 0.0083f; // ppm/s pro Person (~0,005 l/s CO2)
|
||||
co2 += (gen - (achWindow + achVent) / 3600f * (co2 - OutdoorCo2)) * h;
|
||||
co2 = Mathf.Max(OutdoorCo2, co2);
|
||||
}
|
||||
|
||||
if (!IsMeasured("t"))
|
||||
if (!IsProvided("t"))
|
||||
{
|
||||
float pHeat = devices.HeatingLevel * 9000f;
|
||||
float pPeople = persons * 80f;
|
||||
|
|
|
|||
|
|
@ -10,24 +10,22 @@ namespace SmartRoom
|
|||
[DefaultExecutionOrder(-100)]
|
||||
public class SmartRoomApp : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Classic = ursprünglicher Zwilling mit dunklem Dashboard, Ambient = Optik des Web-Frontends (Ambient²)")]
|
||||
public RoomStyle style = RoomStyle.Classic;
|
||||
|
||||
public RoomDevices Devices { get; private set; }
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Devices = RoomBuilder.Build(transform);
|
||||
Devices = RoomBuilder.Build(transform, style);
|
||||
|
||||
var env = GetOrAdd<RoomEnvironment>();
|
||||
env.devices = Devices;
|
||||
Devices.env = env;
|
||||
|
||||
var backend = GetOrAdd<BackendLink>();
|
||||
backend.env = env;
|
||||
backend.devices = Devices;
|
||||
|
||||
var bridge = GetOrAdd<ArduinoBridge>();
|
||||
bridge.env = env;
|
||||
bridge.devices = Devices;
|
||||
bridge.backend = backend;
|
||||
|
||||
var weather = GetOrAdd<WeatherService>();
|
||||
weather.env = env;
|
||||
|
|
@ -35,26 +33,63 @@ namespace SmartRoom
|
|||
var controller = GetOrAdd<ClimateController>();
|
||||
controller.env = env;
|
||||
controller.devices = Devices;
|
||||
controller.backend = backend;
|
||||
bridge.scenarioProvider = () => controller.Scenario;
|
||||
bridge.controller = controller;
|
||||
|
||||
// Außenlärm im 3D-Raum sichtbar machen (Schallwellen vor der Fensterfront)
|
||||
var noise = new GameObject("Außenlärm (Visualisierung)").AddComponent<NoiseVisualizer>();
|
||||
noise.transform.SetParent(transform, false);
|
||||
noise.env = env;
|
||||
noise.controller = controller;
|
||||
noise.bridge = bridge;
|
||||
|
||||
Devices.sun = SetupSun();
|
||||
var orbit = SetupCamera();
|
||||
QualitySettings.pixelLightCount = Mathf.Max(QualitySettings.pixelLightCount, 8);
|
||||
|
||||
if (style == RoomStyle.Ambient)
|
||||
{
|
||||
SetupAmbient(env, controller, bridge, weather, orbit);
|
||||
return;
|
||||
}
|
||||
|
||||
var hud = GetOrAdd<SmartRoomHUD>();
|
||||
hud.env = env;
|
||||
hud.devices = Devices;
|
||||
hud.controller = controller;
|
||||
hud.bridge = bridge;
|
||||
hud.backend = backend;
|
||||
hud.weather = weather;
|
||||
hud.orbit = orbit;
|
||||
|
||||
Devices.projector.contentProvider = () =>
|
||||
$"Innen {env.indoorTemp:0.0} °C · CO2 {env.co2:0} ppm · {env.indoorLux:0} lx\n" +
|
||||
$"Außen {env.outdoorTemp:0.0} °C · Wind {env.windSpeed:0.0} m/s · AQI {env.outdoorAqi:0}\n" +
|
||||
$"Fenster {Devices.WindowLabel} · Lüftung {Devices.VentLevel * 100f:0} % · Heizung {Devices.HeatingLevel * 100f:0} %";
|
||||
$"Fenster {Devices.WindowLabel} · Lüftung {Devices.VentLevel * 100f:0} % · Heizung {Devices.HeatingLevel * 100f:0} %\n" +
|
||||
$"Szenario {controller.Scenario} · Quelle {(env.AnyMeasured ? "Arduino" : "Simulation")}";
|
||||
}
|
||||
|
||||
QualitySettings.pixelLightCount = Mathf.Max(QualitySettings.pixelLightCount, 8);
|
||||
/// <summary>Helles, weiches Licht und das Dashboard im Look des Web-Frontends.</summary>
|
||||
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<AmbientHUD>();
|
||||
hud.env = env;
|
||||
hud.devices = Devices;
|
||||
hud.controller = controller;
|
||||
hud.bridge = bridge;
|
||||
hud.weather = weather;
|
||||
hud.orbit = orbit;
|
||||
hud.roomCamera = orbit.GetComponent<Camera>();
|
||||
|
||||
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<T>() where T : Component
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -22,6 +22,9 @@ namespace SmartRoom
|
|||
|
||||
public bool IsDragging => dragging;
|
||||
|
||||
/// <summary>Optional: rechnet eine GUI-Position in einen Strahl um (wenn die Kamera in eine Textur rendert).</summary>
|
||||
public System.Func<Vector2, Ray> 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;
|
||||
}
|
||||
|
||||
/// <summary>Beliebige Ansicht anfahren (snap = sofort statt weich).</summary>
|
||||
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<DoorActuator>();
|
||||
|
|
|
|||
|
|
@ -8,8 +8,6 @@ namespace SmartRoom
|
|||
/// Schlichtes, dunkles Dashboard (IMGUI, keine Zusatzpakete nötig):
|
||||
/// links Raumklima + Außenwerte + Szenarien, rechts Steuerung / Nutzerwünsche / Verbindung,
|
||||
/// unten der zuletzt durchlaufene Pfad der Entscheidungslogik.
|
||||
/// Ist das gemeinsame Backend verbunden, zeigt das HUD dessen Zustand und schickt Eingaben dorthin
|
||||
/// (dieselben Endpunkte wie das Webinterface) – Website und Zwilling zeigen dann immer dasselbe.
|
||||
/// </summary>
|
||||
public class SmartRoomHUD : MonoBehaviour
|
||||
{
|
||||
|
|
@ -17,7 +15,6 @@ namespace SmartRoom
|
|||
public RoomDevices devices;
|
||||
public ClimateController controller;
|
||||
public ArduinoBridge bridge;
|
||||
public BackendLink backend;
|
||||
public WeatherService weather;
|
||||
public OrbitCamera orbit;
|
||||
public bool visible = true;
|
||||
|
|
@ -37,30 +34,12 @@ namespace SmartRoom
|
|||
bool showBottom, logCollapsed;
|
||||
Vector2 leftScroll, rightScroll, logScroll;
|
||||
int tab;
|
||||
string latField, lonField, udpField, urlField;
|
||||
string latField, lonField, udpField, backendField;
|
||||
string[] foundPorts;
|
||||
|
||||
static readonly string[] Tabs = { "Steuerung", "Wünsche", "Verbindung" };
|
||||
static readonly string[] SpeedLabels = { "Pause", "1×", "5×", "20×" };
|
||||
static readonly float[] Speeds = { 0f, 1f, 5f, 20f };
|
||||
static readonly string[] TempVotes = { "kuehler", "angenehm", "waermer" };
|
||||
static readonly string[] TempVoteLabels = { "Kühler", "Angenehm", "Wärmer" };
|
||||
static readonly string[] LightVotes = { "dunkler", "passt", "heller" };
|
||||
static readonly string[] LightVoteLabels = { "Dunkler", "Passt", "Heller" };
|
||||
static readonly int[] LectureMinutes = { 30, 60, 90 };
|
||||
static readonly string[] WindowVotes = { "auf", "zu" };
|
||||
static readonly string[] WindowVoteLabels = { "Auf", "Zu lassen" };
|
||||
// Manuelle Einstellungen: Index 0 = Automatik, Werte als JSON für /api/manuell
|
||||
static readonly string[] ManualWindowCodes = { "", "closed", "tilted", "open" };
|
||||
static readonly string[] ManualWindowLabels = { "Auto", "Zu", "Kipp", "Auf" };
|
||||
static readonly int[] ManualPercent = { -1, 0, 50, 100 };
|
||||
static readonly string[] ManualBlindLabels = { "Auto", "Oben", "Halb", "Unten" };
|
||||
static readonly string[] ManualLightLabels = { "Auto", "Aus", "50 %", "100 %" };
|
||||
static readonly string[] ManualVentLabels = { "Auto", "Aus", "An" };
|
||||
|
||||
/// <summary>Backend verbunden: Es entscheidet, das HUD zeigt nur an und leitet Eingaben weiter.</summary>
|
||||
bool Shared => backend != null && backend.Connected && backend.State != null;
|
||||
BackendState B => backend.State;
|
||||
|
||||
float S(float v) => v * scale;
|
||||
int I(float v) => Mathf.RoundToInt(v * scale);
|
||||
|
|
@ -115,9 +94,8 @@ namespace SmartRoom
|
|||
case KeyCode.Alpha3: orbit?.Preset(2); break;
|
||||
case KeyCode.Alpha4: orbit?.Preset(3); break;
|
||||
case KeyCode.T: devices.door?.Toggle(); break;
|
||||
case KeyCode.B:
|
||||
if (Shared) backend.SetLecture(!B.vortrag.aktiv); // Beamer folgt dem Vortragsmodus des Backends
|
||||
else if (devices.projector != null) devices.projector.beamerOn = !devices.projector.beamerOn;
|
||||
case KeyCode.B: // mit Backend steuert das Webinterface den Beamer
|
||||
if (devices.projector != null && (bridge == null || !bridge.CentralActive)) devices.projector.beamerOn = !devices.projector.beamerOn;
|
||||
break;
|
||||
case KeyCode.Space: controller.RunCycle(); break;
|
||||
default: return;
|
||||
|
|
@ -139,11 +117,25 @@ namespace SmartRoom
|
|||
void DrawLeft()
|
||||
{
|
||||
GUILayout.Label("Smart Lecture Room", title);
|
||||
string src = Shared ? "gemeinsames Backend"
|
||||
: bridge.mode == LinkMode.Backend ? "Backend getrennt, lokale Logik"
|
||||
: env.AnyMeasured ? "Arduino live" : "Simulation";
|
||||
string src = bridge != null && !bridge.UseArduinoData ? "Simulation" : env.AnyMeasured ? "Arduino live" : bridge != null && bridge.Connected ? "warte auf Arduino" : "Simulation";
|
||||
GUILayout.Label($"Digitaler Zwilling · {env.ClockText} · {src}", dim);
|
||||
|
||||
// Arduino-Status und Umschalter Arduino-Werte ↔ Simulation (Beispielwerte)
|
||||
if (bridge != null)
|
||||
{
|
||||
bool arduino = bridge.ArduinoConnected;
|
||||
GUILayout.Space(S(6));
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
Tag(arduino ? "ARDUINO VERBUNDEN" : "ARDUINO NICHT VERBUNDEN", arduino ? Good : Bad);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(bridge.ArduinoDetail, dim);
|
||||
int src2 = GUILayout.Toolbar(bridge.UseArduinoData ? 0 : 1, new[] { "Arduino-Werte", "Simulation" }, seg);
|
||||
if (src2 != (bridge.UseArduinoData ? 0 : 1)) bridge.UseArduinoData = src2 == 0;
|
||||
GUILayout.EndVertical();
|
||||
}
|
||||
|
||||
GUILayout.Space(S(8));
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Vorlesung läuft", label);
|
||||
|
|
@ -164,30 +156,44 @@ namespace SmartRoom
|
|||
env.IsMeasured("t"));
|
||||
Metric("CO2", $"{co2:0} ppm", Mathf.InverseLerp(400f, 2000f, co2),
|
||||
co2 < 800f ? Good : co2 <= controller.limits.co2Limit ? Warn : Bad, env.IsMeasured("co2"));
|
||||
Metric("Helligkeit", $"{env.indoorLux:0} lx", Mathf.InverseLerp(0f, 1200f, env.indoorLux), Accent, env.IsMeasured("lux"));
|
||||
Metric("Lärm", $"{env.indoorNoise:0} dB", Mathf.InverseLerp(30f, 90f, env.indoorNoise),
|
||||
Metric("Helligkeit", env.IsMeasured("lightpct") ? $"{env.lightPercent:0} % (≈ {env.indoorLux:0} lx)" : $"{env.indoorLux:0} lx",
|
||||
Mathf.InverseLerp(0f, 1200f, env.indoorLux), Accent, env.IsMeasured("lux"));
|
||||
Metric("Lärm im Raum", $"{env.indoorNoise:0} dB", Mathf.InverseLerp(30f, 90f, env.indoorNoise),
|
||||
env.indoorNoise < 55f ? Good : env.indoorNoise < 70f ? Warn : Bad, env.IsMeasured("noise"));
|
||||
// Luftfeuchte und TVOC werden nicht simuliert – nur anzeigen, wenn der Arduino sie liefert
|
||||
if (env.IsMeasured("rh"))
|
||||
Metric("Luftfeuchte", $"{env.indoorHumidity:0} %", env.indoorHumidity / 100f,
|
||||
env.indoorHumidity >= 30f && env.indoorHumidity <= 60f ? Good : Warn, true);
|
||||
if (env.IsMeasured("tvoc"))
|
||||
Metric("TVOC", $"{env.tvoc:0} ppb", Mathf.InverseLerp(0f, 1000f, env.tvoc),
|
||||
env.tvoc < 220f ? Good : env.tvoc < 660f ? Warn : Bad, true);
|
||||
|
||||
env.occupants = Mathf.RoundToInt(SliderRow("Personen im Raum", env.occupants, 0f, 120f, "{0:0}", !env.IsMeasured("persons")));
|
||||
if (!env.IsMeasured("t"))
|
||||
if (!env.IsProvided("t"))
|
||||
env.indoorTemp = SliderRow("Temperatur innen setzen", env.indoorTemp, 10f, 35f, "{0:0.0} °C");
|
||||
if (!env.IsMeasured("co2"))
|
||||
if (!env.IsProvided("co2"))
|
||||
env.co2 = SliderRow("CO2 innen setzen", env.co2, 400f, 2500f, "{0:0} ppm");
|
||||
|
||||
Section(weather != null && weather.useLiveWeather ? "AUSSEN · OPEN-METEO" : "AUSSEN");
|
||||
// Werte vom Backend/Arduino lassen sich nicht verschieben (würden sofort wieder überschrieben)
|
||||
env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C", !env.IsMeasured("tout"));
|
||||
env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}", !env.IsMeasured("aq"));
|
||||
env.outdoorNoise = SliderRow("Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsMeasured("nout"));
|
||||
env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s", !env.IsMeasured("wind"));
|
||||
env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²", !env.IsMeasured("sun"));
|
||||
env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C", !env.IsProvided("tout"));
|
||||
env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}", !env.IsProvided("aq"));
|
||||
env.outdoorNoise = SliderRow(env.IsMeasured("nout") ? "Lärm (Mikrofon draußen)" : "Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsProvided("nout"));
|
||||
env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s", !env.IsProvided("wind"));
|
||||
env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²", !env.IsProvided("sun"));
|
||||
|
||||
Section("SZENARIEN");
|
||||
if (Shared)
|
||||
if (bridge != null && bridge.CentralActive)
|
||||
{
|
||||
DrawBackendScenarios();
|
||||
DrawCentralScenarios(bridge.Central);
|
||||
return;
|
||||
}
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Erkannt", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag(controller.Scenario, controller.Scenario == ClimateController.NormalScenario ? Good : Warn);
|
||||
Tag(env.AnyMeasured ? "AUS SENSORDATEN" : "AUS SIMULATION", env.AnyMeasured ? Good : TextDim);
|
||||
GUILayout.EndHorizontal();
|
||||
ScenarioRow("Hitze 30 °C", () => { env.indoorTemp = 30f; env.outdoorTemp = 24f; env.solar = 750f; env.windSpeed = 2f; env.outdoorNoise = 55f; env.outdoorAqi = 25f; },
|
||||
"Stickig + kalt", () => { env.co2 = 1600f; env.outdoorTemp = -2f; env.solar = 150f; });
|
||||
ScenarioRow("Schlechte Außenluft", () => { env.co2 = 1450f; env.outdoorAqi = 85f; env.outdoorTemp = 15f; },
|
||||
|
|
@ -200,38 +206,48 @@ namespace SmartRoom
|
|||
env.indoorTemp = 22f; env.co2 = 650f; env.outdoorTemp = 14f; env.outdoorAqi = 25f;
|
||||
env.outdoorNoise = 55f; env.windSpeed = 3f; env.solar = 350f;
|
||||
});
|
||||
GUILayout.Label("Szenarien setzen Werte und lösen sofort einen Prüfzyklus aus. Mit Arduino werden gemessene Innenwerte überschrieben.", dim);
|
||||
GUILayout.Label("Das passende Szenario wird aus den Werten erkannt (hervorgehoben) und löst sofort einen Prüfzyklus aus. Mit Arduino kommen Temperatur und CO2 vom Sensor – Knöpfe setzen dann nur noch die Außenwerte.", dim);
|
||||
GUILayout.Space(S(4));
|
||||
GUILayout.Label("Maus: ziehen = drehen · Shift/rechts = schieben · Rad = Zoom · Tür anklicken\nTasten: 1–4 Ansichten · T Tür · B Beamer · Leertaste prüfen · H Dashboard", dim);
|
||||
}
|
||||
|
||||
void DrawBackendScenarios()
|
||||
/// <summary>Zentrales Backend: Demo-Szenarien gelten für Webinterface und Unity gleichzeitig.</summary>
|
||||
void DrawCentralScenarios(CentralState c)
|
||||
{
|
||||
var list = B.szenarien;
|
||||
for (int i = 0; i < list.Length; i += 2)
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Backend", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag(c.status ?? "", c.ton == "good" ? Good : c.ton == "danger" ? Bad : Warn);
|
||||
GUILayout.EndHorizontal();
|
||||
for (int i = 0; i < c.szenarien.Length; i += 2)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
for (int k = i; k < Mathf.Min(i + 2, list.Length); k++)
|
||||
for (int j = i; j < i + 2 && j < c.szenarien.Length; j++)
|
||||
{
|
||||
var sc = list[k];
|
||||
bool on = sc.id == B.szenario;
|
||||
if (GUILayout.Toggle(on, sc.text, button) && !on) backend.ChooseScenario(sc.id);
|
||||
var s = c.szenarien[j];
|
||||
bool on = s.id == c.szenario;
|
||||
GUILayout.Toggle(on, s.text, button); // Anzeige: Szenarien werden im Webinterface gewählt
|
||||
}
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
GUILayout.Label("Szenarien des Backends gelten auch im Webinterface. „Live“ nutzt nur echte Sensordaten und Stimmen.", dim);
|
||||
GUILayout.Space(S(4));
|
||||
GUILayout.Label("Maus: ziehen = drehen · Shift/rechts = schieben · Rad = Zoom · Tür anklicken\nTasten: 1–4 Ansichten · T Tür · B Vortragsmodus · H Dashboard", dim);
|
||||
GUILayout.Label($"Entschieden wird im Backend (server.js), Unity zeigt nur an. Szenarien wählt ihr im Webinterface. Nächste Prüfung in {c.pruefung.restSekunden / 60}:{c.pruefung.restSekunden % 60:00} (Zeitraffer {c.pruefung.zeitraffer}×).", dim);
|
||||
}
|
||||
|
||||
void ScenarioRow(string a, Action fa, string b, Action fb)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
if (GUILayout.Button(a, button)) { fa(); controller.RunCycle(); }
|
||||
if (GUILayout.Button(b, button)) { fb(); controller.RunCycle(); }
|
||||
ScenarioButton(a, fa);
|
||||
ScenarioButton(b, fb);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
void ScenarioButton(string text, Action set)
|
||||
{
|
||||
// erkanntes Szenario wird wie ein aktiver Knopf dargestellt ("Hitze 30 °C" passt zu "Hitze")
|
||||
bool active = text.StartsWith(controller.Scenario, StringComparison.Ordinal);
|
||||
if (GUILayout.Toggle(active, text, button) != active) { set(); controller.RunCycle(); }
|
||||
}
|
||||
|
||||
// ================================================================ Rechts: Tabs
|
||||
void DrawRight()
|
||||
{
|
||||
|
|
@ -247,12 +263,13 @@ namespace SmartRoom
|
|||
|
||||
void DrawControl()
|
||||
{
|
||||
if (Shared)
|
||||
{
|
||||
DrawBackendControl();
|
||||
return;
|
||||
}
|
||||
Section("BETRIEBSART");
|
||||
if (bridge != null && bridge.CentralActive)
|
||||
{
|
||||
var c = bridge.Central;
|
||||
GUILayout.Label($"Zentrales Backend entscheidet: {c.status} · Priorität {c.prioritaetNummer}: {c.prioritaet}" +
|
||||
(c.vetos.laerm ? " · Lärmschutz aktiv" : ""), dim);
|
||||
}
|
||||
int mode = GUILayout.Toolbar(controller.autoMode ? 0 : 1, new[] { "Automatik", "Manuell" }, seg);
|
||||
bool auto = mode == 0;
|
||||
if (auto != controller.autoMode)
|
||||
|
|
@ -314,88 +331,6 @@ namespace SmartRoom
|
|||
GUILayout.EndHorizontal();
|
||||
}
|
||||
if (!manual) GUILayout.Label("Im Automatikmodus steuert die Logik Fenster, Jalousien, Heizung, Lüftung und Licht. Für Handsteuerung auf \"Manuell\" wechseln.", dim);
|
||||
else GUILayout.Label($"Manuelle Einstellungen gelten noch {controller.ManualMinutesLeft:0} min. Bei Sturm öffnet das Fenster höchstens gekippt, bei zu hohem CO₂ läuft die Lüftungsanlage weiter.", dim);
|
||||
}
|
||||
|
||||
void DrawBackendControl()
|
||||
{
|
||||
Section("BETRIEBSART");
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(B.status, label);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag(B.prioritaet.ToUpperInvariant(), Accent);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(B.detail, dim);
|
||||
GUILayout.EndVertical();
|
||||
GUILayout.Label($"Das Backend entscheidet für Webinterface und Zwilling. Zielwert {B.zielTemperatur:0.0} °C.", dim);
|
||||
|
||||
Section("AKTOREN");
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Fenster (4×)", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label(devices.WindowLabel, valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
Bar(devices.WindowAirflow, Accent);
|
||||
GUILayout.EndVertical();
|
||||
DeviceRow("Jalousien", devices.BlindPosition > 0.5f ? "unten" : "oben", devices.BlindPosition, devices.BlindTarget, false);
|
||||
DeviceRow("Heizung", null, devices.HeatingLevel, devices.HeatingTarget, false, new Color(1f, 0.55f, 0.35f));
|
||||
DeviceRow("Lüftungsanlage", null, devices.VentLevel, devices.VentTarget, false);
|
||||
DeviceRow("Licht", null, devices.LightLevel, devices.LightTarget, false, new Color(1f, 0.9f, 0.6f));
|
||||
|
||||
Section("DOZENT");
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Vortragsmodus (Beamer, Jalousie zu)", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bool lecture = Switch(B.vortrag.aktiv);
|
||||
GUILayout.EndHorizontal();
|
||||
if (lecture != B.vortrag.aktiv) backend.SetLecture(lecture);
|
||||
int di = Array.IndexOf(LectureMinutes, B.vortrag.dauerMinuten);
|
||||
int ndi = GUILayout.Toolbar(di, new[] { "30 min", "60 min", "90 min" }, seg);
|
||||
if (ndi != di && ndi >= 0) backend.SetLectureDuration(LectureMinutes[ndi]);
|
||||
if (B.vortrag.aktiv) GUILayout.Label($"Noch {B.vortrag.restMinuten} min", dim);
|
||||
GUILayout.EndVertical();
|
||||
|
||||
var m = B.manuell;
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Manuelle Einstellungen", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (m.aktiv && GUILayout.Button("Automatik", button, GUILayout.Width(S(90)))) backend.ResetManual();
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label("Fenster", dim);
|
||||
int wi = Mathf.Max(0, Array.IndexOf(ManualWindowCodes, m.fenster));
|
||||
int nwi = GUILayout.Toolbar(wi, ManualWindowLabels, seg);
|
||||
if (nwi != wi) backend.SetManual("fenster", nwi == 0 ? "\"auto\"" : $"\"{ManualWindowCodes[nwi]}\"");
|
||||
ManualPercentRow("Jalousie", "jalousie", m.jalousie, ManualBlindLabels);
|
||||
ManualPercentRow("Licht", "licht", m.licht, ManualLightLabels);
|
||||
GUILayout.Label("Lüftungsanlage", dim);
|
||||
int vi = m.lueftung + 1; // -1 Auto, 0 aus, 1 an
|
||||
int nvi = GUILayout.Toolbar(vi, ManualVentLabels, seg);
|
||||
if (nvi != vi) backend.SetManual("lueftung", nvi == 0 ? "\"auto\"" : nvi == 1 ? "\"aus\"" : "\"an\"");
|
||||
GUILayout.Label(m.aktiv ? $"Manuell bis {m.bis} (90 min), dann wieder Automatik." : "Manuelle Werte haben Vorrang und gelten 90 min.", dim);
|
||||
GUILayout.EndVertical();
|
||||
|
||||
if (devices.door != null)
|
||||
{
|
||||
Section("ZUGANG");
|
||||
GUILayout.BeginHorizontal(card);
|
||||
GUILayout.Label("Tür offen (nur im Zwilling)", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
devices.door.open = Switch(devices.door.open);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
GUILayout.Label("Schutzregeln bleiben: Bei zu hohem CO₂ läuft die Lüftungsanlage weiter, bei Sturm öffnen die Fenster höchstens gekippt.", dim);
|
||||
}
|
||||
|
||||
void ManualPercentRow(string title, string field, int current, string[] labels)
|
||||
{
|
||||
GUILayout.Label(title, dim);
|
||||
int i = Mathf.Max(0, Array.IndexOf(ManualPercent, current));
|
||||
int ni = GUILayout.Toolbar(i, labels, seg);
|
||||
if (ni != i) backend.SetManual(field, ni == 0 ? "\"auto\"" : ManualPercent[ni].ToString());
|
||||
}
|
||||
|
||||
float DeviceRow(string name, string state, float current, float target, bool editable, Color? color = null)
|
||||
|
|
@ -415,12 +350,13 @@ namespace SmartRoom
|
|||
|
||||
void DrawWishes()
|
||||
{
|
||||
if (Shared)
|
||||
{
|
||||
DrawBackendWishes();
|
||||
return;
|
||||
}
|
||||
Section("DEIN WUNSCH");
|
||||
if (bridge != null && bridge.CentralActive)
|
||||
{
|
||||
var v = bridge.Central.stimmen;
|
||||
GUILayout.Label($"Stimmen im Backend: kühler {v.kuehler} · angenehm {v.angenehm} · wärmer {v.waermer} → Zielwert {bridge.Central.zielTemperatur:0.0} °C", dim);
|
||||
GUILayout.Label("Abgestimmt wird im Webinterface (jeder Browser-Tab ist eine Person). Die lokalen Wünsche unten gelten nur im Modus „Simulation“.", dim);
|
||||
}
|
||||
if (controller.wishes.Count == 0) controller.wishes.Add(new UserWish("Du", 22f, false));
|
||||
var own = controller.wishes[0];
|
||||
own.temperature = SliderRow("Wunschtemperatur", own.temperature, 18f, 26f, "{0:0.0} °C");
|
||||
|
|
@ -460,54 +396,6 @@ namespace SmartRoom
|
|||
GUILayout.Label("Die Wünsche werden gemittelt (Aggregation) und fließen beim nächsten Prüfzyklus in Heizung und Fenstersteuerung ein.", dim);
|
||||
}
|
||||
|
||||
void DrawBackendWishes()
|
||||
{
|
||||
var v = B.stimmen;
|
||||
Section("DEINE STIMME");
|
||||
GUILayout.Label("Temperatur", dim);
|
||||
int ti = Array.IndexOf(TempVotes, v.eigeneTemperatur);
|
||||
int nti = GUILayout.Toolbar(ti, TempVoteLabels, seg);
|
||||
if (nti != ti && nti >= 0) backend.VoteTemperature(TempVotes[nti]);
|
||||
GUILayout.Label("Licht", dim);
|
||||
int li = Array.IndexOf(LightVotes, v.eigeneLicht);
|
||||
int nli = GUILayout.Toolbar(li, LightVoteLabels, seg);
|
||||
if (nli != li && nli >= 0) backend.VoteLight(LightVotes[nli]);
|
||||
GUILayout.Label("Fenster öffnen?", dim);
|
||||
int fi = Array.IndexOf(WindowVotes, v.eigeneFenster);
|
||||
int nfi = GUILayout.Toolbar(fi, WindowVoteLabels, seg);
|
||||
if (nfi != fi && nfi >= 0) backend.VoteWindow(WindowVotes[nfi]);
|
||||
GUILayout.Label("Eine Stimme pro Gerät, wie im Webinterface. Sie verfällt nach 30 min.", dim);
|
||||
|
||||
Section("ALLE EINGABEN");
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label($"Ziel {B.zielTemperatur:0.0} °C", bigValue);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label($"{v.gesamt} Stimmen", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.EndVertical();
|
||||
VoteRow("Kühler", v.kuehler);
|
||||
VoteRow("Angenehm", v.angenehm);
|
||||
VoteRow("Wärmer", v.waermer);
|
||||
GUILayout.Space(S(4));
|
||||
VoteRow("Licht dunkler", v.dunkler);
|
||||
VoteRow("Licht passt", v.passt);
|
||||
VoteRow("Licht heller", v.heller);
|
||||
GUILayout.Space(S(4));
|
||||
VoteRow("Fenster auf", v.auf);
|
||||
VoteRow("Fenster zu lassen", v.zu);
|
||||
GUILayout.Label("Temperatur und Licht: Durchschnitt aller Stimmen aus Webinterface und Zwilling. Fenster: Mehrheit, bei Außenlärm öffnet es nur auf Wunsch. Gegen den CO₂-Grenzwert kommen Stimmen nicht an.", dim);
|
||||
}
|
||||
|
||||
void VoteRow(string name, int count)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(name, label);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label(count.ToString(), valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
void DrawConnection()
|
||||
{
|
||||
Section("SENSORQUELLE");
|
||||
|
|
@ -542,13 +430,20 @@ namespace SmartRoom
|
|||
udpField = GUILayout.TextField(udpField, field);
|
||||
if (int.TryParse(udpField, out var port)) bridge.udpListenPort = port;
|
||||
}
|
||||
else if (bridge.mode == LinkMode.Backend && backend != null)
|
||||
else if (bridge.mode == LinkMode.Backend)
|
||||
{
|
||||
GUILayout.Label("Server-URL des gemeinsamen Backends (backend/server.js)", dim);
|
||||
if (urlField == null) urlField = backend.serverUrl;
|
||||
urlField = GUILayout.TextField(urlField, field);
|
||||
backend.serverUrl = urlField.Trim();
|
||||
GUILayout.Label("Anderer Laptop im Hotspot: http://<Laptop-IP>:3000. Nach Änderung neu verbinden.", dim);
|
||||
GUILayout.Label("Adresse von backend/server.py (Arduino → ESP-01 → Server → Unity)", dim);
|
||||
if (backendField == null) backendField = bridge.backendUrl;
|
||||
backendField = GUILayout.TextField(backendField, field);
|
||||
bridge.backendUrl = backendField.Trim();
|
||||
GUILayout.Label($"Fragt alle {bridge.backendPollSeconds:0.#} s GET /api/messwerte ab (Temperatur, Luftfeuchte, eCO2, TVOC, Lautstärke, Helligkeit) und meldet die Steuerbefehle per POST /api/steuerung zurück.", dim);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Mikrofon steht draußen", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bridge.MicrophoneOutdoor = Switch(bridge.MicrophoneOutdoor);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(bridge.MicrophoneOutdoor ? "Lautstärke zählt als Außenlärm: über 70 dB wird die Fensteröffnung gesperrt."
|
||||
: "Lautstärke zählt als Lärm im Raum (nur Anzeige).", dim);
|
||||
}
|
||||
|
||||
if (bridge.mode != LinkMode.Simulation)
|
||||
|
|
@ -558,49 +453,27 @@ namespace SmartRoom
|
|||
{
|
||||
if (bridge.Connected) bridge.Disconnect(); else bridge.Connect();
|
||||
}
|
||||
if (bridge.mode != LinkMode.Backend)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Steuerbefehle senden", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bridge.sendCommands = Switch(bridge.sendCommands);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Steuerbefehle senden", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bridge.sendCommands = Switch(bridge.sendCommands);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
GUILayout.BeginVertical(card);
|
||||
if (bridge.mode == LinkMode.Backend && backend != null)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
Tag(backend.Connected ? "VERBUNDEN" : backend.Active ? "KEINE ANTWORT" : "GETRENNT", backend.Connected ? Good : Warn);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (backend.LastPacketTime >= 0f)
|
||||
GUILayout.Label($"{backend.PacketCount} Abfragen · vor {Time.unscaledTime - backend.LastPacketTime:0} s", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(backend.Status, dim);
|
||||
GUILayout.Label("Kennung: " + backend.ClientId, dim);
|
||||
}
|
||||
else
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
Tag(bridge.Connected ? "VERBUNDEN" : bridge.mode == LinkMode.Simulation ? "SIMULATION" : "GETRENNT",
|
||||
bridge.Connected ? Good : TextDim);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (bridge.LastPacketTime >= 0f)
|
||||
GUILayout.Label($"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(bridge.Status, dim);
|
||||
if (!string.IsNullOrEmpty(bridge.LastLine)) GUILayout.Label("← " + bridge.LastLine, dim);
|
||||
if (bridge.Connected && !string.IsNullOrEmpty(bridge.LastSent)) GUILayout.Label("→ " + bridge.LastSent, dim);
|
||||
}
|
||||
GUILayout.BeginHorizontal();
|
||||
Tag(bridge.Connected ? "VERBUNDEN" : bridge.mode == LinkMode.Simulation ? "SIMULATION" : "GETRENNT",
|
||||
bridge.Connected ? Good : TextDim);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (bridge.LastPacketTime >= 0f)
|
||||
GUILayout.Label($"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(bridge.Status, dim);
|
||||
if (!string.IsNullOrEmpty(bridge.LastLine)) GUILayout.Label("← " + bridge.LastLine, dim);
|
||||
if (bridge.Connected && !string.IsNullOrEmpty(bridge.LastSent)) GUILayout.Label("→ " + bridge.LastSent, dim);
|
||||
GUILayout.EndVertical();
|
||||
|
||||
if (Shared)
|
||||
{
|
||||
Section("WETTERDATEN (EXTERN)");
|
||||
GUILayout.Label("Kommen vom Backend (Open-Meteo, Mannheim), damit Webinterface und Zwilling dieselben Werte nutzen.", dim);
|
||||
}
|
||||
else if (weather != null)
|
||||
if (weather != null)
|
||||
{
|
||||
Section("WETTERDATEN (EXTERN)");
|
||||
GUILayout.BeginHorizontal();
|
||||
|
|
@ -628,7 +501,7 @@ namespace SmartRoom
|
|||
}
|
||||
|
||||
Section("PROTOKOLL");
|
||||
GUILayout.Label("Arduino → Unity (eine JSON-Zeile, alle Felder optional):\n{\"t\":30.2,\"co2\":1250,\"lux\":320,\"noise\":48,\"tout\":12,\"aq\":30,\"nout\":55,\"wind\":3.5,\"sun\":420,\"persons\":40}\n\nUnity → Arduino:\n{\"window\":\"open|tilted|closed\",\"blind\":1.00,\"heat\":0.50,\"vent\":0.80,\"light\":0.40,\"beamer\":0}", dim);
|
||||
GUILayout.Label("Arduino → Unity (eine JSON-Zeile, alle Felder optional):\n{\"t\":30.2,\"co2\":1250,\"rh\":45,\"tvoc\":30,\"lux\":320,\"noise\":48,\"tout\":12,\"aq\":30,\"nout\":55,\"wind\":3.5,\"sun\":420,\"persons\":40}\n\nBackend (server.py): {\"temperatur\":22.5,\"luftfeuchte\":45,\"eco2\":612,\"tvoc\":30,\"lautstaerke\":48.5,\"helligkeit\":60}\n\nUnity → Arduino:\n{\"window\":\"open|tilted|closed\",\"blind\":1.00,\"heat\":0.50,\"vent\":0.80,\"light\":0.40,\"beamer\":0}", dim);
|
||||
}
|
||||
|
||||
// ================================================================ Unten: Entscheidungslogik
|
||||
|
|
@ -636,12 +509,6 @@ namespace SmartRoom
|
|||
{
|
||||
GUI.Box(bottomRect, GUIContent.none, panel);
|
||||
GUILayout.BeginArea(new Rect(bottomRect.x + S(16), bottomRect.y + S(10), bottomRect.width - S(32), bottomRect.height - S(18)));
|
||||
if (Shared)
|
||||
{
|
||||
DrawBackendDecision();
|
||||
GUILayout.EndArea();
|
||||
return;
|
||||
}
|
||||
var d = controller.Last;
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("ENTSCHEIDUNGSLOGIK" + (d != null ? " · " + d.time : ""), header);
|
||||
|
|
@ -669,28 +536,6 @@ namespace SmartRoom
|
|||
GUILayout.EndArea();
|
||||
}
|
||||
|
||||
void DrawBackendDecision()
|
||||
{
|
||||
var c = B.steuerung;
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("ENTSCHEIDUNG BACKEND · " + B.prioritaet, header);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag($"Fenster {devices.WindowTarget.Label()}", Accent);
|
||||
Tag($"Lüftung {c.vent * 100:0} %", Accent);
|
||||
Tag($"Heizung {c.heat * 100:0} %", new Color(1f, 0.55f, 0.35f));
|
||||
Tag($"Jalousie {c.blind * 100:0} %", TextDim);
|
||||
if (GUILayout.Button(logCollapsed ? "+" : "–", button, GUILayout.Width(S(30)))) logCollapsed = !logCollapsed;
|
||||
GUILayout.EndHorizontal();
|
||||
if (logCollapsed) return;
|
||||
|
||||
logScroll = GUILayout.BeginScrollView(logScroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
|
||||
GUILayout.Label(B.status, logLineStrong);
|
||||
GUILayout.Label(B.detail, logLine);
|
||||
for (int i = 0; i < B.pfad.Length; i++)
|
||||
GUILayout.Label($"{i + 1,2}. {B.pfad[i]}", B.pfad[i].Contains("→") ? logLineStrong : logLine);
|
||||
GUILayout.EndScrollView();
|
||||
}
|
||||
|
||||
// ================================================================ Bausteine
|
||||
void Section(string text)
|
||||
{
|
||||
|
|
@ -704,7 +549,7 @@ namespace SmartRoom
|
|||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(name, dim);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag(measured ? (Shared ? "BACKEND" : "SENSOR") : "SIM", measured ? Good : TextDim);
|
||||
Tag(measured ? "SENSOR" : "SIM", measured ? Good : TextDim);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(value, bigValue);
|
||||
Bar(norm, status);
|
||||
|
|
|
|||
|
|
@ -7,12 +7,30 @@ Ein 3D-Vorlesungsraum als digitaler Zwilling für ein Smart-Home-Projekt. Er ste
|
|||
1. **Unity Hub → Add → Add project from disk** und den Ordner `frontend/SmartLectureRoom` wählen.
|
||||
Ausgelegt ist das Projekt für **Unity 6 (6000.0 LTS)**. Unity 2022.3 LTS funktioniert ebenfalls. Fragt der Hub nach einer Version, eine installierte wählen.
|
||||
2. Beim ersten Öffnen wird automatisch die Szene `Assets/Scenes/SmartRoom.unity` angelegt und geöffnet. Falls nicht: Menü **Smart Room → Szene öffnen**.
|
||||
3. Das gemeinsame Backend starten (`backend/start.bat` bzw. `node backend/server.js`, siehe unten).
|
||||
4. **Play** drücken.
|
||||
3. **Play** drücken.
|
||||
|
||||
Der ganze Raum wird beim Start per Code erzeugt (`RoomBuilder.cs`), es gibt also keine Modelle oder Prefabs, die fehlen könnten. Wenn du in einer beliebigen anderen Szene Play drückst, entsteht der Raum dort ebenfalls.
|
||||
Das Projekt läuft mit der Built-in Render Pipeline und mit URP.
|
||||
|
||||
## Zwei Szenen: Classic und Ambient
|
||||
|
||||
| Szene | Optik |
|
||||
|---|---|
|
||||
| `Assets/Scenes/SmartRoom.unity` | Ursprünglicher Zwilling: dunkles Dashboard links/rechts, Raum bildschirmfüllend |
|
||||
| `Assets/Scenes/SmartRoomAmbient.unity` | Look des Web-Frontends **Ambient²**: hell, Salbei/Grün, Karten. Der Raum erscheint als Frontansicht in der Karte „Raumstatus“ |
|
||||
|
||||
Beide Szenen nutzen dieselbe Logik (Simulation, Entscheidungslogik, Arduino/Backend, Wetter); umgeschaltet wird nur über das Feld **Style** am `SmartRoom`-Objekt. Öffnen: Menü **Smart Room → Ambient-Szene öffnen** (wird beim ersten Mal angelegt).
|
||||
|
||||
**Ambient-Dashboard:**
|
||||
- **Kopfzeile:** Umschalter *Studierende / Dozent*; der Status oben rechts („System aktiv“ / „Arduino live“) öffnet die **Einstellungen** (Sensorquelle inkl. Backend-Adresse, Live-Wetter, Vorlesung läuft, Zeitraffer).
|
||||
- **Hinweisband:** aktueller Zustand mit Priorität (1 Gesundheit, 2 Kontext, 3 Mehrheit, 4 Energie).
|
||||
- **Raumstatus:** 3D-Raum (ziehen = drehen, Mausrad = Zoom, Tür anklicken), Chips für Fenster/Heizung/Lüftung/Licht/Jalousien; „⟲ Frontansicht“ setzt die Ansicht zurück.
|
||||
- **Kacheln:** Luftqualität (CO2), Temperatur, Außenlärm, Wind – „● Sensor“, wenn der Wert vom Arduino kommt.
|
||||
- **Dozentensteuerung:** Beamer-Modus mit Dauer 30/60/90 min (endet automatisch), Jalousien ↑/↓ (pausiert die Jalousie-Automatik für 30 min; Schutzregeln bleiben aktiv).
|
||||
- **Raumstimmung:** Kühler / Angenehm / Wärmer setzt deinen Temperaturwunsch (21 / 22 / 23 °C), alle Wünsche werden gemittelt. Wünsche außerhalb 18–26 °C werden vorher begrenzt („Ausreißer-Stimme“). Studierende können zusätzlich „Frische Luft“ wünschen.
|
||||
- **Verlauf:** die letzten Entscheidungen der Steuerung. **Demo-Szenarien:** Normal, CO₂ zu hoch, CO₂ + Außenlärm, Sturm, Vortragsmodus, Ausreißer-Stimme, Hitze, Kalter Morgen – das aus den Messwerten erkannte Szenario ist markiert.
|
||||
- Tasten: `0`/`R` Frontansicht, `1`–`4` Ansichten, `B` Beamer, `T` Tür, Leertaste prüfen.
|
||||
|
||||
## Bedienung
|
||||
|
||||
| Eingabe | Wirkung |
|
||||
|
|
@ -22,53 +40,98 @@ Das Projekt läuft mit der Built-in Render Pipeline und mit URP.
|
|||
| Mausrad | Zoom |
|
||||
| Tür anklicken / `T` | Tür öffnen/schließen |
|
||||
| `1` – `4` | Ansichten: Gesamt, Fensterfront, Leinwand & Tür, Decke & Lüftung |
|
||||
| `B` | Beamer (Leinwand fährt herunter, Bild blendet ein); mit Backend: Vortragsmodus an/aus |
|
||||
| Leertaste | sofort einen Prüfzyklus ausführen (nur ohne Backend) |
|
||||
| `B` | Beamer (Leinwand fährt herunter, Bild blendet ein) |
|
||||
| Leertaste | sofort einen Prüfzyklus ausführen |
|
||||
| `H` | Dashboard ein-/ausblenden |
|
||||
|
||||
**Dashboard links:** Innenwerte (Temperatur, CO2, Licht, Lärm) mit „SIM“/„SENSOR“-Kennzeichnung, Außenwerte als Schieberegler, Zeitraffer und **Szenarien** (z. B. „Hitze 30 °C“: Fenster öffnet, Jalousie fährt runter; „Stickig + kalt“: Fenster bleibt zu, Lüftung läuft).
|
||||
**Dashboard rechts:** Automatik/Manuell, Aktorzustände, Nutzerwünsche (Wunschtemperatur, Fenster ja/nein), Verbindung zu Arduino und Live-Wetter.
|
||||
**Unten:** der Pfad, den die Logik im letzten Zyklus durch das Aktivitätsdiagramm genommen hat.
|
||||
|
||||
## Gemeinsames Backend (Standard)
|
||||
## Logik (Aktivitätsdiagramm → `ClimateController.cs`)
|
||||
|
||||
Der Zwilling startet im Modus **Verbindung → Backend** und verbindet sich mit `http://localhost:3000` (`backend/server.js`). Das ist dasselbe Backend, das auch das Webinterface nutzt. Es entscheidet für beide. Der Zwilling zeigt nur an und animiert:
|
||||
Alle 10 simulierten Minuten läuft ein Prüfzyklus. Wird ein Grenzwert neu überschritten, läuft er sofort.
|
||||
|
||||
- Sensorwerte (Arduino über ESP, Wetter, Demo-Szenario) und Steuerbefehle kommen jede Sekunde von `GET /api/unity` (`IO/BackendLink.cs`). Werte vom Backend tragen im Dashboard das Kennzeichen „BACKEND“, alle anderen simuliert Unity weiter („SIM“).
|
||||
- **Wünsche:** Stimme Kühler/Angenehm/Wärmer, Dunkler/Passt/Heller und „Fenster öffnen? Auf/Zu lassen“ wie im Webinterface. Der Zwilling zählt als ein Gerät.
|
||||
- **Steuerung:** Status und Priorität des Backends, dazu die Dozentenfunktionen Vortragsmodus (30/60/90 min) und manuelle Einstellungen für Fenster, Jalousie, Licht und Lüftungsanlage (gelten 90 min, „Automatik“ setzt zurück). Bei zu hohem CO₂ bleibt die Lüftungsanlage trotzdem an, bei Sturm öffnet das Fenster höchstens gekippt.
|
||||
- **Szenarien:** die Demo-Szenarien des Backends (Live, Normal, CO₂ zu hoch, CO₂ + Außenlärm, Sturm, Vortragsmodus, Ausreißer-Stimme, Lärm + Fensterwunsch). Ein Wechsel gilt auch im Webinterface.
|
||||
|
||||
Läuft das Backend auf einem anderen Laptop, unter **Verbindung** die URL ändern (z. B. `http://172.20.10.2:3000`) und neu verbinden. Antwortet das Backend länger als 5 s nicht, übernimmt die lokale Logik unten. Das Dashboard zeigt dann „Backend getrennt, lokale Logik“.
|
||||
|
||||
## Lokale Logik (Aktivitätsdiagramm → `ClimateController.cs`)
|
||||
|
||||
Nur aktiv in den Modi Simulation, Seriell und UDP oder wenn das Backend nicht erreichbar ist.
|
||||
|
||||
Die Regeln und Grenzwerte entsprechen dem Backend (`backend/logik.js`), damit der Zwilling ohne Backend genauso entscheidet. Alle 10 simulierten Minuten läuft ein Prüfzyklus. Wird ein Grenzwert neu überschritten, läuft er sofort.
|
||||
|
||||
1. Sensordaten, Fensterzustand und Nutzerwünsche erfassen. Zielwert = Ø-Wunschtemperatur, begrenzt auf 20–24 °C. Fenster gewünscht, wenn mehr als die Hälfte es will.
|
||||
2. **CO2 > 1000 ppm** → Lüftung erforderlich. Sonst **Temperatur**: unter Ziel − 0,5 °C heizen, über Ziel + 1 °C (und draußen kühler) Lüftung erforderlich.
|
||||
1. Sensordaten, Fensterzustand und Nutzerwünsche erfassen. Die Wünsche werden gemittelt (Aggregation).
|
||||
2. **CO2 > 1000 ppm** → Lüftung erforderlich. Sonst **Temperatur**: unter 20 °C heizen, 20–25 °C Komfortbereich, über 25 °C Lüftung erforderlich.
|
||||
3. Ist Lüftung erforderlich:
|
||||
- **Außenluft schlecht (AQI > 60) oder draußen zu kalt (< 5 °C)**: Fenster zu, Lüftungsanlage an
|
||||
- **Extremer Außenlärm (> 70 dB)**: Fensteröffnung gesperrt. Will die Mehrheit trotzdem lüften, öffnet das Fenster, sonst läuft die Lüftungsanlage.
|
||||
- **Außenluft schlecht (AQI > 60) oder draußen zu kalt (< 5 °C)**: Fenster zu, Lüftungsanlage an (deine Vorgabe)
|
||||
- **Extremer Außenlärm (> 70 dB)**: Fensteröffnung gesperrt. Wollen die Nutzer trotzdem lüften, öffnet das Fenster, sonst läuft die alternative Lüftung.
|
||||
- **Starker Wind (> 10 m/s)**: Fenster gekippt
|
||||
- sonst: Fenster offen
|
||||
4. Ohne Lüftungsbedarf entscheidet der Mehrheitswunsch über das Fenster.
|
||||
5. **Starker Wind (> 16,7 m/s = 60 km/h)**: Fenster höchstens gekippt, auch bei manueller Einstellung. Bei zu hohem CO₂ läuft die Lüftungsanlage, solange das Fenster nicht offen ist.
|
||||
6. Geheizt wird auf den Zielwert, bei offenem Fenster ist die Heizung aus. Dann Soll- und Ist-Zustand des Fensters vergleichen.
|
||||
7. **Beamer an** → Licht aus, Jalousie runter. Sonst **Sonneneinstrahlung > 500 W/m²** → Jalousie runter, Licht an; sonst Jalousie hoch. Das Licht ergänzt das Tageslicht auf 500 lx.
|
||||
8. **Manuell:** Die Handeinstellungen haben Vorrang, die Schutzregeln aus Schritt 5 gelten weiter. Nach 90 simulierten Minuten werden sie gelöscht und die Automatik übernimmt.
|
||||
9. Die virtuellen Aktoren werden angesteuert. Nach 10 Minuten wird erneut geprüft.
|
||||
10. Läuft keine Vorlesung, werden die gespeicherten Einstellungen gelöscht und der Raum geht in den Energiesparmodus.
|
||||
4. Ohne Lüftungsbedarf entscheidet der Nutzerwunsch über das Fenster. Geheizt wird auf die Ø-Wunschtemperatur, bei offenem Fenster ist die Heizung aus.
|
||||
5. Soll- und Ist-Zustand des Fensters vergleichen, dann beibehalten oder anpassen.
|
||||
6. **Sonneneinstrahlung > 500 W/m²** → Jalousie runter, sonst hoch. Als Erweiterung fährt die Jalousie auch bei laufendem Beamer runter.
|
||||
7. Als Erweiterung wird das Licht auf 500 lx ergänzt und für den Beamer gedimmt.
|
||||
8. Die virtuellen Aktoren werden angesteuert. Nach 10 Minuten wird erneut geprüft.
|
||||
9. Läuft keine Vorlesung, geht der Raum in den Energiesparmodus.
|
||||
|
||||
Alle Grenzwerte lassen sich im Inspector am `SmartRoom`-Objekt unter **Climate Controller → Limits** einstellen.
|
||||
|
||||
## Arduino anbinden (Architekturdiagramm: Physische Umgebung → Backend)
|
||||
|
||||
### Gemeinsames Backend: Arduino → `server.js` ← Webinterface, → Unity
|
||||
|
||||
Das Node-Backend (`node backend/server.js`) ist das **eine** Backend für Webinterface und Unity. Es nimmt die Messwerte des ESP-01 an, aggregiert die Stimmen und entscheidet alle 2 Minuten nach Gesundheit, Kontext, Mehrheit und Energie (Übersicht: `docs/regeln.md`). **Bedient wird im Webinterface.** Unity fragt jede Sekunde `GET /api/unity` ab und **zeigt nur, was die Entscheidung im Raum auslöst**:
|
||||
|
||||
```
|
||||
DHT11 + CCS811 + MAX9814 + LDR ─▶ Arduino Uno ─▶ ESP-01 ─WLAN─▶ server.js :3000 ◀──▶ Webinterface (Ambient², Bedienung)
|
||||
│
|
||||
GET /api/unity ▼
|
||||
Unity-Zwilling (nur Anzeige)
|
||||
```
|
||||
|
||||
- **Plug & Play:** Modus **Backend** ist Standard, Adresse `http://localhost:3000`. Unity erkennt selbst, welches Backend läuft: `server.js` (zentral, Unity führt aus) oder `server.py` (nur Messwerte, Unity entscheidet selbst, siehe unten). Ohne Server läuft die Simulation.
|
||||
- **Alle Sensoren:** Temperatur, eCO₂, Luftfeuchte, TVOC, Helligkeit und Lautstärke. „● Sensor“ steht nur an echten Sensorwerten; Wetter- und Demo-Werte ersetzen die Simulation ebenfalls, aber ohne diese Kennzeichnung.
|
||||
- **Lautstärkesensor:** zählt als Außenlärm. Über 70 dB sperrt das Backend die Fenster, die Lüftungsanlage übernimmt (nur wenn die Mehrheit im Webinterface „Fenster auf“ wählt, wird trotzdem gelüftet). Im 3D-Raum: Schallwellen vor der Fensterfront (ab dem Grenzwert rot), Pegelschild an der Fassade, Chip „Lärmschutz: Fenster gesperrt“.
|
||||
- **Status und Umschalter:** Oben rechts steht „● Arduino verbunden“ (grün) bzw. „● Arduino nicht verbunden“ (rot, mit Grund im Raumstatus, z. B. „Backend nicht erreichbar“). Der Umschalter **Arduino-Werte | Simulation** wechselt zwischen den echten Werten (und Entscheidungen des Backends) und den Beispielwerten der Simulation, bei der Unity selbst entscheidet. Der Status bleibt auch im Simulationsmodus aktuell. Im Classic-Dashboard sitzt beides links unter dem Titel.
|
||||
- **Nur Anzeige:** Mit Backend zeigen Dozentensteuerung, Raumstimmung und Demo-Szenarien in Unity den Zustand aus dem Webinterface; Klicks darauf bewirken nichts. Ebenfalls angezeigt: nächste Prüfung (Prüfzyklus 2 min, Zeitraffer aus dem Webinterface).
|
||||
- **WebGL:** Die Abfrage läuft über `UnityWebRequest`, der Zwilling funktioniert also auch als WebGL-Build im Browser und übernimmt dort die Adresse der Seite als Backend (Anleitung in `backend/README.md`, „Live-Demo im Browser“).
|
||||
|
||||
### Älteres Backend: Arduino Uno + ESP-01 → `server.py` → Unity (Modus „Backend“)
|
||||
|
||||
Der Sensor-Arduino aus dem GruppeC-Repo (`firmware/dht11_lcd`, DHT11 + CCS811) schickt seine Messwerte per ESP-01 als HTTP-POST an `backend/server.py` auf dem Laptop. Unity holt sie dort jede Sekunde ab, die Website läuft parallel weiter:
|
||||
|
||||
```
|
||||
DHT11 + CCS811 ─▶ Arduino Uno ─▶ ESP-01 ─WLAN─▶ server.py :3000 ─GET /api/messwerte─▶ Unity-Zwilling
|
||||
▲ │
|
||||
└──────── POST /api/steuerung ─────────┘
|
||||
```
|
||||
|
||||
| Backend-Feld | Unity | Wirkung in der Simulation |
|
||||
|---|---|---|
|
||||
| `temperatur` | Temperatur innen | ersetzt das Wärmemodell → Heizen (< 20 °C) / Lüften (> 25 °C) |
|
||||
| `eco2` | CO2 innen | ersetzt das CO2-Modell → Lüften ab 1000 ppm (Hard-Constraint) |
|
||||
| `luftfeuchte` | Luftfeuchte | nur Anzeige im Dashboard |
|
||||
| `tvoc` | TVOC | nur Anzeige im Dashboard |
|
||||
| `lautstaerke` | Lärm (MAX9814) | Schalter **„Mikrofon steht draußen“** (Verbindung → Backend bzw. Einstellungen): aus = Lärm im Raum (Anzeige), an = Außenlärm → über 70 dB Sensor-Veto, Fenster bleiben zu |
|
||||
| `helligkeit` | Helligkeit (Fotowiderstand, %) | grob in lx umgerechnet (100 % ≈ 1000 lx, `luxPerLightPercent`); die Lichtsteuerung rechnet dann mit dem gemessenen statt dem geschätzten Tageslicht |
|
||||
|
||||
So läuft es:
|
||||
1. `python backend/server.py` starten (GruppeC-Repo, bzw. `start.bat`).
|
||||
2. Unity: **Play** → Dashboard rechts **Verbindung → Backend** → Adresse prüfen (`http://localhost:3000`, läuft Unity auf einem anderen Rechner: `http://<Laptop-IP>:3000`) → **Verbinden**.
|
||||
3. Sobald Messwerte kommen, stehen Temperatur und CO2 auf **SENSOR**, links oben „Arduino live“.
|
||||
|
||||
Was dann automatisch passiert:
|
||||
- **Szenario-Erkennung:** Aus den Messwerten (plus Außenwerten) wird das passende Szenario erkannt und im Dashboard hervorgehoben, z. B. „Hitze“, „Stickige Luft“, „Stickig + kalt“, „Wintermorgen“. Es steht auch auf der Beamer-Leinwand und im Entscheidungspfad.
|
||||
- **Sofortige Reaktion:** Wechselt das Szenario (z. B. CO2 steigt über 1000 ppm) oder kommen die ersten Arduino-Werte an, läuft sofort ein Prüfzyklus. Fenster, Lüftung, Heizung, Jalousie und Licht werden ohne Klick angesteuert.
|
||||
- **Rückkanal:** Unity meldet die Aktor-Sollwerte und das erkannte Szenario per `POST /api/steuerung` an den Server (`GET /api/steuerung` zeigt den letzten Stand, das Serverfenster gibt ihn aus).
|
||||
- Kommen 25 s lang keine neuen Messwerte (die Station sendet ca. alle 7–8 s), übernimmt wieder die Simulation. Messwerte, die beim Verbinden schon älter als 30 s sind, werden ignoriert.
|
||||
|
||||
**Ohne Arduino testen** (Server muss laufen):
|
||||
```bash
|
||||
python backend/simulator.py --szenario demo
|
||||
```
|
||||
`demo` läuft nacheinander normal → stickig → laerm → normal → hitze → dunkel → kalt durch (je ca. 1 min). Einzeln: `--szenario normal|hitze|stickig|kalt|laerm|dunkel`.
|
||||
|
||||
Die Szenario-Knöpfe im Dashboard funktionieren weiter; mit Arduino überschreibt der nächste Messwert aber Temperatur und CO2 innen, wirksam bleiben dann die Außenwerte (Wind, Lärm, Luftqualität, Sonne).
|
||||
|
||||
### Eigenes JSON-Protokoll (USB-Seriell / UDP)
|
||||
|
||||
Unity empfängt pro Zeile ein JSON-Objekt. Alle Felder sind optional, gesendete Felder überschreiben die Simulation:
|
||||
|
||||
```json
|
||||
{"t":30.2,"co2":1250,"lux":320,"noise":48,"tout":12,"aq":30,"nout":55,"wind":3.5,"sun":420,"persons":40}
|
||||
{"t":30.2,"co2":1250,"rh":45,"tvoc":30,"lux":320,"noise":48,"tout":12,"aq":30,"nout":55,"wind":3.5,"sun":420,"persons":40}
|
||||
```
|
||||
|
||||
Unity sendet die Steuerbefehle zurück, sobald sie sich ändern:
|
||||
|
|
@ -97,8 +160,9 @@ Assets/SmartRoom/Scripts
|
|||
Actuators/* Animationen: Fenster (Dreh-Kipp), Jalousie, Heizung, Lüftung, Licht, Beamer, Tür
|
||||
Simulation/RoomEnvironment.cs Raumklima-Modell (CO2, Wärme, Licht, Lärm) + Messwertübernahme
|
||||
Control/ClimateController.cs Entscheidungslogik
|
||||
IO/ArduinoBridge.cs Seriell/UDP, JSON-Protokoll, Moduswahl
|
||||
IO/BackendLink.cs gemeinsames Backend (GET /api/unity, Stimmen, Szenarien, Dozentenfunktionen)
|
||||
IO/ArduinoBridge.cs Seriell/UDP/Backend (HTTP), JSON-Protokoll
|
||||
IO/WeatherService.cs Open-Meteo
|
||||
UI/SmartRoomHUD.cs, UI/OrbitCamera.cs
|
||||
UI/SmartRoomHUD.cs Dashboard Classic
|
||||
UI/AmbientHUD.cs Dashboard im Look des Web-Frontends (Ambient²)
|
||||
UI/OrbitCamera.cs
|
||||
```
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,525 @@
|
|||
// Webinterface Ambient² im Figma-Design v2 (frontend/figma/Ambient2_v2.html), angebunden an backend/server.js.
|
||||
// Die Seite entscheidet nichts selbst: Sie zeigt, was GET /api/zustand liefert, und schickt Eingaben an
|
||||
// dieselben Endpunkte wie der Unity-Zwilling. Kein Framework, kein Build-Schritt.
|
||||
"use strict";
|
||||
|
||||
const ABFRAGE_MS = 1000;
|
||||
|
||||
// Jeder Browser-Tab ist ein eigener Teilnehmer: sessionStorage gilt pro Tab, ein neuer Tab bekommt eine neue Kennung.
|
||||
const CLIENT = (() => {
|
||||
const neu = () => "tab-" + Math.random().toString(36).slice(2, 10);
|
||||
try {
|
||||
let id = sessionStorage.getItem("ambient-client");
|
||||
if (!id) {
|
||||
id = neu();
|
||||
sessionStorage.setItem("ambient-client", id);
|
||||
}
|
||||
return id;
|
||||
} catch {
|
||||
return neu();
|
||||
}
|
||||
})();
|
||||
|
||||
const ui = {
|
||||
rolle: lies("ambient-rolle") || "dozent",
|
||||
wunsch: null, // Wert im Stepper (noch nicht gesendet)
|
||||
demoOffen: true,
|
||||
datenOffen: false,
|
||||
toast: "",
|
||||
toastBis: 0,
|
||||
};
|
||||
let zustand = null;
|
||||
let verbunden = false;
|
||||
let antwortZeit = 0; // Zeitpunkt der letzten Antwort (fuer Countdowns zwischen zwei Abfragen)
|
||||
let letzterSchluessel = "";
|
||||
let zeigerUnten = false; // waehrend eines Klicks nicht neu zeichnen, sonst geht der Klick verloren
|
||||
|
||||
function lies(schluessel) {
|
||||
try { return sessionStorage.getItem(schluessel); } catch { return null; }
|
||||
}
|
||||
function merke(schluessel, wert) {
|
||||
try { sessionStorage.setItem(schluessel, wert); } catch { /* privates Fenster: egal */ }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Formatierung
|
||||
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
const zahl = (w, stellen = 1) =>
|
||||
w === null || w === undefined ? "–" : Number(w).toLocaleString("de-DE", { minimumFractionDigits: stellen, maximumFractionDigits: stellen });
|
||||
const uhr = (d) => new Date(d).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
|
||||
const mmss = (ms) => {
|
||||
const s = Math.max(0, Math.round(ms / 1000));
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
||||
};
|
||||
const gruss = () => {
|
||||
const h = new Date().getHours();
|
||||
return h < 11 ? "Guten Morgen" : h < 18 ? "Guten Tag" : "Guten Abend";
|
||||
};
|
||||
const QUELLE_TEXT = { sensor: "Arduino", wetter: "Wetter", demo: "Demo" };
|
||||
const quelle = (eingabe) =>
|
||||
eingabe && eingabe.quelle ? `<span class="source-tag ${esc(eingabe.quelle)}">${QUELLE_TEXT[eingabe.quelle] || esc(eingabe.quelle)}</span>` : `<span class="source-tag fehlt">kein Wert</span>`;
|
||||
|
||||
// Icons aus dem Figma-Export (Komponente "W")
|
||||
const ICONS = {
|
||||
air: '<path d="M4 8h10a3 3 0 1 0-3-3"/><path d="M4 12h15a3 3 0 1 1-3 3"/><path d="M4 16h7"/>',
|
||||
blinds: '<path d="M5 4h14v16H5z"/><path d="M5 8h14M5 12h14M5 16h14"/><path d="M19 4h2v8"/>',
|
||||
check: '<path d="m5 12 4 4L19 6"/>',
|
||||
chevron: '<path d="m7 10 5 5 5-5"/>',
|
||||
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
|
||||
energy: '<path d="m13 2-8 12h7l-1 8 8-12h-7z"/>',
|
||||
history: '<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5M12 7v5l3 2"/>',
|
||||
info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/>',
|
||||
lock: '<rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
|
||||
people: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.9M16 3.1a4 4 0 0 1 0 7.8"/>',
|
||||
presentation: '<path d="M3 4h18v12H3zM8 21l4-5 4 5M8 9h8M8 12h5"/>',
|
||||
shield: '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>',
|
||||
spark: '<path d="m12 3 1.4 4.1L17 9l-3.6 1.9L12 15l-1.4-4.1L7 9l3.6-1.9z"/><path d="m19 15 .7 2.3L22 18l-2.3.7L19 21l-.7-2.3L16 18l2.3-.7z"/>',
|
||||
temperature: '<path d="M14 14.8V5a4 4 0 0 0-8 0v9.8a6 6 0 1 0 8 0z"/><path d="M10 9v8"/>',
|
||||
volume: '<path d="M11 5 6 9H2v6h4l5 4z"/><path d="M15.5 8.5a5 5 0 0 1 0 7M18 6a8 8 0 0 1 0 12"/>',
|
||||
wind: '<path d="M3 8h11a3 3 0 1 0-3-3"/><path d="M3 12h17M3 16h11a3 3 0 1 1-3 3"/>',
|
||||
undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>',
|
||||
refresh: '<path d="M20 11a8 8 0 0 0-14.9-3.6L3 10"/><path d="M3 4v6h6"/><path d="M4 13a8 8 0 0 0 14.9 3.6L21 14"/><path d="M21 20v-6h-6"/>',
|
||||
offline: '<path d="M2 8.8a15 15 0 0 1 4.2-2.6M10.7 5.1A15 15 0 0 1 22 8.8M5 12.5a10 10 0 0 1 3-1.8M16.3 10.8A10 10 0 0 1 19 12.5M8.5 16a5 5 0 0 1 7 0M12 20h.01"/><path d="m3 3 18 18"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
};
|
||||
const icon = (name, size = 20) =>
|
||||
`<svg class="icon" width="${size}" height="${size}" viewBox="0 0 24 24" aria-hidden="true">${ICONS[name] || ""}</svg>`;
|
||||
|
||||
// ---------------------------------------------------------------- Backend
|
||||
|
||||
async function holen() {
|
||||
try {
|
||||
const r = await fetch(`/api/zustand?client=${encodeURIComponent(CLIENT)}`, { cache: "no-store" });
|
||||
if (!r.ok) throw new Error("HTTP " + r.status);
|
||||
zustand = await r.json();
|
||||
verbunden = true;
|
||||
antwortZeit = Date.now();
|
||||
} catch {
|
||||
verbunden = false;
|
||||
}
|
||||
zeichne();
|
||||
}
|
||||
|
||||
async function senden(pfad, daten, meldung) {
|
||||
try {
|
||||
const r = await fetch(pfad, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(daten) });
|
||||
const antwort = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(antwort.fehler || "HTTP " + r.status);
|
||||
if (meldung) zeigeToast(meldung);
|
||||
} catch (fehler) {
|
||||
zeigeToast("Nicht gesendet: " + fehler.message);
|
||||
}
|
||||
await holen();
|
||||
}
|
||||
|
||||
function zeigeToast(text) {
|
||||
ui.toast = text;
|
||||
ui.toastBis = Date.now() + 6000;
|
||||
zeichne(true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Zeichnen
|
||||
|
||||
/** Neu zeichnen nur, wenn sich Daten oder Bedienzustand geaendert haben (sonst gehen Klicks verloren). */
|
||||
function zeichne(erzwingen = false) {
|
||||
if (zeigerUnten && !erzwingen) return ticke();
|
||||
if (ui.toast && Date.now() > ui.toastBis) ui.toast = "";
|
||||
const fluechtig = zustand
|
||||
? { ...zustand, jetzt: null, pruefung: { ...zustand.pruefung, restSekunden: null }, vortrag: { ...zustand.vortrag, restMs: null } }
|
||||
: null;
|
||||
const schluessel = JSON.stringify([fluechtig, ui, verbunden]);
|
||||
if (erzwingen || schluessel !== letzterSchluessel) {
|
||||
letzterSchluessel = schluessel;
|
||||
document.getElementById("root").innerHTML = seite();
|
||||
}
|
||||
ticke();
|
||||
}
|
||||
|
||||
/** Uhrzeit und Countdowns jede Sekunde aktualisieren, ohne die Seite neu aufzubauen. */
|
||||
function ticke() {
|
||||
const vergangen = Date.now() - antwortZeit;
|
||||
document.querySelectorAll("[data-tick]").forEach((el) => {
|
||||
const art = el.dataset.tick;
|
||||
if (art === "uhr") el.textContent = uhr(Date.now());
|
||||
else if (art === "pruefung" && zustand) el.textContent = mmss(zustand.pruefung.restSekunden * 1000 - vergangen);
|
||||
else if (art === "vortrag" && zustand) el.textContent = mmss(zustand.vortrag.restMs - vergangen);
|
||||
});
|
||||
}
|
||||
|
||||
function seite() {
|
||||
if (!zustand) {
|
||||
return `<main class="app-shell">${kopf(null)}<div class="page">${verbindungsBanner()}</div></main>`;
|
||||
}
|
||||
const z = zustand;
|
||||
const dozent = ui.rolle === "dozent";
|
||||
return `<main class="app-shell">
|
||||
<a class="skip-link" href="#raumstatus">Zum Raumstatus springen</a>
|
||||
${kopf(z)}
|
||||
<div class="page">
|
||||
${kontext(z)}
|
||||
${verbunden ? banner(z) : verbindungsBanner()}
|
||||
${ui.toast ? `<div class="toast" role="status">${icon("check", 16)} ${esc(ui.toast)}</div>` : ""}
|
||||
<div class="content-grid">
|
||||
<div class="main-column">${raumstatus(z)}${raumansicht(z)}</div>
|
||||
<aside class="side-column">${dozent ? dozentensteuerung(z) : ""}${wunschkarte(z)}${verlauf(z)}</aside>
|
||||
</div>
|
||||
${demos(z)}
|
||||
${fuss(z)}
|
||||
</div>
|
||||
</main>`;
|
||||
}
|
||||
|
||||
function kopf(z) {
|
||||
const rolle = (name, text) =>
|
||||
`<button type="button" class="role-option ${ui.rolle === name ? "active" : ""}" aria-pressed="${ui.rolle === name}" data-action="rolle:${name}">${text}</button>`;
|
||||
let status;
|
||||
if (!z || !verbunden) status = `<div class="live-status is-offline">${icon("offline", 16)} Backend nicht erreichbar</div>`;
|
||||
else if (z.szenario !== "live") status = `<div class="live-status"><span class="live-dot"></span> Demo-Szenario</div>`;
|
||||
else if (z.sensorOnline) status = `<div class="live-status"><span class="live-dot"></span> Arduino verbunden</div>`;
|
||||
else status = `<div class="live-status is-offline">${icon("offline", 16)} Arduino nicht verbunden</div>`;
|
||||
return `<header class="topbar">
|
||||
<div class="brand-group"><div class="brand-mark">${icon("wind", 22)}</div>
|
||||
<div><div class="brand-name">KlimaCampus</div><div class="brand-subtitle">Raum 2.14 · Gebäude West</div></div></div>
|
||||
<div class="role-switch" role="group" aria-label="Rollenansicht">${rolle("studierende", "Studierende")}${rolle("dozent", "Dozent")}</div>
|
||||
${status}
|
||||
</header>`;
|
||||
}
|
||||
|
||||
function kontext(z) {
|
||||
const w = z.werte;
|
||||
return `<div class="context-bar">
|
||||
<div class="greeting"><b>${gruss()}, ${ui.rolle === "dozent" ? "Herr Weber" : "zusammen"}.</b>
|
||||
<span>Seminarraum 2.14 · Raumklima wird automatisch und fair gesteuert</span></div>
|
||||
<div class="outside-chip">${icon("temperature", 17)}<span><b>${zahl(w.aussenTemperatur.wert, 0)} °C</b> außen</span>
|
||||
<span class="divider"></span>${icon("wind", 17)}<span><b>${zahl(w.wind.wert, 0)} km/h</b> Wind</span></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function verbindungsBanner() {
|
||||
return `<section class="status-banner tone-danger" role="status" aria-live="polite">
|
||||
<div class="status-symbol">${icon("offline", 24)}</div>
|
||||
<div class="status-copy"><div class="status-title">Backend nicht erreichbar</div>
|
||||
<div class="status-detail">Läuft <b>node backend/server.js</b>? Die Seite versucht es jede Sekunde erneut.</div></div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function banner(z) {
|
||||
const e = z.entscheidung;
|
||||
const offline = z.szenario === "offline";
|
||||
const ton = offline ? "neutral" : e.status.ton;
|
||||
const symbol = offline ? "offline" : ton === "good" ? "check" : ton === "info" ? "presentation" : "info";
|
||||
const vortragTitel = z.vortrag.aktiv && !e.vetos.co2 && !e.vetos.wind && !offline;
|
||||
const titel = offline ? "Sensor offline – sicherer Zustand" : vortragTitel ? `Vortragsmodus aktiv bis ${uhr(z.vortrag.ende)}` : e.status.titel;
|
||||
const detail = offline ? "Es kommen keine aktuellen Messwerte. Die Automatik hält die letzten sicheren Einstellungen." : e.status.detail;
|
||||
let rechts;
|
||||
if (offline) rechts = `<button type="button" class="banner-action" data-action="szenario:live">${icon("refresh", 16)} Erneut verbinden</button>`;
|
||||
else if (ui.rolle === "studierende" && z.vortrag.aktiv)
|
||||
rechts = `<div class="priority-chip countdown-chip">${icon("clock", 16)} noch <span data-tick="vortrag"></span></div>`;
|
||||
else rechts = `<div class="priority-chip">${icon(e.prioritaet.icon, 16)} Priorität ${e.prioritaet.nummer}: ${esc(e.prioritaet.text)}</div>`;
|
||||
return `<section class="status-banner tone-${esc(ton)}" role="status" aria-live="polite">
|
||||
<div class="status-symbol">${icon(symbol, 24)}</div>
|
||||
<div class="status-copy"><div class="status-title">${esc(titel)}</div><div class="status-detail">${esc(detail)}</div></div>
|
||||
${rechts}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function raumstatus(z) {
|
||||
const w = z.werte, e = z.entscheidung, g = z.grenzwerte;
|
||||
const offline = z.szenario === "offline";
|
||||
const soll = e.zielTemperatur;
|
||||
const ist = w.temperatur.wert;
|
||||
const zustandText = (wert, normal) => (offline ? "Veraltet" : wert === null ? "Kein Wert" : normal);
|
||||
|
||||
const co2 = w.eco2.wert;
|
||||
const co2Hoch = co2 !== null && co2 > g.co2Ppm;
|
||||
const abw = ist === null ? 0 : ist - soll;
|
||||
const tempText = Math.abs(abw) <= 0.5 ? "Im Ziel" : abw > 0 ? "Über Soll" : "Unter Soll";
|
||||
const laerm = w.laerm.wert;
|
||||
const laut = laerm !== null && laerm > g.laermDb;
|
||||
const wind = w.wind.wert;
|
||||
const sturm = wind !== null && wind > g.windKmh;
|
||||
|
||||
const karte = (klasse, iconName, status, label, wert, einheit, balken, fuss, eingabe) => `
|
||||
<article class="metric-card ${!offline ? klasse : ""}">
|
||||
<div class="metric-top"><span class="metric-icon">${icon(iconName)}</span><span class="metric-state">${status}</span></div>
|
||||
<div class="metric-label" title="Quelle: ${eingabe && eingabe.quelle ? QUELLE_TEXT[eingabe.quelle] : "kein Wert"}">${label}</div>
|
||||
<div class="metric-value">${wert} <small>${einheit}</small></div>
|
||||
${balken}
|
||||
<div class="metric-foot">${fuss}</div>
|
||||
</article>`;
|
||||
const balken = (breite, marke, neutral = false) =>
|
||||
`<div class="metric-bar ${neutral ? "neutral" : ""}"><i style="width:${Math.max(0, Math.min(100, breite))}%"></i><em style="left:${marke}%"></em></div>`;
|
||||
|
||||
const p = z.pruefung;
|
||||
const geraet = (klasse, iconName, name, wert) => `<div class="device ${klasse}">${icon(iconName, 18)}<span>${name}<b>${wert}</b></span></div>`;
|
||||
const manuell = z.manuell;
|
||||
const automatik = offline ? "Eingeschränkt" : manuell.aktiv ? `Manuell bis ${uhr(manuell.bis)}` : z.vortrag.aktiv ? "Vortragsmodus" : "Aktiv";
|
||||
const fensterText = e.fenster.text + (e.fenster.oeffnung > 0 ? ` · ${e.fenster.oeffnung} %` : "");
|
||||
const fensterKlasse = e.fenster.text === "Gesperrt" ? "locked" : manuell.fenster ? "manual" : "";
|
||||
|
||||
const s = z.letzterMesswert;
|
||||
const chip = (name, eingabe, einheit, stellen = 0) =>
|
||||
`<span class="sensor-chip ${eingabe.wert === null ? "is-off" : ""}">${name} <b>${zahl(eingabe.wert, stellen)}${eingabe.wert === null ? "" : " " + einheit}</b> ${quelle(eingabe)}</span>`;
|
||||
|
||||
return `<section class="card status-card" id="raumstatus" tabindex="-1">
|
||||
<div class="section-header">
|
||||
<div><h2 class="section-title">Raumstatus</h2><div class="section-subtitle">Messwerte und Gerätezustand in Raum 2.14</div></div>
|
||||
<div class="updated ${offline || !z.sensorOnline ? "stale" : ""}">${
|
||||
offline ? `${icon("offline", 14)} Sensor offline · veraltet`
|
||||
: z.sensorOnline ? `<span class="live-dot"></span> Live · <span data-tick="uhr"></span> Uhr`
|
||||
: `${icon("offline", 14)} Kein Arduino${s ? " · letzte Messung " + uhr(s.zeit) : ""}`}</div>
|
||||
</div>
|
||||
<div class="check-bar">
|
||||
${icon("clock", 16)}<span>Nächste Prüfung in <b data-tick="pruefung"></b></span>
|
||||
<span>· alle ${p.abstandSekunden >= 60 ? zahl(p.abstandSekunden / 60, 0) + " min" : p.abstandSekunden + " s"}${p.letzteUhrzeit ? " · zuletzt " + esc(p.letzteUhrzeit) : ""}</span>
|
||||
<span class="spacer"></span>
|
||||
<button type="button" class="icon-button" data-action="pruefen">${icon("refresh", 15)} Jetzt prüfen</button>
|
||||
<span class="speed-group" role="group" aria-label="Zeitraffer">Zeitraffer
|
||||
${[1, 5, 10].map((f) => `<button type="button" class="duration-button ${p.zeitraffer === f ? "active" : ""}" aria-pressed="${p.zeitraffer === f}" data-action="raffer:${f}">${f}×</button>`).join("")}
|
||||
</span>
|
||||
</div>
|
||||
<div class="measure-grid ${offline ? "is-stale" : ""}">
|
||||
${karte(co2Hoch ? "metric-alert" : "", "air", zustandText(co2, co2Hoch ? "Zu hoch" : "Gut"), "Luft (CO₂)", co2 === null ? "–" : co2.toLocaleString("de-DE"), "ppm",
|
||||
balken((co2 ?? 0) / 15, g.co2Ppm / 15), `${icon("lock", 13)} Grenzwert ${g.co2Ppm.toLocaleString("de-DE")} ppm`, w.eco2)}
|
||||
${karte(tempText !== "Im Ziel" ? "metric-warning" : "", "temperature", zustandText(ist, tempText), "Temperatur", zahl(ist), "°C Ist",
|
||||
balken((((ist ?? 18) - 18) / 8) * 100, ((soll - 18) / 8) * 100, true), `<b>Soll ${zahl(soll)} °C</b> · ${g.zielMinC}–${g.zielMaxC} °C`, w.temperatur)}
|
||||
${karte(laut ? "metric-warning" : "", "volume", zustandText(laerm, laut ? "Außen laut" : "Ruhig"), "Außenlärm", zahl(laerm, 0), "dB",
|
||||
balken(laerm ?? 0, g.laermDb), `${icon("shield", 13)} Ab ${g.laermDb} dB Fenster gesperrt`, w.laerm)}
|
||||
${karte(sturm ? "metric-warning" : "", "wind", zustandText(wind, sturm ? "Sturm" : "Leicht"), "Wind", zahl(wind, 0), "km/h",
|
||||
balken(wind ?? 0, g.windKmh), `Feinstaub ${zahl(w.feinstaub.wert, 0)} µg/m³`, w.wind)}
|
||||
</div>
|
||||
<div class="sensor-strip">
|
||||
<span class="sensor-chip ${z.sensorOnline ? "" : "is-off"}">${z.sensorOnline ? `Arduino <b>live</b> · ${uhr(s.zeit)}` : "Arduino <b>nicht verbunden</b>"}</span>
|
||||
${chip("Luftfeuchte", w.luftfeuchte, "%")}${chip("TVOC", w.tvoc, "ppb")}${chip("Helligkeit", w.helligkeit, "%")}
|
||||
</div>
|
||||
<div class="device-row">
|
||||
${geraet(fensterKlasse, e.fenster.text === "Gesperrt" ? "lock" : "air", "Fenster", esc(fensterText))}
|
||||
${geraet(manuell.jalousie !== null ? "manual" : "", "blinds", "Jalousien", `${Math.round(e.jalousie)} % geschlossen${manuell.jalousie !== null ? " · manuell" : ""}`)}
|
||||
${geraet(offline ? "unknown" : manuell.aktiv ? "manual" : "", "spark", "Automatik", esc(automatik))}
|
||||
${geraet("", "people", "Sollwert", `${zahl(soll)} °C · ${z.stimmen.gesamt} Wünsche`)}
|
||||
</div>
|
||||
<div class="device-row">
|
||||
${geraet(manuell.lueftung ? "manual" : "", "air", "Lüftungsanlage", e.lueftung > 0 ? `An · ${Math.round(e.lueftung * 100)} %` : "Aus")}
|
||||
${geraet("", "temperature", "Heizung", e.heizung > 0 ? `${Math.round(e.heizung * 100)} %` : "Aus")}
|
||||
${geraet(manuell.licht !== null ? "manual" : "", "energy", "Licht", `${Math.round(e.licht * 100)} %`)}
|
||||
${geraet("", "presentation", "Beamer", e.beamer ? "An" : "Aus")}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function raumansicht(z) {
|
||||
const e = z.entscheidung;
|
||||
const offen = e.fenster.oeffnung > 0;
|
||||
const fenster = (seite) => `<div class="window-unit ${seite}-window">
|
||||
<div class="window-panel open-${offen ? "yes" : "no"}"><span></span><span></span><span></span></div>
|
||||
<div class="blind-overlay" style="height:${e.jalousie}%"></div></div>`;
|
||||
const fensterIcon = e.fenster.text === "Gesperrt" ? "lock" : "air";
|
||||
return `<section class="card room-card">
|
||||
<div class="section-header compact"><div><h2 class="section-title">Raumansicht</h2>
|
||||
<div class="section-subtitle">Visualisierung von Fenstern und Jalousien</div></div></div>
|
||||
<div class="room-visual" aria-hidden="true"><div class="room-wall">
|
||||
<div class="ceiling-light one"></div><div class="ceiling-light two"></div>
|
||||
<div class="screen"><div class="screen-title">RAUM 2.14</div><div class="screen-temp">${zahl(z.werte.temperatur.wert)}°</div>
|
||||
<div class="screen-note">Ist · Soll ${zahl(e.zielTemperatur)} °C</div></div>
|
||||
${fenster("left")}${fenster("right")}
|
||||
${offen ? `<div class="airflow"><span>→</span><span>→</span><span>→</span></div>` : ""}
|
||||
<div class="room-floor"></div>
|
||||
<div class="desk desk-one"><i></i><i></i></div><div class="desk desk-two"><i></i><i></i></div><div class="desk desk-three"><i></i><i></i></div>
|
||||
<div class="teacher-desk"></div>
|
||||
<div class="room-label window-label">${icon(fensterIcon, 15)} Fenster: ${esc(e.fenster.text)}</div>
|
||||
<div class="room-label blind-label">${icon("blinds", 15)} Jalousien: ${Math.round(e.jalousie)} %</div>
|
||||
</div></div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function dozentensteuerung(z) {
|
||||
const v = z.vortrag, m = z.manuell;
|
||||
return `<section class="card presentation-card ${v.aktiv ? "is-active" : ""}">
|
||||
<div class="card-kicker">${icon("presentation", 17)} Dozentensteuerung</div>
|
||||
<div class="presentation-heading">
|
||||
<div><h2 class="section-title">Beamer-Modus</h2><div class="section-subtitle">Beamer an, Licht aus, Jalousien schließen</div></div>
|
||||
<div class="switch-wrap"><span class="switch-text">${v.aktiv ? "An" : "Aus"}</span>
|
||||
<button type="button" class="big-switch ${v.aktiv ? "on" : ""}" aria-pressed="${v.aktiv}" aria-label="Beamer-Modus umschalten" title="Beamer-Modus umschalten" data-action="beamer"><span></span></button></div>
|
||||
</div>
|
||||
<div class="duration-label">Dauer</div>
|
||||
<div class="duration-group" role="group" aria-label="Dauer des Beamer-Modus">
|
||||
${[30, 60, 90].map((d) => `<button type="button" class="duration-button ${v.dauerMinuten === d ? "active" : ""}" aria-pressed="${v.dauerMinuten === d}" data-action="dauer:${d}">${d} Min.</button>`).join("")}
|
||||
</div>
|
||||
${v.aktiv ? `<div class="countdown-box"><div class="countdown-icon">${icon("clock")}</div>
|
||||
<div><span>Verbleibende Zeit</span><b data-tick="vortrag"></b></div><div class="until">bis ${uhr(v.ende)}</div></div>` : ""}
|
||||
<div class="blind-controls">
|
||||
<div><div class="duration-label">Jalousien manuell</div><div class="section-subtitle">Übersteuert die Automatik für 90 Min.</div></div>
|
||||
<div class="blind-buttons">
|
||||
<button type="button" class="icon-button" title="Jalousien öffnen" aria-label="Jalousien öffnen" data-action="jalousie:0">↑ Auf</button>
|
||||
<button type="button" class="icon-button" title="Jalousien schließen" aria-label="Jalousien schließen" data-action="jalousie:100">↓ Zu</button>
|
||||
</div>
|
||||
</div>
|
||||
${m.aktiv ? `<div class="pause-note"><span>${icon("clock", 15)} Automatik pausiert bis ${uhr(m.bis)}</span>
|
||||
<span class="pause-actions"><button type="button" class="text-button" data-action="automatik">Automatik fortsetzen</button></span></div>` : ""}
|
||||
<div class="guard-note">${icon("shield", 17)}<span><b>Schutzregeln bleiben aktiv.</b> CO₂-Grenzwert und Sturm-Sperre können nicht überschrieben werden.</span></div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function wunschkarte(z) {
|
||||
const e = z.entscheidung, g = z.grenzwerte, st = z.stimmen;
|
||||
const eigene = st.eigene;
|
||||
const eigenerWunsch = eigene ? eigene.temperaturWunsch : null;
|
||||
const offline = z.szenario === "offline";
|
||||
if (ui.wunsch === null) ui.wunsch = eigenerWunsch ?? e.zielTemperatur ?? 22;
|
||||
const wert = ui.wunsch;
|
||||
const geaendert = eigenerWunsch === null || eigenerWunsch !== wert;
|
||||
const knopf = eigenerWunsch === null ? "Wunsch senden" : geaendert ? "Wunsch aktualisieren" : "Wunsch gezählt ✓";
|
||||
const ausserhalb = wert < g.zielMinC || wert > g.zielMaxC;
|
||||
|
||||
const grade = [19, 20, 21, 22, 23, 24, 25];
|
||||
const verteilung = st.verteilung || {};
|
||||
const max = Math.max(1, ...grade.map((d) => verteilung[d] || 0));
|
||||
const agg = e.aggregation.temperatur;
|
||||
const fenster = st.fenster || { auf: 0, zu: 0 };
|
||||
const fensterWahl = eigene ? eigene.fenster : null;
|
||||
|
||||
return `<section class="card wish-card">
|
||||
<div class="section-header compact"><div><h2 class="section-title">Dein Temperaturwunsch</h2>
|
||||
<div class="section-subtitle">Ist ${zahl(z.werte.temperatur.wert)} °C · Soll ${zahl(e.zielTemperatur)} °C</div></div>${icon("temperature")}</div>
|
||||
<div class="stepper" role="group" aria-label="Temperaturwunsch einstellen">
|
||||
<button type="button" class="step-button" aria-label="0,5 Grad kühler" data-action="minus" ${wert <= g.wunschMinC ? "disabled" : ""}>${icon("minus", 22)}</button>
|
||||
<div class="step-value" aria-live="polite"><b>${zahl(wert)}</b><span>°C</span>
|
||||
<small>${ausserhalb ? `außerhalb ${g.zielMinC}–${g.zielMaxC} °C – wird begrenzt` : "in 0,5 °C-Schritten"}</small></div>
|
||||
<button type="button" class="step-button" aria-label="0,5 Grad wärmer" data-action="plus" ${wert >= g.wunschMaxC ? "disabled" : ""}>${icon("plus", 22)}</button>
|
||||
</div>
|
||||
<div class="wish-actions">
|
||||
<button type="button" class="primary-button" data-action="senden" ${offline || !geaendert ? "disabled" : ""}>${knopf}</button>
|
||||
${eigene ? `<button type="button" class="secondary-button" data-action="zurueck">${icon("undo", 15)} Rückgängig</button>` : ""}
|
||||
</div>
|
||||
${eigenerWunsch !== null ? `<div class="my-wish">${icon("lock", 15)} <span>Dein Wunsch: <b>${zahl(eigenerWunsch)} °C</b> · gesendet ${uhr(eigene.zeit)} Uhr
|
||||
<small>Nur für dich sichtbar – nicht im gemeinsamen Verlauf.</small></span></div>` : ""}
|
||||
${offline ? `<div class="wish-offline">${icon("offline", 15)} Senden ist möglich, sobald der Sensor wieder verbunden ist.</div>` : ""}
|
||||
<div class="vote-row">
|
||||
<div class="duration-label">Fenster öffnen? <span class="section-subtitle">Auf ${fenster.auf} : Zu ${fenster.zu} – bei Außenlärm öffnet nur die Mehrheit</span></div>
|
||||
<div class="duration-group" role="group" aria-label="Fensterwunsch">
|
||||
<button type="button" class="duration-button ${fensterWahl === "auf" ? "active" : ""}" data-action="fenster:auf">Auf</button>
|
||||
<button type="button" class="duration-button ${fensterWahl === "zu" ? "active" : ""}" data-action="fenster:zu">Zu</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="distribution" aria-label="Verteilung der Temperaturwünsche">
|
||||
${grade.map((d) => `<div class="bucket ${Math.round(e.zielTemperatur) === d ? "is-target" : ""}"><span class="bucket-count">${verteilung[d] || 0}</span>
|
||||
<i style="height:${((verteilung[d] || 0) / max) * 100}%"></i><span class="bucket-label">${d === 19 ? "≤19" : d === 25 ? "≥25" : d}°</span></div>`).join("")}
|
||||
</div>
|
||||
<div class="wish-summary"><b>Sollwert ${zahl(e.zielTemperatur)} °C</b> = Durchschnitt aus ${agg.gesamt} Wünschen${agg.begrenzt ? `, auf ${g.zielMinC}–${g.zielMaxC} °C begrenzt` : ""}.${
|
||||
agg.ausreisser ? " Einzelne Ausreißer verschieben den Wert nicht." : ""}${
|
||||
st.zielNachPruefung !== e.zielTemperatur ? ` Nach der nächsten Prüfung: <b class="next-target">${zahl(st.zielNachPruefung)} °C</b> (${st.gesamt} Wünsche).` : ""}</div>
|
||||
<div class="fairness-note">${icon("info", 16)} <span>Anonym – gespeichert wird nur der Wert. Jeder Browser-Tab zählt als eigene Person
|
||||
(Kennung <span class="client-id">${esc(CLIENT.slice(4))}</span>). Die Stimme des Dozenten zählt wie jede andere.</span></div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function verlauf(z) {
|
||||
return `<section class="card history-card">
|
||||
<div class="section-header compact"><div><h2 class="section-title">Verlauf</h2>
|
||||
<div class="section-subtitle">Was das System getan hat – und warum. Keine einzelnen Wünsche.</div></div>${icon("history")}</div>
|
||||
<div class="timeline">${z.verlauf.slice(0, 4).map((v) => `<div class="timeline-row"><div class="timeline-dot ${esc(v.ton)}"></div>
|
||||
<div class="timeline-content"><div><b>${esc(v.titel)}</b><time>${esc(v.uhrzeit)}</time></div><p>${esc(v.grund)}</p></div></div>`).join("")}</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function demos(z) {
|
||||
const aktiv = z.szenarien.find((s) => s.id === z.szenario);
|
||||
return `<section class="demo-panel ${ui.demoOffen ? "open" : ""}">
|
||||
<button type="button" class="demo-header" aria-pressed="${ui.demoOffen}" data-action="demo">
|
||||
<span class="demo-title"><span class="demo-spark">${icon("spark", 17)}</span>
|
||||
<span><b>Demo-Szenarien</b><small>Systemreaktionen direkt simulieren – „Live“ nutzt die echten Arduino-Werte</small></span></span>
|
||||
<span class="demo-current">Aktiv: ${esc(aktiv ? aktiv.text : z.szenario)}</span>
|
||||
<span class="chevron ${ui.demoOffen ? "up" : ""}">${icon("chevron")}</span>
|
||||
</button>
|
||||
${ui.demoOffen ? `<div class="scenario-grid">${z.szenarien.map((s) => `
|
||||
<button type="button" class="scenario-button ${s.id === z.szenario ? "active" : ""}" aria-pressed="${s.id === z.szenario}" data-action="szenario:${esc(s.id)}">
|
||||
<span class="scenario-check">${s.id === z.szenario ? icon("check", 14) : ""}</span>
|
||||
<span><b>${esc(s.text)}</b><small>${esc(s.beschreibung)}</small></span></button>`).join("")}</div>` : ""}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function fuss(z) {
|
||||
return `<footer>
|
||||
<div>${icon("shield", 15)} Reihenfolge: Gesundheit → Kontext → Dozent/Mehrheit → Energie</div>
|
||||
<details class="data-info" ${ui.datenOffen ? "open" : ""} data-details="daten"><summary>Welche Daten werden erfasst?</summary>
|
||||
<p>CO₂, TVOC, Temperatur, Luftfeuchte, Helligkeit und Lautstärke vom Arduino im Raum, Wind, Außentemperatur und Feinstaub vom Wetterdienst.
|
||||
Lärm nur als Pegel in dB – <b>keine Mikrofonaufnahmen, keine Kameras</b>. Temperaturwünsche anonym, ohne Namen – deinen eigenen Wunsch siehst nur du,
|
||||
im gemeinsamen Verlauf erscheinen nur Entscheidungen. Alles liegt nur im Arbeitsspeicher des Backends und ist nach einem Neustart weg; Wünsche verfallen nach 30 Minuten.</p></details>
|
||||
<div>${z.sensorOnline ? "Arduino verbunden" : "Arduino nicht verbunden"} · Prüfung alle ${zahl(z.pruefung.intervallSekunden / 60, 0)} min</div>
|
||||
</footer>`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Bedienung
|
||||
|
||||
document.getElementById("root").addEventListener("click", (ereignis) => {
|
||||
const ziel = ereignis.target.closest("[data-action]");
|
||||
if (!ziel || ziel.disabled || !zustand) return;
|
||||
const [aktion, wert] = ziel.dataset.action.split(":");
|
||||
const z = zustand;
|
||||
switch (aktion) {
|
||||
case "rolle":
|
||||
ui.rolle = wert;
|
||||
merke("ambient-rolle", wert);
|
||||
zeichne(true);
|
||||
break;
|
||||
case "minus":
|
||||
ui.wunsch = Math.max(z.grenzwerte.wunschMinC, ui.wunsch - 0.5);
|
||||
zeichne(true);
|
||||
break;
|
||||
case "plus":
|
||||
ui.wunsch = Math.min(z.grenzwerte.wunschMaxC, ui.wunsch + 0.5);
|
||||
zeichne(true);
|
||||
break;
|
||||
case "senden":
|
||||
senden("/api/stimme", { client: CLIENT, rolle: ui.rolle, temperaturWunsch: ui.wunsch },
|
||||
`Dein Wunsch von ${zahl(ui.wunsch)} °C wurde gezählt. Er wirkt bei der nächsten Prüfung.`);
|
||||
break;
|
||||
case "zurueck":
|
||||
ui.wunsch = null;
|
||||
senden("/api/stimme", { client: CLIENT, zuruecknehmen: true }, "Deine Stimme wurde zurückgezogen.");
|
||||
break;
|
||||
case "fenster":
|
||||
senden("/api/stimme", { client: CLIENT, rolle: ui.rolle, fenster: wert }, `Fensterwunsch „${wert === "auf" ? "Auf" : "Zu"}“ gezählt.`);
|
||||
break;
|
||||
case "beamer":
|
||||
senden("/api/vortragsmodus", { rolle: "dozent", aktiv: !z.vortrag.aktiv, dauerMinuten: z.vortrag.dauerMinuten });
|
||||
break;
|
||||
case "dauer":
|
||||
senden("/api/vortragsmodus", { rolle: "dozent", dauerMinuten: Number(wert) });
|
||||
break;
|
||||
case "jalousie":
|
||||
senden("/api/jalousie", { rolle: "dozent", position: Number(wert) }, Number(wert) ? "Jalousien manuell geschlossen." : "Jalousien manuell geöffnet.");
|
||||
break;
|
||||
case "automatik":
|
||||
senden("/api/manuell", { rolle: "dozent", zuruecksetzen: true }, "Automatik fortgesetzt.");
|
||||
break;
|
||||
case "pruefen":
|
||||
senden("/api/pruefen", {}, "Prüfung ausgeführt – Entscheidung ist aktuell.");
|
||||
break;
|
||||
case "raffer":
|
||||
senden("/api/zeitraffer", { faktor: Number(wert) }, `Zeitraffer ${wert}×: Prüfung alle ${Math.round(z.pruefung.intervallSekunden / Number(wert))} s.`);
|
||||
break;
|
||||
case "demo":
|
||||
ui.demoOffen = !ui.demoOffen;
|
||||
zeichne(true);
|
||||
break;
|
||||
case "szenario":
|
||||
senden("/api/szenario", { id: wert });
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("pointerdown", () => { zeigerUnten = true; }, true);
|
||||
document.addEventListener("pointerup", () => {
|
||||
zeigerUnten = false;
|
||||
setTimeout(() => zeichne(), 0); // nach dem Klick-Ereignis nachholen
|
||||
}, true);
|
||||
|
||||
document.getElementById("root").addEventListener("toggle", (ereignis) => {
|
||||
if (ereignis.target.dataset && ereignis.target.dataset.details === "daten") ui.datenOffen = ereignis.target.open;
|
||||
}, true);
|
||||
|
||||
holen();
|
||||
setInterval(holen, ABFRAGE_MS);
|
||||
setInterval(ticke, 1000);
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
/* Ergaenzungen zum Figma-Design (ambient.css bleibt unveraendert):
|
||||
Pruefzyklus mit "Jetzt pruefen" und Zeitraffer, weitere Arduino-Werte, Fensterwunsch, Teilnehmerkennung. */
|
||||
|
||||
.loading { padding: 40px 0; color: var(--muted); font-size: 15px; }
|
||||
|
||||
/* Pruefzyklus: Leiste unter der Kopfzeile des Raumstatus */
|
||||
.check-bar {
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px;
|
||||
margin: 10px 0 2px; padding: 8px 10px;
|
||||
border: 1px solid var(--line); border-radius: 11px; background: var(--soft);
|
||||
font-size: 13px; color: var(--muted);
|
||||
}
|
||||
.check-bar b { color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
.check-bar .spacer { flex: 1; }
|
||||
.check-bar .icon-button { height: 34px; min-width: 0; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; }
|
||||
.speed-group { display: inline-flex; gap: 4px; align-items: center; }
|
||||
.speed-group .duration-button { min-height: 34px; padding: 4px 10px; font-size: 13px; }
|
||||
.duration-button.active, .vote-row .duration-button.active {
|
||||
color: #fff; background: var(--green); border-color: var(--green);
|
||||
}
|
||||
|
||||
/* Weitere Arduino-Werte (Luftfeuchte, TVOC, Helligkeit) und Herkunft */
|
||||
.sensor-strip { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
|
||||
.sensor-chip {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px;
|
||||
border: 1px solid var(--line); border-radius: 999px; background: #fff;
|
||||
font-size: 13px; color: var(--muted);
|
||||
}
|
||||
.sensor-chip b { color: var(--ink); }
|
||||
.sensor-chip.is-off { color: var(--grey, #6b7280); background: var(--soft); }
|
||||
.source-tag { font-size: 11px; font-weight: 700; letter-spacing: .02em; color: var(--green-2); text-transform: uppercase; }
|
||||
.source-tag.demo { color: var(--amber); }
|
||||
.source-tag.wetter { color: var(--blue); }
|
||||
.source-tag.fehlt { color: var(--grey, #6b7280); }
|
||||
|
||||
/* zweite Geraetezeile: Lueftungsanlage, Heizung, Licht, Beamer */
|
||||
.device-row + .device-row { margin-top: 6px; }
|
||||
|
||||
/* Fensterwunsch (Mehrheit oeffnet trotz Laerm) */
|
||||
.vote-row { margin-top: 12px; }
|
||||
.vote-row .duration-group { grid-template-columns: repeat(2, 1fr); }
|
||||
.vote-row .duration-button { min-height: 38px; }
|
||||
.next-target { color: var(--blue); }
|
||||
.client-id { font-variant-numeric: tabular-nums; }
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue