Fixed debug

This commit is contained in:
erik 2025-04-27 20:02:47 +02:00
parent 78a2479d6c
commit b027a79201
2 changed files with 70 additions and 72 deletions

View file

@ -10,6 +10,7 @@
<RootNamespace>MosswartMassacre</RootNamespace> <RootNamespace>MosswartMassacre</RootNamespace>
<AssemblyName>MosswartMassacre</AssemblyName> <AssemblyName>MosswartMassacre</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
</PropertyGroup> </PropertyGroup>

View file

@ -1,64 +1,73 @@
using System; // Telemetry.cs ───────────────────────────────────────────────────────────────
using System;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Timers; using System.Threading;
using System.Threading.Tasks;
using Decal.Adapter; using Decal.Adapter;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace MosswartMassacre namespace MosswartMassacre
{ {
/// <summary>
/// Periodically sends gameplay telemetry to your FastAPI collector.
/// Toggle with: Telemetry.Start() / Telemetry.Stop()
/// </summary>
public static class Telemetry public static class Telemetry
{ {
/* ============ CONFIG ============ */ /* ───────────── configuration ───────────── */
private const string Endpoint = "https://mosswart.snakedesert.se/position/"; // <- trailing slash!
private const string Endpoint = "https://mosswart.snakedesert.se/position"; private const string SharedSecret = "your_shared_secret"; // <- keep in sync
private const string SharedSecret = "your_shared_secret"; private const int IntervalSec = 5; // seconds between posts
private const int IntervalSec = 5; // send every 5 s
/* ============ internals ========== */
/* ───────────── runtime state ───────────── */
private static readonly HttpClient _http = new HttpClient(); private static readonly HttpClient _http = new HttpClient();
private static Timer _timer;
private static bool _enabled;
private static string _sessionId; private static string _sessionId;
private static CancellationTokenSource _cts;
private static bool _enabled;
/* ============ public API ========= */ /* ───────────── public API ───────────── */
public static void Start() public static void Start()
{ {
if (_enabled) return; // already on if (_enabled) return;
_sessionId = $"{CoreManager.Current.CharacterFilter.Name}-{DateTime.UtcNow:yyyyMMdd-HHmmss}";
_timer = new Timer(IntervalSec * 1000);
_timer.Elapsed += (_, __) => SendSnapshot();
_timer.Start();
_enabled = true; _enabled = true;
_sessionId = $"{CoreManager.Current.CharacterFilter.Name}-{DateTime.UtcNow:yyyyMMdd-HHmmss}";
_cts = new CancellationTokenSource();
PluginCore.WriteToChat("[Telemetry] HTTP streaming ENABLED"); PluginCore.WriteToChat("[Telemetry] HTTP streaming ENABLED");
PluginCore.WriteToChat("[Tel] timer every " + IntervalSec + " s");
_ = Task.Run(() => LoopAsync(_cts.Token)); // fire-and-forget
} }
public static void Stop() public static void Stop()
{ {
if (!_enabled) return; if (!_enabled) return;
_cts.Cancel();
_enabled = false; _enabled = false;
_timer?.Stop();
_timer?.Dispose();
_timer = null;
PluginCore.WriteToChat("[Telemetry] HTTP streaming DISABLED"); PluginCore.WriteToChat("[Telemetry] HTTP streaming DISABLED");
} }
/* ============ snapshot builder === */ /* ───────────── async loop ───────────── */
private static async Task LoopAsync(CancellationToken token)
private static async void SendSnapshot() {
while (!token.IsCancellationRequested)
{ {
try try
{
await SendSnapshotAsync(token);
}
catch (Exception ex)
{
PluginCore.WriteToChat($"[Telemetry] send failed: {ex.Message}");
}
try
{
await Task.Delay(TimeSpan.FromSeconds(IntervalSec), token);
}
catch (TaskCanceledException) { } // expected on Stop()
}
}
/* ───────────── single POST ───────────── */
private static async Task SendSnapshotAsync(CancellationToken token)
{ {
var coords = Coordinates.Me; var coords = Coordinates.Me;
@ -81,30 +90,18 @@ namespace MosswartMassacre
}; };
string json = JsonConvert.SerializeObject(payload); string json = JsonConvert.SerializeObject(payload);
var req = new HttpRequestMessage(HttpMethod.Post, Endpoint) var req = new HttpRequestMessage(HttpMethod.Post, Endpoint)
{ {
Content = new StringContent(json, Encoding.UTF8, "application/json") Content = new StringContent(json, Encoding.UTF8, "application/json")
}; };
req.Headers.Add("X-Plugin-Secret", SharedSecret); req.Headers.Add("X-Plugin-Secret", SharedSecret);
/* ---------- NEW: wait for response & print result ---------- */ using var resp = await _http.SendAsync(req, token);
var resp = await _http.SendAsync(req);
if (resp.IsSuccessStatusCode)
{
PluginCore.WriteToChat($"[Tel] ✓ {resp.StatusCode}");
}
else
{
PluginCore.WriteToChat($"[Tel] ✗ {resp.StatusCode} ({await resp.Content.ReadAsStringAsync()})");
}
}
catch (Exception ex)
{
var inner = ex.InnerException?.Message ?? "no inner msg";
PluginCore.WriteToChat($"[Tel] FAILED — {ex.GetType().Name}: {ex.Message} ⇢ {inner}");
}
}
if (!resp.IsSuccessStatusCode) // stay quiet on success
{
PluginCore.WriteToChat($"[Telemetry] server replied {resp.StatusCode}");
}
}
} }
} }