GruppeC/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs

907 lines
45 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.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.
/// Ist das gemeinsame Backend verbunden, zeigt das HUD dessen Zustand und schickt Eingaben dorthin
/// (dieselben Endpunkte wie das Webinterface) – Website und Zwilling zeigen dann immer dasselbe.
/// </summary>
public class SmartRoomHUD : MonoBehaviour
{
public RoomEnvironment env;
public RoomDevices devices;
public ClimateController controller;
public ArduinoBridge bridge;
public BackendLink backend;
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, urlField;
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 };
static readonly string[] TempVotes = { "kuehler", "angenehm", "waermer" };
static readonly string[] TempVoteLabels = { "Kühler", "Angenehm", "Wärmer" };
static readonly string[] LightVotes = { "dunkler", "passt", "heller" };
static readonly string[] LightVoteLabels = { "Dunkler", "Passt", "Heller" };
static readonly int[] LectureMinutes = { 30, 60, 90 };
static readonly string[] WindowVotes = { "auf", "zu" };
static readonly string[] WindowVoteLabels = { "Auf", "Zu lassen" };
// Manuelle Einstellungen: Index 0 = Automatik, Werte als JSON für /api/manuell
static readonly string[] ManualWindowCodes = { "", "closed", "tilted", "open" };
static readonly string[] ManualWindowLabels = { "Auto", "Zu", "Kipp", "Auf" };
static readonly int[] ManualPercent = { -1, 0, 50, 100 };
static readonly string[] ManualBlindLabels = { "Auto", "Oben", "Halb", "Unten" };
static readonly string[] ManualLightLabels = { "Auto", "Aus", "50 %", "100 %" };
static readonly string[] ManualVentLabels = { "Auto", "Aus", "An" };
/// <summary>Backend verbunden: Es entscheidet, das HUD zeigt nur an und leitet Eingaben weiter.</summary>
bool Shared => backend != null && backend.Connected && backend.State != null;
BackendState B => backend.State;
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 (Shared) backend.SetLecture(!B.vortrag.aktiv); // Beamer folgt dem Vortragsmodus des Backends
else 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 = Shared ? "gemeinsames Backend"
: bridge.mode == LinkMode.Backend ? "Backend getrennt, lokale Logik"
: 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");
// Werte vom Backend/Arduino lassen sich nicht verschieben (würden sofort wieder überschrieben)
env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C", !env.IsMeasured("tout"));
env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}", !env.IsMeasured("aq"));
env.outdoorNoise = SliderRow("Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsMeasured("nout"));
env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s", !env.IsMeasured("wind"));
env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²", !env.IsMeasured("sun"));
Section("SZENARIEN");
if (Shared)
{
DrawBackendScenarios();
return;
}
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 DrawBackendScenarios()
{
var list = B.szenarien;
for (int i = 0; i < list.Length; i += 2)
{
GUILayout.BeginHorizontal();
for (int k = i; k < Mathf.Min(i + 2, list.Length); k++)
{
var sc = list[k];
bool on = sc.id == B.szenario;
if (GUILayout.Toggle(on, sc.text, button) && !on) backend.ChooseScenario(sc.id);
}
GUILayout.EndHorizontal();
}
GUILayout.Label("Szenarien des Backends gelten auch im Webinterface. „Live“ nutzt nur echte Sensordaten und Stimmen.", 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 Vortragsmodus · 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()
{
if (Shared)
{
DrawBackendControl();
return;
}
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);
else GUILayout.Label($"Manuelle Einstellungen gelten noch {controller.ManualMinutesLeft:0} min. Bei Sturm öffnet das Fenster höchstens gekippt, bei zu hohem CO₂ läuft die Lüftungsanlage weiter.", dim);
}
void DrawBackendControl()
{
Section("BETRIEBSART");
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label(B.status, label);
GUILayout.FlexibleSpace();
Tag(B.prioritaet.ToUpperInvariant(), Accent);
GUILayout.EndHorizontal();
GUILayout.Label(B.detail, dim);
GUILayout.EndVertical();
GUILayout.Label($"Das Backend entscheidet für Webinterface und Zwilling. Zielwert {B.zielTemperatur:0.0} °C.", dim);
Section("AKTOREN");
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label("Fenster (4×)", label);
GUILayout.FlexibleSpace();
GUILayout.Label(devices.WindowLabel, valueRight);
GUILayout.EndHorizontal();
Bar(devices.WindowAirflow, Accent);
GUILayout.EndVertical();
DeviceRow("Jalousien", devices.BlindPosition > 0.5f ? "unten" : "oben", devices.BlindPosition, devices.BlindTarget, false);
DeviceRow("Heizung", null, devices.HeatingLevel, devices.HeatingTarget, false, new Color(1f, 0.55f, 0.35f));
DeviceRow("Lüftungsanlage", null, devices.VentLevel, devices.VentTarget, false);
DeviceRow("Licht", null, devices.LightLevel, devices.LightTarget, false, new Color(1f, 0.9f, 0.6f));
Section("DOZENT");
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label("Vortragsmodus (Beamer, Jalousie zu)", label);
GUILayout.FlexibleSpace();
bool lecture = Switch(B.vortrag.aktiv);
GUILayout.EndHorizontal();
if (lecture != B.vortrag.aktiv) backend.SetLecture(lecture);
int di = Array.IndexOf(LectureMinutes, B.vortrag.dauerMinuten);
int ndi = GUILayout.Toolbar(di, new[] { "30 min", "60 min", "90 min" }, seg);
if (ndi != di && ndi >= 0) backend.SetLectureDuration(LectureMinutes[ndi]);
if (B.vortrag.aktiv) GUILayout.Label($"Noch {B.vortrag.restMinuten} min", dim);
GUILayout.EndVertical();
var m = B.manuell;
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label("Manuelle Einstellungen", label);
GUILayout.FlexibleSpace();
if (m.aktiv && GUILayout.Button("Automatik", button, GUILayout.Width(S(90)))) backend.ResetManual();
GUILayout.EndHorizontal();
GUILayout.Label("Fenster", dim);
int wi = Mathf.Max(0, Array.IndexOf(ManualWindowCodes, m.fenster));
int nwi = GUILayout.Toolbar(wi, ManualWindowLabels, seg);
if (nwi != wi) backend.SetManual("fenster", nwi == 0 ? "\"auto\"" : $"\"{ManualWindowCodes[nwi]}\"");
ManualPercentRow("Jalousie", "jalousie", m.jalousie, ManualBlindLabels);
ManualPercentRow("Licht", "licht", m.licht, ManualLightLabels);
GUILayout.Label("Lüftungsanlage", dim);
int vi = m.lueftung + 1; // -1 Auto, 0 aus, 1 an
int nvi = GUILayout.Toolbar(vi, ManualVentLabels, seg);
if (nvi != vi) backend.SetManual("lueftung", nvi == 0 ? "\"auto\"" : nvi == 1 ? "\"aus\"" : "\"an\"");
GUILayout.Label(m.aktiv ? $"Manuell bis {m.bis} (90 min), dann wieder Automatik." : "Manuelle Werte haben Vorrang und gelten 90 min.", dim);
GUILayout.EndVertical();
if (devices.door != null)
{
Section("ZUGANG");
GUILayout.BeginHorizontal(card);
GUILayout.Label("Tür offen (nur im Zwilling)", label);
GUILayout.FlexibleSpace();
devices.door.open = Switch(devices.door.open);
GUILayout.EndHorizontal();
}
GUILayout.Label("Schutzregeln bleiben: Bei zu hohem CO₂ läuft die Lüftungsanlage weiter, bei Sturm öffnen die Fenster höchstens gekippt.", dim);
}
void ManualPercentRow(string title, string field, int current, string[] labels)
{
GUILayout.Label(title, dim);
int i = Mathf.Max(0, Array.IndexOf(ManualPercent, current));
int ni = GUILayout.Toolbar(i, labels, seg);
if (ni != i) backend.SetManual(field, ni == 0 ? "\"auto\"" : ManualPercent[ni].ToString());
}
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()
{
if (Shared)
{
DrawBackendWishes();
return;
}
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 DrawBackendWishes()
{
var v = B.stimmen;
Section("DEINE STIMME");
GUILayout.Label("Temperatur", dim);
int ti = Array.IndexOf(TempVotes, v.eigeneTemperatur);
int nti = GUILayout.Toolbar(ti, TempVoteLabels, seg);
if (nti != ti && nti >= 0) backend.VoteTemperature(TempVotes[nti]);
GUILayout.Label("Licht", dim);
int li = Array.IndexOf(LightVotes, v.eigeneLicht);
int nli = GUILayout.Toolbar(li, LightVoteLabels, seg);
if (nli != li && nli >= 0) backend.VoteLight(LightVotes[nli]);
GUILayout.Label("Fenster öffnen?", dim);
int fi = Array.IndexOf(WindowVotes, v.eigeneFenster);
int nfi = GUILayout.Toolbar(fi, WindowVoteLabels, seg);
if (nfi != fi && nfi >= 0) backend.VoteWindow(WindowVotes[nfi]);
GUILayout.Label("Eine Stimme pro Gerät, wie im Webinterface. Sie verfällt nach 30 min.", dim);
Section("ALLE EINGABEN");
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label($"Ziel {B.zielTemperatur:0.0} °C", bigValue);
GUILayout.FlexibleSpace();
GUILayout.Label($"{v.gesamt} Stimmen", valueRight);
GUILayout.EndHorizontal();
GUILayout.EndVertical();
VoteRow("Kühler", v.kuehler);
VoteRow("Angenehm", v.angenehm);
VoteRow("Wärmer", v.waermer);
GUILayout.Space(S(4));
VoteRow("Licht dunkler", v.dunkler);
VoteRow("Licht passt", v.passt);
VoteRow("Licht heller", v.heller);
GUILayout.Space(S(4));
VoteRow("Fenster auf", v.auf);
VoteRow("Fenster zu lassen", v.zu);
GUILayout.Label("Temperatur und Licht: Durchschnitt aller Stimmen aus Webinterface und Zwilling. Fenster: Mehrheit, bei Außenlärm öffnet es nur auf Wunsch. Gegen den CO₂-Grenzwert kommen Stimmen nicht an.", dim);
}
void VoteRow(string name, int count)
{
GUILayout.BeginHorizontal();
GUILayout.Label(name, label);
GUILayout.FlexibleSpace();
GUILayout.Label(count.ToString(), valueRight);
GUILayout.EndHorizontal();
}
void DrawConnection()
{
Section("SENSORQUELLE");
int m = GUILayout.Toolbar((int)bridge.mode, new[] { "Simulation", "Seriell", "UDP", "Backend" }, 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;
}
else if (bridge.mode == LinkMode.Backend && backend != null)
{
GUILayout.Label("Server-URL des gemeinsamen Backends (backend/server.js)", dim);
if (urlField == null) urlField = backend.serverUrl;
urlField = GUILayout.TextField(urlField, field);
backend.serverUrl = urlField.Trim();
GUILayout.Label("Anderer Laptop im Hotspot: http://<Laptop-IP>:3000. Nach Änderung neu verbinden.", dim);
}
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();
}
if (bridge.mode != LinkMode.Backend)
{
GUILayout.BeginHorizontal();
GUILayout.Label("Steuerbefehle senden", label);
GUILayout.FlexibleSpace();
bridge.sendCommands = Switch(bridge.sendCommands);
GUILayout.EndHorizontal();
}
}
GUILayout.BeginVertical(card);
if (bridge.mode == LinkMode.Backend && backend != null)
{
GUILayout.BeginHorizontal();
Tag(backend.Connected ? "VERBUNDEN" : backend.Active ? "KEINE ANTWORT" : "GETRENNT", backend.Connected ? Good : Warn);
GUILayout.FlexibleSpace();
if (backend.LastPacketTime >= 0f)
GUILayout.Label($"{backend.PacketCount} Abfragen · vor {Time.unscaledTime - backend.LastPacketTime:0} s", valueRight);
GUILayout.EndHorizontal();
GUILayout.Label(backend.Status, dim);
GUILayout.Label("Kennung: " + backend.ClientId, dim);
}
else
{
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 (Shared)
{
Section("WETTERDATEN (EXTERN)");
GUILayout.Label("Kommen vom Backend (Open-Meteo, Mannheim), damit Webinterface und Zwilling dieselben Werte nutzen.", dim);
}
else 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)));
if (Shared)
{
DrawBackendDecision();
GUILayout.EndArea();
return;
}
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();
}
void DrawBackendDecision()
{
var c = B.steuerung;
GUILayout.BeginHorizontal();
GUILayout.Label("ENTSCHEIDUNG BACKEND · " + B.prioritaet, header);
GUILayout.FlexibleSpace();
Tag($"Fenster {devices.WindowTarget.Label()}", Accent);
Tag($"Lüftung {c.vent * 100:0} %", Accent);
Tag($"Heizung {c.heat * 100:0} %", new Color(1f, 0.55f, 0.35f));
Tag($"Jalousie {c.blind * 100:0} %", TextDim);
if (GUILayout.Button(logCollapsed ? "+" : "–", button, GUILayout.Width(S(30)))) logCollapsed = !logCollapsed;
GUILayout.EndHorizontal();
if (logCollapsed) return;
logScroll = GUILayout.BeginScrollView(logScroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
GUILayout.Label(B.status, logLineStrong);
GUILayout.Label(B.detail, logLine);
for (int i = 0; i < B.pfad.Length; i++)
GUILayout.Label($"{i + 1,2}. {B.pfad[i]}", B.pfad[i].Contains("→") ? logLineStrong : logLine);
GUILayout.EndScrollView();
}
// ================================================================ 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 ? (Shared ? "BACKEND" : "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();
}
}