436 lines
20 KiB
C#
436 lines
20 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;
|
||
}
|
||
}
|
||
|
||
/// <summary>Grenzwerte wie GRENZWERTE in backend/logik.js, damit Ersatzlogik 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 (nur ohne Lichtsensor)")] public float sunLimit = 500f;
|
||
[Tooltip("% – Lichtsensor: darüber zu hell (Jalousie runter)")] public float brightPercent = 80f;
|
||
[Tooltip("% – Lichtsensor: darunter zu dunkel (Licht heller)")] public float darkPercent = 30f;
|
||
[Tooltip("°C – draußen zu kalt zum Lüften per Fenster")] public float outdoorColdLimit = 5f;
|
||
[Tooltip("European AQI – Außenluft schlecht")] public float outdoorAqiLimit = 60f;
|
||
[Tooltip("lx – Zielbeleuchtung")] public float targetLux = 500f;
|
||
[Tooltip("°C – Eingabebereich eines einzelnen Wunschs (Ausreißer werden begrenzt)")] public float wishMin = 18f, wishMax = 26f;
|
||
}
|
||
|
||
/// <summary>Ergebnis eines Prüfzyklus inkl. durchlaufenem Pfad im Aktivitätsdiagramm.</summary>
|
||
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>
|
||
/// Steuerung des Raums. Im Normalfall entscheidet das gemeinsame Backend (backend/logik.js) und Unity führt
|
||
/// nur aus (<see cref="ApplyRemote"/>). Ohne Backend oder im Modus „Simulation“ entscheidet diese Ersatzlogik
|
||
/// nach denselben Regeln (Aktivitätsdiagramm): CO2 → Lüftung, Lärm sperrt das Fenster außer auf Mehrheitswunsch,
|
||
/// Wind max. gekippt, Beamer → Licht aus und Jalousie unten, manuelle Einstellungen haben Vorrang (90 min).
|
||
/// </summary>
|
||
public class ClimateController : MonoBehaviour
|
||
{
|
||
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 Decision Last { get; private set; }
|
||
public event Action<Decision> Decided;
|
||
|
||
double nextCheckAt = double.NegativeInfinity;
|
||
double manualSince;
|
||
bool wasCritical, wasRunning = true, wasAuto = true;
|
||
string lastScenario;
|
||
|
||
public const string NormalScenario = "Normalbetrieb";
|
||
|
||
/// <summary>Erkanntes Szenario (aus Sensor- bzw. Simulationswerten), Namen wie die Szenario-Knöpfe im HUD.</summary>
|
||
public string Scenario { get; private set; } = NormalScenario;
|
||
|
||
public float MinutesUntilNextCheck => Mathf.Max(0f, (float)(nextCheckAt - env.simMinutes));
|
||
public float ManualMinutesLeft => autoMode ? 0f : Mathf.Max(0f, (float)(manualSince + manualMinutes - env.simMinutes));
|
||
|
||
/// <summary>Zielwert = Ø-Wunschtemperatur, begrenzt auf den zulässigen Bereich.</summary>
|
||
public float TargetTemp => Mathf.Clamp(AverageWish, limits.tempLow, limits.tempHigh);
|
||
|
||
/// <summary>Ø aller Temperaturwünsche; jeder Wunsch wird vorher auf den Eingabebereich begrenzt (wie im Backend).</summary>
|
||
public float AverageWish
|
||
{
|
||
get
|
||
{
|
||
if (wishes.Count == 0) return 22f;
|
||
float s = 0f;
|
||
foreach (var w in wishes) s += Mathf.Clamp(w.temperature, limits.wishMin, limits.wishMax);
|
||
return s / wishes.Count;
|
||
}
|
||
}
|
||
|
||
/// <summary>Anzahl der Wünsche außerhalb des Eingabebereichs.</summary>
|
||
public int ClampedWishes => wishes.FindAll(w => w.temperature < limits.wishMin || w.temperature > limits.wishMax).Count;
|
||
|
||
public int WindowVotes => wishes.FindAll(w => w.windowOpen).Count;
|
||
public bool WindowWanted => wishes.Count > 0 && WindowVotes * 2 > wishes.Count;
|
||
|
||
// ---------------------------------------------------------------- Jalousie von Hand (Simulation)
|
||
double blindOverrideUntil = double.NegativeInfinity;
|
||
float blindOverride;
|
||
|
||
public bool BlindOverrideActive => env != null && env.simMinutes < blindOverrideUntil;
|
||
public float BlindOverrideMinutesLeft => BlindOverrideActive ? (float)(blindOverrideUntil - env.simMinutes) : 0f;
|
||
|
||
/// <summary>Jalousien von Hand fahren; die Automatik übernimmt nach <paramref name="minutes"/> simulierten Minuten wieder.</summary>
|
||
public void OverrideBlinds(float position, float minutes = 30f)
|
||
{
|
||
blindOverride = Mathf.Clamp01(position);
|
||
blindOverrideUntil = env.simMinutes + minutes;
|
||
devices.SetBlinds(blindOverride);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Gemeinsames Backend
|
||
float remoteUntil = -1f;
|
||
CentralCommand lastRemote;
|
||
string lastRemoteStatus;
|
||
|
||
/// <summary>Das Backend entscheidet gerade (Unity führt nur aus, die Ersatzlogik ruht).</summary>
|
||
public bool RemoteActive => Time.unscaledTime < remoteUntil;
|
||
|
||
/// <summary>Entscheidung des Backends ausführen (GET /api/unity, ca. jede Sekunde).</summary>
|
||
public void ApplyRemote(CentralState s)
|
||
{
|
||
remoteUntil = Time.unscaledTime + 5f;
|
||
var c = s.steuerung ?? new CentralCommand();
|
||
bool changed = lastRemote == null || lastRemote.window != c.window || !Same(lastRemote.blind, c.blind) ||
|
||
!Same(lastRemote.heat, c.heat) || !Same(lastRemote.vent, c.vent) || !Same(lastRemote.light, c.light) ||
|
||
lastRemote.beamer != c.beamer || lastRemoteStatus != s.status;
|
||
lastRemote = c;
|
||
lastRemoteStatus = s.status;
|
||
|
||
var d = new Decision
|
||
{
|
||
time = env.ClockText,
|
||
scenario = s.status,
|
||
window = c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed,
|
||
blinds = c.blind, heating = c.heat, ventilation = c.vent, lights = c.light,
|
||
};
|
||
d.path.Add($"Backend: {s.status} (Priorität {s.prioritaetNummer}: {s.prioritaet})");
|
||
if (s.pfad != null) d.path.AddRange(s.pfad);
|
||
if (s.vetos != null && s.vetos.laerm) d.path.Add("Lärmsensor: Außenlärm über dem Grenzwert → Fenster gesperrt");
|
||
Apply(d);
|
||
if (devices.projector != null) devices.projector.beamerOn = c.beamer == 1;
|
||
d.path.Add("Unity führt nur aus: virtuelle Aktoren angesteuert");
|
||
Last = d;
|
||
if (changed) Decided?.Invoke(d);
|
||
}
|
||
|
||
/// <summary>Zurück zur Ersatzlogik (Umschalter „Simulation“), sofort neu prüfen.</summary>
|
||
public void ReleaseRemote()
|
||
{
|
||
remoteUntil = -1f;
|
||
lastRemote = null;
|
||
lastRemoteStatus = null;
|
||
nextCheckAt = double.NegativeInfinity;
|
||
}
|
||
|
||
static bool Same(float a, float b) => Mathf.Abs(a - b) < 0.005f;
|
||
|
||
// ---------------------------------------------------------------- Ersatzlogik
|
||
void Update()
|
||
{
|
||
if (env == null || devices == null) return;
|
||
if (RemoteActive)
|
||
{
|
||
Scenario = DetectScenario(); // nur zur Anzeige, entschieden wird im Backend
|
||
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);
|
||
|
||
// Szenarien werden aus den Messwerten erkannt: Kommt ein neues hinzu, wird sofort geprüft
|
||
Scenario = DetectScenario();
|
||
float target = TargetTemp;
|
||
bool critical = env.co2 > limits.co2Limit || env.indoorTemp > target + limits.coolAbove || env.indoorTemp < target - limits.heatBelow;
|
||
bool newScenario = Scenario != lastScenario && Scenario != NormalScenario;
|
||
if (env.simMinutes >= nextCheckAt || (reactImmediately && ((critical && !wasCritical) || newScenario)))
|
||
RunCycle();
|
||
wasCritical = critical;
|
||
lastScenario = Scenario;
|
||
}
|
||
|
||
/// <summary>Ordnet die aktuellen Werte einem Szenario zu (Anzeige und Demo-Knöpfe). Reihenfolge = Priorität.</summary>
|
||
public string DetectScenario()
|
||
{
|
||
var L = limits;
|
||
float target = TargetTemp;
|
||
bool co2High = env.co2 > L.co2Limit;
|
||
bool ventNeeded = co2High || env.indoorTemp > target + L.coolAbove;
|
||
if (ventNeeded && env.outdoorAqi > L.outdoorAqiLimit) return "Schlechte Außenluft";
|
||
if (ventNeeded && env.outdoorTemp < L.outdoorColdLimit) return "Stickig + kalt";
|
||
if (ventNeeded && env.outdoorNoise > L.noiseLimit) return "Baustellenlärm";
|
||
if (ventNeeded && env.windSpeed > L.windLimit) return "Sturm";
|
||
if (co2High) return "Stickige Luft";
|
||
if (env.indoorTemp > target + L.coolAbove) return "Hitze";
|
||
if (env.indoorTemp < target - L.heatBelow) return "Wintermorgen";
|
||
if (env.solar > L.sunLimit) return "Pralle Sonne";
|
||
return NormalScenario;
|
||
}
|
||
|
||
/// <summary>Einen kompletten Prüfzyklus der Ersatzlogik ausführen (auch per HUD "Jetzt prüfen").</summary>
|
||
public void RunCycle()
|
||
{
|
||
if (RemoteActive) 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, scenario = DetectScenario() };
|
||
var p = d.path;
|
||
float t = env.indoorTemp, co2 = env.co2;
|
||
float target = TargetTemp;
|
||
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: Ziel {target:0.0} °C (Ø {AverageWish:0.0} °C), Fenster {(wantWindow ? "gewünscht" : "nicht gewünscht")} ({WindowVotes}/{wishes.Count})");
|
||
if (ClampedWishes > 0)
|
||
p.Add($"Temperaturwunsch begrenzt: {ClampedWishes} Wunsch außerhalb {L.wishMin:0}–{L.wishMax:0} °C");
|
||
|
||
// --- CO2 / Temperatur
|
||
bool co2High = co2 > L.co2Limit;
|
||
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 / Helligkeit → Jalousie und Licht (wie im Backend: Lichtsensor vor Sonnenstand)
|
||
bool lightSensor = env.IsMeasured("lightpct");
|
||
bool tooBright = lightSensor ? env.lightPercent > L.brightPercent : env.solar > L.sunLimit;
|
||
bool tooDark = lightSensor && env.lightPercent < L.darkPercent;
|
||
if (devices.BeamerOn)
|
||
{
|
||
d.blinds = 1f;
|
||
d.lights = 0f;
|
||
p.Add("Beamermodus aktiv → Lichter aus, Jalousie nach unten");
|
||
}
|
||
else if (tooBright)
|
||
{
|
||
d.blinds = 1f;
|
||
d.lights = lightSensor ? 0.6f : Mathf.Clamp01((L.targetLux - env.DaylightLux(1f)) / 520f);
|
||
p.Add(lightSensor
|
||
? $"Lichtsensor {env.lightPercent:0} % > {L.brightPercent:0} % → zu hell, Jalousie unten, Licht an"
|
||
: $"Sonneneinstrahlung zu hoch ({env.solar:0} W/m²) → Lichter an ({d.lights * 100:0} %), Jalousie nach unten");
|
||
}
|
||
else
|
||
{
|
||
d.blinds = 0f;
|
||
d.lights = lightSensor ? (tooDark ? 0.8f : 0.4f) : Mathf.Clamp01((L.targetLux - env.DaylightLux(0f)) / 520f);
|
||
p.Add(tooDark
|
||
? $"Lichtsensor {env.lightPercent:0} % < {L.darkPercent:0} % → zu dunkel, Licht heller"
|
||
: $"Helligkeit ok → Jalousie nach oben, Licht {d.lights * 100:0} %");
|
||
}
|
||
if (BlindOverrideActive)
|
||
{
|
||
d.blinds = blindOverride;
|
||
p.Add($"Jalousien manuell auf {blindOverride * 100:0} % (Automatik pausiert, noch {BlindOverrideMinutesLeft:0} min)");
|
||
}
|
||
return d;
|
||
}
|
||
|
||
string SourceText()
|
||
{
|
||
var measured = new List<string>();
|
||
if (env.IsMeasured("t")) measured.Add("Temperatur");
|
||
if (env.IsMeasured("co2")) measured.Add("CO2");
|
||
if (env.IsMeasured("lightpct")) measured.Add("Licht");
|
||
if (env.IsMeasured("noise")) measured.Add("Lärm innen");
|
||
if (env.IsMeasured("nout")) measured.Add("Außenlärm");
|
||
return measured.Count == 0 ? "Simulation" : "Arduino: " + string.Join(", ", measured);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Schutzregeln, die auch manuelle Einstellungen nicht aufheben (wie im Backend):
|
||
/// bei Sturm höchstens gekippt, bei zu hohem CO2 läuft die Lüftungsanlage, solange das Fenster nicht offen ist.
|
||
/// </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);
|
||
}
|
||
}
|
||
}
|