using System;
using System.Collections.Generic;
using UnityEngine;
namespace SmartRoom
{
///
/// Umgebungszustand des Raums (innen + außen) mit einem einfachen physikalischen Modell.
/// Werte, die vom Arduino gemessen werden, überschreiben das Modell, solange Messungen eintreffen.
///
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)
[Tooltip("Nur gemessen (DHT11), wird nicht simuliert")]
public float indoorHumidity = 45f; // %
[Tooltip("Nur gemessen (CCS811), wird nicht simuliert")]
public float tvoc = 0f; // ppb
[Tooltip("Nur gemessen (Fotowiderstand), relativ 0–100 %")]
public float lightPercent = 0f;
[Header("Außen (Wetterdaten / Sensoren / manuell)")]
public float outdoorTemp = 14f; // °C
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 = 25f; // Station sendet ca. alle 7–8 s, fällt eine Sendung aus ca. alle 15 s
public RoomDevices devices;
readonly Dictionary measuredAt = new Dictionary(); // echter Sensorwert
readonly Dictionary providedAt = new Dictionary(); // von außen vorgegeben (Sensor, Wetter, Demo)
public string ClockText
{
get
{
var t = TimeSpan.FromMinutes(simMinutes % 1440.0);
return $"{t.Hours:00}:{t.Minutes:00} Uhr";
}
}
// Beispielwerte beim Start (Umschalter "Simulation" stellt sie wieder her)
float[] example;
void Awake()
{
example = new[] { indoorTemp, co2, indoorLux, indoorNoise, indoorHumidity, tvoc, lightPercent,
outdoorTemp, outdoorAqi, outdoorNoise, windSpeed, solar, occupants };
}
/// Zurück zu den Beispielwerten der Simulation; alle Arduino-/Backend-Werte werden verworfen.
public void ResetToExampleValues()
{
measuredAt.Clear();
providedAt.Clear();
if (example == null) return;
indoorTemp = example[0]; co2 = example[1]; indoorLux = example[2]; indoorNoise = example[3];
indoorHumidity = example[4]; tvoc = example[5]; lightPercent = example[6];
outdoorTemp = example[7]; outdoorAqi = example[8]; outdoorNoise = example[9];
windSpeed = example[10]; solar = example[11]; occupants = Mathf.RoundToInt(example[12]);
}
public bool IsMeasured(string channel)
=> measuredAt.TryGetValue(channel, out var t) && Time.unscaledTime - t < measurementTimeout;
/// Wert kommt von außen (Arduino oder zentrales Backend) und wird nicht simuliert.
public bool IsProvided(string channel)
=> providedAt.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;
}
}
/// Übernimmt ein Datenpaket vom Arduino. Fehlende Felder (NaN) werden ignoriert.
public void ApplyMeasurement(SensorPacket p) => Apply(p, _ => true);
///
/// Übernimmt Werte des zentralen Backends. Alle gesendeten Werte ersetzen die Simulation,
/// als "Sensor" gelten aber nur die, für die true liefert (nicht Wetter/Demo).
///
public void ApplyRemote(SensorPacket p, Func isSensor) => Apply(p, isSensor);
void Apply(SensorPacket p, Func isSensor)
{
void Set(string channel, float v, Action apply)
{
if (float.IsNaN(v)) return;
apply(v);
providedAt[channel] = Time.unscaledTime;
if (isSensor(channel)) measuredAt[channel] = Time.unscaledTime;
else measuredAt.Remove(channel);
}
Set("t", p.t, v => indoorTemp = v);
Set("co2", p.co2, v => co2 = v);
Set("lux", p.lux, v => indoorLux = v);
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));
Set("rh", p.rh, v => indoorHumidity = v);
Set("tvoc", p.tvoc, v => tvoc = v);
Set("lightpct", p.lightpct, v => lightPercent = v);
}
/// Kanal sofort wieder simulieren (z. B. wenn das Mikrofon von innen nach außen wechselt).
public void Forget(string channel)
{
measuredAt.Remove(channel);
providedAt.Remove(channel);
}
/// Geschätzte Tageslicht-Beleuchtungsstärke im Raum bei gegebener Jalousie-Abschirmung.
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 (!IsProvided("lux"))
indoorLux = DaylightLux(devices.BlindClosure) + devices.LightLevel * 520f;
if (!IsProvided("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 (!IsProvided("co2"))
{
float gen = persons * 0.0083f; // ppm/s pro Person (~0,005 l/s CO2)
co2 += (gen - (achWindow + achVent) / 3600f * (co2 - OutdoorCo2)) * h;
co2 = Mathf.Max(OutdoorCo2, co2);
}
if (!IsProvided("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;
}
}
}