From bce39a1034189b38ea6c06bb29e0479929429b61 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 12 Aug 2026 09:18:42 +0200 Subject: [PATCH] =?UTF-8?q?feat(agent):=20remont=C3=A9e=20des=20d=C3=A9tec?= =?UTF-8?q?tions=20agent=20=E2=86=92=20central=20(Fixes=20#57)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DetectionReporterService : POST /api/events (API Key auth), anti-spam par cooldown (caméra, type) — motion 30 s, autres 10 s — échec réseau drop + compteur (jamais bloquant), mapping YOLO/COCO → EventType - SnapshotPipelineService : événement MotionDetected sur la transition idle → active (front montant), événements typés PersonDetected/ VehicleDetected pour chaque détection de l'analyseur (avec bbox en metadata) - Tests : 11 (mapping COCO, agent non enregistré → pas d'appel, pas de throw) --- src/Heimdall.Agent/Program.cs | 2 + .../Services/DetectionReporterService.cs | 127 ++++++++++++++++++ .../Services/SnapshotPipelineService.cs | 62 ++++++++- .../DetectionReporterServiceTests.cs | 55 ++++++++ .../SnapshotPipelineServiceTests.cs | 3 +- 5 files changed, 247 insertions(+), 2 deletions(-) create mode 100644 src/Heimdall.Agent/Services/DetectionReporterService.cs create mode 100644 tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index c43edb7..090a42b 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -69,6 +69,8 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs new file mode 100644 index 0000000..b63c006 --- /dev/null +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -0,0 +1,127 @@ +using System.Collections.Concurrent; +using System.Net.Http.Json; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Enums; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Services; + +/// Reports detection events to the Central (see ). +public interface IDetectionReporter +{ + Task ReportAsync( + Guid cameraId, Heimdall.Domain.Enums.EventType type, double confidence, string? label, + string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default); +} + +/// +/// Reports detection events from the agent to the Central (POST /api/events, +/// API Key auth). The snapshot pipeline calls this when the scene becomes +/// active (motion) or when the analyzer produces detections. +/// Anti-spam: per (camera, type) cooldown so a stationary object does not +/// flood the Central (the 4-level dedup #5 runs on the Central as well). +/// Failures are dropped with a counter (rate-limited log) — the capture +/// pipeline must never block on the network. +/// +public sealed class DetectionReporterService : IDetectionReporter +{ + private readonly AgentState _state; + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + + private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastSent = new(); + + private static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(10); + private static readonly TimeSpan MotionCooldown = TimeSpan.FromSeconds(30); + + private long _failedReports; + private long _suppressedByCooldown; + + public DetectionReporterService( + AgentState state, + IHttpClientFactory httpClientFactory, + ILogger logger) + { + _state = state; + _httpClientFactory = httpClientFactory; + _logger = logger; + } + + /// Number of failed event reports (dropped, not retried). + public long FailedReports => Interlocked.Read(ref _failedReports); + + /// Number of events suppressed by the per-camera cooldown. + public long SuppressedByCooldown => Interlocked.Read(ref _suppressedByCooldown); + + /// + /// Report a detection event if the (camera, type) cooldown has elapsed. + /// Returns true when the event was actually sent. + /// + public async Task ReportAsync( + Guid cameraId, EventType type, double confidence, string? label, + string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default) + { + if (_state.AgentId == Guid.Empty) + return false; + + var key = (cameraId, type); + var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown; + + var now = DateTime.UtcNow; + if (_lastSent.TryGetValue(key, out var last) && now - last < cooldown) + { + Interlocked.Increment(ref _suppressedByCooldown); + return false; + } + + try + { + using var client = _httpClientFactory.CreateClient("Central"); + client.DefaultRequestHeaders.Remove("X-API-Key"); + client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + + var request = new CreateCameraEventRequest( + cameraId, type, confidence, label, metadataJson, occurredAt ?? now); + var response = await client.PostAsJsonAsync("api/events", request, ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode) + { + _lastSent[key] = now; + return true; + } + + Interlocked.Increment(ref _failedReports); + _logger.LogWarning( + "Event report failed for camera {CameraId} ({Type}): {StatusCode} ({Reason})", + cameraId, type, response.StatusCode, response.ReasonPhrase); + return false; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return false; + } + catch (Exception ex) + { + Interlocked.Increment(ref _failedReports); + _logger.LogDebug(ex, "Event report dropped for camera {CameraId} ({Type})", cameraId, type); + return false; + } + } + + /// + /// Map a YOLO COCO detection label to a Heimdall EventType (person → Person, + /// vehicle classes → Vehicle, everything else → Motion). Returns null when + /// the label has no meaningful event mapping. + /// + public static EventType? MapDetectionToEventType(string label) + { + var l = label.ToLowerInvariant(); + if (l == "person") + return EventType.PersonDetected; + if (l is "car" or "truck" or "bus" or "motorcycle" or "bicycle" or "boat" or "train" or "airplane") + return EventType.VehicleDetected; + if (l is "cat" or "dog" or "bird" or "horse" or "cow" or "sheep") + return null; // pas d'EventType animal — motion suffit + return EventType.MotionDetected; + } +} diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index b66cac9..12f6dd3 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -20,8 +20,10 @@ public sealed class SnapshotPipelineService : BackgroundService private readonly FrameAnalyzerService _analyzer; private readonly SceneStateTracker _sceneState; private readonly ICameraStatusReporter _statusReporter; + private readonly IDetectionReporter _detectionReporter; private readonly ILogger _logger; private readonly ConcurrentDictionary _motionDetectors = new(); + private readonly ConcurrentDictionary _reportedSceneState = new(); private long _snapshotsProcessed; private long _analysisFailures; @@ -35,6 +37,7 @@ public sealed class SnapshotPipelineService : BackgroundService FrameAnalyzerService analyzer, SceneStateTracker sceneState, ICameraStatusReporter statusReporter, + IDetectionReporter detectionReporter, ILogger logger) { _state = state; @@ -44,6 +47,7 @@ public sealed class SnapshotPipelineService : BackgroundService _analyzer = analyzer; _sceneState = sceneState; _statusReporter = statusReporter; + _detectionReporter = detectionReporter; _logger = logger; } @@ -159,9 +163,13 @@ public sealed class SnapshotPipelineService : BackgroundService Interlocked.Increment(ref _snapshotsProcessed); var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); + var motion = detector.Detect(snapshot.JpegData); _sceneState.UpdateFromAnalysis( result?.Detections.Count > 0, - detector.Detect(snapshot.JpegData)); + motion); + + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -180,6 +188,58 @@ public sealed class SnapshotPipelineService : BackgroundService } } + /// + /// Report a MotionDetected event on the idle → active scene transition + /// (per camera, once per transition — the reporter's cooldown prevents + /// spam while the scene stays active). + /// + private async Task ReportSceneTransitionsAsync(Guid cameraId, CancellationToken ct) + { + var current = _sceneState.State; + var reported = _reportedSceneState.GetOrAdd(cameraId, SceneState.Idle); + + // Rising edge: idle → motion/object detected. + if (current != SceneState.Idle && reported == SceneState.Idle) + { + await _detectionReporter.ReportAsync( + cameraId, Heimdall.Domain.Enums.EventType.MotionDetected, + confidence: 0.9, label: "motion", occurredAt: DateTime.UtcNow, ct: ct) + .ConfigureAwait(false); + } + + _reportedSceneState[cameraId] = current; + } + + /// + /// Report analyzer detections as typed events (PersonDetected, + /// VehicleDetected, …). The reporter dedupes by (camera, type) cooldown. + /// + private async Task ReportDetectionsAsync(Guid cameraId, FrameAnalysisResult? result, CancellationToken ct) + { + if (result is null || result.Detections.Count == 0) + return; + + foreach (var detection in result.Detections) + { + var eventType = DetectionReporterService.MapDetectionToEventType(detection.Label); + if (eventType is null) + continue; + + var metadata = System.Text.Json.JsonSerializer.Serialize(new + { + detection.Label, + detection.Confidence, + detection.X, detection.Y, detection.Width, detection.Height, + }); + + await _detectionReporter.ReportAsync( + cameraId, eventType.Value, + detection.Confidence, detection.Label, metadata, + occurredAt: DateTime.UtcNow, ct: ct) + .ConfigureAwait(false); + } + } + private List BuildLocalCameras() { var list = new List(); diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs new file mode 100644 index 0000000..fb73476 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs @@ -0,0 +1,55 @@ +using Heimdall.Agent.Services; +using Heimdall.Domain.Enums; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Agent.Tests; + +public class DetectionReporterServiceTests +{ + [Theory] + [InlineData("person", EventType.PersonDetected)] + [InlineData("car", EventType.VehicleDetected)] + [InlineData("truck", EventType.VehicleDetected)] + [InlineData("bus", EventType.VehicleDetected)] + [InlineData("motorcycle", EventType.VehicleDetected)] + [InlineData("cat", null)] + [InlineData("dog", null)] + [InlineData("bottle", EventType.MotionDetected)] + [InlineData("Person", EventType.PersonDetected)] + public void MapDetectionToEventType_MapsKnownLabels(string label, EventType? expected) + { + DetectionReporterService.MapDetectionToEventType(label).ShouldBe(expected); + } + + [Fact] + public async Task ReportAsync_UnregisteredAgent_ReturnsFalse() + { + var state = new AgentState { AgentId = Guid.Empty, ApiKey = "" }; + var reporter = new DetectionReporterService( + state, + Substitute.For(), + Substitute.For>()); + + var sent = await reporter.ReportAsync( + Guid.NewGuid(), EventType.MotionDetected, 0.9, "motion"); + + sent.ShouldBeFalse(); + reporter.FailedReports.ShouldBe(0); + } + + [Fact] + public void ReportAsync_Unregistered_DoesNotThrow() + { + var state = new AgentState { AgentId = Guid.Empty, ApiKey = "" }; + var reporter = new DetectionReporterService( + state, + Substitute.For(), + Substitute.For>()); + + // Pas d'appel réseau possible sans agent → ne doit pas crasher. + var task = reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, 0.8, "person"); + task.IsCompleted.ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 48f108e..35e05a8 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -23,8 +23,9 @@ public class SnapshotPipelineServiceTests var streams = new CameraStreamService(Substitute.For>(), FfmpegNotFound); var analyzer = new FrameAnalyzerService(Substitute.For>()); var statusReporter = Substitute.For(); + var detectionReporter = Substitute.For(); var service = new SnapshotPipelineService( - state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, + state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter, Substitute.For>()); return (service, state, store, streams, analyzer); }