Compare commits
2 Commits
main
...
claude/ard
| Author | SHA1 | Date |
|---|---|---|
|
|
756630e7dc | |
|
|
027444b0c3 |
10
README.md
10
README.md
|
|
@ -10,8 +10,12 @@ Sensoren (Arduino UNO) ➔ WiFi/Bluetooth ➔ Backend (Aggregation & Regeln) ➔
|
|||
Aktuell umgesetzt:
|
||||
```
|
||||
DHT11 + CCS811 ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Handy-Hotspot)─▶ Laptop: backend/server.py :3000 ◀── Browser
|
||||
▲
|
||||
└──▶ Unity-Zwilling (SmartLectureRoom)
|
||||
```
|
||||
|
||||
Der Unity-Zwilling (eigenes Repo `SmartLectureRoom`) holt im Modus **Verbindung → Backend** jede Sekunde `GET /api/messwerte` ab. Temperatur und eCO₂ vom Arduino ersetzen dann die simulierten Werte, das passende Szenario (Hitze, stickige Luft, Wintermorgen …) wird erkannt und Fenster, Lüftung, Heizung, Jalousie und Licht werden automatisch angesteuert. Die Entscheidung meldet Unity per `POST /api/steuerung` zurück. Details: README im Unity-Projekt, Abschnitt „Arduino anbinden“.
|
||||
|
||||
## Repo-Struktur
|
||||
| Ordner | Inhalt |
|
||||
|---|---|
|
||||
|
|
@ -21,7 +25,7 @@ DHT11 + CCS811 ─▶ Arduino Uno ─Serial (Pin 0/1)─▶ ESP-01 ─WLAN (Hand
|
|||
| `frontend/` | Responsive Webinterface (Live-Werte, Präferenz-Slider) und 3D-Raum |
|
||||
|
||||
## Status
|
||||
Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, eCO₂ und TVOC, zeigt sie auf dem LCD und sendet sie per ESP-01 an `backend/server.py`; die Website (`frontend/`) zeigt sie live mit Verlauf und CO₂-Alarm. Aggregation/Präferenzen und 3D-Zwilling fehlen noch (siehe [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 an `backend/server.py`; die Website (`frontend/`) zeigt sie live mit Verlauf und CO₂-Alarm. Der Unity-Zwilling ist an den Server angebunden (mit `simulator.py` vorbereitet, mit dem echten Arduino noch nicht getestet). Aggregation/Präferenzen im Backend fehlen noch (siehe [docs/offene-punkte.md](docs/offene-punkte.md)).
|
||||
|
||||
## Komponenten und ihre Aufgabe
|
||||
|
||||
|
|
@ -44,10 +48,10 @@ Live-Messwerte laufen Ende-zu-Ende: Der Arduino misst Temperatur, Luftfeuchte, e
|
|||
| `firmware/dht11_lcd/dht11_lcd.ino` | **Hauptprogramm** auf dem Uno: Sensoren lesen, LCD anzeigen, Senden anstoßen. Speichert außerdem stündlich die Kalibrierung („Baseline“) des CCS811 im EEPROM, damit die Werte nach einem Neustart schneller stimmen. |
|
||||
| `firmware/dht11_lcd/esp_wifi.h` | Steuert den ESP: Baudrate finden, mit dem Hotspot verbinden, Messwerte als **HTTP-POST** an den Laptop schicken. |
|
||||
| `firmware/dht11_lcd/wifi_config.h` | Zugangsdaten (Hotspot-Name, Passwort, Laptop-IP). Nicht im Repo, Vorlage: `wifi_config.example.h`. |
|
||||
| `backend/server.py` | **Server** auf dem Laptop (Port 3000): nimmt die Messwerte vom ESP an, merkt sich die letzten 100 und liefert die Website aus. |
|
||||
| `backend/server.py` | **Server** auf dem Laptop (Port 3000): nimmt die Messwerte vom ESP an, merkt sich die letzten 100, liefert die Website aus und stellt die Werte dem Unity-Zwilling bereit (dessen Steuerbefehle kommen per `POST /api/steuerung` zurück). |
|
||||
| `backend/start.bat` | Startet den Server per Doppelklick und prüft, ob die Laptop-IP zu `wifi_config.h` passt. |
|
||||
| `backend/firewall_freigeben.bat` | Gibt Port 3000 in der Windows-Firewall frei, damit der ESP den Laptop erreicht. |
|
||||
| `backend/simulator.py` | Schickt erfundene Werte – zum Testen ohne Arduino. |
|
||||
| `backend/simulator.py` | Schickt erfundene Werte – zum Testen ohne Arduino. Mit `--szenario hitze/stickig/kalt/normal/demo` gezielt Szenarien für den Unity-Zwilling auslösen. |
|
||||
| `frontend/` | **Website**: fragt alle 2 s beim Server die neuesten Werte ab und zeigt Kacheln, Verlaufsdiagramm und CO₂-Alarm ab 1000 ppm. |
|
||||
| `firmware/esp_test`, `firmware/ccs811_test`, `firmware/ccs811_diagnose` | Testprogramme zur Fehlersuche, im normalen Betrieb nicht nötig. |
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ Minimaler Server mit Python-Bordmitteln (Python ≥ 3.8, kein `pip install`, lä
|
|||
|
||||
```
|
||||
ESP8266 ──POST /api/messwerte──▶ backend/server.py ◀──GET /api/messwerte── Browser (frontend/)
|
||||
▲ ◀──GET /api/messwerte── Unity-Zwilling
|
||||
└───────────POST /api/steuerung─── Unity-Zwilling
|
||||
```
|
||||
|
||||
## Starten
|
||||
|
|
@ -11,7 +13,9 @@ Doppelklick auf `start.bat` oder:
|
|||
```bash
|
||||
python backend/server.py # Port 3000 (oder: python backend/server.py 8080)
|
||||
python backend/simulator.py # optional: Fake-Sensordaten ohne Hardware
|
||||
python backend/simulator.py --szenario demo # Szenarien nacheinander: normal, stickig, normal, hitze, kalt
|
||||
```
|
||||
Szenarien des Simulators: `wechsel` (Standard, Werte schwanken), `normal`, `hitze` (→ ca. 30 °C), `stickig` (→ ca. 1600 ppm), `kalt` (→ ca. 17 °C), `demo`. Die Werte ändern sich langsam wie in echt, damit man im Unity-Zwilling sieht, wann die Steuerung umschaltet.
|
||||
Frontend: http://localhost:3000, im Hotspot von anderen Geräten: `http://<Laptop-IP>:3000`
|
||||
|
||||
Beim Start zeigt der Server die IP-Adressen des Laptops und prüft, ob `SERVER_IP` in `firmware/dht11_lcd/wifi_config.h` dazu passt („OK“ bzw. „ACHTUNG“). Jeder empfangene Messwert erscheint mit Absender-IP im Fenster (`127.0.0.1` = Simulator, `172.20.10.x` = ESP im Hotspot).
|
||||
|
|
@ -37,6 +41,22 @@ Alle Felder sind Zahlen; ein Feld darf fehlen oder `null` sein (z. B. CCS811 noc
|
|||
|
||||
`GET /api/messwerte` liefert `{"aktuell": {...} | null, "verlauf": [...]}`.
|
||||
|
||||
### Steuerbefehle vom Unity-Zwilling
|
||||
`POST /api/steuerung` (sendet Unity im Modus „Backend“, sobald sich etwas ändert, sonst alle 10 s):
|
||||
|
||||
```json
|
||||
{"window": "open", "blind": 1.0, "heat": 0.0, "vent": 0.0, "light": 0.4, "beamer": 0, "szenario": "Hitze"}
|
||||
```
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|---|---|
|
||||
| `window` | `closed`, `tilted` oder `open` |
|
||||
| `blind`, `heat`, `vent`, `light` | Sollwert 0 … 1 (Jalousie unten, Heizung, Lüftungsanlage, Licht) |
|
||||
| `beamer` | 0/1 |
|
||||
| `szenario` | vom Zwilling erkanntes Szenario |
|
||||
|
||||
Der Server merkt sich nur den letzten Stand (`GET /api/steuerung` → `{"aktuell": {...} | null}`) und gibt ihn im Fenster aus. Echte Aktoren gibt es noch nicht.
|
||||
|
||||
Test ohne Hardware (PowerShell):
|
||||
```powershell
|
||||
Invoke-RestMethod -Method Post -Uri http://localhost:3000/api/messwerte -ContentType "application/json" `
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
# Minimaler Empfangs-Server: ESP8266 -> POST /api/messwerte -> Website (GET /api/messwerte)
|
||||
# Minimaler Empfangs-Server: ESP8266 -> POST /api/messwerte -> Website/Unity-Zwilling (GET /api/messwerte)
|
||||
# Der Unity-Zwilling meldet seine Steuerentscheidung per POST /api/steuerung zurueck (GET liefert sie).
|
||||
# Nur Python-Bordmittel, kein pip install noetig. Start: python server.py [Port] (oder start.bat)
|
||||
import json
|
||||
import math
|
||||
|
|
@ -22,6 +23,11 @@ FELDER = ["temperatur", "luftfeuchte", "eco2", "tvoc"]
|
|||
|
||||
verlauf = deque(maxlen=MAX_VERLAUF) # { zeit: ISO-String, temperatur, luftfeuchte, eco2, tvoc }
|
||||
|
||||
# Steuerbefehle des Unity-Zwillings, z. B. {"window":"open","blind":1.0,"heat":0,"vent":0,"light":0.4,"beamer":0,"szenario":"Hitze"}
|
||||
STEUER_TEXTFELDER = {"window", "szenario"}
|
||||
STEUER_ZAHLFELDER = {"blind", "heat", "vent", "light", "beamer"}
|
||||
steuerung = None
|
||||
|
||||
MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
|
|
@ -43,19 +49,31 @@ class Handler(BaseHTTPRequestHandler):
|
|||
def pfad(self):
|
||||
return self.path.split("?", 1)[0]
|
||||
|
||||
def do_POST(self):
|
||||
if self.pfad() != "/api/messwerte":
|
||||
return self.sende_json(405, {"fehler": "Methode nicht erlaubt"})
|
||||
|
||||
def lies_json_objekt(self):
|
||||
"""Liest den Body als JSON-Objekt. Bei Fehlern wird die Antwort gesendet und None geliefert."""
|
||||
laenge = int(self.headers.get("Content-Length") or 0)
|
||||
if laenge > MAX_BODY_BYTES:
|
||||
return self.sende_json(413, {"fehler": "Anfrage zu gross"})
|
||||
self.sende_json(413, {"fehler": "Anfrage zu gross"})
|
||||
return None
|
||||
try:
|
||||
daten = json.loads(self.rfile.read(laenge))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return self.sende_json(400, {"fehler": "Ungueltiges JSON"})
|
||||
self.sende_json(400, {"fehler": "Ungueltiges JSON"})
|
||||
return None
|
||||
if not isinstance(daten, dict):
|
||||
return self.sende_json(400, {"fehler": "JSON-Objekt erwartet"})
|
||||
self.sende_json(400, {"fehler": "JSON-Objekt erwartet"})
|
||||
return None
|
||||
return daten
|
||||
|
||||
def do_POST(self):
|
||||
if self.pfad() == "/api/steuerung":
|
||||
return self.steuerung_empfangen()
|
||||
if self.pfad() != "/api/messwerte":
|
||||
return self.sende_json(405, {"fehler": "Methode nicht erlaubt"})
|
||||
|
||||
daten = self.lies_json_objekt()
|
||||
if daten is None:
|
||||
return
|
||||
|
||||
eintrag = {"zeit": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")}
|
||||
for feld in FELDER:
|
||||
|
|
@ -72,10 +90,27 @@ class Handler(BaseHTTPRequestHandler):
|
|||
print(datetime.now().strftime("%H:%M:%S"), self.client_address[0], json.dumps(eintrag), flush=True)
|
||||
self.sende_json(200, {"ok": True})
|
||||
|
||||
def steuerung_empfangen(self):
|
||||
global steuerung
|
||||
daten = self.lies_json_objekt()
|
||||
if daten is None:
|
||||
return
|
||||
eintrag = {"zeit": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")}
|
||||
for feld, wert in daten.items():
|
||||
if feld in STEUER_TEXTFELDER and isinstance(wert, str):
|
||||
eintrag[feld] = wert[:40]
|
||||
elif feld in STEUER_ZAHLFELDER and isinstance(wert, (int, float)) and not isinstance(wert, bool) and math.isfinite(wert):
|
||||
eintrag[feld] = wert
|
||||
steuerung = eintrag
|
||||
print(datetime.now().strftime("%H:%M:%S"), "Unity-Steuerung", json.dumps(eintrag, ensure_ascii=False), flush=True)
|
||||
self.sende_json(200, {"ok": True})
|
||||
|
||||
def do_GET(self):
|
||||
pfad = self.pfad()
|
||||
if pfad == "/api/messwerte":
|
||||
return self.sende_json(200, {"aktuell": verlauf[-1] if verlauf else None, "verlauf": list(verlauf)})
|
||||
if pfad == "/api/steuerung":
|
||||
return self.sende_json(200, {"aktuell": steuerung})
|
||||
|
||||
datei = (FRONTEND_DIR / ("index.html" if pfad == "/" else pfad.lstrip("/"))).resolve()
|
||||
if FRONTEND_DIR not in datei.parents:
|
||||
|
|
|
|||
|
|
@ -1,27 +1,61 @@
|
|||
# Simuliert den ESP8266: schickt alle 2 s Fantasiewerte an den Server (Entwicklung ohne Hardware).
|
||||
# Start: python simulator.py [Server-URL] z. B. http://localhost:3000
|
||||
# Start: python simulator.py [Server-URL] [--szenario NAME] z. B. http://localhost:3000 --szenario hitze
|
||||
#
|
||||
# Szenarien (fuer die Vorfuehrung mit dem Unity-Zwilling, Modus "Backend"):
|
||||
# wechsel (Standard) Temperatur und CO2 schwanken, CO2 ueberschreitet zeitweise 1000 ppm
|
||||
# normal angenehmes Raumklima (22 °C, ca. 650 ppm)
|
||||
# hitze Temperatur steigt langsam auf ca. 30 °C -> Unity oeffnet die Fenster
|
||||
# stickig CO2 steigt langsam auf ca. 1600 ppm -> Unity lueftet (Fenster oder Lueftungsanlage)
|
||||
# kalt Temperatur faellt auf ca. 17 °C -> Unity heizt
|
||||
# demo laeuft nacheinander normal -> stickig -> normal -> hitze -> kalt durch (je ca. 1 min)
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
basis = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:3000"
|
||||
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"])
|
||||
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),
|
||||
}
|
||||
DEMO_ABLAUF = ["normal", "stickig", "normal", "hitze", "kalt"]
|
||||
DEMO_SCHRITTE = 30 # 30 x 2 s = 1 min je Abschnitt
|
||||
|
||||
temperatur, eco2 = 22.0, 650.0
|
||||
schritt = 0
|
||||
|
||||
while True:
|
||||
schritt += 1
|
||||
if args.szenario == "wechsel":
|
||||
temperatur = 22 + 2 * math.sin(schritt / 20)
|
||||
eco2 = 800 + 400 * math.sin(schritt / 25) # ueberschreitet zeitweise 1000 ppm
|
||||
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))
|
||||
|
||||
messwert = {
|
||||
"temperatur": round(22 + 2 * math.sin(schritt / 20), 1),
|
||||
"temperatur": round(temperatur + 0.1 * math.sin(schritt), 1),
|
||||
"luftfeuchte": round(45 + 5 * math.sin(schritt / 15), 1),
|
||||
"eco2": round(800 + 400 * math.sin(schritt / 25)), # ueberschreitet zeitweise 1000 ppm
|
||||
"tvoc": round(70 + 30 * math.sin(schritt / 10)),
|
||||
"eco2": round(eco2 + 10 * math.sin(schritt / 3)),
|
||||
"tvoc": round(70 + 30 * math.sin(schritt / 10) + max(0.0, eco2 - 800) / 10),
|
||||
}
|
||||
anfrage = urllib.request.Request(basis + "/api/messwerte", data=json.dumps(messwert).encode(),
|
||||
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("gesendet", json.dumps(messwert))
|
||||
print(f"gesendet [{aktiv}]", json.dumps(messwert))
|
||||
except OSError as fehler:
|
||||
print("Server nicht erreichbar:", fehler)
|
||||
time.sleep(2)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
/[Ll]ibrary/
|
||||
/[Tt]emp/
|
||||
/[Oo]bj/
|
||||
/[Bb]uild/
|
||||
/[Bb]uilds/
|
||||
/[Ll]ogs/
|
||||
/[Uu]ser[Ss]ettings/
|
||||
*.csproj
|
||||
*.sln
|
||||
.vs/
|
||||
.idea/
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
/*
|
||||
Smart Lecture Room – Sensorknoten für den Unity-Zwilling
|
||||
---------------------------------------------------------
|
||||
Sendet alle 2 s eine JSON-Zeile über USB-Seriell (115200 Baud) an Unity:
|
||||
{"t":23.4,"co2":812,"lux":350,"noise":46}
|
||||
und empfängt die Steuerbefehle der virtuellen Aktoren:
|
||||
{"window":"open","blind":1.00,"heat":0.50,"vent":0.80,"light":0.40,"beamer":0}
|
||||
|
||||
Verdrahtung (Beispiel, Arduino Uno – einfach an eure Sensoren anpassen):
|
||||
A0 TMP36 Temperatursensor
|
||||
A1 MQ-135 Gassensor (grobe CO2-Schätzung; besser: SCD30/SCD41 über I2C)
|
||||
A2 LDR-Spannungsteiler (Helligkeit)
|
||||
A3 Mikrofonmodul (Lärm)
|
||||
D9 Servo -> Fenstermodell (0° zu, 30° gekippt, 90° offen)
|
||||
D6 PWM -> Lüfter (über MOSFET/Transistor!)
|
||||
D5 PWM -> LED Heizung
|
||||
D3 PWM -> LED Licht
|
||||
|
||||
Auf dem ESP32 statt <Servo.h> die Bibliothek "ESP32Servo" verwenden; für WLAN die
|
||||
JSON-Zeile per UDP an Port 5005 des Unity-Rechners senden (Antworten kommen auf Port 5006).
|
||||
*/
|
||||
|
||||
#include <Servo.h>
|
||||
|
||||
const int PIN_TEMP = A0;
|
||||
const int PIN_GAS = A1;
|
||||
const int PIN_LDR = A2;
|
||||
const int PIN_MIC = A3;
|
||||
const int PIN_SERVO = 9;
|
||||
const int PIN_FAN = 6;
|
||||
const int PIN_HEAT_LED = 5;
|
||||
const int PIN_LIGHT_LED = 3;
|
||||
|
||||
const unsigned long SEND_INTERVAL_MS = 2000;
|
||||
|
||||
Servo windowServo;
|
||||
String inbox;
|
||||
unsigned long lastSend = 0;
|
||||
|
||||
float readTemperatureC() {
|
||||
float volts = analogRead(PIN_TEMP) * (5.0 / 1023.0);
|
||||
return (volts - 0.5) * 100.0; // TMP36: 10 mV/°C, 500 mV Offset
|
||||
}
|
||||
|
||||
float readCo2ppm() {
|
||||
// Sehr grobe Abbildung des MQ-135 – für echte Messungen SCD30/SCD41 nutzen und kalibrieren.
|
||||
int raw = analogRead(PIN_GAS);
|
||||
return 400.0 + raw * (4600.0 / 1023.0);
|
||||
}
|
||||
|
||||
float readLux() {
|
||||
int raw = analogRead(PIN_LDR);
|
||||
return raw * (1000.0 / 1023.0); // grob, je nach Widerstand anpassen
|
||||
}
|
||||
|
||||
float readNoiseDb() {
|
||||
// Spitze-Spitze-Wert über 50 ms -> grobe dB-Schätzung
|
||||
unsigned long start = millis();
|
||||
int lo = 1023, hi = 0;
|
||||
while (millis() - start < 50) {
|
||||
int v = analogRead(PIN_MIC);
|
||||
if (v < lo) lo = v;
|
||||
if (v > hi) hi = v;
|
||||
}
|
||||
int pp = max(hi - lo, 1);
|
||||
return 30.0 + 20.0 * log10(pp);
|
||||
}
|
||||
|
||||
// Liest einen Zahlenwert zu "key" aus einer flachen JSON-Zeile (ohne Bibliothek).
|
||||
float jsonNumber(const String& json, const char* key, float fallback) {
|
||||
String k = String("\"") + key + "\":";
|
||||
int i = json.indexOf(k);
|
||||
if (i < 0) return fallback;
|
||||
return json.substring(i + k.length()).toFloat();
|
||||
}
|
||||
|
||||
String jsonString(const String& json, const char* key) {
|
||||
String k = String("\"") + key + "\":\"";
|
||||
int i = json.indexOf(k);
|
||||
if (i < 0) return "";
|
||||
int start = i + k.length();
|
||||
int end = json.indexOf('"', start);
|
||||
return end < 0 ? "" : json.substring(start, end);
|
||||
}
|
||||
|
||||
void applyCommand(const String& json) {
|
||||
String window = jsonString(json, "window");
|
||||
if (window == "open") windowServo.write(90);
|
||||
else if (window == "tilted") windowServo.write(30);
|
||||
else if (window == "closed") windowServo.write(0);
|
||||
|
||||
analogWrite(PIN_FAN, (int)(constrain(jsonNumber(json, "vent", 0), 0, 1) * 255));
|
||||
analogWrite(PIN_HEAT_LED, (int)(constrain(jsonNumber(json, "heat", 0), 0, 1) * 255));
|
||||
analogWrite(PIN_LIGHT_LED, (int)(constrain(jsonNumber(json, "light", 0), 0, 1) * 255));
|
||||
// "blind" (0 = oben, 1 = unten) und "beamer" stehen ebenfalls zur Verfügung, z. B. für einen Schrittmotor.
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
windowServo.attach(PIN_SERVO);
|
||||
windowServo.write(0);
|
||||
pinMode(PIN_FAN, OUTPUT);
|
||||
pinMode(PIN_HEAT_LED, OUTPUT);
|
||||
pinMode(PIN_LIGHT_LED, OUTPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Befehle von Unity zeilenweise einlesen
|
||||
while (Serial.available()) {
|
||||
char c = (char)Serial.read();
|
||||
if (c == '\n') {
|
||||
if (inbox.startsWith("{")) applyCommand(inbox);
|
||||
inbox = "";
|
||||
} else if (inbox.length() < 200) {
|
||||
inbox += c;
|
||||
}
|
||||
}
|
||||
|
||||
if (millis() - lastSend >= SEND_INTERVAL_MS) {
|
||||
lastSend = millis();
|
||||
Serial.print("{\"t\":"); Serial.print(readTemperatureC(), 1);
|
||||
Serial.print(",\"co2\":"); Serial.print(readCo2ppm(), 0);
|
||||
Serial.print(",\"lux\":"); Serial.print(readLux(), 0);
|
||||
Serial.print(",\"noise\":"); Serial.print(readNoiseDb(), 0);
|
||||
Serial.println("}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
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.
|
||||
/// </summary>
|
||||
[InitializeOnLoad]
|
||||
static class SmartRoomSceneSetup
|
||||
{
|
||||
const string ScenePath = "Assets/Scenes/SmartRoom.unity";
|
||||
|
||||
static SmartRoomSceneSetup()
|
||||
{
|
||||
if (SessionState.GetBool("SmartRoom.SetupChecked", false)) return;
|
||||
SessionState.SetBool("SmartRoom.SetupChecked", true);
|
||||
EditorApplication.delayCall += () =>
|
||||
{
|
||||
if (EditorApplication.isPlayingOrWillChangePlaymode) return;
|
||||
if (!File.Exists(ScenePath)) CreateScene();
|
||||
};
|
||||
}
|
||||
|
||||
[MenuItem("Smart Room/Szene öffnen")]
|
||||
static void OpenScene()
|
||||
{
|
||||
if (!File.Exists(ScenePath)) { CreateScene(); return; }
|
||||
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
|
||||
EditorSceneManager.OpenScene(ScenePath);
|
||||
}
|
||||
|
||||
[MenuItem("Smart Room/Szene neu erstellen")]
|
||||
static void CreateScene()
|
||||
{
|
||||
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) };
|
||||
AssetDatabase.Refresh();
|
||||
Debug.Log("[Smart Room] Szene erstellt: " + ScenePath + " – Play drücken, um den Raum zu simulieren.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Außenjalousie: die Endschiene fährt herunter, Lamellen werden nacheinander aus dem Paket
|
||||
/// "abgewickelt" und stellen sich beim Herunterfahren schräg.
|
||||
/// </summary>
|
||||
public class BlindActuator : MonoBehaviour
|
||||
{
|
||||
[Range(0, 1)] public float target; // 0 = oben, 1 = unten
|
||||
public float speed = 0.12f; // ~8 s für eine komplette Fahrt
|
||||
public Transform[] slats;
|
||||
public Transform bottomRail;
|
||||
public float top, bottom, stackBase;
|
||||
public float stackGap = 0.008f, maxSlatAngle = 65f;
|
||||
|
||||
public float Current { get; private set; }
|
||||
public bool IsMoving => !Mathf.Approximately(Current, target);
|
||||
|
||||
float SlatFactor => Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.15f, 1f, Current));
|
||||
|
||||
/// <summary>Wie stark die Jalousie Licht/Sonne abschirmt (0..1).</summary>
|
||||
public float Closure => Current * (0.55f + 0.45f * SlatFactor);
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsMoving) return;
|
||||
Current = Mathf.MoveTowards(Current, target, speed * Time.deltaTime);
|
||||
Apply();
|
||||
}
|
||||
|
||||
public void Apply()
|
||||
{
|
||||
if (slats == null || slats.Length == 0) return;
|
||||
int n = slats.Length;
|
||||
float railY = Mathf.Lerp(stackBase, bottom, Current);
|
||||
float spacing = (top - bottom) / (n + 1);
|
||||
var rot = Quaternion.Euler(0f, 0f, maxSlatAngle * SlatFactor);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float y = Mathf.Max(top - (i + 1) * spacing, railY + (n - i) * stackGap);
|
||||
slats[i].localPosition = new Vector3(0f, y, 0f);
|
||||
slats[i].localRotation = rot;
|
||||
}
|
||||
bottomRail.localPosition = new Vector3(0f, railY, 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Tür (öffnet nach außen, Fluchtrichtung). Per Klick oder HUD bedienbar.</summary>
|
||||
public class DoorActuator : MonoBehaviour
|
||||
{
|
||||
public bool open;
|
||||
public Transform pivot;
|
||||
public float maxAngle = 100f, speed = 0.7f;
|
||||
|
||||
float v;
|
||||
|
||||
public float Openness => v * v * (3f - 2f * v);
|
||||
|
||||
public void Toggle() => open = !open;
|
||||
|
||||
void Update()
|
||||
{
|
||||
v = Mathf.MoveTowards(v, open ? 1f : 0f, speed * Time.deltaTime);
|
||||
pivot.localRotation = Quaternion.Euler(0f, -maxAngle * Openness, 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Heizkörper: glüht je nach Leistung warm auf, aufsteigende Wärme als Partikel.</summary>
|
||||
public class HeaterActuator : MonoBehaviour
|
||||
{
|
||||
[Range(0, 1)] public float target;
|
||||
[Tooltip("Thermische Trägheit")] public float speed = 0.08f;
|
||||
public Material finMaterial;
|
||||
public ParticleSystem heatFx;
|
||||
|
||||
public float Current { get; private set; }
|
||||
|
||||
static readonly Color Cold = new Color(0.93f, 0.93f, 0.92f);
|
||||
static readonly Color Warm = new Color(1f, 0.5f, 0.3f);
|
||||
|
||||
void Update()
|
||||
{
|
||||
Current = Mathf.MoveTowards(Current, target, speed * Time.deltaTime);
|
||||
float glow = Current * (0.85f + 0.15f * Mathf.Sin(Time.time * 2.2f));
|
||||
Mat.SetColor(finMaterial, Color.Lerp(Cold, Warm, Current * 0.55f));
|
||||
Mat.SetEmission(finMaterial, Warm * (glow * 0.45f));
|
||||
var em = heatFx.emission;
|
||||
em.rateOverTime = 14f * Current;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Deckenbeleuchtung: weiches Dimmen von Leuchtpanels und Lichtquellen.</summary>
|
||||
public class LightActuator : MonoBehaviour
|
||||
{
|
||||
[Range(0, 1)] public float target = 0.6f;
|
||||
public float speed = 1.2f;
|
||||
public float maxIntensity = 1f;
|
||||
public Material panelMaterial;
|
||||
public List<Light> lamps = new List<Light>();
|
||||
|
||||
public float Current { get; private set; }
|
||||
|
||||
static readonly Color Warm = new Color(1f, 0.97f, 0.9f);
|
||||
|
||||
void Update()
|
||||
{
|
||||
Current = Mathf.MoveTowards(Current, target, speed * Time.deltaTime);
|
||||
foreach (var l in lamps)
|
||||
{
|
||||
l.intensity = maxIntensity * Current;
|
||||
l.enabled = Current > 0.001f;
|
||||
}
|
||||
Mat.SetColor(panelMaterial, Color.Lerp(new Color(0.75f, 0.75f, 0.75f), Color.white, Current));
|
||||
Mat.SetEmission(panelMaterial, Warm * (Current * 1.6f));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Beamer + motorisierte Leinwand. Einschalten: Leinwand fährt herunter, dann blendet das Bild ein.
|
||||
/// Ausschalten: Bild aus, dann fährt die Leinwand wieder hoch.
|
||||
/// </summary>
|
||||
public class ProjectorActuator : MonoBehaviour
|
||||
{
|
||||
public bool beamerOn;
|
||||
public Transform fabric, bottomBar;
|
||||
public float top, maxDrop, minDrop = 0.04f;
|
||||
public float dropSpeed = 0.22f;
|
||||
public GameObject slide;
|
||||
public Material slideMaterial, lensMaterial;
|
||||
public Light beam;
|
||||
public TextMesh[] texts;
|
||||
public TextMesh body;
|
||||
public Func<string> contentProvider;
|
||||
|
||||
float drop, projection, nextText;
|
||||
Color[] baseColors;
|
||||
|
||||
public float Drop => drop;
|
||||
|
||||
void Start()
|
||||
{
|
||||
baseColors = new Color[texts.Length];
|
||||
for (int i = 0; i < texts.Length; i++) baseColors[i] = texts[i].color;
|
||||
Apply();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
float dt = Time.deltaTime;
|
||||
bool showImage = beamerOn && drop >= 1f;
|
||||
projection = Mathf.MoveTowards(projection, showImage ? 1f : 0f, 1.5f * dt);
|
||||
if (beamerOn || projection <= 0f)
|
||||
drop = Mathf.MoveTowards(drop, beamerOn ? 1f : 0f, dropSpeed * dt);
|
||||
|
||||
if (projection > 0f && Time.unscaledTime >= nextText && contentProvider != null)
|
||||
{
|
||||
body.text = contentProvider();
|
||||
nextText = Time.unscaledTime + 0.5f;
|
||||
}
|
||||
Apply();
|
||||
}
|
||||
|
||||
void Apply()
|
||||
{
|
||||
float e = drop * drop * (3f - 2f * drop);
|
||||
float len = Mathf.Lerp(minDrop, maxDrop, e);
|
||||
var p = fabric.localPosition;
|
||||
fabric.localPosition = new Vector3(p.x, top - len / 2f, p.z);
|
||||
var s = fabric.localScale;
|
||||
fabric.localScale = new Vector3(s.x, len, s.z);
|
||||
var b = bottomBar.localPosition;
|
||||
bottomBar.localPosition = new Vector3(b.x, top - len, b.z);
|
||||
|
||||
slide.SetActive(projection > 0.001f);
|
||||
Mat.SetEmission(slideMaterial, Color.white * (0.85f * projection));
|
||||
Mat.SetEmission(lensMaterial, new Color(0.7f, 0.85f, 1f) * (beamerOn ? 2f : 0f));
|
||||
beam.intensity = 1.2f * projection;
|
||||
if (baseColors != null)
|
||||
for (int i = 0; i < texts.Length; i++)
|
||||
{
|
||||
var c = baseColors[i];
|
||||
texts[i].color = new Color(c.r, c.g, c.b, c.a * projection);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Lüftungsgerät: Rotor läuft hoch/aus, Luftstrom als Partikel, Status-LED.</summary>
|
||||
public class VentilationActuator : MonoBehaviour
|
||||
{
|
||||
[Range(0, 1)] public float target;
|
||||
public float speed = 0.4f;
|
||||
public float maxRpmDegrees = 900f;
|
||||
public Transform rotor;
|
||||
public ParticleSystem air;
|
||||
public Material led;
|
||||
|
||||
public float Current { get; private set; }
|
||||
|
||||
static readonly Color LedOn = new Color(0.16f, 0.85f, 0.85f);
|
||||
|
||||
void Update()
|
||||
{
|
||||
Current = Mathf.MoveTowards(Current, target, speed * Time.deltaTime);
|
||||
rotor.Rotate(0f, Current * maxRpmDegrees * Time.deltaTime, 0f, Space.Self);
|
||||
var em = air.emission;
|
||||
em.rateOverTime = 70f * Current;
|
||||
var main = air.main;
|
||||
main.startSpeed = 0.4f + 1.0f * Current;
|
||||
Mat.SetEmission(led, Current > 0.02f ? LedOn * 2f : Color.black);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
public enum WindowState { Closed, Tilted, Open }
|
||||
|
||||
public static class WindowStateExt
|
||||
{
|
||||
public static string Label(this WindowState s)
|
||||
=> s == WindowState.Open ? "offen" : s == WindowState.Tilted ? "gekippt" : "geschlossen";
|
||||
|
||||
/// <summary>Kennung im Arduino-Protokoll.</summary>
|
||||
public static string Code(this WindowState s)
|
||||
=> s == WindowState.Open ? "open" : s == WindowState.Tilted ? "tilted" : "closed";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dreh-Kipp-Fenster. Ablauf wie in echt: erst Griff drehen, dann Flügel bewegen.
|
||||
/// Beim Wechsel zwischen Kipp- und Drehstellung wird der Flügel zuerst geschlossen.
|
||||
/// </summary>
|
||||
public class WindowActuator : MonoBehaviour
|
||||
{
|
||||
public WindowState target = WindowState.Closed;
|
||||
public Transform hinge, tilt, handle;
|
||||
public float maxSwing = 80f, maxTilt = 12f;
|
||||
[Tooltip("Normierte Geschwindigkeit pro Sekunde")] public float swingSpeed = 0.3f, tiltSpeed = 0.6f;
|
||||
public float handleSpeed = 300f;
|
||||
|
||||
float swing, tiltV, handleAngle;
|
||||
|
||||
public bool IsMoving { get; private set; }
|
||||
|
||||
/// <summary>0 = dicht, 1 = vollständig geöffnet (gekippt ≈ 0,3).</summary>
|
||||
public float Airflow => Mathf.Max(Ease(swing), 0.3f * Ease(tiltV));
|
||||
|
||||
public WindowState Current
|
||||
{
|
||||
get
|
||||
{
|
||||
if (swing > 0.98f) return WindowState.Open;
|
||||
if (tiltV > 0.98f) return WindowState.Tilted;
|
||||
return WindowState.Closed;
|
||||
}
|
||||
}
|
||||
|
||||
static float Ease(float x) => x * x * (3f - 2f * x);
|
||||
|
||||
static float HandleFor(WindowState s) => s == WindowState.Open ? 90f : s == WindowState.Tilted ? 180f : 0f;
|
||||
|
||||
void Update()
|
||||
{
|
||||
float dt = Time.deltaTime;
|
||||
float tiltGoal = target == WindowState.Tilted ? 1f : 0f;
|
||||
float swingGoal = target == WindowState.Open ? 1f : 0f;
|
||||
float before = swing + tiltV + handleAngle;
|
||||
|
||||
if (swing <= 0f && tiltV <= 0f)
|
||||
{
|
||||
// Flügel liegt im Rahmen: erst Griff in Zielstellung, dann bewegen
|
||||
float h = HandleFor(target);
|
||||
handleAngle = Mathf.MoveTowards(handleAngle, h, handleSpeed * dt);
|
||||
if (Mathf.Approximately(handleAngle, h))
|
||||
{
|
||||
tiltV = Mathf.MoveTowards(tiltV, tiltGoal, tiltSpeed * dt);
|
||||
swing = Mathf.MoveTowards(swing, swingGoal, swingSpeed * dt);
|
||||
}
|
||||
}
|
||||
else if (tiltV > 0f && tiltGoal == 0f) tiltV = Mathf.MoveTowards(tiltV, 0f, tiltSpeed * dt);
|
||||
else if (swing > 0f && swingGoal == 0f) swing = Mathf.MoveTowards(swing, 0f, swingSpeed * dt);
|
||||
else
|
||||
{
|
||||
tiltV = Mathf.MoveTowards(tiltV, tiltGoal, tiltSpeed * dt);
|
||||
swing = Mathf.MoveTowards(swing, swingGoal, swingSpeed * dt);
|
||||
}
|
||||
|
||||
IsMoving = !Mathf.Approximately(before, swing + tiltV + handleAngle);
|
||||
|
||||
hinge.localRotation = Quaternion.Euler(0f, maxSwing * Ease(swing), 0f);
|
||||
tilt.localRotation = Quaternion.Euler(0f, 0f, -maxTilt * Ease(tiltV));
|
||||
handle.localRotation = Quaternion.Euler(handleAngle, 0f, 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,278 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
[Serializable]
|
||||
public class UserWish
|
||||
{
|
||||
public string name;
|
||||
public float temperature;
|
||||
public bool windowOpen;
|
||||
|
||||
public UserWish(string name, float temperature, bool windowOpen)
|
||||
{
|
||||
this.name = name;
|
||||
this.temperature = temperature;
|
||||
this.windowOpen = windowOpen;
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class ClimateThresholds
|
||||
{
|
||||
[Tooltip("ppm")] public float co2Limit = 1000f;
|
||||
[Tooltip("°C")] public float tempLow = 20f, tempHigh = 25f;
|
||||
[Tooltip("dB(A) – extremer Außenlärm")] public float noiseLimit = 70f;
|
||||
[Tooltip("m/s – starker Wind")] public float windLimit = 10f;
|
||||
[Tooltip("W/m² – Sonneneinstrahlung zu hoch")] public float sunLimit = 500f;
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>Ergebnis eines Prüfzyklus inkl. durchlaufenem Pfad im Aktivitätsdiagramm.</summary>
|
||||
public class Decision
|
||||
{
|
||||
public WindowState window = WindowState.Closed;
|
||||
public float blinds, heating, ventilation, lights;
|
||||
public string time;
|
||||
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.
|
||||
/// </summary>
|
||||
public class ClimateController : MonoBehaviour
|
||||
{
|
||||
public bool autoMode = true;
|
||||
[Tooltip("Prüfintervall in simulierten Minuten")] public float checkIntervalMinutes = 10f;
|
||||
[Tooltip("Bei neu überschrittenem Grenzwert sofort reagieren statt auf den nächsten Zyklus zu warten")]
|
||||
public bool reactImmediately = true;
|
||||
public ClimateThresholds limits = new ClimateThresholds();
|
||||
public List<UserWish> wishes = new List<UserWish>
|
||||
{
|
||||
new UserWish("Du", 22f, false),
|
||||
new UserWish("Teilnehmer 1", 21f, false),
|
||||
new UserWish("Teilnehmer 2", 22.5f, false),
|
||||
new UserWish("Teilnehmer 3", 21.5f, true),
|
||||
new UserWish("Teilnehmer 4", 23f, false),
|
||||
};
|
||||
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
|
||||
public Decision Last { get; private set; }
|
||||
public event Action<Decision> Decided;
|
||||
|
||||
double nextCheckAt = double.NegativeInfinity;
|
||||
bool wasCritical, wasRunning = true;
|
||||
|
||||
public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes));
|
||||
|
||||
public float AverageWish
|
||||
{
|
||||
get
|
||||
{
|
||||
if (wishes.Count == 0) return 22f;
|
||||
float s = 0f;
|
||||
foreach (var w in wishes) s += w.temperature;
|
||||
return s / wishes.Count;
|
||||
}
|
||||
}
|
||||
|
||||
public int WindowVotes => wishes.FindAll(w => w.windowOpen).Count;
|
||||
public bool WindowWanted => wishes.Count > 0 && WindowVotes * 2 > wishes.Count;
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (env == null || devices == null) return;
|
||||
|
||||
if (!env.lectureRunning)
|
||||
{
|
||||
if (wasRunning) EnterIdle();
|
||||
wasRunning = false;
|
||||
return;
|
||||
}
|
||||
if (!wasRunning) nextCheckAt = double.NegativeInfinity; // Vorlesung beginnt -> sofort prüfen
|
||||
wasRunning = true;
|
||||
|
||||
bool critical = env.co2 > limits.co2Limit || env.indoorTemp > limits.tempHigh || env.indoorTemp < limits.tempLow;
|
||||
if (env.simMinutes >= nextCheckAt || (reactImmediately && critical && !wasCritical))
|
||||
RunCycle();
|
||||
wasCritical = critical;
|
||||
}
|
||||
|
||||
/// <summary>Einen kompletten Prüfzyklus ausführen (auch per HUD "Jetzt prüfen").</summary>
|
||||
public void RunCycle()
|
||||
{
|
||||
var d = Evaluate();
|
||||
if (autoMode)
|
||||
{
|
||||
Apply(d);
|
||||
d.path.Add("Unity-Simulation: virtuelle Aktoren angesteuert");
|
||||
}
|
||||
else d.path.Add("Manueller Modus: Empfehlung wird nicht automatisch angewendet");
|
||||
d.path.Add($"Erneut prüfen in {checkIntervalMinutes:0} min");
|
||||
Last = d;
|
||||
nextCheckAt = env.simMinutes + checkIntervalMinutes;
|
||||
Decided?.Invoke(d);
|
||||
}
|
||||
|
||||
public Decision Evaluate()
|
||||
{
|
||||
var L = limits;
|
||||
var d = new Decision { time = env.ClockText };
|
||||
var p = d.path;
|
||||
float t = env.indoorTemp, co2 = env.co2;
|
||||
float avgWish = AverageWish;
|
||||
bool wantWindow = WindowWanted;
|
||||
|
||||
p.Add($"Sensordaten: {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx");
|
||||
p.Add($"Nutzerwünsche: Ø {avgWish:0.0} °C, Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})");
|
||||
|
||||
// --- CO2 / Temperatur
|
||||
bool ventilationNeeded = false, heat = false;
|
||||
if (co2 > L.co2Limit)
|
||||
{
|
||||
p.Add($"CO2-Grenzwert überschritten ({co2:0} > {L.co2Limit:0} ppm) → Lüftung erforderlich");
|
||||
ventilationNeeded = true;
|
||||
}
|
||||
else if (t < L.tempLow)
|
||||
{
|
||||
p.Add($"CO2 ok, T_innen < {L.tempLow:0} °C → heizen");
|
||||
heat = true;
|
||||
}
|
||||
else if (t > L.tempHigh)
|
||||
{
|
||||
p.Add($"CO2 ok, T_innen > {L.tempHigh:0} °C → Lüftung erforderlich");
|
||||
ventilationNeeded = true;
|
||||
}
|
||||
else p.Add($"CO2 ok, {L.tempLow:0} °C ≤ T_innen ≤ {L.tempHigh:0} °C → Komfortbereich");
|
||||
|
||||
// --- Lüftung / Fenstersollzustand
|
||||
float ventLevel = co2 > L.co2Limit ? Mathf.Clamp01(0.4f + (co2 - L.co2Limit) / 800f) : 0.6f;
|
||||
if (ventilationNeeded)
|
||||
{
|
||||
bool aqBad = env.outdoorAqi > L.outdoorAqiLimit;
|
||||
bool cold = env.outdoorTemp < L.outdoorColdLimit;
|
||||
if (aqBad || cold)
|
||||
{
|
||||
p.Add(aqBad
|
||||
? $"Außenluft schlecht (AQI {env.outdoorAqi:0} > {L.outdoorAqiLimit:0}) → Lüftungsanlage statt Fenster"
|
||||
: $"Außen zu kalt ({env.outdoorTemp:0.0} °C < {L.outdoorColdLimit:0} °C) → Lüftungsanlage statt Fenster");
|
||||
d.window = WindowState.Closed;
|
||||
d.ventilation = ventLevel;
|
||||
}
|
||||
else if (env.outdoorNoise > L.noiseLimit)
|
||||
{
|
||||
p.Add($"Extremer Außenlärm ({env.outdoorNoise:0} dB) → Fensteröffnung sperren");
|
||||
if (wantWindow)
|
||||
{
|
||||
p.Add("Fensteröffnung von Menschen gewünscht → Fenstersollzustand: offen");
|
||||
d.window = WindowState.Open;
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Add("Keine Fensteröffnung gewünscht → alternative Lüftung aktivieren, Fenster geschlossen");
|
||||
d.window = WindowState.Closed;
|
||||
d.ventilation = ventLevel;
|
||||
}
|
||||
}
|
||||
else if (env.windSpeed > L.windLimit)
|
||||
{
|
||||
p.Add($"Starker Wind ({env.windSpeed:0.0} m/s) → Fenstersollzustand: gekippt");
|
||||
d.window = WindowState.Tilted;
|
||||
d.ventilation = 0.4f;
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Add("Kein starker Wind → Fenstersollzustand: offen");
|
||||
d.window = WindowState.Open;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Add($"Temperaturwünsche durch Eingabe anpassen (Ziel {Mathf.Clamp(avgWish, 18f, 26f):0.0} °C)");
|
||||
if (wantWindow)
|
||||
{
|
||||
p.Add("Fensteröffnung gewünscht → Fenstersollzustand: offen");
|
||||
d.window = WindowState.Open;
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Add("Keine Fensteröffnung gewünscht → Fenstersollzustand: geschlossen");
|
||||
d.window = WindowState.Closed;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Heizung (Ziel = Ø Wunschtemperatur)
|
||||
float target = Mathf.Clamp(avgWish, 18f, 26f);
|
||||
bool needsHeat = heat || t < target - 0.3f;
|
||||
if (needsHeat && d.window == WindowState.Open)
|
||||
p.Add("Fenster offen → Heizung aus (Energie sparen)");
|
||||
else if (needsHeat)
|
||||
{
|
||||
d.heating = Mathf.Clamp((target - t) / 2.5f, 0.25f, 1f);
|
||||
p.Add($"Heizen auf {target:0.0} °C → Heizung {d.heating * 100:0} %");
|
||||
}
|
||||
|
||||
// --- Soll/Ist-Abgleich Fenster
|
||||
var current = devices.WindowCurrent;
|
||||
p.Add(current == d.window
|
||||
? $"Aktueller Fensterzustand = Sollzustand ({d.window.Label()}) → beibehalten"
|
||||
: $"Fensterzustand {current.Label()} ≠ Soll {d.window.Label()} → anpassen");
|
||||
|
||||
// --- Sonne / Jalousie
|
||||
if (env.solar > L.sunLimit)
|
||||
{
|
||||
d.blinds = 1f;
|
||||
p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Jalousie nach unten");
|
||||
}
|
||||
else if (devices.BeamerOn)
|
||||
{
|
||||
d.blinds = 1f;
|
||||
p.Add("Beamer aktiv → Jalousie nach unten (blendfrei, Erweiterung)");
|
||||
}
|
||||
else
|
||||
{
|
||||
d.blinds = 0f;
|
||||
p.Add($"Sonneneinstrahlung ok ({env.solar:0} W/m²) → Jalousie nach oben");
|
||||
}
|
||||
|
||||
// --- Licht (Erweiterung: Tageslicht ergänzen)
|
||||
float daylight = env.DaylightLux(d.blinds);
|
||||
d.lights = Mathf.Clamp01((L.targetLux - daylight) / 520f);
|
||||
if (devices.BeamerOn) d.lights = Mathf.Min(d.lights, 0.3f);
|
||||
p.Add($"Tageslicht ≈ {daylight:0} lx → Licht {d.lights * 100:0} %{(devices.BeamerOn ? " (gedimmt für Beamer)" : "")}");
|
||||
return d;
|
||||
}
|
||||
|
||||
public void Apply(Decision d)
|
||||
{
|
||||
devices.SetWindows(d.window);
|
||||
devices.SetVentilation(d.ventilation);
|
||||
devices.SetHeating(d.heating);
|
||||
devices.SetBlinds(d.blinds);
|
||||
devices.SetLights(d.lights);
|
||||
d.applied = true;
|
||||
}
|
||||
|
||||
void EnterIdle()
|
||||
{
|
||||
var d = new Decision { time = env.ClockText };
|
||||
d.path.Add("Vorlesung läuft nicht → Simulation beendet, Raum im Energiesparmodus");
|
||||
if (autoMode)
|
||||
{
|
||||
Apply(d); // alles aus, Fenster zu, Jalousie oben
|
||||
d.path.Add("Fenster geschlossen, Heizung/Lüftung/Licht aus");
|
||||
}
|
||||
Last = d;
|
||||
Decided?.Invoke(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Erzeugt Materialien zur Laufzeit. Funktioniert mit der Built-in Render Pipeline und mit URP.
|
||||
/// </summary>
|
||||
public static class Mat
|
||||
{
|
||||
static Shader lit;
|
||||
static Material particle;
|
||||
static Texture2D softDot;
|
||||
|
||||
static Shader Lit
|
||||
{
|
||||
get
|
||||
{
|
||||
if (lit == null)
|
||||
{
|
||||
if (GraphicsSettings.currentRenderPipeline != null)
|
||||
lit = Shader.Find("Universal Render Pipeline/Lit");
|
||||
if (lit == null) lit = Shader.Find("Standard");
|
||||
}
|
||||
return lit;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material Solid(Color c, float smoothness = 0.25f, float metallic = 0f)
|
||||
{
|
||||
var m = new Material(Lit);
|
||||
SetColor(m, c);
|
||||
if (m.HasProperty("_Smoothness")) m.SetFloat("_Smoothness", smoothness);
|
||||
if (m.HasProperty("_Glossiness")) m.SetFloat("_Glossiness", smoothness);
|
||||
if (m.HasProperty("_Metallic")) m.SetFloat("_Metallic", metallic);
|
||||
return m;
|
||||
}
|
||||
|
||||
/// <summary>Material mit aktivierter Emission (wird von Aktoren zur Laufzeit animiert).</summary>
|
||||
public static Material Emissive(Color c, Color emission)
|
||||
{
|
||||
var m = Solid(c, 0.4f);
|
||||
m.EnableKeyword("_EMISSION");
|
||||
m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
|
||||
SetEmission(m, emission);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static Material Transparent(Color c, float smoothness = 0.92f)
|
||||
{
|
||||
var m = Solid(c, smoothness);
|
||||
m.SetOverrideTag("RenderType", "Transparent");
|
||||
if (m.HasProperty("_Surface")) // URP Lit
|
||||
{
|
||||
m.SetFloat("_Surface", 1f);
|
||||
m.SetFloat("_Blend", 0f);
|
||||
m.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha);
|
||||
m.SetFloat("_DstBlend", (float)BlendMode.OneMinusSrcAlpha);
|
||||
m.SetFloat("_ZWrite", 0f);
|
||||
m.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
}
|
||||
else // Standard Shader, Modus "Transparent"
|
||||
{
|
||||
m.SetFloat("_Mode", 3f);
|
||||
m.SetFloat("_SrcBlend", (float)BlendMode.One);
|
||||
m.SetFloat("_DstBlend", (float)BlendMode.OneMinusSrcAlpha);
|
||||
m.SetFloat("_ZWrite", 0f);
|
||||
m.DisableKeyword("_ALPHATEST_ON");
|
||||
m.DisableKeyword("_ALPHABLEND_ON");
|
||||
m.EnableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
}
|
||||
m.renderQueue = (int)RenderQueue.Transparent;
|
||||
return m;
|
||||
}
|
||||
|
||||
/// <summary>Weiches Partikel-Material (Luftstrom, Wärme). "Sprites/Default" existiert in jeder Pipeline.</summary>
|
||||
public static Material Particle
|
||||
{
|
||||
get
|
||||
{
|
||||
if (particle == null)
|
||||
{
|
||||
particle = new Material(Shader.Find("Sprites/Default")) { mainTexture = SoftDot };
|
||||
particle.renderQueue = (int)RenderQueue.Transparent;
|
||||
}
|
||||
return particle;
|
||||
}
|
||||
}
|
||||
|
||||
static Texture2D SoftDot
|
||||
{
|
||||
get
|
||||
{
|
||||
if (softDot != null) return softDot;
|
||||
const int n = 32;
|
||||
softDot = new Texture2D(n, n, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp };
|
||||
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 - d);
|
||||
px[y * n + x] = new Color(1f, 1f, 1f, a * a);
|
||||
}
|
||||
softDot.SetPixels(px);
|
||||
softDot.Apply();
|
||||
return softDot;
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetColor(Material m, Color c)
|
||||
{
|
||||
if (m.HasProperty("_BaseColor")) m.SetColor("_BaseColor", c);
|
||||
if (m.HasProperty("_Color")) m.SetColor("_Color", c);
|
||||
}
|
||||
|
||||
public static void SetEmission(Material m, Color e)
|
||||
{
|
||||
if (m.HasProperty("_EmissionColor")) m.SetColor("_EmissionColor", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>Kleine Helfer zum Erzeugen von Geometrie aus Unity-Primitiven.</summary>
|
||||
public static class Prim
|
||||
{
|
||||
public static Transform Pivot(string name, Transform parent, Vector3 localPos)
|
||||
{
|
||||
var t = new GameObject(name).transform;
|
||||
t.SetParent(parent, false);
|
||||
t.localPosition = localPos;
|
||||
return t;
|
||||
}
|
||||
|
||||
public static GameObject Box(string name, Transform parent, Vector3 pos, Vector3 size, Material m, bool keepCollider = false)
|
||||
=> Make(PrimitiveType.Cube, name, parent, pos, size, m, keepCollider);
|
||||
|
||||
/// <summary>Zylinder entlang der lokalen Y-Achse.</summary>
|
||||
public static GameObject Cylinder(string name, Transform parent, Vector3 pos, float diameter, float height, Material m)
|
||||
=> Make(PrimitiveType.Cylinder, name, parent, pos, new Vector3(diameter, height * 0.5f, diameter), m, false);
|
||||
|
||||
public static GameObject Sphere(string name, Transform parent, Vector3 pos, float diameter, Material m)
|
||||
=> Make(PrimitiveType.Sphere, name, parent, pos, Vector3.one * diameter, m, false);
|
||||
|
||||
static GameObject Make(PrimitiveType type, string name, Transform parent, Vector3 pos, Vector3 scale, Material m, bool keepCollider)
|
||||
{
|
||||
var go = GameObject.CreatePrimitive(type);
|
||||
go.name = name;
|
||||
go.transform.SetParent(parent, false);
|
||||
go.transform.localPosition = pos;
|
||||
go.transform.localScale = scale;
|
||||
go.GetComponent<Renderer>().sharedMaterial = m;
|
||||
if (!keepCollider) Object.Destroy(go.GetComponent<Collider>());
|
||||
return go;
|
||||
}
|
||||
|
||||
public static void NoShadows(GameObject go)
|
||||
{
|
||||
var r = go.GetComponent<Renderer>();
|
||||
r.shadowCastingMode = ShadowCastingMode.Off;
|
||||
r.receiveShadows = false;
|
||||
}
|
||||
|
||||
public static Font BuiltinFont()
|
||||
{
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
return Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
|
||||
#else
|
||||
return Resources.GetBuiltinResource<Font>("Arial.ttf");
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>3D-Text (liest sich von hinten im Raum Richtung Leinwand, also Blick entlang +Z).</summary>
|
||||
public static TextMesh Text(string name, Transform parent, Vector3 pos, string text, float charSize, Color c, Font font, FontStyle style = FontStyle.Normal)
|
||||
{
|
||||
var go = new GameObject(name);
|
||||
go.transform.SetParent(parent, false);
|
||||
go.transform.localPosition = pos;
|
||||
var tm = go.AddComponent<TextMesh>();
|
||||
tm.font = font;
|
||||
tm.text = text;
|
||||
tm.fontSize = 64;
|
||||
tm.fontStyle = style;
|
||||
tm.characterSize = charSize;
|
||||
tm.color = c;
|
||||
tm.anchor = TextAnchor.UpperLeft;
|
||||
tm.alignment = TextAlignment.Left;
|
||||
tm.lineSpacing = 1.15f;
|
||||
var mr = go.GetComponent<MeshRenderer>();
|
||||
if (mr == null) mr = go.AddComponent<MeshRenderer>();
|
||||
mr.sharedMaterial = font.material;
|
||||
return tm;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Partikeleffekte (Luftstrom der Lüftung, aufsteigende Wärme).</summary>
|
||||
public static class Fx
|
||||
{
|
||||
public static ParticleSystem Make(string name, Transform parent, Vector3 pos, Quaternion rot, Color color,
|
||||
float size, float lifetime, float speed, ParticleSystemShapeType shape, Vector3 shapeScale,
|
||||
float angle = 25f, float radius = 0.25f)
|
||||
{
|
||||
var go = new GameObject(name);
|
||||
go.transform.SetParent(parent, false);
|
||||
go.transform.localPosition = pos;
|
||||
go.transform.localRotation = rot;
|
||||
|
||||
var ps = go.AddComponent<ParticleSystem>();
|
||||
ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
||||
|
||||
var main = ps.main;
|
||||
main.loop = true;
|
||||
main.playOnAwake = true;
|
||||
main.startLifetime = lifetime;
|
||||
main.startSpeed = speed;
|
||||
main.startSize = new ParticleSystem.MinMaxCurve(size * 0.7f, size * 1.3f);
|
||||
main.startColor = color;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.maxParticles = 300;
|
||||
|
||||
var emission = ps.emission;
|
||||
emission.rateOverTime = 0f;
|
||||
|
||||
var sh = ps.shape;
|
||||
sh.enabled = true;
|
||||
sh.shapeType = shape;
|
||||
sh.scale = shapeScale;
|
||||
sh.angle = angle;
|
||||
sh.radius = radius;
|
||||
|
||||
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.25f), new GradientAlphaKey(0f, 1f) });
|
||||
var col = ps.colorOverLifetime;
|
||||
col.enabled = true;
|
||||
col.color = new ParticleSystem.MinMaxGradient(g);
|
||||
|
||||
var sol = ps.sizeOverLifetime;
|
||||
sol.enabled = true;
|
||||
sol.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.Linear(0f, 0.6f, 1f, 1.6f));
|
||||
|
||||
var r = go.GetComponent<ParticleSystemRenderer>();
|
||||
r.sharedMaterial = Mat.Particle;
|
||||
r.renderMode = ParticleSystemRenderMode.Billboard;
|
||||
r.shadowCastingMode = ShadowCastingMode.Off;
|
||||
r.receiveShadows = false;
|
||||
|
||||
ps.Play();
|
||||
return ps;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,286 @@
|
|||
// Serielle Schnittstelle gibt es nur mit "Api Compatibility Level = .NET Framework" (Player Settings).
|
||||
#if (NET_4_6 || NET_UNITY_4_8) && !UNITY_WEBGL && !UNITY_ANDROID && !UNITY_IOS
|
||||
#define SMARTROOM_SERIAL
|
||||
#endif
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using UnityEngine;
|
||||
#if SMARTROOM_SERIAL
|
||||
using System.IO.Ports;
|
||||
#endif
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Ein JSON-Datenpaket vom Arduino, z. B. {"t":30.2,"co2":1250,"lux":320}.
|
||||
/// Alle Felder sind optional – nicht gesendete Felder bleiben NaN und werden ignoriert.
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class SensorPacket
|
||||
{
|
||||
public float t = float.NaN; // Temperatur innen °C
|
||||
public float co2 = float.NaN; // CO2 innen ppm
|
||||
public float lux = float.NaN; // Helligkeit innen lx
|
||||
public float noise = float.NaN; // Lärm innen dB
|
||||
public float tout = float.NaN; // Temperatur außen °C
|
||||
public float aq = float.NaN; // Luftqualität außen (AQI)
|
||||
public float nout = float.NaN; // Lärm außen dB
|
||||
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 enum LinkMode { Simulation, Serial, Udp }
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public class ArduinoBridge : MonoBehaviour
|
||||
{
|
||||
public LinkMode mode = LinkMode.Simulation;
|
||||
[Tooltip("macOS: /dev/cu.usbmodem… · Windows: COM3")]
|
||||
public string serialPort = "/dev/cu.usbmodem101";
|
||||
public int baudRate = 115200;
|
||||
public int udpListenPort = 5005;
|
||||
[Tooltip("Port, an den Steuerbefehle an den Absender zurückgeschickt werden")]
|
||||
public int udpReplyPort = 5006;
|
||||
public bool sendCommands = true;
|
||||
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
|
||||
public string Status { get; private set; } = "Simulation aktiv";
|
||||
public bool Connected { get; private set; }
|
||||
public string LastLine { get; private set; } = "";
|
||||
public string LastSent { get; private set; } = "";
|
||||
public float LastPacketTime { get; private set; } = -1f;
|
||||
public int PacketCount { get; private set; }
|
||||
|
||||
public static bool SerialSupported
|
||||
{
|
||||
get
|
||||
{
|
||||
#if SMARTROOM_SERIAL
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
readonly ConcurrentQueue<string> inbox = new ConcurrentQueue<string>();
|
||||
readonly object remoteLock = new object();
|
||||
Thread worker;
|
||||
volatile bool running;
|
||||
UdpClient udp;
|
||||
IPEndPoint remote;
|
||||
float nextSend;
|
||||
#if SMARTROOM_SERIAL
|
||||
SerialPort port;
|
||||
#endif
|
||||
|
||||
public static string[] ListSerialPorts()
|
||||
{
|
||||
#if SMARTROOM_SERIAL
|
||||
try { return SerialPort.GetPortNames(); } catch { return new string[0]; }
|
||||
#else
|
||||
return new string[0];
|
||||
#endif
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (mode != LinkMode.Simulation) Connect();
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
Disconnect();
|
||||
try
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case LinkMode.Serial: OpenSerial(); break;
|
||||
case LinkMode.Udp: OpenUdp(); break;
|
||||
default: Status = "Simulation aktiv"; break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Disconnect();
|
||||
Status = "Fehler: " + ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
void OpenSerial()
|
||||
{
|
||||
#if SMARTROOM_SERIAL
|
||||
port = new SerialPort(serialPort, baudRate) { ReadTimeout = 500, NewLine = "\n", DtrEnable = true };
|
||||
port.Open();
|
||||
StartWorker(SerialLoop);
|
||||
Status = "Verbunden mit " + serialPort;
|
||||
#else
|
||||
Status = "Seriell nicht verfügbar: Player Settings → Api Compatibility Level → .NET Framework (oder UDP nutzen)";
|
||||
#endif
|
||||
}
|
||||
|
||||
void OpenUdp()
|
||||
{
|
||||
udp = new UdpClient(udpListenPort);
|
||||
StartWorker(UdpLoop);
|
||||
Status = $"Lausche auf UDP-Port {udpListenPort}";
|
||||
}
|
||||
|
||||
void StartWorker(ThreadStart loop)
|
||||
{
|
||||
running = true;
|
||||
Connected = true;
|
||||
worker = new Thread(loop) { IsBackground = true, Name = "ArduinoBridge" };
|
||||
worker.Start();
|
||||
}
|
||||
|
||||
public void Disconnect()
|
||||
{
|
||||
bool was = Connected;
|
||||
running = false;
|
||||
Connected = false;
|
||||
#if SMARTROOM_SERIAL
|
||||
try { if (port != null && port.IsOpen) port.Close(); } catch { }
|
||||
port = null;
|
||||
#endif
|
||||
try { udp?.Close(); } catch { }
|
||||
udp = null;
|
||||
if (worker != null && worker.IsAlive) worker.Join(800);
|
||||
worker = null;
|
||||
lock (remoteLock) remote = null;
|
||||
if (was) Status = "Getrennt";
|
||||
if (mode == LinkMode.Simulation) Status = "Simulation aktiv";
|
||||
}
|
||||
|
||||
#if SMARTROOM_SERIAL
|
||||
void SerialLoop()
|
||||
{
|
||||
while (running)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = port.ReadLine();
|
||||
if (!string.IsNullOrWhiteSpace(line)) inbox.Enqueue(line.Trim());
|
||||
}
|
||||
catch (TimeoutException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (running) inbox.Enqueue("!ERR " + ex.Message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void UdpLoop()
|
||||
{
|
||||
var any = new IPEndPoint(IPAddress.Any, 0);
|
||||
while (running)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] data = udp.Receive(ref any);
|
||||
lock (remoteLock) remote = new IPEndPoint(any.Address, udpReplyPort);
|
||||
foreach (var line in Encoding.UTF8.GetString(data).Split('\n'))
|
||||
if (!string.IsNullOrWhiteSpace(line)) inbox.Enqueue(line.Trim());
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
if (!running) break;
|
||||
inbox.Enqueue("!ERR " + ex.Message);
|
||||
}
|
||||
catch (ObjectDisposedException) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
while (inbox.TryDequeue(out var line))
|
||||
{
|
||||
if (line.StartsWith("!ERR"))
|
||||
{
|
||||
Status = "Verbindungsfehler: " + line.Substring(4).Trim();
|
||||
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;
|
||||
PacketCount++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status = "Ungültiges JSON: " + ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
// Steuerbefehle senden, sobald sie sich ändern (spätestens alle 10 s als Heartbeat)
|
||||
if (Connected && sendCommands && devices != null)
|
||||
{
|
||||
string cmd = BuildCommand();
|
||||
if (cmd != LastSent || Time.unscaledTime >= nextSend)
|
||||
{
|
||||
Send(cmd);
|
||||
nextSend = Time.unscaledTime + 10f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string BuildCommand()
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("{\"window\":\"").Append(devices.WindowTarget.Code()).Append('"');
|
||||
sb.Append(",\"blind\":").Append(devices.BlindTarget.ToString("0.00", ci));
|
||||
sb.Append(",\"heat\":").Append(devices.HeatingTarget.ToString("0.00", ci));
|
||||
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);
|
||||
sb.Append('}');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
void Send(string json)
|
||||
{
|
||||
LastSent = json;
|
||||
try
|
||||
{
|
||||
#if SMARTROOM_SERIAL
|
||||
if (mode == LinkMode.Serial && port != null && port.IsOpen) port.WriteLine(json);
|
||||
#endif
|
||||
if (mode == LinkMode.Udp && udp != null)
|
||||
{
|
||||
IPEndPoint target;
|
||||
lock (remoteLock) target = remote;
|
||||
if (target != null)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(json + "\n");
|
||||
udp.Send(bytes, bytes.Length, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status = "Senden fehlgeschlagen: " + ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
void OnDisable() => Disconnect();
|
||||
void OnApplicationQuit() => Disconnect();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Externe Daten laut Architekturdiagramm: Wetterdaten (Außentemperatur, Wind, Sonne) und Luftqualität
|
||||
/// von Open-Meteo (kostenlos, kein API-Key). Standardmäßig aus – im HUD unter "Verbindung" einschalten.
|
||||
/// </summary>
|
||||
public class WeatherService : MonoBehaviour
|
||||
{
|
||||
public bool useLiveWeather;
|
||||
public float latitude = 52.52f; // Berlin – an Hochschulstandort anpassen
|
||||
public float longitude = 13.405f;
|
||||
[Tooltip("Aktualisierung in Echtzeit-Minuten")] public float refreshMinutes = 10f;
|
||||
|
||||
public RoomEnvironment env;
|
||||
public string Status { get; private set; } = "aus";
|
||||
|
||||
Coroutine loop;
|
||||
|
||||
[Serializable] class WeatherCurrent { public float temperature_2m; public float wind_speed_10m; public float shortwave_radiation; }
|
||||
[Serializable] class WeatherResponse { public WeatherCurrent current; }
|
||||
[Serializable] class AirCurrent { public float european_aqi; }
|
||||
[Serializable] class AirResponse { public AirCurrent current; }
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (useLiveWeather) SetLive(true);
|
||||
}
|
||||
|
||||
public void SetLive(bool on)
|
||||
{
|
||||
useLiveWeather = on;
|
||||
if (on && loop == null) loop = StartCoroutine(Loop());
|
||||
if (!on && loop != null)
|
||||
{
|
||||
StopCoroutine(loop);
|
||||
loop = null;
|
||||
Status = "aus";
|
||||
}
|
||||
}
|
||||
|
||||
public void RefreshNow()
|
||||
{
|
||||
if (useLiveWeather) StartCoroutine(Fetch());
|
||||
}
|
||||
|
||||
IEnumerator Loop()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
yield return Fetch();
|
||||
yield return new WaitForSecondsRealtime(refreshMinutes * 60f);
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator Fetch()
|
||||
{
|
||||
Status = "lädt …";
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
string lat = latitude.ToString(ci), lon = longitude.ToString(ci);
|
||||
|
||||
string url = $"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}" +
|
||||
"¤t=temperature_2m,wind_speed_10m,shortwave_radiation&wind_speed_unit=ms";
|
||||
using (var req = UnityWebRequest.Get(url))
|
||||
{
|
||||
yield return req.SendWebRequest();
|
||||
if (req.result != UnityWebRequest.Result.Success)
|
||||
{
|
||||
Status = "Fehler: " + req.error;
|
||||
yield break;
|
||||
}
|
||||
var r = JsonUtility.FromJson<WeatherResponse>(req.downloadHandler.text);
|
||||
if (r != null && r.current != null)
|
||||
{
|
||||
env.outdoorTemp = r.current.temperature_2m;
|
||||
env.windSpeed = r.current.wind_speed_10m;
|
||||
env.solar = r.current.shortwave_radiation;
|
||||
}
|
||||
}
|
||||
|
||||
string aqUrl = $"https://air-quality-api.open-meteo.com/v1/air-quality?latitude={lat}&longitude={lon}¤t=european_aqi";
|
||||
using (var req = UnityWebRequest.Get(aqUrl))
|
||||
{
|
||||
yield return req.SendWebRequest();
|
||||
if (req.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
var r = JsonUtility.FromJson<AirResponse>(req.downloadHandler.text);
|
||||
if (r != null && r.current != null) env.outdoorAqi = r.current.european_aqi;
|
||||
}
|
||||
}
|
||||
Status = $"Open-Meteo · {DateTime.Now:HH:mm}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,392 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Baut den Vorlesungsraum komplett prozedural auf (keine externen Assets nötig).
|
||||
/// Koordinaten: x = links(-)/rechts(+), z = hinten(-)/vorne(+, Leinwand), y = oben.
|
||||
/// Links: Fensterfront mit Außenjalousien und Heizkörpern. Vorne: Leinwand mittig, Tür links davon.
|
||||
/// Rechts: geschlossene Wand.
|
||||
/// </summary>
|
||||
public static class RoomBuilder
|
||||
{
|
||||
public const float W = 12f, D = 14f, H = 3.6f, T = 0.25f;
|
||||
public const float SillY = 0.9f, WinTopY = 2.8f, WinWidth = 2.2f;
|
||||
public const float DoorX0 = -4.8f, DoorX1 = -3.6f, DoorH = 2.25f;
|
||||
public const float ScreenW = 4.6f, ScreenTop = 3.22f, ScreenDrop = 2.25f;
|
||||
public static readonly float[] WindowZ = { -4.5f, -1.5f, 1.5f, 4.5f };
|
||||
public static readonly float[] VentZ = { -3.2f, 2.4f };
|
||||
|
||||
public static readonly Color Accent = new Color(0.16f, 0.70f, 0.75f);
|
||||
|
||||
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)
|
||||
{
|
||||
CreateMaterials();
|
||||
var devices = root.GetComponent<RoomDevices>();
|
||||
if (devices == null) devices = root.gameObject.AddComponent<RoomDevices>();
|
||||
|
||||
BuildShell(Prim.Pivot("Gebäude", root, Vector3.zero));
|
||||
BuildOutside(Prim.Pivot("Außenbereich", root, Vector3.zero));
|
||||
BuildWindows(Prim.Pivot("Fenster", root, Vector3.zero), devices);
|
||||
BuildBlinds(Prim.Pivot("Jalousien", root, Vector3.zero), devices);
|
||||
BuildHeaters(Prim.Pivot("Heizkörper", root, Vector3.zero), devices);
|
||||
BuildVentilation(Prim.Pivot("Lüftung", root, Vector3.zero), devices);
|
||||
BuildLights(Prim.Pivot("Beleuchtung", root, Vector3.zero), devices);
|
||||
BuildProjection(Prim.Pivot("Beamer & Leinwand", root, Vector3.zero), devices);
|
||||
BuildDoor(Prim.Pivot("Tür", root, Vector3.zero), devices);
|
||||
BuildFurniture(Prim.Pivot("Möblierung", root, Vector3.zero));
|
||||
return devices;
|
||||
}
|
||||
|
||||
static void CreateMaterials()
|
||||
{
|
||||
wall = Mat.Solid(new Color(0.92f, 0.92f, 0.90f), 0.1f);
|
||||
accentWall = Mat.Solid(new Color(0.80f, 0.83f, 0.85f), 0.1f);
|
||||
floor = Mat.Solid(new Color(0.30f, 0.33f, 0.37f), 0.45f);
|
||||
ceiling = Mat.Solid(new Color(0.96f, 0.96f, 0.96f), 0.05f);
|
||||
frame = Mat.Solid(new Color(0.20f, 0.21f, 0.23f), 0.45f, 0.3f);
|
||||
glass = Mat.Transparent(new Color(0.75f, 0.88f, 0.95f, 0.18f));
|
||||
alu = Mat.Solid(new Color(0.74f, 0.76f, 0.79f), 0.55f, 0.6f);
|
||||
white = Mat.Solid(new Color(0.95f, 0.95f, 0.95f), 0.3f);
|
||||
oak = Mat.Solid(new Color(0.80f, 0.67f, 0.50f), 0.35f);
|
||||
doorWood = Mat.Solid(new Color(0.62f, 0.48f, 0.35f), 0.3f);
|
||||
dark = Mat.Solid(new Color(0.16f, 0.17f, 0.19f), 0.35f, 0.2f);
|
||||
seat = Mat.Solid(new Color(0.17f, 0.44f, 0.50f), 0.2f);
|
||||
metal = Mat.Solid(new Color(0.70f, 0.72f, 0.75f), 0.6f, 0.8f);
|
||||
grass = Mat.Solid(new Color(0.36f, 0.50f, 0.30f), 0.05f);
|
||||
leaves = Mat.Solid(new Color(0.25f, 0.45f, 0.25f), 0.1f);
|
||||
bark = Mat.Solid(new Color(0.35f, 0.27f, 0.20f), 0.1f);
|
||||
stone = Mat.Solid(new Color(0.85f, 0.85f, 0.83f), 0.4f);
|
||||
screenMat = Mat.Solid(new Color(0.97f, 0.97f, 0.97f), 0.05f);
|
||||
exitSign = Mat.Emissive(new Color(0.1f, 0.6f, 0.3f), new Color(0.1f, 0.9f, 0.4f) * 1.5f);
|
||||
heaterMat = Mat.Emissive(new Color(0.93f, 0.93f, 0.92f), Color.black);
|
||||
panelMat = Mat.Emissive(new Color(0.9f, 0.9f, 0.9f), Color.white);
|
||||
ledMat = Mat.Emissive(Color.gray, Color.black);
|
||||
lensMat = Mat.Emissive(new Color(0.1f, 0.1f, 0.12f), Color.black);
|
||||
slideMat = Mat.Emissive(Color.white, Color.black);
|
||||
slideAccent = Mat.Emissive(Accent, Accent);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Gebäudehülle
|
||||
static void BuildShell(Transform p)
|
||||
{
|
||||
Prim.Box("Boden", p, new Vector3(0, -0.05f, 0), new Vector3(W + 2 * T, 0.1f, D + 2 * T), floor);
|
||||
Prim.Box("Decke", p, new Vector3(0, H + 0.05f, 0), new Vector3(W + 2 * T, 0.1f, D + 2 * T), ceiling);
|
||||
Prim.Box("Wand rechts", p, new Vector3(W / 2 + T / 2, H / 2, 0), new Vector3(T, H, D + 2 * T), wall);
|
||||
Prim.Box("Wand hinten", p, new Vector3(0, H / 2, -D / 2 - T / 2), new Vector3(W, H, T), wall);
|
||||
|
||||
// Vorderwand mit Türöffnung links von der Leinwand
|
||||
float zf = D / 2 + T / 2;
|
||||
Prim.Box("Wand vorne links", p, new Vector3((-W / 2 + DoorX0) / 2, H / 2, zf), new Vector3(DoorX0 + W / 2, H, T), wall);
|
||||
Prim.Box("Wand vorne rechts", p, new Vector3((DoorX1 + W / 2) / 2, H / 2, zf), new Vector3(W / 2 - DoorX1, H, T), wall);
|
||||
Prim.Box("Sturz Tür", p, new Vector3((DoorX0 + DoorX1) / 2, (DoorH + H) / 2, zf), new Vector3(DoorX1 - DoorX0, H - DoorH, T), wall);
|
||||
Prim.Box("Akzentwand", p, new Vector3(0, H / 2, D / 2 - 0.011f), new Vector3(ScreenW + 2f, H, 0.02f), accentWall);
|
||||
|
||||
// Linke Wand mit vier Fensteröffnungen
|
||||
float xl = -W / 2 - T / 2;
|
||||
Prim.Box("Brüstung", p, new Vector3(xl, SillY / 2, 0), new Vector3(T, SillY, D + 2 * T), wall);
|
||||
Prim.Box("Wand über Fenstern", p, new Vector3(xl, (WinTopY + H) / 2, 0), new Vector3(T, H - WinTopY, D + 2 * T), wall);
|
||||
float prev = -D / 2 - T;
|
||||
for (int i = 0; i <= WindowZ.Length; i++)
|
||||
{
|
||||
float next = i < WindowZ.Length ? WindowZ[i] - WinWidth / 2 : D / 2 + T;
|
||||
Prim.Box("Pfeiler", p, new Vector3(xl, (SillY + WinTopY) / 2, (prev + next) / 2), new Vector3(T, WinTopY - SillY, next - prev), wall);
|
||||
if (i < WindowZ.Length) prev = WindowZ[i] + WinWidth / 2;
|
||||
}
|
||||
}
|
||||
|
||||
static void BuildOutside(Transform p)
|
||||
{
|
||||
Prim.Box("Wiese", p, new Vector3(0, -0.13f, 0), new Vector3(90f, 0.06f, 90f), grass);
|
||||
Prim.Box("Weg", p, new Vector3(-W / 2 - 3f, -0.095f, 0), new Vector3(2.4f, 0.01f, 60f), stone);
|
||||
float[] tz = { -10f, -3.5f, 3f, 9.5f };
|
||||
for (int i = 0; i < tz.Length; i++)
|
||||
{
|
||||
float x = -W / 2 - 11f - (i % 2) * 2.5f;
|
||||
Prim.Cylinder("Stamm", p, new Vector3(x, 1.3f, tz[i]), 0.35f, 2.6f, bark);
|
||||
Prim.Sphere("Krone", p, new Vector3(x, 3.7f, tz[i]), 3.4f, leaves);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Fenster (Dreh-Kipp)
|
||||
static void BuildWindows(Transform parent, RoomDevices dev)
|
||||
{
|
||||
float h = WinTopY - SillY;
|
||||
const float fp = 0.07f; // Profilbreite Blendrahmen
|
||||
const float sp = 0.06f; // Profilbreite Flügel
|
||||
float fx = T / 2 - 0.06f; // Fensterebene (lokal, nahe Innenseite)
|
||||
float sw = WinWidth - 2 * fp, sh = h - 2 * fp;
|
||||
|
||||
for (int i = 0; i < WindowZ.Length; i++)
|
||||
{
|
||||
var root = Prim.Pivot($"Fenster {i + 1}", parent, new Vector3(-W / 2 - T / 2, 0, WindowZ[i]));
|
||||
Prim.Box("Rahmen oben", root, new Vector3(fx, WinTopY - fp / 2, 0), new Vector3(0.1f, fp, WinWidth), frame);
|
||||
Prim.Box("Rahmen unten", root, new Vector3(fx, SillY + fp / 2, 0), new Vector3(0.1f, fp, WinWidth), frame);
|
||||
Prim.Box("Rahmen links", root, new Vector3(fx, SillY + h / 2, -WinWidth / 2 + fp / 2), new Vector3(0.1f, h, fp), frame);
|
||||
Prim.Box("Rahmen rechts", root, new Vector3(fx, SillY + h / 2, WinWidth / 2 - fp / 2), new Vector3(0.1f, h, fp), frame);
|
||||
|
||||
// Drehachse (vertikal) -> Kippachse (unten) -> Flügel
|
||||
var hinge = Prim.Pivot("Drehachse", root, new Vector3(fx, SillY + fp, -WinWidth / 2 + fp));
|
||||
var tilt = Prim.Pivot("Kippachse", hinge, Vector3.zero);
|
||||
Prim.Box("Flügel unten", tilt, new Vector3(0, sp / 2, sw / 2), new Vector3(0.07f, sp, sw), frame);
|
||||
Prim.Box("Flügel oben", tilt, new Vector3(0, sh - sp / 2, sw / 2), new Vector3(0.07f, sp, sw), frame);
|
||||
Prim.Box("Flügel links", tilt, new Vector3(0, sh / 2, sp / 2), new Vector3(0.07f, sh, sp), frame);
|
||||
Prim.Box("Flügel rechts", tilt, new Vector3(0, sh / 2, sw - sp / 2), new Vector3(0.07f, sh, sp), frame);
|
||||
Prim.NoShadows(Prim.Box("Glas", tilt, new Vector3(0, sh / 2, sw / 2), new Vector3(0.012f, sh - 2 * sp, sw - 2 * sp), glass));
|
||||
|
||||
Prim.Box("Rosette", tilt, new Vector3(0.04f, sh / 2, sw - 0.04f), new Vector3(0.02f, 0.07f, 0.035f), metal);
|
||||
var handle = Prim.Pivot("Griff", tilt, new Vector3(0.055f, sh / 2, sw - 0.04f));
|
||||
Prim.Box("Hebel", handle, new Vector3(0, -0.055f, 0), new Vector3(0.02f, 0.12f, 0.025f), metal);
|
||||
|
||||
var act = root.gameObject.AddComponent<WindowActuator>();
|
||||
act.hinge = hinge;
|
||||
act.tilt = tilt;
|
||||
act.handle = handle;
|
||||
dev.windows.Add(act);
|
||||
|
||||
Prim.Box("Fensterbank", parent, new Vector3(-W / 2 + 0.1f, SillY - 0.015f, WindowZ[i]), new Vector3(0.24f, 0.03f, WinWidth + 0.12f), stone);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Außenjalousien (Raffstore)
|
||||
static void BuildBlinds(Transform parent, RoomDevices dev)
|
||||
{
|
||||
const int n = 22;
|
||||
float len = WinWidth + 0.04f;
|
||||
for (int i = 0; i < WindowZ.Length; i++)
|
||||
{
|
||||
var root = Prim.Pivot($"Jalousie {i + 1}", parent, new Vector3(-W / 2 - T - 0.08f, 0, WindowZ[i]));
|
||||
Prim.Box("Blende", root, new Vector3(-0.01f, WinTopY + 0.11f, 0), new Vector3(0.18f, 0.22f, WinWidth + 0.16f), frame);
|
||||
float rh = WinTopY - SillY;
|
||||
Prim.Box("Führungsschiene", root, new Vector3(0, SillY + rh / 2, len / 2 + 0.025f), new Vector3(0.05f, rh, 0.025f), frame);
|
||||
Prim.Box("Führungsschiene", root, new Vector3(0, SillY + rh / 2, -len / 2 - 0.025f), new Vector3(0.05f, rh, 0.025f), frame);
|
||||
|
||||
var slats = new Transform[n];
|
||||
for (int k = 0; k < n; k++)
|
||||
slats[k] = Prim.Box($"Lamelle {k + 1}", root, Vector3.zero, new Vector3(0.085f, 0.006f, len), alu).transform;
|
||||
var rail = Prim.Box("Endschiene", root, Vector3.zero, new Vector3(0.09f, 0.03f, len), frame).transform;
|
||||
|
||||
var act = root.gameObject.AddComponent<BlindActuator>();
|
||||
act.slats = slats;
|
||||
act.bottomRail = rail;
|
||||
act.top = WinTopY - 0.01f;
|
||||
act.bottom = SillY + 0.02f;
|
||||
act.stackBase = WinTopY + 0.02f;
|
||||
act.Apply();
|
||||
dev.blinds.Add(act);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Heizkörper
|
||||
static void BuildHeaters(Transform parent, RoomDevices dev)
|
||||
{
|
||||
const int fins = 16;
|
||||
const float width = 1.6f;
|
||||
for (int i = 0; i < WindowZ.Length; i++)
|
||||
{
|
||||
var root = Prim.Pivot($"Heizkörper {i + 1}", parent, new Vector3(-W / 2 + 0.09f, 0, WindowZ[i]));
|
||||
for (int f = 0; f < fins; f++)
|
||||
{
|
||||
float z = -width / 2 + (f + 0.5f) * width / fins;
|
||||
Prim.Box("Rippe", root, new Vector3(0, 0.46f, z), new Vector3(0.08f, 0.56f, 0.06f), heaterMat);
|
||||
}
|
||||
Prim.Box("Sammler unten", root, new Vector3(0, 0.2f, 0), new Vector3(0.05f, 0.04f, width), heaterMat);
|
||||
Prim.Box("Sammler oben", root, new Vector3(0, 0.72f, 0), new Vector3(0.05f, 0.04f, width), heaterMat);
|
||||
Prim.Box("Rohr", root, new Vector3(-0.02f, 0.1f, -width / 2 - 0.05f), new Vector3(0.025f, 0.2f, 0.025f), white);
|
||||
var valve = Prim.Cylinder("Thermostatkopf", root, new Vector3(0, 0.72f, width / 2 + 0.06f), 0.06f, 0.1f, white);
|
||||
valve.transform.localRotation = Quaternion.Euler(90f, 0, 0);
|
||||
|
||||
var heat = Fx.Make("Wärme", root, new Vector3(0.05f, 0.8f, 0), Quaternion.Euler(-90f, 0, 0),
|
||||
new Color(1f, 0.6f, 0.35f, 0.22f), 0.14f, 2.5f, 0.25f,
|
||||
ParticleSystemShapeType.Box, new Vector3(0.08f, width, 0.01f));
|
||||
|
||||
var act = root.gameObject.AddComponent<HeaterActuator>();
|
||||
act.finMaterial = heaterMat;
|
||||
act.heatFx = heat;
|
||||
dev.heaters.Add(act);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Lüftungsanlage
|
||||
static void BuildVentilation(Transform parent, RoomDevices dev)
|
||||
{
|
||||
var duct = Prim.Cylinder("Lüftungskanal", parent, new Vector3(0, H - 0.32f, -0.4f), 0.44f, D - 2.6f, metal);
|
||||
duct.transform.localRotation = Quaternion.Euler(90f, 0, 0);
|
||||
foreach (float z in new[] { -5f, -0.4f, 4.2f })
|
||||
Prim.Box("Abhängung", parent, new Vector3(0, H - 0.05f, z), new Vector3(0.03f, 0.1f, 0.03f), dark);
|
||||
|
||||
for (int i = 0; i < VentZ.Length; i++)
|
||||
{
|
||||
var u = Prim.Pivot($"Lüftungsgerät {i + 1}", parent, new Vector3(0, H - 0.6f, VentZ[i]));
|
||||
Prim.Box("Gehäuse", u, new Vector3(0, 0.03f, 0), new Vector3(0.95f, 0.16f, 0.95f), white);
|
||||
Prim.Cylinder("Ring", u, new Vector3(0, -0.055f, 0), 0.74f, 0.02f, dark);
|
||||
|
||||
var rotor = Prim.Pivot("Rotor", u, new Vector3(0, -0.075f, 0));
|
||||
Prim.Cylinder("Nabe", rotor, Vector3.zero, 0.13f, 0.04f, metal);
|
||||
for (int b = 0; b < 5; b++)
|
||||
{
|
||||
var arm = Prim.Pivot("Arm", rotor, Vector3.zero);
|
||||
arm.localRotation = Quaternion.Euler(0, b * 72f, 0);
|
||||
var blade = Prim.Box("Blatt", arm, new Vector3(0.18f, 0, 0), new Vector3(0.26f, 0.008f, 0.09f), white);
|
||||
blade.transform.localRotation = Quaternion.Euler(22f, 0, 0);
|
||||
}
|
||||
Prim.Box("Gitter", u, new Vector3(0, -0.1f, 0), new Vector3(0.7f, 0.01f, 0.02f), dark);
|
||||
Prim.Box("Gitter", u, new Vector3(0, -0.1f, 0), new Vector3(0.02f, 0.01f, 0.7f), dark);
|
||||
Prim.Box("Status-LED", u, new Vector3(0.476f, 0.05f, 0.3f), new Vector3(0.01f, 0.025f, 0.06f), ledMat);
|
||||
|
||||
var air = Fx.Make("Luftstrom", u, new Vector3(0, -0.11f, 0), Quaternion.Euler(90f, 0, 0),
|
||||
new Color(0.75f, 0.88f, 1f, 0.3f), 0.1f, 2.2f, 0.8f,
|
||||
ParticleSystemShapeType.Cone, Vector3.one, 35f, 0.3f);
|
||||
|
||||
var act = u.gameObject.AddComponent<VentilationActuator>();
|
||||
act.rotor = rotor;
|
||||
act.air = air;
|
||||
act.led = ledMat;
|
||||
dev.vents.Add(act);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Beleuchtung
|
||||
static void BuildLights(Transform parent, RoomDevices dev)
|
||||
{
|
||||
var act = parent.gameObject.AddComponent<LightActuator>();
|
||||
act.panelMaterial = panelMat;
|
||||
foreach (float x in new[] { -3.2f, 3.2f })
|
||||
{
|
||||
foreach (float z in new[] { -5.2f, -1.9f, 1.4f, 4.7f })
|
||||
{
|
||||
Prim.Box("Leuchtenrahmen", parent, new Vector3(x, H - 0.01f, z), new Vector3(0.68f, 0.02f, 1.3f), white);
|
||||
Prim.NoShadows(Prim.Box("Leuchtpanel", parent, new Vector3(x, H - 0.022f, z), new Vector3(0.62f, 0.01f, 1.24f), panelMat));
|
||||
}
|
||||
foreach (float z in new[] { -3.5f, 3.0f })
|
||||
{
|
||||
var go = new GameObject("Deckenlicht");
|
||||
go.transform.SetParent(parent, false);
|
||||
go.transform.localPosition = new Vector3(x, H - 0.4f, z);
|
||||
var l = go.AddComponent<Light>();
|
||||
l.type = LightType.Point;
|
||||
l.range = 9f;
|
||||
l.color = new Color(1f, 0.97f, 0.92f);
|
||||
l.shadows = LightShadows.None;
|
||||
act.lamps.Add(l);
|
||||
}
|
||||
}
|
||||
dev.lights = act;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Leinwand + Beamer
|
||||
static void BuildProjection(Transform parent, RoomDevices dev)
|
||||
{
|
||||
float zs = D / 2 - 0.1f;
|
||||
Prim.Box("Leinwandkasten", parent, new Vector3(0, ScreenTop + 0.06f, zs), new Vector3(ScreenW + 0.2f, 0.12f, 0.12f), white);
|
||||
var fabric = Prim.Box("Leinwand", parent, new Vector3(0, ScreenTop, zs), new Vector3(ScreenW, 0.04f, 0.006f), screenMat).transform;
|
||||
var bar = Prim.Box("Leinwandstab", parent, new Vector3(0, ScreenTop, zs), new Vector3(ScreenW + 0.04f, 0.025f, 0.025f), dark).transform;
|
||||
|
||||
// Projiziertes Bild (Folie mit Live-Werten)
|
||||
float sw = ScreenW - 0.3f, shh = ScreenDrop - 0.35f;
|
||||
var slide = Prim.Pivot("Projektion", parent, new Vector3(0, ScreenTop - ScreenDrop / 2 - 0.05f, zs - 0.006f));
|
||||
Prim.NoShadows(Prim.Box("Folie", slide, Vector3.zero, new Vector3(sw, shh, 0.002f), slideMat));
|
||||
Prim.NoShadows(Prim.Box("Akzent", slide, new Vector3(-sw / 2 + 0.12f, 0, -0.002f), new Vector3(0.04f, shh - 0.3f, 0.002f), slideAccent));
|
||||
var font = Prim.BuiltinFont();
|
||||
float tx = -sw / 2 + 0.28f;
|
||||
var title = Prim.Text("Titel", slide, new Vector3(tx, shh / 2 - 0.18f, -0.004f), "Smart Lecture Room", 0.031f, new Color(0.10f, 0.12f, 0.15f), font, FontStyle.Bold);
|
||||
var sub = Prim.Text("Untertitel", slide, new Vector3(tx, shh / 2 - 0.42f, -0.004f), "Digitaler Zwilling · Raumklima live", 0.015f, new Color(0.35f, 0.4f, 0.45f), font);
|
||||
var body = Prim.Text("Inhalt", slide, new Vector3(tx, shh / 2 - 0.72f, -0.004f), "", 0.017f, new Color(0.12f, 0.14f, 0.17f), font);
|
||||
|
||||
// Beamer an der Decke
|
||||
var proj = Prim.Pivot("Beamer", parent, new Vector3(0, H - 0.28f, 1.2f));
|
||||
Prim.Box("Halterung", proj, new Vector3(0, 0.15f, 0), new Vector3(0.05f, 0.26f, 0.05f), dark);
|
||||
Prim.Box("Gehäuse", proj, Vector3.zero, new Vector3(0.42f, 0.13f, 0.34f), white);
|
||||
var lens = Prim.Cylinder("Objektiv", proj, new Vector3(0.1f, 0, 0.175f), 0.09f, 0.03f, lensMat);
|
||||
lens.transform.localRotation = Quaternion.Euler(90f, 0, 0);
|
||||
var beamGo = new GameObject("Lichtkegel");
|
||||
beamGo.transform.SetParent(proj, false);
|
||||
beamGo.transform.localPosition = new Vector3(0.1f, 0, 0.2f);
|
||||
Vector3 aim = parent.TransformPoint(new Vector3(0, ScreenTop - ScreenDrop / 2, zs));
|
||||
beamGo.transform.rotation = Quaternion.LookRotation(aim - beamGo.transform.position);
|
||||
var spot = beamGo.AddComponent<Light>();
|
||||
spot.type = LightType.Spot;
|
||||
spot.spotAngle = 40f;
|
||||
spot.range = 10f;
|
||||
spot.intensity = 0f;
|
||||
spot.color = new Color(0.9f, 0.95f, 1f);
|
||||
|
||||
var act = parent.gameObject.AddComponent<ProjectorActuator>();
|
||||
act.fabric = fabric;
|
||||
act.bottomBar = bar;
|
||||
act.top = ScreenTop;
|
||||
act.maxDrop = ScreenDrop;
|
||||
act.slide = slide.gameObject;
|
||||
act.slideMaterial = slideMat;
|
||||
act.lensMaterial = lensMat;
|
||||
act.beam = spot;
|
||||
act.texts = new[] { title, sub, body };
|
||||
act.body = body;
|
||||
dev.projector = act;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Tür
|
||||
static void BuildDoor(Transform parent, RoomDevices dev)
|
||||
{
|
||||
float zf = D / 2 + T / 2, dw = DoorX1 - DoorX0, zi = D / 2 - 0.02f;
|
||||
Prim.Box("Zarge links", parent, new Vector3(DoorX0 - 0.03f, DoorH / 2, zi), new Vector3(0.06f, DoorH + 0.06f, 0.05f), frame);
|
||||
Prim.Box("Zarge rechts", parent, new Vector3(DoorX1 + 0.03f, DoorH / 2, zi), new Vector3(0.06f, DoorH + 0.06f, 0.05f), frame);
|
||||
Prim.Box("Zarge oben", parent, new Vector3((DoorX0 + DoorX1) / 2, DoorH + 0.03f, zi), new Vector3(dw + 0.12f, 0.06f, 0.05f), frame);
|
||||
|
||||
var hinge = Prim.Pivot("Türangel", parent, new Vector3(DoorX0 + 0.01f, 0, zf));
|
||||
float lw = dw - 0.02f;
|
||||
Prim.Box("Türblatt", hinge, new Vector3(lw / 2, (DoorH - 0.01f) / 2, 0), new Vector3(lw, DoorH - 0.01f, 0.05f), doorWood, keepCollider: true);
|
||||
Prim.Box("Drücker innen", hinge, new Vector3(lw - 0.14f, 1.05f, -0.055f), new Vector3(0.14f, 0.02f, 0.025f), metal);
|
||||
Prim.Box("Drücker außen", hinge, new Vector3(lw - 0.14f, 1.05f, 0.055f), new Vector3(0.14f, 0.02f, 0.025f), metal);
|
||||
|
||||
Prim.Box("Notausgang", parent, new Vector3((DoorX0 + DoorX1) / 2, DoorH + 0.26f, D / 2 - 0.03f), new Vector3(0.38f, 0.15f, 0.04f), exitSign);
|
||||
Prim.Box("Raumpanel", parent, new Vector3(DoorX1 + 0.5f, 1.4f, D / 2 - 0.015f), new Vector3(0.22f, 0.15f, 0.02f), dark);
|
||||
Prim.Box("Raumpanel Display", parent, new Vector3(DoorX1 + 0.5f, 1.4f, D / 2 - 0.027f), new Vector3(0.18f, 0.11f, 0.004f), slideAccent);
|
||||
|
||||
var act = hinge.gameObject.AddComponent<DoorActuator>();
|
||||
act.pivot = hinge;
|
||||
dev.door = act;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Möbel
|
||||
static void BuildFurniture(Transform p)
|
||||
{
|
||||
float[] rows = { -5.6f, -4.05f, -2.5f, -0.95f, 0.6f, 2.15f };
|
||||
float[] blocks = { -2.9f, 2.9f };
|
||||
foreach (float z in rows)
|
||||
{
|
||||
foreach (float cx in blocks)
|
||||
{
|
||||
Prim.Box("Tisch", p, new Vector3(cx, 0.74f, z + 0.3f), new Vector3(4.2f, 0.03f, 0.55f), oak);
|
||||
Prim.Box("Sichtblende", p, new Vector3(cx, 0.45f, z + 0.56f), new Vector3(4.2f, 0.55f, 0.02f), dark);
|
||||
Prim.Box("Wange", p, new Vector3(cx - 2.08f, 0.37f, z + 0.3f), new Vector3(0.04f, 0.74f, 0.52f), dark);
|
||||
Prim.Box("Wange", p, new Vector3(cx + 2.08f, 0.37f, z + 0.3f), new Vector3(0.04f, 0.74f, 0.52f), dark);
|
||||
for (int j = 0; j < 4; j++)
|
||||
Chair(p, new Vector3(cx - 1.575f + j * 1.05f, 0, z - 0.15f));
|
||||
}
|
||||
}
|
||||
|
||||
// Dozentenpult vorne rechts
|
||||
Prim.Box("Pult", p, new Vector3(3.4f, 0.52f, 5.3f), new Vector3(1.0f, 1.04f, 0.6f), dark);
|
||||
Prim.Box("Pultplatte", p, new Vector3(3.4f, 1.06f, 5.3f), new Vector3(1.1f, 0.04f, 0.7f), oak);
|
||||
Prim.Box("Laptop", p, new Vector3(3.4f, 1.088f, 5.32f), new Vector3(0.34f, 0.015f, 0.24f), metal);
|
||||
Prim.Box("Laptop Display", p, new Vector3(3.4f, 1.2f, 5.2f), new Vector3(0.34f, 0.22f, 0.012f), metal);
|
||||
|
||||
// Pflanze hinten rechts
|
||||
Prim.Cylinder("Topf", p, new Vector3(5.3f, 0.25f, -6.3f), 0.45f, 0.5f, dark);
|
||||
Prim.Sphere("Pflanze", p, new Vector3(5.3f, 0.95f, -6.3f), 0.9f, leaves);
|
||||
}
|
||||
|
||||
static void Chair(Transform p, Vector3 at)
|
||||
{
|
||||
Prim.Box("Sitz", p, at + new Vector3(0, 0.46f, 0), new Vector3(0.46f, 0.05f, 0.44f), seat);
|
||||
var back = Prim.Box("Lehne", p, at + new Vector3(0, 0.8f, -0.21f), new Vector3(0.46f, 0.38f, 0.04f), seat);
|
||||
back.transform.localRotation = Quaternion.Euler(-8f, 0, 0);
|
||||
Prim.Box("Säule", p, at + new Vector3(0, 0.23f, 0), new Vector3(0.05f, 0.44f, 0.05f), dark);
|
||||
Prim.Cylinder("Fuß", p, at + new Vector3(0, 0.015f, 0), 0.5f, 0.03f, dark);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Zentrale Schnittstelle zu allen (virtuellen) Aktoren des Raums.
|
||||
/// Später kann dieselbe Schnittstelle echte Aktoren über den Arduino ansteuern.
|
||||
/// </summary>
|
||||
public class RoomDevices : MonoBehaviour
|
||||
{
|
||||
public readonly List<WindowActuator> windows = new List<WindowActuator>();
|
||||
public readonly List<BlindActuator> blinds = new List<BlindActuator>();
|
||||
public readonly List<HeaterActuator> heaters = new List<HeaterActuator>();
|
||||
public readonly List<VentilationActuator> vents = new List<VentilationActuator>();
|
||||
public LightActuator lights;
|
||||
public ProjectorActuator projector;
|
||||
public DoorActuator door;
|
||||
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);
|
||||
|
||||
// ---------------------------------------------------------------- Fenster
|
||||
public void SetWindows(WindowState s) { foreach (var w in windows) w.target = s; }
|
||||
public WindowState WindowTarget => windows.Count > 0 ? windows[0].target : WindowState.Closed;
|
||||
public WindowState WindowCurrent => windows.Count > 0 ? windows[0].Current : WindowState.Closed;
|
||||
public bool WindowsMoving => windows.Exists(w => w.IsMoving);
|
||||
public float WindowAirflow => Average(windows, w => w.Airflow);
|
||||
public string WindowLabel => WindowsMoving ? (WindowTarget == WindowState.Closed ? "schließt …" : "öffnet …") : WindowCurrent.Label();
|
||||
|
||||
// ---------------------------------------------------------------- Jalousien
|
||||
public void SetBlinds(float v) { foreach (var b in blinds) b.target = Mathf.Clamp01(v); }
|
||||
public float BlindTarget => blinds.Count > 0 ? blinds[0].target : 0f;
|
||||
public float BlindPosition => Average(blinds, b => b.Current);
|
||||
public float BlindClosure => Average(blinds, b => b.Closure);
|
||||
|
||||
// ---------------------------------------------------------------- Heizung
|
||||
public void SetHeating(float v) { foreach (var h in heaters) h.target = Mathf.Clamp01(v); }
|
||||
public float HeatingTarget => heaters.Count > 0 ? heaters[0].target : 0f;
|
||||
public float HeatingLevel => Average(heaters, h => h.Current);
|
||||
|
||||
// ---------------------------------------------------------------- Lüftung
|
||||
public void SetVentilation(float v) { foreach (var x in vents) x.target = Mathf.Clamp01(v); }
|
||||
public float VentTarget => vents.Count > 0 ? vents[0].target : 0f;
|
||||
public float VentLevel => Average(vents, x => x.Current);
|
||||
|
||||
// ---------------------------------------------------------------- Licht
|
||||
public void SetLights(float v) { if (lights != null) lights.target = Mathf.Clamp01(v); }
|
||||
public float LightTarget => lights != null ? lights.target : 0f;
|
||||
public float LightLevel => lights != null ? lights.Current : 0f;
|
||||
|
||||
public bool BeamerOn => projector != null && projector.beamerOn;
|
||||
public float DoorOpenness => door != null ? door.Openness : 0f;
|
||||
|
||||
static float Average<T>(List<T> list, System.Func<T, float> f)
|
||||
{
|
||||
if (list.Count == 0) return 0f;
|
||||
float s = 0f;
|
||||
foreach (var x in list) s += f(x);
|
||||
return s / list.Count;
|
||||
}
|
||||
|
||||
/// <summary>Sonne + Umgebungslicht passend zu Sonneneinstrahlung, Jalousien und Kunstlicht.</summary>
|
||||
void Update()
|
||||
{
|
||||
float solar = env != null ? env.solar : 300f;
|
||||
float day = Mathf.Clamp01(solar / 800f);
|
||||
if (sun != null)
|
||||
{
|
||||
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);
|
||||
RenderSettings.ambientMode = AmbientMode.Trilight;
|
||||
RenderSettings.ambientSkyColor = AmbSky * k;
|
||||
RenderSettings.ambientEquatorColor = AmbEquator * k;
|
||||
RenderSettings.ambientGroundColor = AmbGround * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Umgebungszustand des Raums (innen + außen) mit einem einfachen physikalischen Modell.
|
||||
/// Werte, die vom Arduino gemessen werden, überschreiben das Modell, solange Messungen eintreffen.
|
||||
/// </summary>
|
||||
public class RoomEnvironment : MonoBehaviour
|
||||
{
|
||||
public const float RoomVolume = RoomBuilder.W * RoomBuilder.D * RoomBuilder.H; // m³
|
||||
public const float OutdoorCo2 = 420f;
|
||||
|
||||
[Header("Simulationszeit")]
|
||||
[Tooltip("Simulierte Minuten pro Echtzeit-Sekunde (0 = Pause)")]
|
||||
public float timeScale = 1f;
|
||||
public double simMinutes = 8 * 60 + 15;
|
||||
|
||||
[Header("Vorlesung")]
|
||||
public bool lectureRunning = true;
|
||||
public int occupants = 45;
|
||||
|
||||
[Header("Innenraum (gemessen oder simuliert)")]
|
||||
public float indoorTemp = 22f; // °C
|
||||
public float co2 = 650f; // ppm
|
||||
public float indoorLux = 300f; // lx
|
||||
public float indoorNoise = 42f; // dB(A)
|
||||
|
||||
[Header("Außen (Wetterdaten / Sensoren / manuell)")]
|
||||
public float outdoorTemp = 14f; // °C
|
||||
public float outdoorAqi = 25f; // European AQI (0 gut … 100 sehr schlecht)
|
||||
public float outdoorNoise = 55f; // dB(A)
|
||||
public float windSpeed = 3f; // m/s
|
||||
public float solar = 350f; // W/m² Globalstrahlung
|
||||
|
||||
[Tooltip("Sekunden, die ein Messwert als 'live' gilt")]
|
||||
public float measurementTimeout = 15f;
|
||||
|
||||
public RoomDevices devices;
|
||||
|
||||
readonly Dictionary<string, float> measuredAt = new Dictionary<string, float>();
|
||||
|
||||
public string ClockText
|
||||
{
|
||||
get
|
||||
{
|
||||
var t = TimeSpan.FromMinutes(simMinutes % 1440.0);
|
||||
return $"{t.Hours:00}:{t.Minutes:00} Uhr";
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsMeasured(string channel)
|
||||
=> measuredAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout;
|
||||
|
||||
public bool AnyMeasured
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (var t in measuredAt.Values)
|
||||
if (Time.unscaledTime - t < measurementTimeout) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Übernimmt ein Datenpaket vom Arduino. Fehlende Felder (NaN) werden ignoriert.</summary>
|
||||
public void ApplyMeasurement(SensorPacket p)
|
||||
{
|
||||
Set("t", p.t, v => indoorTemp = v);
|
||||
Set("co2", p.co2, v => co2 = v);
|
||||
Set("lux", p.lux, v => indoorLux = v);
|
||||
Set("noise", p.noise, v => indoorNoise = v);
|
||||
Set("tout", p.tout, v => outdoorTemp = v);
|
||||
Set("aq", p.aq, v => outdoorAqi = v);
|
||||
Set("nout", p.nout, v => outdoorNoise = v);
|
||||
Set("wind", p.wind, v => windSpeed = v);
|
||||
Set("sun", p.sun, v => solar = v);
|
||||
Set("persons", p.persons, v => occupants = Mathf.RoundToInt(v));
|
||||
}
|
||||
|
||||
void Set(string channel, float v, Action<float> apply)
|
||||
{
|
||||
if (float.IsNaN(v)) return;
|
||||
apply(v);
|
||||
measuredAt[channel] = Time.unscaledTime;
|
||||
}
|
||||
|
||||
/// <summary>Geschätzte Tageslicht-Beleuchtungsstärke im Raum bei gegebener Jalousie-Abschirmung.</summary>
|
||||
public float DaylightLux(float blindClosure)
|
||||
=> solar * 1.4f * (1f - 0.92f * Mathf.Clamp01(blindClosure)) + (solar > 5f ? 20f : 0f);
|
||||
|
||||
void Update()
|
||||
{
|
||||
float simDt = Time.deltaTime * timeScale * 60f; // simulierte Sekunden
|
||||
if (simDt <= 0f || devices == null) return;
|
||||
simMinutes += simDt / 60f;
|
||||
|
||||
int steps = Mathf.CeilToInt(simDt / 10f);
|
||||
float h = simDt / steps;
|
||||
for (int i = 0; i < steps; i++) Integrate(h);
|
||||
|
||||
float win = devices.WindowAirflow;
|
||||
if (!IsMeasured("lux"))
|
||||
indoorLux = DaylightLux(devices.BlindClosure) + devices.LightLevel * 520f;
|
||||
if (!IsMeasured("noise"))
|
||||
{
|
||||
float people = lectureRunning ? 45f : 30f;
|
||||
float outside = outdoorNoise - Mathf.Lerp(32f, 8f, win);
|
||||
float vent = devices.VentLevel > 0.01f ? 28f + 14f * devices.VentLevel : 0f;
|
||||
indoorNoise = DbSum(people, outside, vent);
|
||||
}
|
||||
}
|
||||
|
||||
void Integrate(float h)
|
||||
{
|
||||
float win = devices.WindowAirflow;
|
||||
float vent = devices.VentLevel;
|
||||
float achWindow = win * (5f + 0.8f * windSpeed) + devices.DoorOpenness * 0.8f + 0.25f; // Luftwechsel / h
|
||||
float achVent = vent * 6f;
|
||||
int persons = lectureRunning ? occupants : 0;
|
||||
|
||||
if (!IsMeasured("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"))
|
||||
{
|
||||
float pHeat = devices.HeatingLevel * 9000f;
|
||||
float pPeople = persons * 80f;
|
||||
float pSun = solar * 9f * 0.45f * (1f - 0.85f * devices.BlindClosure);
|
||||
float pLight = devices.LightLevel * 600f;
|
||||
// Lüftungsanlage mit 75 % Wärmerückgewinnung
|
||||
float airWk = (achWindow + achVent * 0.25f) * RoomVolume / 3600f * 1210f;
|
||||
float loss = (180f + airWk) * (indoorTemp - outdoorTemp);
|
||||
indoorTemp += (pHeat + pPeople + pSun + pLight - loss) / 6.0e6f * h;
|
||||
}
|
||||
}
|
||||
|
||||
static float DbSum(params float[] levels)
|
||||
{
|
||||
float s = 0f;
|
||||
foreach (var l in levels) if (l > 0f) s += Mathf.Pow(10f, l / 10f);
|
||||
return s > 0f ? 10f * Mathf.Log10(s) : 0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Einstiegspunkt: baut den Raum, verdrahtet Simulation, Steuerlogik, Arduino-Anbindung, Kamera und HUD.
|
||||
/// Liegt in der Szene "Assets/Scenes/SmartRoom.unity" – wird aber auch in jeder anderen Szene
|
||||
/// automatisch erzeugt (siehe <see cref="SmartRoomBootstrap"/>).
|
||||
/// </summary>
|
||||
[DefaultExecutionOrder(-100)]
|
||||
public class SmartRoomApp : MonoBehaviour
|
||||
{
|
||||
public RoomDevices Devices { get; private set; }
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Devices = RoomBuilder.Build(transform);
|
||||
|
||||
var env = GetOrAdd<RoomEnvironment>();
|
||||
env.devices = Devices;
|
||||
Devices.env = env;
|
||||
|
||||
var bridge = GetOrAdd<ArduinoBridge>();
|
||||
bridge.env = env;
|
||||
bridge.devices = Devices;
|
||||
|
||||
var weather = GetOrAdd<WeatherService>();
|
||||
weather.env = env;
|
||||
|
||||
var controller = GetOrAdd<ClimateController>();
|
||||
controller.env = env;
|
||||
controller.devices = Devices;
|
||||
|
||||
Devices.sun = SetupSun();
|
||||
var orbit = SetupCamera();
|
||||
|
||||
var hud = GetOrAdd<SmartRoomHUD>();
|
||||
hud.env = env;
|
||||
hud.devices = Devices;
|
||||
hud.controller = controller;
|
||||
hud.bridge = bridge;
|
||||
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} %";
|
||||
|
||||
QualitySettings.pixelLightCount = Mathf.Max(QualitySettings.pixelLightCount, 8);
|
||||
}
|
||||
|
||||
T GetOrAdd<T>() where T : Component
|
||||
{
|
||||
var c = GetComponent<T>();
|
||||
return c != null ? c : gameObject.AddComponent<T>();
|
||||
}
|
||||
|
||||
static Light SetupSun()
|
||||
{
|
||||
Light sun = null;
|
||||
foreach (var l in Object.FindObjectsByType<Light>(FindObjectsSortMode.None))
|
||||
if (l.type == LightType.Directional) { sun = l; break; }
|
||||
if (sun == null)
|
||||
{
|
||||
sun = new GameObject("Sonne").AddComponent<Light>();
|
||||
sun.type = LightType.Directional;
|
||||
}
|
||||
// Sonne steht links (Fensterseite) und scheint schräg in den Raum
|
||||
sun.transform.rotation = Quaternion.Euler(35f, 100f, 0f);
|
||||
sun.shadows = LightShadows.Soft;
|
||||
sun.shadowStrength = 0.85f;
|
||||
RenderSettings.sun = sun;
|
||||
return sun;
|
||||
}
|
||||
|
||||
static OrbitCamera SetupCamera()
|
||||
{
|
||||
var cam = Camera.main;
|
||||
if (cam == null)
|
||||
{
|
||||
var go = new GameObject("Main Camera", typeof(Camera), typeof(AudioListener)) { tag = "MainCamera" };
|
||||
cam = go.GetComponent<Camera>();
|
||||
}
|
||||
cam.nearClipPlane = 0.05f;
|
||||
cam.fieldOfView = 60f;
|
||||
if (RenderSettings.skybox == null)
|
||||
{
|
||||
cam.clearFlags = CameraClearFlags.SolidColor;
|
||||
cam.backgroundColor = new Color(0.62f, 0.76f, 0.9f);
|
||||
}
|
||||
var orbit = cam.GetComponent<OrbitCamera>();
|
||||
return orbit != null ? orbit : cam.gameObject.AddComponent<OrbitCamera>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Sorgt dafür, dass beim Drücken von Play immer ein Raum entsteht – auch in einer leeren Szene.
|
||||
/// </summary>
|
||||
public static class SmartRoomBootstrap
|
||||
{
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
|
||||
static void Init()
|
||||
{
|
||||
if (Object.FindFirstObjectByType<SmartRoomApp>() != null) return;
|
||||
new GameObject("SmartRoom").AddComponent<SmartRoomApp>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// Orbit-Kamera im Raum. Eingaben kommen über IMGUI-Events vom HUD (funktioniert mit altem und neuem Input System).
|
||||
/// Linke Maustaste ziehen = drehen, rechte/mittlere Taste oder Shift = verschieben, Mausrad = Zoom, Klick auf Tür = öffnen.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(Camera))]
|
||||
public class OrbitCamera : MonoBehaviour
|
||||
{
|
||||
public Vector3 target = new Vector3(0f, 1.3f, 0.5f);
|
||||
public float yaw, pitch = 15f, distance = 8f;
|
||||
public float minDistance = 1.5f, maxDistance = 11f;
|
||||
|
||||
Vector3 goalTarget;
|
||||
float goalYaw, goalPitch, goalDistance;
|
||||
bool dragging;
|
||||
int dragButton;
|
||||
float dragMoved;
|
||||
Camera cam;
|
||||
|
||||
public bool IsDragging => dragging;
|
||||
|
||||
struct View
|
||||
{
|
||||
public Vector3 target; public float yaw, pitch, distance;
|
||||
public View(Vector3 t, float y, float p, float d) { target = t; yaw = y; pitch = p; distance = d; }
|
||||
}
|
||||
|
||||
static readonly View[] Presets =
|
||||
{
|
||||
new View(new Vector3(0f, 1.3f, 0.5f), 0f, 15f, 8f), // 1 Gesamtansicht
|
||||
new View(new Vector3(-5.5f, 1.7f, 0f), -90f, 8f, 6f), // 2 Fensterfront
|
||||
new View(new Vector3(-1.5f, 1.6f, 6.5f), 0f, 6f, 6.5f), // 3 Leinwand & Tür
|
||||
new View(new Vector3(0f, 3.0f, 0f), 35f, -20f, 5f), // 4 Decke & Lüftung
|
||||
};
|
||||
|
||||
void Awake()
|
||||
{
|
||||
cam = GetComponent<Camera>();
|
||||
goalTarget = target; goalYaw = yaw; goalPitch = pitch; goalDistance = distance;
|
||||
}
|
||||
|
||||
public void Preset(int i)
|
||||
{
|
||||
if (i < 0 || i >= Presets.Length) return;
|
||||
var v = Presets[i];
|
||||
goalTarget = v.target; goalYaw = v.yaw; goalPitch = v.pitch; goalDistance = v.distance;
|
||||
}
|
||||
|
||||
public void HandleEvent(Event e)
|
||||
{
|
||||
switch (e.type)
|
||||
{
|
||||
case EventType.MouseDown:
|
||||
dragging = true;
|
||||
dragButton = e.button;
|
||||
dragMoved = 0f;
|
||||
e.Use();
|
||||
break;
|
||||
case EventType.MouseDrag:
|
||||
if (!dragging) break;
|
||||
dragMoved += e.delta.magnitude;
|
||||
if (dragButton != 0 || e.shift)
|
||||
{
|
||||
float k = goalDistance * 0.0015f;
|
||||
goalTarget += (-transform.right * e.delta.x + transform.up * e.delta.y) * k;
|
||||
goalTarget = ClampInside(goalTarget, 0.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
goalYaw += e.delta.x * 0.25f;
|
||||
goalPitch = Mathf.Clamp(goalPitch + e.delta.y * 0.2f, -40f, 75f);
|
||||
}
|
||||
e.Use();
|
||||
break;
|
||||
case EventType.MouseUp:
|
||||
if (dragging && dragButton == 0 && dragMoved < 4f) Click(e.mousePosition);
|
||||
dragging = false;
|
||||
e.Use();
|
||||
break;
|
||||
case EventType.ScrollWheel:
|
||||
goalDistance = Mathf.Clamp(goalDistance * (1f + e.delta.y * 0.04f), minDistance, maxDistance);
|
||||
e.Use();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Click(Vector2 guiPos)
|
||||
{
|
||||
var ray = 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>();
|
||||
if (door != null) door.Toggle();
|
||||
}
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
float t = 1f - Mathf.Exp(-8f * Time.unscaledDeltaTime);
|
||||
target = Vector3.Lerp(target, goalTarget, t);
|
||||
yaw = Mathf.LerpAngle(yaw, goalYaw, t);
|
||||
pitch = Mathf.Lerp(pitch, goalPitch, t);
|
||||
distance = Mathf.Lerp(distance, goalDistance, t);
|
||||
|
||||
var rot = Quaternion.Euler(pitch, yaw, 0f);
|
||||
var pos = ClampInside(target + rot * new Vector3(0f, 0f, -distance), 0.2f);
|
||||
transform.position = pos;
|
||||
var look = target - pos;
|
||||
if (look.sqrMagnitude > 0.0001f) transform.rotation = Quaternion.LookRotation(look);
|
||||
}
|
||||
|
||||
static Vector3 ClampInside(Vector3 p, float margin)
|
||||
{
|
||||
const float w = RoomBuilder.W / 2f, d = RoomBuilder.D / 2f;
|
||||
return new Vector3(
|
||||
Mathf.Clamp(p.x, -w + margin, w - margin),
|
||||
Mathf.Clamp(p.y, 0.3f, RoomBuilder.H - 0.15f),
|
||||
Mathf.Clamp(p.z, -d + margin, d - margin));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,657 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using UnityEngine;
|
||||
|
||||
namespace SmartRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class SmartRoomHUD : MonoBehaviour
|
||||
{
|
||||
public RoomEnvironment env;
|
||||
public RoomDevices devices;
|
||||
public ClimateController controller;
|
||||
public ArduinoBridge bridge;
|
||||
public WeatherService weather;
|
||||
public OrbitCamera orbit;
|
||||
public bool visible = true;
|
||||
|
||||
static readonly Color Accent = new Color(0.20f, 0.74f, 0.78f);
|
||||
static readonly Color Good = new Color(0.35f, 0.82f, 0.55f);
|
||||
static readonly Color Warn = new Color(0.98f, 0.74f, 0.30f);
|
||||
static readonly Color Bad = new Color(0.95f, 0.40f, 0.38f);
|
||||
static readonly Color TextMain = new Color(0.93f, 0.95f, 0.97f);
|
||||
static readonly Color TextDim = new Color(0.60f, 0.65f, 0.70f);
|
||||
|
||||
float scale = -1f;
|
||||
GUIStyle panel, card, title, header, label, dim, valueRight, bigValue, button, seg, slider, thumb, field, tagStyle, bar, pill, logLine, logLineStrong;
|
||||
Texture2D texPanel, texCard, texBtn, texBtnHover, texBtnOn, texTrack, texThumb, texWhite, texField, texPill;
|
||||
|
||||
Rect leftRect, rightRect, bottomRect;
|
||||
bool showBottom, logCollapsed;
|
||||
Vector2 leftScroll, rightScroll, logScroll;
|
||||
int tab;
|
||||
string latField, lonField, udpField;
|
||||
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 };
|
||||
|
||||
float S(float v) => v * scale;
|
||||
int I(float v) => Mathf.RoundToInt(v * scale);
|
||||
|
||||
// ================================================================ OnGUI
|
||||
void OnGUI()
|
||||
{
|
||||
if (env == null || devices == null || controller == null) return;
|
||||
EnsureStyles();
|
||||
var e = Event.current;
|
||||
|
||||
if (e.type == EventType.KeyDown && GUIUtility.keyboardControl == 0) HandleKeys(e);
|
||||
|
||||
if (!visible)
|
||||
{
|
||||
GUI.Label(new Rect(S(16), Screen.height - S(36), S(400), S(24)), "H – Dashboard einblenden", dim);
|
||||
ForwardToCamera(e, false);
|
||||
return;
|
||||
}
|
||||
|
||||
float m = S(16);
|
||||
leftRect = new Rect(m, m, S(330), Screen.height - 2 * m);
|
||||
rightRect = new Rect(Screen.width - S(350) - m, m, S(350), Screen.height - 2 * m);
|
||||
float bw = Mathf.Min(S(760), rightRect.x - leftRect.xMax - 2 * m);
|
||||
float bh = logCollapsed ? S(46) : S(230);
|
||||
bottomRect = new Rect((leftRect.xMax + rightRect.x) / 2f - bw / 2f, Screen.height - bh - m, bw, bh);
|
||||
showBottom = bw > S(280);
|
||||
|
||||
DrawPanel(leftRect, ref leftScroll, DrawLeft);
|
||||
DrawPanel(rightRect, ref rightScroll, DrawRight);
|
||||
if (showBottom) DrawBottom();
|
||||
|
||||
bool over = leftRect.Contains(e.mousePosition) || rightRect.Contains(e.mousePosition) ||
|
||||
(showBottom && bottomRect.Contains(e.mousePosition));
|
||||
ForwardToCamera(e, over);
|
||||
}
|
||||
|
||||
void ForwardToCamera(Event e, bool overUi)
|
||||
{
|
||||
if (orbit == null || e.type == EventType.Used) return;
|
||||
bool relevant = e.isMouse || e.type == EventType.ScrollWheel;
|
||||
if (relevant && (!overUi || orbit.IsDragging)) orbit.HandleEvent(e);
|
||||
}
|
||||
|
||||
void HandleKeys(Event e)
|
||||
{
|
||||
switch (e.keyCode)
|
||||
{
|
||||
case KeyCode.H: visible = !visible; break;
|
||||
case KeyCode.Alpha1: orbit?.Preset(0); break;
|
||||
case KeyCode.Alpha2: orbit?.Preset(1); break;
|
||||
case KeyCode.Alpha3: orbit?.Preset(2); break;
|
||||
case KeyCode.Alpha4: orbit?.Preset(3); break;
|
||||
case KeyCode.T: devices.door?.Toggle(); break;
|
||||
case KeyCode.B: if (devices.projector != null) devices.projector.beamerOn = !devices.projector.beamerOn; break;
|
||||
case KeyCode.Space: controller.RunCycle(); break;
|
||||
default: return;
|
||||
}
|
||||
e.Use();
|
||||
}
|
||||
|
||||
void DrawPanel(Rect r, ref Vector2 scroll, Action content)
|
||||
{
|
||||
GUI.Box(r, GUIContent.none, panel);
|
||||
GUILayout.BeginArea(new Rect(r.x + S(16), r.y + S(14), r.width - S(32), r.height - S(28)));
|
||||
scroll = GUILayout.BeginScrollView(scroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
|
||||
content();
|
||||
GUILayout.EndScrollView();
|
||||
GUILayout.EndArea();
|
||||
}
|
||||
|
||||
// ================================================================ Links: Raumklima
|
||||
void DrawLeft()
|
||||
{
|
||||
GUILayout.Label("Smart Lecture Room", title);
|
||||
string src = env.AnyMeasured ? "Arduino live" : "Simulation";
|
||||
GUILayout.Label($"Digitaler Zwilling · {env.ClockText} · {src}", dim);
|
||||
|
||||
GUILayout.Space(S(8));
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Vorlesung läuft", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
env.lectureRunning = Switch(env.lectureRunning);
|
||||
GUILayout.EndHorizontal();
|
||||
|
||||
GUILayout.Space(S(4));
|
||||
GUILayout.Label("Zeitraffer (simulierte Minuten pro Sekunde)", dim);
|
||||
int speedIdx = Array.IndexOf(Speeds, env.timeScale);
|
||||
int newIdx = GUILayout.Toolbar(speedIdx, SpeedLabels, seg);
|
||||
if (newIdx != speedIdx && newIdx >= 0) env.timeScale = Speeds[newIdx];
|
||||
|
||||
Section("INNENRAUM");
|
||||
float t = env.indoorTemp, co2 = env.co2;
|
||||
Metric("Temperatur", $"{t:0.0} °C", Mathf.InverseLerp(10f, 35f, t),
|
||||
t >= controller.limits.tempLow && t <= controller.limits.tempHigh ? Good : (t >= 18f && t <= 27f ? Warn : Bad),
|
||||
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),
|
||||
env.indoorNoise < 55f ? Good : env.indoorNoise < 70f ? Warn : Bad, env.IsMeasured("noise"));
|
||||
|
||||
env.occupants = Mathf.RoundToInt(SliderRow("Personen im Raum", env.occupants, 0f, 120f, "{0:0}", !env.IsMeasured("persons")));
|
||||
if (!env.IsMeasured("t"))
|
||||
env.indoorTemp = SliderRow("Temperatur innen setzen", env.indoorTemp, 10f, 35f, "{0:0.0} °C");
|
||||
if (!env.IsMeasured("co2"))
|
||||
env.co2 = SliderRow("CO2 innen setzen", env.co2, 400f, 2500f, "{0:0} ppm");
|
||||
|
||||
Section(weather != null && weather.useLiveWeather ? "AUSSEN · OPEN-METEO" : "AUSSEN");
|
||||
env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C");
|
||||
env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}");
|
||||
env.outdoorNoise = SliderRow("Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB");
|
||||
env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s");
|
||||
env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²");
|
||||
|
||||
Section("SZENARIEN");
|
||||
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; },
|
||||
"Baustellenlärm", () => { env.co2 = 1350f; env.outdoorNoise = 82f; env.outdoorTemp = 15f; env.outdoorAqi = 25f; });
|
||||
ScenarioRow("Sturm", () => { env.co2 = 1300f; env.windSpeed = 16f; env.outdoorTemp = 12f; env.outdoorNoise = 55f; env.outdoorAqi = 25f; },
|
||||
"Wintermorgen", () => { env.indoorTemp = 17.5f; env.co2 = 600f; env.outdoorTemp = -3f; env.solar = 80f; env.windSpeed = 3f; });
|
||||
ScenarioRow("Pralle Sonne", () => { env.solar = 850f; env.outdoorTemp = 22f; },
|
||||
"Normalbetrieb", () =>
|
||||
{
|
||||
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.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 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(); }
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
// ================================================================ Rechts: Tabs
|
||||
void DrawRight()
|
||||
{
|
||||
tab = GUILayout.Toolbar(tab, Tabs, seg);
|
||||
GUILayout.Space(S(6));
|
||||
switch (tab)
|
||||
{
|
||||
case 0: DrawControl(); break;
|
||||
case 1: DrawWishes(); break;
|
||||
default: DrawConnection(); break;
|
||||
}
|
||||
}
|
||||
|
||||
void DrawControl()
|
||||
{
|
||||
Section("BETRIEBSART");
|
||||
int mode = GUILayout.Toolbar(controller.autoMode ? 0 : 1, new[] { "Automatik", "Manuell" }, seg);
|
||||
bool auto = mode == 0;
|
||||
if (auto != controller.autoMode)
|
||||
{
|
||||
controller.autoMode = auto;
|
||||
if (auto) controller.RunCycle();
|
||||
}
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(env.lectureRunning
|
||||
? $"Nächste Prüfung in {controller.MinutesUntilNextCheck:0} min (alle {controller.checkIntervalMinutes:0} min)"
|
||||
: "Keine Vorlesung – Steuerung pausiert", dim);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (GUILayout.Button("Jetzt prüfen", button, GUILayout.Width(S(110)))) controller.RunCycle();
|
||||
GUILayout.EndHorizontal();
|
||||
|
||||
Section("AKTOREN");
|
||||
bool manual = !controller.autoMode;
|
||||
|
||||
// Fenster
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Fenster (4×)", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label(devices.WindowLabel, valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
Bar(devices.WindowAirflow, Accent);
|
||||
if (manual)
|
||||
{
|
||||
int w = GUILayout.Toolbar((int)devices.WindowTarget, new[] { "Zu", "Kipp", "Auf" }, seg);
|
||||
if (w != (int)devices.WindowTarget) devices.SetWindows((WindowState)w);
|
||||
}
|
||||
GUILayout.EndVertical();
|
||||
|
||||
float v;
|
||||
v = DeviceRow("Jalousien", devices.BlindPosition > 0.5f ? "unten" : "oben", devices.BlindPosition, devices.BlindTarget, manual);
|
||||
if (manual && !Mathf.Approximately(v, devices.BlindTarget)) devices.SetBlinds(v);
|
||||
v = DeviceRow("Heizung", null, devices.HeatingLevel, devices.HeatingTarget, manual, new Color(1f, 0.55f, 0.35f));
|
||||
if (manual && !Mathf.Approximately(v, devices.HeatingTarget)) devices.SetHeating(v);
|
||||
v = DeviceRow("Lüftungsanlage", null, devices.VentLevel, devices.VentTarget, manual);
|
||||
if (manual && !Mathf.Approximately(v, devices.VentTarget)) devices.SetVentilation(v);
|
||||
v = DeviceRow("Licht", null, devices.LightLevel, devices.LightTarget, manual, new Color(1f, 0.9f, 0.6f));
|
||||
if (manual && !Mathf.Approximately(v, devices.LightTarget)) devices.SetLights(v);
|
||||
|
||||
Section("MEDIEN & ZUGANG");
|
||||
if (devices.projector != null)
|
||||
{
|
||||
GUILayout.BeginHorizontal(card);
|
||||
GUILayout.Label("Beamer + Leinwand", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
devices.projector.beamerOn = Switch(devices.projector.beamerOn);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
if (devices.door != null)
|
||||
{
|
||||
GUILayout.BeginHorizontal(card);
|
||||
GUILayout.Label("Tür offen", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
devices.door.open = Switch(devices.door.open);
|
||||
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);
|
||||
}
|
||||
|
||||
float DeviceRow(string name, string state, float current, float target, bool editable, Color? color = null)
|
||||
{
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(name, label);
|
||||
GUILayout.FlexibleSpace();
|
||||
string pct = $"{current * 100f:0} %";
|
||||
GUILayout.Label(state != null ? $"{state} · {pct}" : pct, valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
Bar(current, color ?? Accent);
|
||||
if (editable) target = GUILayout.HorizontalSlider(target, 0f, 1f, slider, thumb);
|
||||
GUILayout.EndVertical();
|
||||
return target;
|
||||
}
|
||||
|
||||
void DrawWishes()
|
||||
{
|
||||
Section("DEIN WUNSCH");
|
||||
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");
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Fenster öffnen gewünscht", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
own.windowOpen = Switch(own.windowOpen);
|
||||
GUILayout.EndHorizontal();
|
||||
|
||||
Section("ALLE EINGABEN");
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label($"Ø {controller.AverageWish:0.0} °C", bigValue);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label($"Fenster: {controller.WindowVotes} von {controller.wishes.Count} dafür", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.EndVertical();
|
||||
|
||||
for (int i = 1; i < controller.wishes.Count; i++)
|
||||
{
|
||||
var w = controller.wishes[i];
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(w.name, label);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label($"{w.temperature:0.0} °C · Fenster {(w.windowOpen ? "ja" : "nein")}", valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
GUILayout.Space(S(4));
|
||||
GUILayout.BeginHorizontal();
|
||||
if (GUILayout.Button("+ Teilnehmer", button))
|
||||
controller.wishes.Add(new UserWish($"Teilnehmer {controller.wishes.Count}",
|
||||
Mathf.Round(UnityEngine.Random.Range(19.5f, 24f) * 2f) / 2f, UnityEngine.Random.value < 0.35f));
|
||||
if (GUILayout.Button("– Teilnehmer", button) && controller.wishes.Count > 1)
|
||||
controller.wishes.RemoveAt(controller.wishes.Count - 1);
|
||||
GUILayout.EndHorizontal();
|
||||
if (GUILayout.Button("Wünsche jetzt anwenden", button)) controller.RunCycle();
|
||||
GUILayout.Label("Die Wünsche werden gemittelt (Aggregation) und fließen beim nächsten Prüfzyklus in Heizung und Fenstersteuerung ein.", dim);
|
||||
}
|
||||
|
||||
void DrawConnection()
|
||||
{
|
||||
Section("SENSORQUELLE");
|
||||
int m = GUILayout.Toolbar((int)bridge.mode, new[] { "Simulation", "Seriell", "UDP / WLAN" }, seg);
|
||||
if (m != (int)bridge.mode)
|
||||
{
|
||||
bridge.Disconnect();
|
||||
bridge.mode = (LinkMode)m;
|
||||
bridge.Disconnect(); // Status aktualisieren
|
||||
}
|
||||
|
||||
if (bridge.mode == LinkMode.Serial)
|
||||
{
|
||||
GUILayout.Label("Serieller Port", dim);
|
||||
bridge.serialPort = GUILayout.TextField(bridge.serialPort, field);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label($"Baudrate {bridge.baudRate}", dim);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (ArduinoBridge.SerialSupported && GUILayout.Button("Ports suchen", button, GUILayout.Width(S(110))))
|
||||
foundPorts = ArduinoBridge.ListSerialPorts();
|
||||
GUILayout.EndHorizontal();
|
||||
if (foundPorts != null)
|
||||
foreach (var p in foundPorts)
|
||||
if (GUILayout.Button(p, button)) bridge.serialPort = p;
|
||||
if (!ArduinoBridge.SerialSupported)
|
||||
GUILayout.Label("Hinweis: Für USB-Seriell in Unity unter Project Settings → Player → Api Compatibility Level \".NET Framework\" wählen. Alternativ UDP/WLAN nutzen.", dim);
|
||||
}
|
||||
else if (bridge.mode == LinkMode.Udp)
|
||||
{
|
||||
GUILayout.Label("Empfangsport (Antworten gehen an Port " + bridge.udpReplyPort + " des Absenders)", dim);
|
||||
if (udpField == null) udpField = bridge.udpListenPort.ToString();
|
||||
udpField = GUILayout.TextField(udpField, field);
|
||||
if (int.TryParse(udpField, out var port)) bridge.udpListenPort = port;
|
||||
}
|
||||
|
||||
if (bridge.mode != LinkMode.Simulation)
|
||||
{
|
||||
GUILayout.Space(S(4));
|
||||
if (GUILayout.Button(bridge.Connected ? "Trennen" : "Verbinden", button))
|
||||
{
|
||||
if (bridge.Connected) bridge.Disconnect(); else bridge.Connect();
|
||||
}
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Steuerbefehle senden", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bridge.sendCommands = Switch(bridge.sendCommands);
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
GUILayout.BeginVertical(card);
|
||||
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 (weather != null)
|
||||
{
|
||||
Section("WETTERDATEN (EXTERN)");
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Live-Wetter (Open-Meteo)", label);
|
||||
GUILayout.FlexibleSpace();
|
||||
bool live = Switch(weather.useLiveWeather);
|
||||
if (live != weather.useLiveWeather) weather.SetLive(live);
|
||||
GUILayout.EndHorizontal();
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
if (latField == null) latField = weather.latitude.ToString(ci);
|
||||
if (lonField == null) lonField = weather.longitude.ToString(ci);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("Breite", dim, GUILayout.Width(S(50)));
|
||||
latField = GUILayout.TextField(latField, field);
|
||||
GUILayout.Label("Länge", dim, GUILayout.Width(S(50)));
|
||||
lonField = GUILayout.TextField(lonField, field);
|
||||
GUILayout.EndHorizontal();
|
||||
if (float.TryParse(latField, NumberStyles.Float, ci, out var lat)) weather.latitude = lat;
|
||||
if (float.TryParse(lonField, NumberStyles.Float, ci, out var lon)) weather.longitude = lon;
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(weather.Status, dim);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (weather.useLiveWeather && GUILayout.Button("Aktualisieren", button, GUILayout.Width(S(110)))) weather.RefreshNow();
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// ================================================================ Unten: Entscheidungslogik
|
||||
void DrawBottom()
|
||||
{
|
||||
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)));
|
||||
var d = controller.Last;
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label("ENTSCHEIDUNGSLOGIK" + (d != null ? " · " + d.time : ""), header);
|
||||
GUILayout.FlexibleSpace();
|
||||
if (d != null)
|
||||
{
|
||||
Tag($"Fenster {d.window.Label()}", Accent);
|
||||
Tag($"Lüftung {d.ventilation * 100:0} %", Accent);
|
||||
Tag($"Heizung {d.heating * 100:0} %", new Color(1f, 0.55f, 0.35f));
|
||||
Tag(d.blinds > 0.5f ? "Jalousie ↓" : "Jalousie ↑", TextDim);
|
||||
}
|
||||
if (GUILayout.Button(logCollapsed ? "+" : "–", button, GUILayout.Width(S(30)))) logCollapsed = !logCollapsed;
|
||||
GUILayout.EndHorizontal();
|
||||
|
||||
if (!logCollapsed && d != null)
|
||||
{
|
||||
logScroll = GUILayout.BeginScrollView(logScroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
|
||||
for (int i = 0; i < d.path.Count; i++)
|
||||
{
|
||||
string line = d.path[i];
|
||||
GUILayout.Label($"{i + 1,2}. {line}", line.Contains("→") ? logLineStrong : logLine);
|
||||
}
|
||||
GUILayout.EndScrollView();
|
||||
}
|
||||
GUILayout.EndArea();
|
||||
}
|
||||
|
||||
// ================================================================ Bausteine
|
||||
void Section(string text)
|
||||
{
|
||||
GUILayout.Space(S(12));
|
||||
GUILayout.Label(text, header);
|
||||
}
|
||||
|
||||
void Metric(string name, string value, float norm, Color status, bool measured)
|
||||
{
|
||||
GUILayout.BeginVertical(card);
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(name, dim);
|
||||
GUILayout.FlexibleSpace();
|
||||
Tag(measured ? "SENSOR" : "SIM", measured ? Good : TextDim);
|
||||
GUILayout.EndHorizontal();
|
||||
GUILayout.Label(value, bigValue);
|
||||
Bar(norm, status);
|
||||
GUILayout.EndVertical();
|
||||
}
|
||||
|
||||
float SliderRow(string name, float v, float min, float max, string fmt, bool enabled = true)
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
GUILayout.Label(name, label);
|
||||
GUILayout.FlexibleSpace();
|
||||
GUILayout.Label(string.Format(fmt, v), valueRight);
|
||||
GUILayout.EndHorizontal();
|
||||
bool was = GUI.enabled;
|
||||
GUI.enabled = was && enabled;
|
||||
v = GUILayout.HorizontalSlider(v, min, max, slider, thumb);
|
||||
GUI.enabled = was;
|
||||
GUILayout.Space(S(2));
|
||||
return v;
|
||||
}
|
||||
|
||||
bool Switch(bool on)
|
||||
{
|
||||
Rect r = GUILayoutUtility.GetRect(S(40), S(22), GUILayout.Width(S(40)), GUILayout.Height(S(22)));
|
||||
if (GUI.Button(r, GUIContent.none, GUIStyle.none)) on = !on;
|
||||
if (Event.current.type == EventType.Repaint)
|
||||
{
|
||||
var old = GUI.color;
|
||||
GUI.color = on ? Accent : new Color(1f, 1f, 1f, 0.18f);
|
||||
pill.Draw(r, false, false, false, false);
|
||||
GUI.color = Color.white;
|
||||
float k = S(18);
|
||||
var knob = new Rect(on ? r.xMax - k - S(2) : r.x + S(2), r.y + (r.height - k) / 2f, k, k);
|
||||
GUI.DrawTexture(knob, texThumb);
|
||||
GUI.color = old;
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
void Bar(float v, Color c)
|
||||
{
|
||||
Rect r = GUILayoutUtility.GetRect(S(10), S(6), GUILayout.ExpandWidth(true), GUILayout.Height(S(6)));
|
||||
if (Event.current.type != EventType.Repaint) return;
|
||||
var old = GUI.color;
|
||||
GUI.color = new Color(1f, 1f, 1f, 0.08f);
|
||||
bar.Draw(r, false, false, false, false);
|
||||
v = Mathf.Clamp01(v);
|
||||
if (v > 0.002f)
|
||||
{
|
||||
GUI.color = c;
|
||||
bar.Draw(new Rect(r.x, r.y, Mathf.Max(r.height, r.width * v), r.height), false, false, false, false);
|
||||
}
|
||||
GUI.color = old;
|
||||
}
|
||||
|
||||
void Tag(string text, Color c)
|
||||
{
|
||||
var bg = GUI.backgroundColor;
|
||||
var cc = GUI.contentColor;
|
||||
GUI.backgroundColor = new Color(c.r, c.g, c.b, 0.22f);
|
||||
GUI.contentColor = c;
|
||||
GUILayout.Label(text, tagStyle);
|
||||
GUI.backgroundColor = bg;
|
||||
GUI.contentColor = cc;
|
||||
}
|
||||
|
||||
// ================================================================ Styles
|
||||
void EnsureStyles()
|
||||
{
|
||||
float s = Mathf.Clamp(Screen.height / 1000f, 0.8f, 2.2f);
|
||||
if (panel != null && Mathf.Approximately(s, scale)) return;
|
||||
scale = s;
|
||||
DestroyTextures();
|
||||
|
||||
texPanel = Rounded(I(14), new Color(0.07f, 0.08f, 0.10f, 0.88f));
|
||||
texCard = Rounded(I(10), new Color(1f, 1f, 1f, 0.045f));
|
||||
texBtn = Rounded(I(7), new Color(1f, 1f, 1f, 0.07f));
|
||||
texBtnHover = Rounded(I(7), new Color(1f, 1f, 1f, 0.13f));
|
||||
texBtnOn = Rounded(I(7), new Color(Accent.r, Accent.g, Accent.b, 0.85f));
|
||||
texField = Rounded(I(6), new Color(0f, 0f, 0f, 0.35f));
|
||||
texWhite = Rounded(I(3), Color.white);
|
||||
texPill = Rounded(I(11), Color.white);
|
||||
texThumb = Circle(I(16), Color.white);
|
||||
texTrack = Track(I(4), new Color(1f, 1f, 1f, 0.18f));
|
||||
|
||||
int fs = I(13);
|
||||
panel = Styled(texPanel, I(14), 0);
|
||||
card = Styled(texCard, I(10), 0);
|
||||
card.padding = new RectOffset(I(12), I(12), I(9), I(10));
|
||||
card.margin = new RectOffset(0, 0, I(3), I(5));
|
||||
|
||||
title = Text(I(19), TextMain, FontStyle.Bold);
|
||||
header = Text(I(11), TextDim, FontStyle.Bold);
|
||||
header.margin = new RectOffset(0, 0, I(2), I(4));
|
||||
label = Text(fs, TextMain);
|
||||
dim = Text(I(12), TextDim);
|
||||
dim.wordWrap = true;
|
||||
valueRight = Text(fs, TextMain, FontStyle.Bold);
|
||||
valueRight.alignment = TextAnchor.MiddleRight;
|
||||
bigValue = Text(I(22), TextMain, FontStyle.Bold);
|
||||
logLine = Text(I(12), TextDim);
|
||||
logLine.wordWrap = true;
|
||||
logLineStrong = Text(I(12), TextMain);
|
||||
logLineStrong.wordWrap = true;
|
||||
|
||||
button = Styled(texBtn, I(7), fs);
|
||||
button.hover.background = texBtnHover;
|
||||
button.active.background = texBtnOn;
|
||||
button.onNormal.background = texBtnOn;
|
||||
button.onHover.background = texBtnOn;
|
||||
button.onActive.background = texBtnOn;
|
||||
foreach (var st in new[] { button.normal, button.hover, button.active, button.onNormal, button.onHover, button.onActive })
|
||||
st.textColor = TextMain;
|
||||
button.alignment = TextAnchor.MiddleCenter;
|
||||
button.padding = new RectOffset(I(10), I(10), I(6), I(6));
|
||||
button.margin = new RectOffset(I(2), I(2), I(2), I(2));
|
||||
seg = new GUIStyle(button) { fontStyle = FontStyle.Bold };
|
||||
|
||||
slider = new GUIStyle { normal = { background = texTrack }, border = new RectOffset(I(4), I(4), 0, 0), fixedHeight = S(18), margin = new RectOffset(I(2), I(2), I(2), I(4)) };
|
||||
thumb = new GUIStyle { normal = { background = texThumb }, hover = { background = texThumb }, active = { background = texThumb }, fixedWidth = S(16), fixedHeight = S(16), margin = new RectOffset(0, 0, I(1), 0) };
|
||||
|
||||
field = Styled(texField, I(6), fs);
|
||||
field.normal.textColor = field.focused.textColor = field.hover.textColor = TextMain;
|
||||
field.focused.background = texField;
|
||||
field.hover.background = texField;
|
||||
field.padding = new RectOffset(I(8), I(8), I(5), I(5));
|
||||
field.margin = new RectOffset(I(2), I(2), I(2), I(4));
|
||||
field.alignment = TextAnchor.MiddleLeft;
|
||||
field.clipping = TextClipping.Clip;
|
||||
|
||||
tagStyle = Styled(texWhite, I(3), I(10));
|
||||
tagStyle.normal.textColor = Color.white;
|
||||
tagStyle.fontStyle = FontStyle.Bold;
|
||||
tagStyle.padding = new RectOffset(I(6), I(6), I(2), I(2));
|
||||
tagStyle.margin = new RectOffset(I(3), I(3), I(3), I(3));
|
||||
tagStyle.alignment = TextAnchor.MiddleCenter;
|
||||
|
||||
bar = Styled(texWhite, I(3), 0);
|
||||
pill = Styled(texPill, I(11), 0);
|
||||
}
|
||||
|
||||
static GUIStyle Styled(Texture2D bg, int border, int fontSize)
|
||||
=> new GUIStyle { normal = { background = bg }, border = new RectOffset(border, border, border, border), fontSize = fontSize };
|
||||
|
||||
static GUIStyle Text(int size, Color c, FontStyle style = FontStyle.Normal)
|
||||
=> new GUIStyle { fontSize = size, fontStyle = style, normal = { textColor = c }, margin = new RectOffset(0, 0, 2, 2), padding = new RectOffset(0, 0, 1, 1), alignment = TextAnchor.MiddleLeft };
|
||||
|
||||
static Texture2D NewTex(int w, int h)
|
||||
=> new Texture2D(w, h, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, hideFlags = HideFlags.HideAndDontSave };
|
||||
|
||||
/// <summary>Abgerundetes Rechteck mit weichen Kanten (für 9-Slice, border = r).</summary>
|
||||
static Texture2D Rounded(int r, Color c)
|
||||
{
|
||||
r = Mathf.Max(r, 1);
|
||||
int n = 2 * r + 4;
|
||||
var t = NewTex(n, n);
|
||||
var px = new Color[n * n];
|
||||
for (int y = 0; y < n; y++)
|
||||
for (int x = 0; x < n; x++)
|
||||
{
|
||||
var p = new Vector2(x + 0.5f, y + 0.5f);
|
||||
var q = new Vector2(Mathf.Clamp(p.x, r, n - r), Mathf.Clamp(p.y, r, n - r));
|
||||
float a = Mathf.Clamp01(r - Vector2.Distance(p, q) + 0.5f);
|
||||
px[y * n + x] = new Color(c.r, c.g, c.b, c.a * a);
|
||||
}
|
||||
t.SetPixels(px);
|
||||
t.Apply();
|
||||
return t;
|
||||
}
|
||||
|
||||
static Texture2D Circle(int r, Color c) => Rounded(r, c);
|
||||
|
||||
/// <summary>Horizontale Schiene, vertikal zentriert in einer höheren Textur (Slider-Hintergrund).</summary>
|
||||
static Texture2D Track(int thickness, Color c)
|
||||
{
|
||||
int w = 16, h = Mathf.Max(16, thickness * 4);
|
||||
var t = NewTex(w, h);
|
||||
var px = new Color[w * h];
|
||||
float mid = h / 2f;
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
float a = Mathf.Clamp01(thickness / 2f - Mathf.Abs(y + 0.5f - mid) + 0.5f);
|
||||
px[y * w + x] = new Color(c.r, c.g, c.b, c.a * a);
|
||||
}
|
||||
t.SetPixels(px);
|
||||
t.Apply();
|
||||
return t;
|
||||
}
|
||||
|
||||
void DestroyTextures()
|
||||
{
|
||||
foreach (var t in new[] { texPanel, texCard, texBtn, texBtnHover, texBtnOn, texTrack, texThumb, texWhite, texField, texPill })
|
||||
if (t != null) Destroy(t);
|
||||
}
|
||||
|
||||
void OnDestroy() => DestroyTextures();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"dependencies": {
|
||||
"com.unity.modules.audio": "1.0.0",
|
||||
"com.unity.modules.imageconversion": "1.0.0",
|
||||
"com.unity.modules.imgui": "1.0.0",
|
||||
"com.unity.modules.jsonserialize": "1.0.0",
|
||||
"com.unity.modules.particlesystem": "1.0.0",
|
||||
"com.unity.modules.physics": "1.0.0",
|
||||
"com.unity.modules.ui": "1.0.0",
|
||||
"com.unity.modules.uielements": "1.0.0",
|
||||
"com.unity.modules.unitywebrequest": "1.0.0"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
m_EditorVersion: 6000.0.40f1
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
# Smart Lecture Room – Unity-Zwilling
|
||||
|
||||
Ein 3D-Vorlesungsraum als digitaler Zwilling für ein Smart-Home-Projekt. Er steuert Fenster, Außenjalousien, Heizkörper, Lüftungsanlage, Licht, Beamer/Leinwand und Tür, und alles ist animiert. Die Steuerlogik folgt den beiden Diagrammen (Aktivitäts- und Architekturdiagramm). Sensordaten kommen wahlweise aus der eingebauten Simulation oder später vom Arduino.
|
||||
|
||||
## Starten
|
||||
|
||||
1. **Unity Hub → Add → Add project from disk** und den Ordner `SmartRoomUnity` 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. **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.
|
||||
|
||||
## Bedienung
|
||||
|
||||
| Eingabe | Wirkung |
|
||||
|---|---|
|
||||
| Linke Maus ziehen | Kamera drehen |
|
||||
| Rechte/mittlere Maus oder Shift + ziehen | Kamera verschieben |
|
||||
| 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) |
|
||||
| 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.
|
||||
|
||||
## Logik (Aktivitätsdiagramm → `ClimateController.cs`)
|
||||
|
||||
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. 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 (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 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)
|
||||
|
||||
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}
|
||||
```
|
||||
|
||||
Unity sendet die Steuerbefehle zurück, sobald sie sich ändern:
|
||||
|
||||
```json
|
||||
{"window":"open","blind":1.00,"heat":0.50,"vent":0.80,"light":0.40,"beamer":0}
|
||||
```
|
||||
|
||||
- **USB-Seriell:** Sketch `Arduino/SmartRoomSensor/SmartRoomSensor.ino` flashen. In Unity unter **Project Settings → Player → Api Compatibility Level** die Option **.NET Framework** wählen, sonst steht `System.IO.Ports` nicht zur Verfügung. Danach im Dashboard **Verbindung → Seriell** öffnen, den Port eintragen oder „Ports suchen“ und dann „Verbinden“.
|
||||
- **WLAN/UDP (ESP32):** Pakete an Port **5005** des Unity-Rechners senden. Die Antworten kommen auf Port **5006**. Dafür ist keine Projekteinstellung nötig.
|
||||
- **Ohne Hardware testen:**
|
||||
```bash
|
||||
python3 Tools/fake_arduino.py --heat
|
||||
```
|
||||
Dann im Dashboard auf UDP stellen und verbinden. Die Temperatur steigt auf 30 °C und das Fenster öffnet sich.
|
||||
|
||||
**Externe Daten:** Unter **Verbindung → Live-Wetter** holt das Projekt Außentemperatur, Wind, Sonneneinstrahlung und Luftqualität von Open-Meteo (kostenlos, ohne API-Key). Die Koordinaten stehen auf Berlin und lassen sich anpassen.
|
||||
|
||||
## Struktur
|
||||
|
||||
```
|
||||
Assets/SmartRoom/Scripts
|
||||
SmartRoomApp.cs Einstieg, verdrahtet alles
|
||||
Room/RoomBuilder.cs prozeduraler Raum (Maße, Fenster, Tür, Möbel …)
|
||||
Room/RoomDevices.cs zentrale Aktor-Schnittstelle + Lichtstimmung
|
||||
Actuators/* Animationen: Fenster (Dreh-Kipp), Jalousie, Heizung, Lüftung, Licht, Beamer, Tür
|
||||
Simulation/RoomEnvironment.cs Raumklima-Modell (CO2, Wärme, Licht, Lärm) + Messwertübernahme
|
||||
Control/ClimateController.cs Entscheidungslogik
|
||||
IO/ArduinoBridge.cs Seriell/UDP, JSON-Protokoll
|
||||
IO/WeatherService.cs Open-Meteo
|
||||
UI/SmartRoomHUD.cs, UI/OrbitCamera.cs
|
||||
```
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simuliert einen Arduino/ESP32 per UDP – zum Testen ohne Hardware.
|
||||
|
||||
1. In Unity: Dashboard → Verbindung → "UDP / WLAN" → Verbinden (Port 5005)
|
||||
2. python3 Tools/fake_arduino.py (normaler Verlauf)
|
||||
python3 Tools/fake_arduino.py --heat (Temperatur steigt auf 30 °C -> Fenster öffnet)
|
||||
python3 Tools/fake_arduino.py --co2 (CO2 steigt über 1000 ppm)
|
||||
|
||||
Empfangene Steuerbefehle von Unity werden ausgegeben.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=5005)
|
||||
parser.add_argument("--reply-port", type=int, default=5006)
|
||||
parser.add_argument("--heat", action="store_true", help="Temperatur langsam auf 30 °C steigen lassen")
|
||||
parser.add_argument("--co2", action="store_true", help="CO2 langsam über den Grenzwert steigen lassen")
|
||||
args = parser.parse_args()
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.bind(("0.0.0.0", args.reply_port))
|
||||
sock.settimeout(0.1)
|
||||
|
||||
temp, co2 = 22.0, 650.0
|
||||
print(f"Sende an {args.host}:{args.port}, empfange Befehle auf Port {args.reply_port} (Strg+C beendet)")
|
||||
try:
|
||||
while True:
|
||||
if args.heat:
|
||||
temp = min(30.5, temp + 0.4)
|
||||
if args.co2:
|
||||
co2 = min(1800.0, co2 + 40)
|
||||
packet = {
|
||||
"t": round(temp + random.uniform(-0.1, 0.1), 1),
|
||||
"co2": round(co2 + random.uniform(-15, 15)),
|
||||
"lux": round(random.uniform(330, 370)),
|
||||
"noise": round(random.uniform(42, 48)),
|
||||
}
|
||||
sock.sendto((json.dumps(packet) + "\n").encode(), (args.host, args.port))
|
||||
print("→", packet)
|
||||
end = time.time() + 2
|
||||
while time.time() < end:
|
||||
try:
|
||||
data, _ = sock.recvfrom(1024)
|
||||
print(" ← Unity:", data.decode().strip())
|
||||
except socket.timeout:
|
||||
pass
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
Loading…
Reference in New Issue