354 lines
16 KiB
C#
354 lines
16 KiB
C#
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;
|
||
[Tooltip("°C – zulässiger Bereich für Temperaturwünsche (Ausreißer werden begrenzt)")] public float wishMin = 18f, wishMax = 26f;
|
||
}
|
||
|
||
/// <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 string scenario;
|
||
public bool applied;
|
||
public readonly List<string> path = new List<string>();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Automatische Steuerentscheidung nach dem Aktivitätsdiagramm:
|
||
/// Datenerfassung → Aggregation (Nutzerwünsche) → CO2/Temperatur → Lüftung/Fenster → Heizung
|
||
/// → Soll/Ist-Abgleich Fenster → Jalousie → Licht → virtuelle Aktoren ansteuern → nach 10 min erneut prüfen.
|
||
/// </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, wasMeasured;
|
||
string lastScenario;
|
||
|
||
public const string NormalScenario = "Normalbetrieb";
|
||
|
||
/// <summary>Aktuell erkanntes Szenario (aus Sensor- bzw. Simulationswerten), Namen wie die Szenario-Knöpfe im HUD.</summary>
|
||
public string Scenario { get; private set; } = NormalScenario;
|
||
|
||
public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes));
|
||
|
||
/// <summary>Ø aller Temperaturwünsche; jeder Wunsch wird vorher auf den zulässigen Bereich begrenzt.</summary>
|
||
public float AverageWish
|
||
{
|
||
get
|
||
{
|
||
if (wishes.Count == 0) return 22f;
|
||
float s = 0f;
|
||
foreach (var w in wishes) s += Mathf.Clamp(w.temperature, limits.wishMin, limits.wishMax);
|
||
return s / wishes.Count;
|
||
}
|
||
}
|
||
|
||
/// <summary>Anzahl der Wünsche außerhalb des zulässigen Bereichs.</summary>
|
||
public int ClampedWishes => wishes.FindAll(w => w.temperature < limits.wishMin || w.temperature > limits.wishMax).Count;
|
||
|
||
// Manuelle Jalousiesteuerung pausiert die Jalousie-Automatik für eine Weile (Schutzregeln bleiben aktiv)
|
||
double blindOverrideUntil = double.NegativeInfinity;
|
||
float blindOverride;
|
||
|
||
public bool BlindOverrideActive => env != null && env.simMinutes < blindOverrideUntil;
|
||
public float BlindOverrideMinutesLeft => BlindOverrideActive ? (float)(blindOverrideUntil - env.simMinutes) : 0f;
|
||
|
||
/// <summary>Jalousien von Hand fahren; die Automatik übernimmt nach <paramref name="minutes"/> simulierten Minuten wieder.</summary>
|
||
public void OverrideBlinds(float position, float minutes = 30f)
|
||
{
|
||
blindOverride = Mathf.Clamp01(position);
|
||
blindOverrideUntil = env.simMinutes + minutes;
|
||
devices.SetBlinds(blindOverride);
|
||
}
|
||
|
||
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;
|
||
|
||
// Szenarien werden aus den Messwerten erkannt: Kommt ein neues Szenario hinzu (z. B. Arduino meldet
|
||
// CO2 > 1000 ppm) oder liefert der Arduino erstmals Werte, wird sofort geprüft statt erst nach 10 min.
|
||
Scenario = DetectScenario();
|
||
bool critical = env.co2 > limits.co2Limit || env.indoorTemp > limits.tempHigh || env.indoorTemp < limits.tempLow;
|
||
bool newScenario = Scenario != lastScenario && Scenario != NormalScenario;
|
||
bool measured = env.AnyMeasured;
|
||
if (env.simMinutes >= nextCheckAt ||
|
||
(reactImmediately && ((critical && !wasCritical) || newScenario || (measured && !wasMeasured))))
|
||
RunCycle();
|
||
wasCritical = critical;
|
||
wasMeasured = measured;
|
||
lastScenario = Scenario;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Ordnet die aktuellen Werte einem Szenario zu. Reihenfolge = Priorität (Lüftungsbedarf zuerst, dann Temperatur, dann Sonne).
|
||
/// </summary>
|
||
public string DetectScenario()
|
||
{
|
||
var L = limits;
|
||
bool co2High = env.co2 > L.co2Limit;
|
||
bool ventNeeded = co2High || env.indoorTemp > L.tempHigh;
|
||
if (ventNeeded && env.outdoorAqi > L.outdoorAqiLimit) return "Schlechte Außenluft";
|
||
if (ventNeeded && env.outdoorTemp < L.outdoorColdLimit) return "Stickig + kalt";
|
||
if (ventNeeded && env.outdoorNoise > L.noiseLimit) return "Baustellenlärm";
|
||
if (ventNeeded && env.windSpeed > L.windLimit) return "Sturm";
|
||
if (co2High) return "Stickige Luft";
|
||
if (env.indoorTemp > L.tempHigh) return "Hitze";
|
||
if (env.indoorTemp < L.tempLow) return "Wintermorgen";
|
||
if (env.solar > L.sunLimit) return "Pralle Sonne";
|
||
return NormalScenario;
|
||
}
|
||
|
||
/// <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, scenario = DetectScenario() };
|
||
var p = d.path;
|
||
float t = env.indoorTemp, co2 = env.co2;
|
||
float avgWish = AverageWish;
|
||
bool wantWindow = WindowWanted;
|
||
|
||
p.Add($"Sensordaten ({SourceText()}): {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx");
|
||
p.Add($"Erkanntes Szenario: {d.scenario}");
|
||
p.Add($"Nutzerwünsche: Ø {avgWish:0.0} °C, Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})");
|
||
if (ClampedWishes > 0)
|
||
p.Add($"Temperaturwunsch begrenzt: {ClampedWishes} Wunsch außerhalb {limits.wishMin:0}–{limits.wishMax:0} °C");
|
||
|
||
// --- CO2 / Temperatur
|
||
bool ventilationNeeded = false, heat = false;
|
||
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 (BlindOverrideActive)
|
||
{
|
||
d.blinds = blindOverride;
|
||
p.Add($"Jalousien manuell auf {blindOverride * 100:0} % (Automatik pausiert, noch {BlindOverrideMinutesLeft:0} min)");
|
||
}
|
||
else if (env.solar > L.sunLimit)
|
||
{
|
||
d.blinds = 1f;
|
||
p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Jalousie nach unten");
|
||
}
|
||
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)
|
||
// Mit Lichtsensor: gemessene Helligkeit minus eigenes Kunstlicht = Tageslicht, sonst Schätzung aus Sonne + Jalousie
|
||
bool luxMeasured = env.IsMeasured("lux");
|
||
float daylight = luxMeasured ? Mathf.Max(0f, env.indoorLux - devices.LightLevel * 520f) : env.DaylightLux(d.blinds);
|
||
d.lights = Mathf.Clamp01((L.targetLux - daylight) / 520f);
|
||
if (devices.BeamerOn) d.lights = Mathf.Min(d.lights, 0.3f);
|
||
p.Add($"Tageslicht ≈ {daylight:0} lx{(luxMeasured ? " (Lichtsensor)" : "")} → Licht {d.lights * 100:0} %{(devices.BeamerOn ? " (gedimmt für Beamer)" : "")}");
|
||
return d;
|
||
}
|
||
|
||
string SourceText()
|
||
{
|
||
var measured = new List<string>();
|
||
if (env.IsMeasured("t")) measured.Add("Temperatur");
|
||
if (env.IsMeasured("co2")) measured.Add("CO2");
|
||
if (env.IsMeasured("lux")) measured.Add("Licht");
|
||
if (env.IsMeasured("noise")) measured.Add("Lärm innen");
|
||
if (env.IsMeasured("nout")) measured.Add("Außenlärm");
|
||
return measured.Count == 0 ? "Simulation" : "Arduino: " + string.Join(", ", measured);
|
||
}
|
||
|
||
public void Apply(Decision d)
|
||
{
|
||
devices.SetWindows(d.window);
|
||
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);
|
||
}
|
||
}
|
||
}
|