GruppeC/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/Control/ClimateController.cs

316 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
}
}
/// <summary>Grenzwerte wie GRENZWERTE in backend/logik.js, damit Fallback und Backend gleich entscheiden.</summary>
[Serializable]
public class ClimateThresholds
{
[Tooltip("ppm")] public float co2Limit = 1000f;
[Tooltip("°C – zulässiger Bereich für die Ø-Wunschtemperatur")] public float tempLow = 20f, tempHigh = 24f;
[Tooltip("°C – unter Ziel minus diesem Wert wird geheizt")] public float heatBelow = 0.5f;
[Tooltip("°C – über Ziel plus diesem Wert wird gelüftet")] public float coolAbove = 1f;
[Tooltip("dB(A) – extremer Außenlärm")] public float noiseLimit = 70f;
[Tooltip("m/s – extremer Wind (60 km/h)")] public float windLimit = 16.7f;
[Tooltip("W/m² – Sonneneinstrahlung zu hoch")] public float sunLimit = 500f;
[Tooltip("°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.
/// Ist das gemeinsame Backend verbunden, entscheidet dieses und die lokale Logik ruht (nur Fallback ohne Backend).
/// Die Regeln entsprechen backend/logik.js: Lärm sperrt das Fenster außer auf Mehrheitswunsch, Wind max. gekippt,
/// Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang, gelten 90 min, CO2 hält die Lüftung an.
/// </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;
[Tooltip("Manuelle Einstellungen werden nach so vielen simulierten Minuten gelöscht")]
public float manualMinutes = 90f;
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 BackendLink backend;
/// <summary>true, solange das Backend entscheidet.</summary>
public bool External => backend != null && backend.Connected;
public Decision Last { get; private set; }
public event Action<Decision> Decided;
double nextCheckAt = double.NegativeInfinity;
double manualSince;
bool wasCritical, wasRunning = true, wasAuto = true;
public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes));
public float ManualMinutesLeft => autoMode ? 0f : Mathf.Max(0f, (float)(manualSince + manualMinutes - env.simMinutes));
/// <summary>Zielwert = Ø-Wunschtemperatur, begrenzt auf den zulässigen Bereich.</summary>
public float TargetTemp => Mathf.Clamp(AverageWish, limits.tempLow, limits.tempHigh);
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 (External)
{
nextCheckAt = double.NegativeInfinity; // fällt das Backend aus, sofort selbst prüfen
return;
}
if (!env.lectureRunning)
{
if (wasRunning) EnterIdle();
wasRunning = false;
return;
}
if (!wasRunning) nextCheckAt = double.NegativeInfinity; // Vorlesung beginnt -> sofort prüfen
wasRunning = true;
// Manuelle Einstellungen: Beginn merken, nach 90 min löschen, Schutzregeln laufend durchsetzen
if (wasAuto && !autoMode) manualSince = env.simMinutes;
wasAuto = autoMode;
if (!autoMode && env.simMinutes - manualSince >= manualMinutes)
{
autoMode = wasAuto = true;
nextCheckAt = double.NegativeInfinity;
}
if (!autoMode) EnforceSafety(null);
float target = TargetTemp;
bool critical = env.co2 > limits.co2Limit || env.indoorTemp > target + limits.coolAbove || env.indoorTemp < target - limits.heatBelow;
if (env.simMinutes >= nextCheckAt || (reactImmediately && critical && !wasCritical))
RunCycle();
wasCritical = critical;
}
/// <summary>Einen kompletten Prüfzyklus ausführen (auch per HUD "Jetzt prüfen").</summary>
public void RunCycle()
{
if (External) return;
var d = Evaluate();
if (autoMode)
{
Apply(d);
d.path.Add("Unity-Simulation: virtuelle Aktoren angesteuert");
}
else
{
d.path.Add($"Manuelle Einstellungen gespeichert → haben Vorrang (noch {ManualMinutesLeft:0} min)");
EnforceSafety(d);
}
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 target = TargetTemp;
bool wantWindow = WindowWanted;
p.Add($"Sensordaten: {t:0.0} °C, CO2 {co2:0} ppm, {env.indoorLux:0} lx");
p.Add($"Nutzerwünsche: Ziel {target:0.0} °C (Ø {AverageWish:0.0} °C), Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})");
// --- CO2 / Temperatur
bool co2High = co2 > L.co2Limit;
bool ventilationNeeded = false;
if (co2High)
{
p.Add($"CO2-Grenzwert überschritten ({co2:0} > {L.co2Limit:0} ppm) → Lüftung erforderlich");
ventilationNeeded = true;
}
else if (t > target + L.coolAbove && env.outdoorTemp < t)
{
p.Add($"T_innen {t:0.0} °C > Ziel {target:0.0} °C → Lüftung erforderlich");
ventilationNeeded = true;
}
else if (t < target - L.heatBelow) p.Add($"T_innen {t:0.0} °C < Ziel {target:0.0} °C → heizen");
else p.Add($"T_innen ≈ Ziel {target:0.0} °C → Komfortbereich");
// --- Lüftung / Fenstersollzustand
bool noise = env.outdoorNoise > L.noiseLimit;
bool storm = env.windSpeed > L.windLimit;
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.ventilation = 1f;
}
else if (noise)
{
p.Add($"Extremer Außenlärm ({env.outdoorNoise:0} dB) → Fensteröffnung sperren");
if (wantWindow)
{
p.Add("Fensteröffnung von der Mehrheit gewünscht → Fenstersollzustand: offen");
d.window = WindowState.Open;
}
else
{
p.Add("Keine Fensteröffnung gewünscht → Lüftungsanlage, Fenster geschlossen");
d.ventilation = 1f;
}
}
else d.window = WindowState.Open;
}
else if (wantWindow)
{
p.Add("Fensteröffnung von der Mehrheit gewünscht → Fenstersollzustand: offen");
d.window = WindowState.Open;
}
else p.Add("Keine Fensteröffnung gewünscht → Fenstersollzustand: geschlossen");
if (storm && d.window == WindowState.Open)
{
p.Add($"Starker Wind ({env.windSpeed:0.0} m/s) → Fenstersollzustand: gekippt");
d.window = WindowState.Tilted;
if (ventilationNeeded) d.ventilation = co2High ? 1f : 0.5f;
}
if (co2High && d.window != WindowState.Open && d.ventilation < 1f) d.ventilation = 1f;
// --- Heizung (Ziel = Ø Wunschtemperatur), bei offenem Fenster aus
if (t < target - L.heatBelow)
{
if (d.window == WindowState.Open) p.Add("Fenster offen → Heizung aus (Energie sparen)");
else
{
d.heating = Mathf.Clamp((target - t) / 3f, 0.2f, 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");
// --- Beamer / Sonne → Jalousie und Licht
if (devices.BeamerOn)
{
d.blinds = 1f;
d.lights = 0f;
p.Add("Beamermodus aktiv → Lichter aus, Jalousie nach unten");
}
else if (env.solar > L.sunLimit)
{
d.blinds = 1f;
d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f);
p.Add($"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten");
}
else
{
d.blinds = 0f;
d.lights = Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f);
p.Add($"Sonneneinstrahlung ok ({env.solar:0} W/m²) → Jalousie nach oben, Licht {d.lights * 100:0} %");
}
return d;
}
/// <summary>
/// Schutzregeln, die auch manuelle Einstellungen nicht aufheben (wie im Backend):
/// bei Sturm höchstens gekippt, bei zu hohem CO2 läuft die Lüftungsanlage, solange das Fenster nicht offen ist.
/// </summary>
void EnforceSafety(Decision d)
{
if (env.windSpeed > limits.windLimit && devices.WindowTarget == WindowState.Open)
{
devices.SetWindows(WindowState.Tilted);
d?.path.Add("Starker Wind → Fenster trotz manueller Einstellung nur gekippt");
}
if (env.co2 > limits.co2Limit && devices.WindowTarget != WindowState.Open && devices.VentTarget < 1f)
{
devices.SetVentilation(1f);
d?.path.Add("CO2 über Grenzwert → alternative Lüftung bleibt an");
}
}
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 → gespeicherte Einstellungen löschen, Raum im Energiesparmodus");
autoMode = wasAuto = true;
Apply(d); // alles aus, Fenster zu, Jalousie oben
d.path.Add("Fenster geschlossen, Heizung/Lüftung/Licht aus");
Last = d;
Decided?.Invoke(d);
}
}
}