127 lines
5.0 KiB
C#
127 lines
5.0 KiB
C#
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;
|
||
|
|
|
||
|
|
/// <summary>Reports detection events to the Central (see <see cref="DetectionReporterService"/>).</summary>
|
||
|
|
public interface IDetectionReporter
|
||
|
|
{
|
||
|
|
Task<bool> ReportAsync(
|
||
|
|
Guid cameraId, Heimdall.Domain.Enums.EventType type, double confidence, string? label,
|
||
|
|
string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 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.
|
||
|
|
/// </summary>
|
||
|
|
public sealed class DetectionReporterService : IDetectionReporter
|
||
|
|
{
|
||
|
|
private readonly AgentState _state;
|
||
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
||
|
|
private readonly ILogger<DetectionReporterService> _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<DetectionReporterService> logger)
|
||
|
|
{
|
||
|
|
_state = state;
|
||
|
|
_httpClientFactory = httpClientFactory;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>Number of failed event reports (dropped, not retried).</summary>
|
||
|
|
public long FailedReports => Interlocked.Read(ref _failedReports);
|
||
|
|
|
||
|
|
/// <summary>Number of events suppressed by the per-camera cooldown.</summary>
|
||
|
|
public long SuppressedByCooldown => Interlocked.Read(ref _suppressedByCooldown);
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Report a detection event if the (camera, type) cooldown has elapsed.
|
||
|
|
/// Returns true when the event was actually sent.
|
||
|
|
/// </summary>
|
||
|
|
public async Task<bool> 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;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 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.
|
||
|
|
/// </summary>
|
||
|
|
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;
|
||
|
|
}
|
||
|
|
}
|