602 lines
24 KiB
C#
602 lines
24 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;
|
||
using System.Collections.Concurrent;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
#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 das Backend auf dem Laptop.
|
||
/// Zentrales Node-Backend (server.js): Unity holt Werte und Entscheidung per GET /api/unity und führt nur aus.
|
||
/// Älteres server.py (ohne /api/unity): Unity holt die Messwerte per GET /api/messwerte und entscheidet selbst.
|
||
/// </summary>
|
||
public enum LinkMode { Simulation, Serial, Udp, Backend }
|
||
|
||
/// <summary>
|
||
/// Verbindung zu den Messwerten. Standard ist das gemeinsame Backend (backend/server.js): Unity holt jede Sekunde
|
||
/// GET /api/unity und zeigt nur an, was das Backend entscheidet (Bedienung läuft über das Webinterface).
|
||
/// Läuft UnityWebRequest-basiert, also auch als WebGL im Browser. Daneben USB-Seriell und UDP für eigene Aufbauten.
|
||
/// </summary>
|
||
public class ArduinoBridge : MonoBehaviour
|
||
{
|
||
[Tooltip("Backend = Werte und Entscheidungen vom Backend (server.js, sonst 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 des Backends (server.js oder 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 ClimateController controller;
|
||
|
||
/// <summary>Letzter Zustand des zentralen Backends (null bei server.py oder ohne Verbindung).</summary>
|
||
public CentralState Central { get; private set; }
|
||
/// <summary>Das zentrale Backend antwortet gerade (letzte Antwort jünger als 5 s).</summary>
|
||
public bool CentralActive => useArduinoData && CentralFresh;
|
||
bool CentralFresh => Central != null && Connected && Time.unscaledTime - centralAt < 5f;
|
||
float centralAt = -100f;
|
||
|
||
[Tooltip("an = Werte vom Arduino übernehmen, aus = Beispielwerte der Simulation (die Verbindung bleibt für die Statusanzeige bestehen)")]
|
||
[SerializeField] bool useArduinoData = true;
|
||
float arduinoSeenAt = -100f; // letzte Messung vom Arduino (auch wenn sie gerade nicht übernommen wird)
|
||
float backendReplyAt = -100f; // letzte Antwort des Backends
|
||
|
||
/// <summary>
|
||
/// Umschalter Arduino-Werte ↔ Simulation. Aus: Beispielwerte wiederherstellen, Unity entscheidet selbst.
|
||
/// An: Werte (und beim zentralen Backend auch die Entscheidungen) wieder vom Arduino bzw. Backend übernehmen.
|
||
/// </summary>
|
||
public bool UseArduinoData
|
||
{
|
||
get => useArduinoData;
|
||
set
|
||
{
|
||
if (value == useArduinoData) return;
|
||
useArduinoData = value;
|
||
if (!value)
|
||
{
|
||
env?.ResetToExampleValues();
|
||
controller?.ReleaseRemote();
|
||
return;
|
||
}
|
||
if (mode == LinkMode.Simulation) mode = LinkMode.Backend;
|
||
if (!Connected) Connect();
|
||
}
|
||
}
|
||
|
||
/// <summary>Kommen gerade Messwerte vom Arduino an (egal ob sie übernommen werden)?</summary>
|
||
public bool ArduinoConnected
|
||
{
|
||
get
|
||
{
|
||
if (!Connected) return false;
|
||
if (CentralFresh) return Central.sensorOnline;
|
||
return Time.unscaledTime - arduinoSeenAt < (env != null ? env.measurementTimeout : 25f);
|
||
}
|
||
}
|
||
|
||
public bool BackendReachable => Connected && Time.unscaledTime - backendReplyAt < 5f;
|
||
|
||
/// <summary>Statuszeile zum Arduino für die Dashboards.</summary>
|
||
public string ArduinoDetail
|
||
{
|
||
get
|
||
{
|
||
if (ArduinoConnected)
|
||
return $"Arduino verbunden · letzte Messung vor {Mathf.Max(0f, Time.unscaledTime - arduinoSeenAt):0} s";
|
||
if (!Connected) return "Arduino nicht verbunden · keine Verbindung eingestellt";
|
||
if (mode == LinkMode.Backend && !BackendReachable) return "Arduino nicht verbunden · Backend nicht erreichbar (läuft server.js?)";
|
||
if (mode == LinkMode.Backend) return "Arduino nicht verbunden · Backend läuft, aber keine Messwerte";
|
||
return "Arduino nicht verbunden · keine Messwerte";
|
||
}
|
||
}
|
||
|
||
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; // Rueckmeldung an server.py (veraltet), server.js braucht keine
|
||
string lastBackendTime;
|
||
const string HttpPrefix = "!HTTP ";
|
||
const string CentralPrefix = "!UNITY ";
|
||
Coroutine backendLoop;
|
||
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 Awake()
|
||
{
|
||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||
// Im Browser läuft der Zwilling auf der Seite des Backends: dessen Adresse übernehmen, nicht "localhost"
|
||
if (Application.absoluteURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
|
||
backendUrl = new Uri(Application.absoluteURL).GetLeftPart(UriPartial.Authority);
|
||
#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()
|
||
{
|
||
#if UNITY_WEBGL && !UNITY_EDITOR
|
||
Status = "UDP im Browser nicht verfügbar: Verbindung → Backend nutzen";
|
||
return;
|
||
#endif
|
||
udp = new UdpClient(udpListenPort);
|
||
StartWorker(UdpLoop);
|
||
Status = $"Lausche auf UDP-Port {udpListenPort}";
|
||
}
|
||
|
||
void OpenBackend()
|
||
{
|
||
lastBackendTime = null;
|
||
pendingCommand = null;
|
||
Central = null;
|
||
running = true;
|
||
Connected = true;
|
||
backendLoop = StartCoroutine(BackendPoll());
|
||
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 (backendLoop != null) StopCoroutine(backendLoop);
|
||
backendLoop = 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, auch WebGL)
|
||
IEnumerator BackendPoll()
|
||
{
|
||
string baseUrl = backendUrl.Trim().TrimEnd('/');
|
||
bool legacy = false; // true: altes server.py ohne /api/unity
|
||
while (running)
|
||
{
|
||
if (!legacy)
|
||
{
|
||
using (var req = UnityWebRequest.Get(baseUrl + "/api/unity"))
|
||
{
|
||
req.timeout = 3;
|
||
yield return req.SendWebRequest();
|
||
if (!running) yield break;
|
||
if (req.result == UnityWebRequest.Result.Success) ApplyCentral(req.downloadHandler.text);
|
||
else if (req.responseCode == 404) legacy = true; // server.py: Messwerte holen und selbst entscheiden
|
||
else Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ") – läuft backend/server.js?";
|
||
}
|
||
}
|
||
else
|
||
{
|
||
using (var req = UnityWebRequest.Get(baseUrl + "/api/messwerte"))
|
||
{
|
||
req.timeout = 3;
|
||
yield return req.SendWebRequest();
|
||
if (!running) yield break;
|
||
if (req.result == UnityWebRequest.Result.Success) ApplyBackend(req.downloadHandler.text);
|
||
else
|
||
{
|
||
Status = "Verbindungsfehler: Backend nicht erreichbar (" + req.error + ")";
|
||
legacy = false; // evtl. wurde inzwischen server.js gestartet
|
||
}
|
||
}
|
||
if (pendingCommand != null)
|
||
{
|
||
string cmd = pendingCommand;
|
||
pendingCommand = null;
|
||
using (var req = new UnityWebRequest(baseUrl + "/api/steuerung", UnityWebRequest.kHttpVerbPOST))
|
||
{
|
||
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(cmd));
|
||
req.downloadHandler = new DownloadHandlerBuffer();
|
||
req.SetRequestHeader("Content-Type", "application/json");
|
||
req.timeout = 3;
|
||
yield return req.SendWebRequest();
|
||
}
|
||
}
|
||
}
|
||
yield return new WaitForSecondsRealtime(backendPollSeconds);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Wertet GET /api/unity des zentralen Backends aus: Sensorwerte (mit Quelle) übernehmen, Entscheidung ausführen.
|
||
/// </summary>
|
||
void ApplyCentral(string json)
|
||
{
|
||
CentralState s;
|
||
try { s = JsonUtility.FromJson<CentralState>(json); }
|
||
catch (Exception ex)
|
||
{
|
||
Status = "Antwort des Backends nicht lesbar: " + ex.Message;
|
||
return;
|
||
}
|
||
if (s == null) return;
|
||
|
||
var p = new SensorPacket();
|
||
string sensorJson = JsonObject(json, "sensor");
|
||
if (sensorJson != null) JsonUtility.FromJsonOverwrite(sensorJson, p);
|
||
if (!float.IsNaN(p.lightpct)) p.lux = p.lightpct * luxPerLightPercent;
|
||
|
||
Central = s;
|
||
centralAt = backendReplyAt = Time.unscaledTime;
|
||
PacketCount++;
|
||
if (s.sensorOnline) LastPacketTime = arduinoSeenAt = Time.unscaledTime;
|
||
LastLine = sensorJson ?? "";
|
||
if (!useArduinoData)
|
||
{
|
||
Status = "Zentrales Backend (server.js) erreichbar · Simulation aktiv, Werte werden nicht übernommen";
|
||
return;
|
||
}
|
||
env.ApplyRemote(p, channel => s.SourceOf(channel) == "sensor");
|
||
controller?.ApplyRemote(s);
|
||
Status = s.sensorOnline ? "Zentrales Backend (server.js) · Arduino live"
|
||
: s.szenario != null && s.szenario != "live" ? $"Zentrales Backend (server.js) · Demo-Szenario „{s.szenario}“"
|
||
: "Zentrales Backend (server.js) · kein Arduino (Werte aus Wetter/Simulation)";
|
||
}
|
||
|
||
/// <summary>Unterobjekt <c>"key":{…}</c> aus einem JSON-Text (für Felder, die NaN-Vorgaben brauchen).</summary>
|
||
static string JsonObject(string json, string key)
|
||
{
|
||
int i = json.IndexOf("\"" + key + "\"", StringComparison.Ordinal);
|
||
if (i < 0) return null;
|
||
i = json.IndexOf('{', i);
|
||
if (i < 0) return null;
|
||
int depth = 0;
|
||
for (int j = i; j < json.Length; j++)
|
||
{
|
||
if (json[j] == '{') depth++;
|
||
else if (json[j] == '}' && --depth == 0) return json.Substring(i, j - i + 1);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// <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)
|
||
{
|
||
backendReplyAt = Time.unscaledTime;
|
||
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;
|
||
LastPacketTime = arduinoSeenAt = Time.unscaledTime;
|
||
PacketCount++;
|
||
if (!useArduinoData)
|
||
{
|
||
Status = "Backend verbunden · Simulation aktiv, Arduino-Werte werden nicht übernommen";
|
||
return;
|
||
}
|
||
env.ApplyMeasurement(p);
|
||
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;
|
||
}
|
||
if (line.StartsWith(CentralPrefix))
|
||
{
|
||
ApplyCentral(line.Substring(CentralPrefix.Length));
|
||
continue;
|
||
}
|
||
LastLine = line;
|
||
if (!line.StartsWith("{")) continue; // Debug-Ausgaben des Arduino ignorieren
|
||
try
|
||
{
|
||
var p = new SensorPacket();
|
||
JsonUtility.FromJsonOverwrite(line, p);
|
||
if (useArduinoData) env.ApplyMeasurement(p);
|
||
LastPacketTime = arduinoSeenAt = 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 && useArduinoData && devices != null && !CentralFresh) // das zentrale Backend braucht keine Rückmeldung
|
||
{
|
||
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) pendingCommand = json; // nur fuer server.py, server.js entscheidet selbst
|
||
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();
|
||
}
|
||
}
|