450 lines
17 KiB
C#
450 lines
17 KiB
C#
// Serielle Schnittstelle gibt es nur mit "Api Compatibility Level = .NET Framework" (Player Settings).
|
||
#if (NET_4_6 || NET_UNITY_4_8) && !UNITY_WEBGL && !UNITY_ANDROID && !UNITY_IOS
|
||
#define SMARTROOM_SERIAL
|
||
#endif
|
||
using System;
|
||
using System.Collections.Concurrent;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
using UnityEngine;
|
||
#if SMARTROOM_SERIAL
|
||
using System.IO.Ports;
|
||
#endif
|
||
|
||
namespace SmartRoom
|
||
{
|
||
/// <summary>
|
||
/// Ein JSON-Datenpaket vom Arduino, z. B. {"t":30.2,"co2":1250,"lux":320}.
|
||
/// Alle Felder sind optional – nicht gesendete Felder bleiben NaN und werden ignoriert.
|
||
/// </summary>
|
||
[Serializable]
|
||
public class SensorPacket
|
||
{
|
||
public float t = float.NaN; // Temperatur innen °C
|
||
public float co2 = float.NaN; // CO2 innen ppm
|
||
public float lux = float.NaN; // Helligkeit innen lx
|
||
public float noise = float.NaN; // Lärm innen dB
|
||
public float tout = float.NaN; // Temperatur außen °C
|
||
public float aq = float.NaN; // Luftqualität außen (AQI)
|
||
public float nout = float.NaN; // Lärm außen dB
|
||
public float wind = float.NaN; // Wind m/s
|
||
public float sun = float.NaN; // Sonneneinstrahlung W/m²
|
||
public float persons = float.NaN; // Personen im Raum
|
||
public float rh = float.NaN; // Luftfeuchte innen %
|
||
public float tvoc = float.NaN; // TVOC innen ppb
|
||
public float lightpct = float.NaN; // Helligkeit innen % (Fotowiderstand, relativ)
|
||
}
|
||
|
||
/// <summary>
|
||
/// Backend = GruppeC-Aufbau: Arduino Uno + ESP-01 schicken per HTTP-POST an backend/server.py,
|
||
/// Unity holt die Werte dort per GET /api/messwerte ab.
|
||
/// </summary>
|
||
public enum LinkMode { Simulation, Serial, Udp, Backend }
|
||
|
||
/// <summary>
|
||
/// Verbindung zum Arduino: empfängt Sensordaten (JSON-Zeilen) per USB-Seriell oder UDP (WLAN, z. B. ESP32)
|
||
/// oder fragt sie beim Backend (ESP-01 → server.py) ab und sendet die Steuerbefehle der virtuellen Aktoren zurück.
|
||
/// </summary>
|
||
public class ArduinoBridge : MonoBehaviour
|
||
{
|
||
[Tooltip("Backend = Werte vom Arduino über backend/server.py (ohne laufenden Server bleibt die Simulation aktiv)")]
|
||
public LinkMode mode = LinkMode.Backend;
|
||
[Tooltip("macOS: /dev/cu.usbmodem… · Windows: COM3")]
|
||
public string serialPort = "/dev/cu.usbmodem101";
|
||
public int baudRate = 115200;
|
||
public int udpListenPort = 5005;
|
||
[Tooltip("Port, an den Steuerbefehle an den Absender zurückgeschickt werden")]
|
||
public int udpReplyPort = 5006;
|
||
[Tooltip("Adresse von backend/server.py – dort kommen die Messwerte des ESP-01 an")]
|
||
public string backendUrl = "http://localhost:3000";
|
||
[Tooltip("Abfrageintervall beim Backend in Sekunden")]
|
||
public float backendPollSeconds = 1f;
|
||
[Tooltip("Ältere Messwerte im Backend gelten als veraltet und werden ignoriert (Sekunden)")]
|
||
public float backendMaxAge = 30f;
|
||
[Tooltip("MAX9814: an = Mikrofon steht draußen (Außenlärm, Sensor-Veto für Fenster), aus = Lärm im Raum")]
|
||
[SerializeField] bool microphoneOutdoor;
|
||
[Tooltip("Umrechnung Fotowiderstand % → lx (grob, 100 % ≈ 1000 lx)")]
|
||
public float luxPerLightPercent = 10f;
|
||
public bool sendCommands = true;
|
||
|
||
/// <summary>Optional: Name des erkannten Szenarios, wird mit den Steuerbefehlen ans Backend gemeldet.</summary>
|
||
public Func<string> scenarioProvider;
|
||
|
||
public RoomEnvironment env;
|
||
public RoomDevices devices;
|
||
|
||
public string Status { get; private set; } = "Simulation aktiv";
|
||
public bool Connected { get; private set; }
|
||
public string LastLine { get; private set; } = "";
|
||
public string LastSent { get; private set; } = "";
|
||
public float LastPacketTime { get; private set; } = -1f;
|
||
public int PacketCount { get; private set; }
|
||
|
||
public bool MicrophoneOutdoor
|
||
{
|
||
get => microphoneOutdoor;
|
||
set
|
||
{
|
||
if (value == microphoneOutdoor) return;
|
||
microphoneOutdoor = value;
|
||
env?.Forget(value ? "noise" : "nout"); // alter Kanal soll nicht noch als "Sensor" gelten
|
||
}
|
||
}
|
||
|
||
public static bool SerialSupported
|
||
{
|
||
get
|
||
{
|
||
#if SMARTROOM_SERIAL
|
||
return true;
|
||
#else
|
||
return false;
|
||
#endif
|
||
}
|
||
}
|
||
|
||
readonly ConcurrentQueue<string> inbox = new ConcurrentQueue<string>();
|
||
readonly object remoteLock = new object();
|
||
Thread worker;
|
||
volatile bool running;
|
||
UdpClient udp;
|
||
IPEndPoint remote;
|
||
float nextSend;
|
||
string pendingCommand; // vom Hauptthread gesetzt, vom Backend-Thread per POST verschickt
|
||
string lastBackendTime;
|
||
const string HttpPrefix = "!HTTP ";
|
||
static readonly Regex AktuellRx = new Regex("\"aktuell\"\\s*:\\s*(null|\\{[^{}]*\\})");
|
||
static readonly Regex FieldRx = new Regex("\"(\\w+)\"\\s*:\\s*(\"[^\"]*\"|[^,}\\s]+)");
|
||
#if SMARTROOM_SERIAL
|
||
SerialPort port;
|
||
#endif
|
||
|
||
public static string[] ListSerialPorts()
|
||
{
|
||
#if SMARTROOM_SERIAL
|
||
try { return SerialPort.GetPortNames(); } catch { return new string[0]; }
|
||
#else
|
||
return new string[0];
|
||
#endif
|
||
}
|
||
|
||
void Start()
|
||
{
|
||
if (mode != LinkMode.Simulation) Connect();
|
||
}
|
||
|
||
public void Connect()
|
||
{
|
||
Disconnect();
|
||
try
|
||
{
|
||
switch (mode)
|
||
{
|
||
case LinkMode.Serial: OpenSerial(); break;
|
||
case LinkMode.Udp: OpenUdp(); break;
|
||
case LinkMode.Backend: OpenBackend(); break;
|
||
default: Status = "Simulation aktiv"; break;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Disconnect();
|
||
Status = "Fehler: " + ex.Message;
|
||
}
|
||
}
|
||
|
||
void OpenSerial()
|
||
{
|
||
#if SMARTROOM_SERIAL
|
||
port = new SerialPort(serialPort, baudRate) { ReadTimeout = 500, NewLine = "\n", DtrEnable = true };
|
||
port.Open();
|
||
StartWorker(SerialLoop);
|
||
Status = "Verbunden mit " + serialPort;
|
||
#else
|
||
Status = "Seriell nicht verfügbar: Player Settings → Api Compatibility Level → .NET Framework (oder UDP nutzen)";
|
||
#endif
|
||
}
|
||
|
||
void OpenUdp()
|
||
{
|
||
udp = new UdpClient(udpListenPort);
|
||
StartWorker(UdpLoop);
|
||
Status = $"Lausche auf UDP-Port {udpListenPort}";
|
||
}
|
||
|
||
void OpenBackend()
|
||
{
|
||
lastBackendTime = null;
|
||
pendingCommand = null;
|
||
StartWorker(BackendLoop);
|
||
Status = "Frage " + backendUrl + " ab …";
|
||
}
|
||
|
||
void StartWorker(ThreadStart loop)
|
||
{
|
||
running = true;
|
||
Connected = true;
|
||
worker = new Thread(loop) { IsBackground = true, Name = "ArduinoBridge" };
|
||
worker.Start();
|
||
}
|
||
|
||
public void Disconnect()
|
||
{
|
||
bool was = Connected;
|
||
running = false;
|
||
Connected = false;
|
||
#if SMARTROOM_SERIAL
|
||
try { if (port != null && port.IsOpen) port.Close(); } catch { }
|
||
port = null;
|
||
#endif
|
||
try { udp?.Close(); } catch { }
|
||
udp = null;
|
||
if (worker != null && worker.IsAlive) worker.Join(800);
|
||
worker = null;
|
||
lock (remoteLock) remote = null;
|
||
if (was) Status = "Getrennt";
|
||
if (mode == LinkMode.Simulation) Status = "Simulation aktiv";
|
||
}
|
||
|
||
#if SMARTROOM_SERIAL
|
||
void SerialLoop()
|
||
{
|
||
while (running)
|
||
{
|
||
try
|
||
{
|
||
string line = port.ReadLine();
|
||
if (!string.IsNullOrWhiteSpace(line)) inbox.Enqueue(line.Trim());
|
||
}
|
||
catch (TimeoutException) { }
|
||
catch (Exception ex)
|
||
{
|
||
if (running) inbox.Enqueue("!ERR " + ex.Message);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
#endif
|
||
|
||
void UdpLoop()
|
||
{
|
||
var any = new IPEndPoint(IPAddress.Any, 0);
|
||
while (running)
|
||
{
|
||
try
|
||
{
|
||
byte[] data = udp.Receive(ref any);
|
||
lock (remoteLock) remote = new IPEndPoint(any.Address, udpReplyPort);
|
||
foreach (var line in Encoding.UTF8.GetString(data).Split('\n'))
|
||
if (!string.IsNullOrWhiteSpace(line)) inbox.Enqueue(line.Trim());
|
||
}
|
||
catch (SocketException ex)
|
||
{
|
||
if (!running) break;
|
||
inbox.Enqueue("!ERR " + ex.Message);
|
||
}
|
||
catch (ObjectDisposedException) { break; }
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Backend (HTTP)
|
||
void BackendLoop()
|
||
{
|
||
string baseUrl = backendUrl.Trim().TrimEnd('/');
|
||
while (running)
|
||
{
|
||
try
|
||
{
|
||
string body = Http("GET", baseUrl + "/api/messwerte", null);
|
||
if (running) inbox.Enqueue(HttpPrefix + body);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (running) inbox.Enqueue("!ERR Backend nicht erreichbar (" + ex.Message + ") – läuft backend/server.py?");
|
||
}
|
||
|
||
string cmd = Interlocked.Exchange(ref pendingCommand, null);
|
||
if (cmd != null)
|
||
{
|
||
try { Http("POST", baseUrl + "/api/steuerung", cmd); }
|
||
catch (Exception ex) { if (running) inbox.Enqueue("!ERR Steuerbefehl nicht angenommen: " + ex.Message); }
|
||
}
|
||
|
||
// in kleinen Schritten schlafen, damit "Trennen" sofort greift
|
||
for (int ms = 0; running && ms < backendPollSeconds * 1000f; ms += 50) Thread.Sleep(50);
|
||
}
|
||
}
|
||
|
||
static string Http(string method, string url, string body)
|
||
{
|
||
var req = (HttpWebRequest)WebRequest.Create(url);
|
||
req.Method = method;
|
||
req.Timeout = 3000;
|
||
req.ReadWriteTimeout = 3000;
|
||
req.Proxy = null;
|
||
if (body != null)
|
||
{
|
||
byte[] bytes = Encoding.UTF8.GetBytes(body);
|
||
req.ContentType = "application/json";
|
||
req.ContentLength = bytes.Length;
|
||
using (var s = req.GetRequestStream()) s.Write(bytes, 0, bytes.Length);
|
||
}
|
||
using (var res = (HttpWebResponse)req.GetResponse())
|
||
using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
|
||
return reader.ReadToEnd();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Wertet die Antwort von GET /api/messwerte aus:
|
||
/// {"aktuell":{"zeit":"…Z","temperatur":22.5,"luftfeuchte":45,"eco2":612,"tvoc":30,"lautstaerke":48.5,"helligkeit":60},"verlauf":[…]}
|
||
/// </summary>
|
||
void ApplyBackend(string json)
|
||
{
|
||
var m = AktuellRx.Match(json);
|
||
if (!m.Success || m.Groups[1].Value == "null")
|
||
{
|
||
Status = "Backend erreichbar · noch keine Messwerte vom Arduino";
|
||
return;
|
||
}
|
||
|
||
var f = new Dictionary<string, string>();
|
||
foreach (Match fm in FieldRx.Matches(m.Groups[1].Value))
|
||
f[fm.Groups[1].Value] = fm.Groups[2].Value.Trim('"');
|
||
f.TryGetValue("zeit", out var zeit);
|
||
|
||
if (zeit != null && zeit == lastBackendTime)
|
||
{
|
||
// kein neuer Messwert seit der letzten Abfrage
|
||
if (LastPacketTime < 0f || Time.unscaledTime - LastPacketTime > env.measurementTimeout)
|
||
Status = "Backend erreichbar · keine neuen Messwerte (Arduino/ESP aus?)";
|
||
return;
|
||
}
|
||
lastBackendTime = zeit;
|
||
|
||
if (zeit != null && DateTime.TryParse(zeit, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var ts))
|
||
{
|
||
double age = (DateTime.UtcNow - ts.ToUniversalTime()).TotalSeconds;
|
||
if (age > backendMaxAge)
|
||
{
|
||
Status = $"Letzter Messwert im Backend ist {age:0} s alt – Arduino sendet gerade nicht";
|
||
return;
|
||
}
|
||
}
|
||
|
||
float laut = Num(f, "lautstaerke"), licht = Num(f, "helligkeit");
|
||
var p = new SensorPacket
|
||
{
|
||
t = Num(f, "temperatur"),
|
||
rh = Num(f, "luftfeuchte"),
|
||
co2 = Num(f, "eco2"),
|
||
tvoc = Num(f, "tvoc"),
|
||
lightpct = licht,
|
||
lux = licht * luxPerLightPercent, // NaN bleibt NaN
|
||
};
|
||
if (microphoneOutdoor) p.nout = laut; else p.noise = laut;
|
||
LastLine = m.Groups[1].Value;
|
||
env.ApplyMeasurement(p);
|
||
LastPacketTime = Time.unscaledTime;
|
||
PacketCount++;
|
||
Status = "Backend verbunden · Messwerte vom Arduino (ESP-01)";
|
||
}
|
||
|
||
static float Num(Dictionary<string, string> f, string key)
|
||
=> f.TryGetValue(key, out var s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : float.NaN;
|
||
|
||
void Update()
|
||
{
|
||
while (inbox.TryDequeue(out var line))
|
||
{
|
||
if (line.StartsWith("!ERR"))
|
||
{
|
||
Status = "Verbindungsfehler: " + line.Substring(4).Trim();
|
||
continue;
|
||
}
|
||
if (line.StartsWith(HttpPrefix))
|
||
{
|
||
ApplyBackend(line.Substring(HttpPrefix.Length));
|
||
continue;
|
||
}
|
||
LastLine = line;
|
||
if (!line.StartsWith("{")) continue; // Debug-Ausgaben des Arduino ignorieren
|
||
try
|
||
{
|
||
var p = new SensorPacket();
|
||
JsonUtility.FromJsonOverwrite(line, p);
|
||
env.ApplyMeasurement(p);
|
||
LastPacketTime = Time.unscaledTime;
|
||
PacketCount++;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Status = "Ungültiges JSON: " + ex.Message;
|
||
}
|
||
}
|
||
|
||
// Steuerbefehle senden, sobald sie sich ändern (spätestens alle 10 s als Heartbeat)
|
||
if (Connected && sendCommands && devices != null)
|
||
{
|
||
string cmd = BuildCommand();
|
||
if (cmd != LastSent || Time.unscaledTime >= nextSend)
|
||
{
|
||
Send(cmd);
|
||
nextSend = Time.unscaledTime + 10f;
|
||
}
|
||
}
|
||
}
|
||
|
||
public string BuildCommand()
|
||
{
|
||
var ci = CultureInfo.InvariantCulture;
|
||
var sb = new StringBuilder();
|
||
sb.Append("{\"window\":\"").Append(devices.WindowTarget.Code()).Append('"');
|
||
sb.Append(",\"blind\":").Append(devices.BlindTarget.ToString("0.00", ci));
|
||
sb.Append(",\"heat\":").Append(devices.HeatingTarget.ToString("0.00", ci));
|
||
sb.Append(",\"vent\":").Append(devices.VentTarget.ToString("0.00", ci));
|
||
sb.Append(",\"light\":").Append(devices.LightTarget.ToString("0.00", ci));
|
||
sb.Append(",\"beamer\":").Append(devices.BeamerOn ? 1 : 0);
|
||
string scenario = scenarioProvider?.Invoke();
|
||
if (mode == LinkMode.Backend && !string.IsNullOrEmpty(scenario))
|
||
sb.Append(",\"szenario\":\"").Append(scenario.Replace("\"", "'")).Append('"');
|
||
sb.Append('}');
|
||
return sb.ToString();
|
||
}
|
||
|
||
void Send(string json)
|
||
{
|
||
LastSent = json;
|
||
try
|
||
{
|
||
#if SMARTROOM_SERIAL
|
||
if (mode == LinkMode.Serial && port != null && port.IsOpen) port.WriteLine(json);
|
||
#endif
|
||
if (mode == LinkMode.Backend) Interlocked.Exchange(ref pendingCommand, json);
|
||
if (mode == LinkMode.Udp && udp != null)
|
||
{
|
||
IPEndPoint target;
|
||
lock (remoteLock) target = remote;
|
||
if (target != null)
|
||
{
|
||
var bytes = Encoding.UTF8.GetBytes(json + "\n");
|
||
udp.Send(bytes, bytes.Length, target);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Status = "Senden fehlgeschlagen: " + ex.Message;
|
||
}
|
||
}
|
||
|
||
void OnDisable() => Disconnect();
|
||
void OnApplicationQuit() => Disconnect();
|
||
}
|
||
}
|