using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace Pokerfreak.Cockpit.Kern; /// Wo der Server steht: 127.0.0.1:8787, sonst --adresse host:port oder POKERFREAK_ADRESSE. public sealed record Adresse(string Host, int Port) { public Uri Ws => new($"ws://{Host}:{Port}/ws"); public Uri Steuern => new($"http://{Host}:{Port}/api/steuern"); public Uri Basis => new($"http://{Host}:{Port}/"); public static Adresse AusBefehlszeile(string[] argv) { string? roh = Environment.GetEnvironmentVariable("POKERFREAK_ADRESSE"); for (int i = 0; i < argv.Length - 1; i++) if (argv[i] == "--adresse") roh = argv[i + 1]; return Lesen(roh); } public static Adresse Lesen(string? roh) { var a = new Adresse("127.0.0.1", 8787); if (string.IsNullOrWhiteSpace(roh)) return a; roh = roh.Trim(); foreach (var p in new[] { "ws://", "http://" }) if (roh.StartsWith(p)) roh = roh[p.Length..]; roh = roh.Split('/')[0]; var teile = roh.Split(':'); return teile.Length == 2 && int.TryParse(teile[1], out var port) ? new Adresse(teile[0], port) : new Adresse(roh, 8787); } } /// Was ein Knopf des Servers zurueckmeldet ({ok, text}, auch ueber den WebSocket). public sealed record Rueckmeldung(string Aktion, bool Ok, string Text, string? Raum = null, string? Bild = null, JsonObject? Roh = null); /// /// Die eine WebSocket-Verbindung zum Server (sicht/ws.py): beim Verbinden alle Bereiche, danach nur /// geaenderte. Haelt die zusammengefuehrte Ansicht und meldet jede Aenderung; verbindet von selbst neu. /// Ereignisse kommen auf einem Hintergrund-Thread - die Oberflaeche wechselt selbst auf ihren. /// public sealed class Verbindung : IDisposable { private readonly Adresse _adresse; private readonly CancellationTokenSource _ende = new(); private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(20) }; private readonly object _sperre = new(); private JsonObject _teile = new(); public event Action? Aktualisiert; public event Action? Zustand; // verbunden?, Grund public event Action? Gemeldet; public Verbindung(Adresse adresse) => _adresse = adresse; public Adresse Adresse => _adresse; public void Starten() => _ = Task.Run(Schleife); private async Task Schleife() { var warte = TimeSpan.FromMilliseconds(500); while (!_ende.IsCancellationRequested) { string grund; try { using var ws = new ClientWebSocket(); ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(15); using (var frist = CancellationTokenSource.CreateLinkedTokenSource(_ende.Token)) { frist.CancelAfter(TimeSpan.FromSeconds(5)); await ws.ConnectAsync(_adresse.Ws, frist.Token); } Zustand?.Invoke(true, ""); warte = TimeSpan.FromMilliseconds(500); await Lesen(ws); grund = "Verbindung geschlossen"; } catch (OperationCanceledException) when (_ende.IsCancellationRequested) { return; } catch (Exception e) { grund = e is WebSocketException or HttpRequestException or OperationCanceledException ? $"kein Cockpit-Server auf {_adresse.Host}:{_adresse.Port}" : e.Message; } Zustand?.Invoke(false, grund); try { await Task.Delay(warte, _ende.Token); } catch (OperationCanceledException) { return; } warte = TimeSpan.FromMilliseconds(Math.Min(4000, warte.TotalMilliseconds * 2)); } } private async Task Lesen(ClientWebSocket ws) { var puffer = new byte[1 << 16]; var text = new MemoryStream(); while (ws.State == WebSocketState.Open && !_ende.IsCancellationRequested) { var r = await ws.ReceiveAsync(puffer, _ende.Token); if (r.MessageType == WebSocketMessageType.Close) return; text.Write(puffer, 0, r.Count); if (!r.EndOfMessage) continue; var json = Encoding.UTF8.GetString(text.GetBuffer(), 0, (int)text.Length); text.SetLength(0); Verarbeiten(json); } } private void Verarbeiten(string json) { JsonNode? n; try { n = JsonNode.Parse(json); } catch (JsonException) { return; } if (n is not JsonObject o) return; var typ = o["typ"]?.GetValue(); if (typ == "ansicht" && o["teile"] is JsonObject neu) { Ansicht a; lock (_sperre) { var kopie = (JsonObject)_teile.DeepClone(); foreach (var (k, v) in neu) kopie[k] = v?.DeepClone(); _teile = kopie; a = new Ansicht(kopie); } Aktualisiert?.Invoke(a); } else if (typ == "rueckmeldung") { Gemeldet?.Invoke(RueckmeldungAus(o)); } } private static Rueckmeldung RueckmeldungAus(JsonObject o) => new( o.Text("aktion") ?? "", o.Wahr("ok"), o.Text("text") ?? "", o.Text("raum"), o.Text("bild"), o); /// Ein Knopf des Servers (POST /api/steuern {aktion, raum?, daten?}); wirft nie. public async Task Senden(string aktion, string? raum = null, JsonNode? daten = null) { var koerper = new JsonObject { ["aktion"] = aktion }; if (raum != null) koerper["raum"] = raum; if (daten != null) koerper["daten"] = daten.DeepClone(); try { using var inhalt = new StringContent(koerper.ToJsonString(), Encoding.UTF8, "application/json"); using var antwort = await _http.PostAsync(_adresse.Steuern, inhalt, _ende.Token); var text = await antwort.Content.ReadAsStringAsync(_ende.Token); var o = JsonNode.Parse(text) as JsonObject; return o == null ? new Rueckmeldung(aktion, false, $"Antwort unlesbar ({(int)antwort.StatusCode})") : new Rueckmeldung(aktion, o.Wahr("ok"), o.Text("text") ?? "", o.Text("raum") ?? raum, o.Text("bild"), o); } catch (Exception e) { return new Rueckmeldung(aktion, false, $"Server nicht erreicht: {e.Message}"); } } /// Ein Bild vom Server (/foto/<name>.png) als Bytes; null bei Fehler. public async Task Laden(string pfad) { try { return await _http.GetByteArrayAsync(new Uri(_adresse.Basis, pfad.TrimStart('/')), _ende.Token); } catch { return null; } } public void Dispose() { _ende.Cancel(); _http.Dispose(); } }