GruppeC/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/IO/BackendLink.cs

196 lines
8.9 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;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace SmartRoom
{
// Antwort von GET /api/unity (backend/raum.js → unity()). Das Backend liefert keine null-Werte.
[Serializable] public class BackendCommand { public string window = "closed"; public float blind, heat, vent, light; public int beamer; }
[Serializable] public class BackendVotes
{
public int kuehler, angenehm, waermer, dunkler, passt, heller, auf, zu, gesamt;
public string eigeneTemperatur = "", eigeneLicht = "", eigeneFenster = "";
}
[Serializable] public class BackendLecture { public bool aktiv; public int restMinuten, dauerMinuten = 60; }
/// <summary>Manuelle Einstellungen des Dozenten: -1 bzw. "" = Automatik.</summary>
[Serializable] public class BackendManual
{
public bool aktiv;
public string fenster = "", bis = "";
public int jalousie = -1, licht = -1, lueftung = -1;
}
[Serializable] public class BackendScenario { public string id, text, beschreibung; }
[Serializable] public class BackendState
{
public string zeit, szenario, status, detail, prioritaet;
public SensorPacket sensor = new SensorPacket();
public string[] sensorFelder = new string[0];
public BackendCommand steuerung = new BackendCommand();
public string[] pfad = new string[0];
public float zielTemperatur = 22f;
public BackendVotes stimmen = new BackendVotes();
public BackendLecture vortrag = new BackendLecture();
public BackendManual manuell = new BackendManual();
public BackendScenario[] szenarien = new BackendScenario[0];
}
/// <summary>
/// Gemeinsames Backend (backend/server.js): Es entscheidet für Webinterface und Zwilling gleichermaßen.
/// Holt jede Sekunde GET /api/unity, übernimmt Sensorwerte und führt den Steuerbefehl nur aus.
/// Stimmen, Szenario, Vortragsmodus und Jalousie aus dem HUD gehen an dieselben Endpunkte wie beim Webinterface.
/// </summary>
public class BackendLink : MonoBehaviour
{
public string serverUrl = "http://localhost:3000";
[Tooltip("Abfrageintervall in Sekunden")] public float pollSeconds = 1f;
[Tooltip("So lange ohne Antwort gilt das Backend als getrennt; dann übernimmt die lokale Logik")]
public float timeoutSeconds = 5f;
public RoomEnvironment env;
public RoomDevices devices;
public bool Active { get; private set; }
public bool Connected => Active && LastPacketTime >= 0f && Time.unscaledTime - LastPacketTime < timeoutSeconds;
public string Status { get; private set; } = "aus";
public BackendState State { get; private set; }
public float LastPacketTime { get; private set; } = -1f;
public int PacketCount { get; private set; }
/// <summary>Eigene Kennung als "Client" – wie ein Browser im Webinterface, eine Stimme pro Zwilling.</summary>
public string ClientId { get; private set; }
Coroutine loop;
void Awake()
{
string id = SystemInfo.deviceUniqueIdentifier;
if (string.IsNullOrEmpty(id) || id == SystemInfo.unsupportedIdentifier) id = Guid.NewGuid().ToString("N");
ClientId = "unity-" + id.Substring(0, Mathf.Min(12, id.Length));
}
string Base => serverUrl.TrimEnd('/');
public void Begin()
{
End();
Active = true;
Status = "Verbinde mit " + Base + " …";
loop = StartCoroutine(Poll());
}
public void End()
{
if (loop != null) StopCoroutine(loop);
loop = null;
Active = false;
Status = "aus";
}
IEnumerator Poll()
{
while (Active)
{
using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId)))
{
req.timeout = 3;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text);
else Status = $"Backend nicht erreichbar ({req.error}) – lokale Logik aktiv";
}
yield return new WaitForSecondsRealtime(pollSeconds);
}
}
void Receive(string json)
{
BackendState s;
try { s = JsonUtility.FromJson<BackendState>(json); }
catch (Exception ex) { Status = "Ungültige Antwort: " + ex.Message; return; }
if (s == null) return;
// Nur Felder übernehmen, die das Backend wirklich kennt – der Rest bleibt simuliert
var p = new SensorPacket();
foreach (var f in s.sensorFelder)
{
switch (f)
{
case "t": p.t = s.sensor.t; break;
case "co2": p.co2 = s.sensor.co2; break;
case "lux": p.lux = s.sensor.lux; break;
case "noise": p.noise = s.sensor.noise; break;
case "tout": p.tout = s.sensor.tout; break;
case "aq": p.aq = s.sensor.aq; break;
case "nout": p.nout = s.sensor.nout; break;
case "wind": p.wind = s.sensor.wind; break;
case "sun": p.sun = s.sensor.sun; break;
case "persons": p.persons = s.sensor.persons; break;
}
}
env.ApplyMeasurement(p);
var c = s.steuerung;
devices.SetWindows(c.window == "open" ? WindowState.Open : c.window == "tilted" ? WindowState.Tilted : WindowState.Closed);
devices.SetBlinds(c.blind);
devices.SetHeating(c.heat);
devices.SetVentilation(c.vent);
devices.SetLights(c.light);
if (devices.projector != null) devices.projector.beamerOn = c.beamer != 0;
State = s;
LastPacketTime = Time.unscaledTime;
PacketCount++;
Status = $"Verbunden mit {Base} · Szenario {s.szenario}";
}
// ---------------------------------------------------------------- Eingaben ans Backend
// Werte wie im Webinterface: temperatur kuehler|angenehm|waermer, licht dunkler|passt|heller
public void VoteTemperature(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"temperatur\":\"{wert}\"}}");
public void VoteLight(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"licht\":\"{wert}\"}}");
/// <summary>auf | zu</summary>
public void VoteWindow(string wert) => Post("/api/stimme", $"{{\"client\":\"{ClientId}\",\"rolle\":\"studierende\",\"fenster\":\"{wert}\"}}");
public void ChooseScenario(string id) => Post("/api/szenario", $"{{\"id\":\"{id}\"}}");
public void SetLecture(bool aktiv) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"aktiv\":{(aktiv ? "true" : "false")}}}");
public void SetLectureDuration(int minuten) => Post("/api/vortragsmodus", $"{{\"rolle\":\"dozent\",\"dauerMinuten\":{minuten}}}");
/// <summary>
/// Manuelle Einstellung (gilt 90 min): feld fenster|jalousie|licht|lueftung, wert als JSON,
/// z. B. "\"open\"", "100", "\"an\"" oder "\"auto\"" für Automatik.
/// </summary>
public void SetManual(string feld, string jsonWert) => Post("/api/manuell", $"{{\"rolle\":\"dozent\",\"{feld}\":{jsonWert}}}");
public void ResetManual() => Post("/api/manuell", "{\"rolle\":\"dozent\",\"zuruecksetzen\":true}");
void Post(string path, string json)
{
if (Active) StartCoroutine(PostRoutine(path, json));
}
IEnumerator PostRoutine(string path, string json)
{
using (var req = new UnityWebRequest(Base + path, UnityWebRequest.kHttpVerbPOST))
{
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
req.downloadHandler = new DownloadHandlerBuffer();
req.SetRequestHeader("Content-Type", "application/json");
req.timeout = 3;
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
{
Status = $"{path} fehlgeschlagen: {req.error} {req.downloadHandler.text}";
yield break;
}
}
// Ergebnis sofort abholen statt bis zur nächsten Abfrage zu warten
using (var req = UnityWebRequest.Get(Base + "/api/unity?client=" + UnityWebRequest.EscapeURL(ClientId)))
{
req.timeout = 3;
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success) Receive(req.downloadHandler.text);
}
}
void OnDisable() => End();
}
}