300 lines
10 KiB
C#
300 lines
10 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.Globalization;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
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 enum LinkMode { Simulation, Serial, Udp, Backend }
|
||
|
||
/// <summary>
|
||
/// Verbindung zum Arduino: empfängt Sensordaten (JSON-Zeilen) per USB-Seriell oder UDP (WLAN, z. B. ESP32)
|
||
/// und sendet die Steuerbefehle der virtuellen Aktoren zurück.
|
||
/// Im Modus Backend (Standard) kommen Sensorwerte und Entscheidungen vom gemeinsamen Backend, siehe <see cref="BackendLink"/>.
|
||
/// </summary>
|
||
public class ArduinoBridge : MonoBehaviour
|
||
{
|
||
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;
|
||
public bool sendCommands = true;
|
||
|
||
public RoomEnvironment env;
|
||
public RoomDevices devices;
|
||
public BackendLink backend;
|
||
|
||
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 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;
|
||
#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:
|
||
backend.Begin();
|
||
Connected = true;
|
||
Status = "Gemeinsames Backend " + backend.serverUrl;
|
||
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()
|
||
{
|
||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||
Status = "UDP im Browser nicht verfügbar: Verbindung → Backend nutzen";
|
||
#else
|
||
udp = new UdpClient(udpListenPort);
|
||
StartWorker(UdpLoop);
|
||
Status = $"Lausche auf UDP-Port {udpListenPort}";
|
||
#endif
|
||
}
|
||
|
||
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 { }
|
||
if (backend != null) backend.End();
|
||
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; }
|
||
}
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
while (inbox.TryDequeue(out var line))
|
||
{
|
||
if (line.StartsWith("!ERR"))
|
||
{
|
||
Status = "Verbindungsfehler: " + line.Substring(4).Trim();
|
||
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)
|
||
// Im Backend-Modus entscheidet das Backend; Unity schickt keine eigenen Befehle
|
||
if (Connected && sendCommands && devices != null && mode != LinkMode.Backend)
|
||
{
|
||
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);
|
||
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.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();
|
||
}
|
||
}
|