diff --git a/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs index 4d6f710..76a7c22 100644 --- a/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs +++ b/src/Heimdall.Agent/Services/AdaptiveSnapshotInterval.cs @@ -12,13 +12,13 @@ public sealed class AdaptiveSnapshotInterval public const int ObjectDetectedMs = 200; public const double CpuThrottlePercent = 80.0; - public TimeSpan GetInterval(SceneState state, double? cpuPercent) + public TimeSpan GetInterval(SceneState state, double? cpuPercent, Heimdall.Application.DTOs.DetectionProfileDto? profile = null) { var ms = state switch { - SceneState.ObjectDetected => ObjectDetectedMs, - SceneState.Motion => MotionMs, - _ => IdleMs, + SceneState.ObjectDetected => profile?.ActiveIntervalMs ?? ObjectDetectedMs, + SceneState.Motion => profile?.MotionIntervalMs ?? MotionMs, + _ => profile?.IdleIntervalMs ?? IdleMs, }; if (cpuPercent is >= CpuThrottlePercent) diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs index 13dc713..e2fb29b 100644 --- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -10,7 +10,8 @@ public sealed record AgentCameraConfig( string Name, string RtspUrl, string? SubRtspUrl, - bool Enabled) + bool Enabled, + Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null) { /// /// URL used for AI capture: the low-res sub-stream when available, diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index d093e7a..e5a4ec8 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -1,4 +1,6 @@ using System.Collections.Concurrent; +using System.Text.Json; +using Heimdall.Application.DTOs; namespace Heimdall.Agent.Services; @@ -11,7 +13,7 @@ namespace Heimdall.Agent.Services; /// public sealed class CameraConfigStore { - private readonly ConcurrentDictionary _central = new(); + private ConcurrentDictionary _central = new(); private IReadOnlyList _localFallback = []; private volatile bool _centralReceived; @@ -43,6 +45,7 @@ public sealed class CameraConfigStore _ => BuildConfig(cameraId, parts[2], value), (_, existing) => existing with { + DetectionProfile = parts[2] == "profile" ? ParseProfile(value) : existing.DetectionProfile, Name = parts[2] == "name" ? value : existing.Name, RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl, SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl, @@ -64,6 +67,17 @@ public sealed class CameraConfigStore RaiseChanged(); } + /// Atomically replace the authoritative snapshot, including removals. + public void ReplaceCentral(IReadOnlyDictionary settings) + { + var replacement = new CameraConfigStore(); + foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) + replacement.ApplyCameraSetting(setting.Key, setting.Value); + Interlocked.Exchange(ref _central, replacement._central); + _centralReceived = true; + RaiseChanged(); + } + /// Effective camera assignments: Central list, or local fallback before that. public IReadOnlyList Cameras => _centralReceived ? _central.Values.ToArray() : _localFallback; @@ -73,7 +87,15 @@ public sealed class CameraConfigStore field == "name" ? value : string.Empty, field == "rtsp" ? value : string.Empty, field == "sub_rtsp" ? value : null, - field == "enabled" ? ParseBool(value) : true); + field == "enabled" ? ParseBool(value) : true, + field == "profile" ? ParseProfile(value) : null); + + private static DetectionProfileDto ParseProfile(string value) + { + var profile = JsonSerializer.Deserialize(value) ?? throw new ArgumentException("Empty detection profile"); + profile.Validate(); + return profile; + } private static bool ParseBool(string value) => bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True"; diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index d018874..ec5d04a 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -29,6 +29,9 @@ public sealed class CameraStreamService : IDisposable private readonly ConcurrentDictionary _sessions = new(); private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg + private readonly ConcurrentDictionary _profiles = new(); + public void SetDetectionProfile(Guid cameraId, Heimdall.Application.DTOs.DetectionProfileDto profile) => _profiles[cameraId] = profile; + private long _droppedSnapshots; private DateTime _lastDropLogAt; private DateTime _cpuSampleAt; @@ -41,7 +44,7 @@ public sealed class CameraStreamService : IDisposable public Channel SnapshotChannel { get; } = Channel.CreateBounded( new BoundedChannelOptions(MaxQueueSize) { - FullMode = BoundedChannelFullMode.DropOldest, + FullMode = BoundedChannelFullMode.Wait, SingleReader = true, SingleWriter = false, }); @@ -201,7 +204,7 @@ public sealed class CameraStreamService : IDisposable private void MaybeEmitSnapshot(Guid cameraId, StreamSession session, byte[] frame) { var now = DateTime.UtcNow; - var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent()); + var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent(), _profiles.GetValueOrDefault(cameraId)); // Update snapshot interval metric (spec 13.1) HeimdallMetrics.SetSnapshotInterval(interval); @@ -218,7 +221,7 @@ public sealed class CameraStreamService : IDisposable { _lastDropLogAt = now; _logger.LogWarning( - "Snapshot queue full for camera {CameraId} — oldest frame dropped (total: {Dropped})", + "Snapshot queue full for camera {CameraId} — new frame rejected (total: {Dropped})", cameraId, Interlocked.Read(ref _droppedSnapshots)); } } diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index f3c4e6c..a0e51e7 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -22,6 +22,7 @@ public sealed class ConfigReceiverService : BackgroundService private readonly RuntimeLogLevel _runtimeLogLevel; private readonly CameraConfigStore _cameraStore; private HubConnection? _connection; + private readonly SemaphoreSlim _reloadLock = new(1, 1); /// /// Settings that are known but cannot be applied without an agent restart @@ -82,17 +83,19 @@ public sealed class ConfigReceiverService : BackgroundService _connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger()); // Listen for setting changes - _connection.On("SettingChanged", (key, value) => + _connection.On("SettingChanged", async (key, value) => { + // Keys may identify secret settings; never log their values. _logger.LogInformation("Config update received: {Key}", key); - ApplySetting(key, value); + if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken); + else ApplySetting(key, value); }); // Listen for full reload signal - _connection.On("ConfigReload", () => + _connection.On("ConfigReload", async () => { _logger.LogInformation("Full config reload requested, fetching from API..."); - _ = FetchFullConfigAsync(CancellationToken.None); + await FetchFullConfigAsync(stoppingToken); }); // Reconnection events @@ -108,6 +111,7 @@ public sealed class ConfigReceiverService : BackgroundService try { await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken); + await FetchFullConfigAsync(stoppingToken); } catch (Exception ex) { @@ -130,7 +134,11 @@ public sealed class ConfigReceiverService : BackgroundService await FetchFullConfigAsync(stoppingToken); // Keep service alive until cancellation — auto-reconnect handles reconnection - await Task.Delay(Timeout.Infinite, stoppingToken); + while (!stoppingToken.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + await FetchFullConfigAsync(stoppingToken); + } } catch (OperationCanceledException) { @@ -251,6 +259,7 @@ public sealed class ConfigReceiverService : BackgroundService private async Task FetchFullConfigAsync(CancellationToken ct) { + await _reloadLock.WaitAsync(ct); try { using var http = _httpClientFactory.CreateClient("Central"); @@ -280,8 +289,9 @@ public sealed class ConfigReceiverService : BackgroundService // Apply every key through the same pipeline as live SettingChanged // events — heartbeat interval, log level, credentials, restart-required // documentation, everything. - foreach (var kvp in config) + foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) ApplySetting(kvp.Key, kvp.Value); + _cameraStore.ReplaceCentral(config); // The Central camera list is authoritative once the full config // arrives — even if it is empty, drop the local fallback. @@ -291,6 +301,7 @@ public sealed class ConfigReceiverService : BackgroundService { _logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name); } + finally { _reloadLock.Release(); } } } diff --git a/src/Heimdall.Agent/Services/FrameMotionDetector.cs b/src/Heimdall.Agent/Services/FrameMotionDetector.cs index 61bc72a..fedb692 100644 --- a/src/Heimdall.Agent/Services/FrameMotionDetector.cs +++ b/src/Heimdall.Agent/Services/FrameMotionDetector.cs @@ -1,39 +1,45 @@ +using Heimdall.Application.DTOs; +using ImageMagick; + namespace Heimdall.Agent.Services; -/// -/// Lightweight frame-level motion proxy: compares the compressed size of -/// consecutive JPEG frames — a large relative change usually means scene -/// activity. Deliberately cheap (no JPEG decoding) and clearly documented as -/// a placeholder for the real pixel-diff Motion Gate of Phase 16 -/// (MASTER_SPECIFICATION). One instance per camera. -/// +/// Per-camera pixel difference on a fixed RGB grid; JPEG encoding size is irrelevant. public sealed class FrameMotionDetector { private readonly double _thresholdPercent; - private long _lastFrameLength; + private byte[]? _previous; + private DetectionProfileDto? _profile; - public FrameMotionDetector(double thresholdPercent = 8.0) - { - _thresholdPercent = thresholdPercent; - } + public FrameMotionDetector(double thresholdPercent = 8.0) => _thresholdPercent = thresholdPercent; - /// - /// Feeds the next frame and reports whether the scene changed enough to - /// count as motion. The first frame is always a baseline (no motion). - /// - public bool Detect(byte[] jpegFrame) + public bool Detect(byte[] jpegFrame) => Detect(jpegFrame, + new DetectionProfileDto { MotionThreshold = _thresholdPercent / 100 }); + + public bool Detect(byte[] jpegFrame, DetectionProfileDto profile) { - var length = jpegFrame.Length; - if (_lastFrameLength == 0) + profile.Validate(); + using var image = new MagickImage(jpegFrame); + image.Resize(new MagickGeometry(64, 64) { IgnoreAspectRatio = true }); + var pixels = image.GetPixels().ToByteArray(PixelMapping.RGB) ?? throw new InvalidOperationException("RGB conversion failed"); + var previous = _previous; + _previous = pixels; + if (previous is null || profile != _profile) { - _lastFrameLength = length; + _profile = profile; return false; } - - var change = Math.Abs(length - _lastFrameLength) / (double)_lastFrameLength * 100.0; - _lastFrameLength = length; - return change >= _thresholdPercent; + var changed = 0; + var total = 0; + for (var y = (int)(profile.ZoneY * 64); y < Math.Ceiling((profile.ZoneY + profile.ZoneHeight) * 64); y++) + for (var x = (int)(profile.ZoneX * 64); x < Math.Ceiling((profile.ZoneX + profile.ZoneWidth) * 64); x++) + { + var i = (y * 64 + x) * 3; + var delta = (Math.Abs(pixels[i] - previous[i]) + Math.Abs(pixels[i+1] - previous[i+1]) + Math.Abs(pixels[i+2] - previous[i+2])) / (3.0 * 255); + if (delta >= profile.MotionPixelThreshold) changed++; + total++; + } + return profile.DetectMotion && changed > 0 && changed / (double)total >= profile.MotionThreshold; } - public void Reset() => _lastFrameLength = 0; + public void Reset() { _previous = null; _profile = null; } } diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index eb95efb..4501653 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -1,3 +1,4 @@ +using Heimdall.Application.DTOs; using System.Collections.Concurrent; using Heimdall.Application.Metrics; using Microsoft.Extensions.Options; @@ -51,6 +52,8 @@ public sealed class SnapshotPipelineService : BackgroundService private readonly IRemoteFrameBroker? _broker; private readonly FrameResizer? _resizer; private readonly ILogger _logger; + private readonly SemaphoreSlim _syncLock = new(1, 1); + private readonly Dictionary _streamUrls = new(); private readonly ConcurrentDictionary _motionDetectors = new(); private readonly ConcurrentDictionary _reportedSceneState = new(); @@ -60,6 +63,7 @@ public sealed class SnapshotPipelineService : BackgroundService private long _remoteSubmissions; private long _remoteFallbacks; private bool _storeSubscribed; + private int _configDirty; private DateTime _lastCpuCheckAt = DateTime.MinValue; private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10); @@ -139,8 +143,9 @@ public sealed class SnapshotPipelineService : BackgroundService // (e.g. camera settings applied before we subscribed). while (!stoppingToken.IsCancellationRequested) { - await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); - await SyncStreamsAsync(stoppingToken); + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); + if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0) + await SyncStreamsAsync(stoppingToken); } } finally @@ -158,36 +163,39 @@ public sealed class SnapshotPipelineService : BackgroundService public override async Task StopAsync(CancellationToken cancellationToken) { - await _streams.StopAllAsync(); await base.StopAsync(cancellationToken); + await _streams.StopAllAsync(); } private void OnCameraConfigChanged(object? sender, EventArgs e) { - // Fire-and-forget resync; SyncStreamsAsync is idempotent and cheap. - _ = Task.Run(() => SyncStreamsAsync(CancellationToken.None)); + Interlocked.Exchange(ref _configDirty, 1); } private async Task SyncStreamsAsync(CancellationToken ct) { + await _syncLock.WaitAsync(ct); + try + { var desired = _cameraStore.Cameras .Where(c => c.Enabled && !string.IsNullOrWhiteSpace(c.EffectiveRtspUrl)) .ToList(); // Stop streams for cameras no longer assigned/disabled. var toStop = _streams.ActiveCameraIds - .Where(activeId => !desired.Any(c => c.CameraId == activeId)) + .Where(activeId => !desired.Any(c => c.CameraId == activeId && (!_streamUrls.TryGetValue(activeId, out var url) || url == c.EffectiveRtspUrl))) .ToList(); foreach (var activeId in toStop) { await _streams.StopStreamAsync(activeId); - // Camera removed/disabled → Disabled status at the Central. - await _statusReporter.ReportAsync(activeId, "Disabled", ct); + _streamUrls.Remove(activeId); + _motionDetectors.TryRemove(activeId, out _); } // Start streams for newly assigned cameras. foreach (var camera in desired) { + _streams.SetDetectionProfile(camera.CameraId, camera.DetectionProfile ?? new DetectionProfileDto()); if (_streams.IsStreamActive(camera.CameraId)) { // Capture already running → Online. @@ -198,6 +206,7 @@ public sealed class SnapshotPipelineService : BackgroundService var started = await _streams.StartStreamAsync(camera.CameraId, camera.EffectiveRtspUrl, ct); if (started) { + _streamUrls[camera.CameraId] = camera.EffectiveRtspUrl; _logger.LogInformation("Capture started for camera {CameraId} ({Name})", camera.CameraId, camera.Name); await _statusReporter.ReportAsync(camera.CameraId, "Online", ct); } @@ -210,6 +219,8 @@ public sealed class SnapshotPipelineService : BackgroundService await _statusReporter.ReportAsync(camera.CameraId, "Error", ct); } } + } + finally { _syncLock.Release(); } } /// @@ -257,7 +268,24 @@ public sealed class SnapshotPipelineService : BackgroundService // Motion detection runs in both modes — it gates remote submission. var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); - var motion = detector.Detect(snapshot.JpegData); + var camera = _cameraStore.Cameras.FirstOrDefault(c => c.CameraId == snapshot.CameraId); + if (camera is null || !camera.Enabled) continue; + var profile = camera.DetectionProfile ?? new DetectionProfileDto(); + profile.Validate(); + var motion = detector.Detect(snapshot.JpegData, profile); + if (profile.RequireMotionForAI && !motion) + { + _sceneState.UpdateFromAnalysis(false, false); + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + continue; + } + if (level >= DegradationLevel.ExecutorDown) + { + _sceneState.UpdateFromAnalysis(false, motion); + Interlocked.Increment(ref _snapshotsSkippedByDegradation); + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + continue; + } FrameAnalysisResult? result = null; @@ -271,27 +299,20 @@ public sealed class SnapshotPipelineService : BackgroundService { // Local analysis: either Local mode, or Remote mode with broker fallback, // or Remote mode but no motion (still run local for detection coverage). - result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct: ct); + result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, profile.MinConfidence, ct: ct); } + if (result is null) + throw new InvalidOperationException("Inference unavailable, skipped or saturated"); + result = result with { Detections = result.Detections.Where(d => d.Confidence >= profile.MinConfidence && profile.AllowsClass(d.ClassIndex)).ToArray() }; Interlocked.Increment(ref _snapshotsProcessed); _sceneState.UpdateFromAnalysis( result?.Detections.Count > 0, motion); - if (level >= DegradationLevel.ExecutorDown) - { - // Motion-only mode: skip IA inference reporting - Interlocked.Increment(ref _snapshotsSkippedByDegradation); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - } - else - { - // Normal or SlowExecutor: report full analysis - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); - } + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs index e8cb596..0afa644 100644 --- a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs @@ -51,6 +51,10 @@ public class ReportCameraStatusCommandHandler : IRequestHandler>; + string? Model = null, + DetectionProfileDto? DetectionProfile = null) : IRequest>; public class UpdateCameraCommandHandler : IRequestHandler> { @@ -29,6 +31,16 @@ public class UpdateCameraCommandHandler : IRequestHandler.NotFound("Camera not found"); + if (request.DetectionProfile is { } executionProfile) + { + try { executionProfile.Validate(); } + catch (ArgumentException ex) { return ServiceResult.Failure(ex.Message, 400); } + var profile = await _db.CameraDetectionProfiles.FirstOrDefaultAsync(p => p.CameraId == camera.Id, ct) + ?? new CameraDetectionProfile(camera.Id); + profile.ExecutionProfileJson = JsonSerializer.Serialize(executionProfile); + if (camera.DetectionProfile is null) camera.SetDetectionProfile(profile); + } + var oldName = camera.Name; var oldManufacturer = camera.Manufacturer; var oldModel = camera.Model; camera.Update(request.Name, request.Manufacturer, request.Model, request.RtspUrl); diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs index 43a6291..46bbc52 100644 --- a/src/Heimdall.Application/DTOs/CameraDto.cs +++ b/src/Heimdall.Application/DTOs/CameraDto.cs @@ -14,7 +14,8 @@ public record UpdateCameraRequest( string? RtspUrl, CameraStatus? Status, string? Manufacturer = null, - string? Model = null); + string? Model = null, + DetectionProfileDto? DetectionProfile = null); /// Camera response including all discovery and stream test metadata. public record CameraResponse( diff --git a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs new file mode 100644 index 0000000..6eafacb --- /dev/null +++ b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs @@ -0,0 +1,43 @@ +namespace Heimdall.Application.DTOs; + +/// Version 1 supports COCO object detection and a normalized pixel motion gate. +public sealed record DetectionProfileDto +{ + public int Version { get; init; } = 1; + public int IdleIntervalMs { get; init; } = 1000; + public int MotionIntervalMs { get; init; } = 500; + public int ActiveIntervalMs { get; init; } = 200; + public float MinConfidence { get; init; } = .4f; + public bool DetectPerson { get; init; } = true; + public bool DetectVehicle { get; init; } = true; + public bool DetectAnimal { get; init; } + public bool DetectPackage { get; init; } + public bool DetectMotion { get; init; } = true; + public bool RequireMotionForAI { get; init; } = true; + public double MotionThreshold { get; init; } = .3; + public double MotionPixelThreshold { get; init; } = .08; + public double ZoneX { get; init; } + public double ZoneY { get; init; } + public double ZoneWidth { get; init; } = 1; + public double ZoneHeight { get; init; } = 1; + public string YoloModel { get; init; } = "yolov8n"; + + public void Validate() + { + if (IdleIntervalMs is < 50 or > 60000 || MotionIntervalMs is < 50 or > 60000 || ActiveIntervalMs is < 50 or > 60000 || Version != 1 || !float.IsFinite(MinConfidence) || MinConfidence is < 0 or > 1 || + !double.IsFinite(MotionThreshold) || MotionThreshold is < 0 or > 1 || + !double.IsFinite(MotionPixelThreshold) || MotionPixelThreshold is <= 0 or > 1 || + !double.IsFinite(ZoneX + ZoneY + ZoneWidth + ZoneHeight) || ZoneX < 0 || ZoneY < 0 || + ZoneWidth <= 0 || ZoneHeight <= 0 || ZoneX + ZoneWidth > 1 || ZoneY + ZoneHeight > 1 || + YoloModel != "yolov8n" || DetectPackage) + throw new ArgumentException("Unsupported or invalid detection profile; only COCO yolov8n is available (package detection requires another model)"); + } + + public bool AllowsClass(int? index) => index switch + { + 0 => DetectPerson, + 1 or 2 or 3 or 5 or 7 => DetectVehicle, + >= 14 and <= 23 => DetectAnimal, + _ => false + }; +} diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index b7ebf38..283f4d9 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Common; +using System.Text.Json; using Heimdall.Application.DTOs; using Heimdall.Application.Security; using Heimdall.Domain.Enums; @@ -81,6 +82,7 @@ public class GetEffectiveAgentConfigQueryHandler // carries them to the agent without a new API surface. var cameras = await _db.Cameras .AsNoTracking() + .Include(c => c.DetectionProfile) .Where(c => c.AgentId == request.AgentId && !c.IsDeleted) .ToListAsync(ct) .ConfigureAwait(false); @@ -88,6 +90,16 @@ public class GetEffectiveAgentConfigQueryHandler foreach (var camera in cameras) { var prefix = $"camera.{camera.Id}"; + var p = camera.DetectionProfile; + var profile = p is null ? new DetectionProfileDto() : new DetectionProfileDto + { + IdleIntervalMs = p.IdleIntervalMs, MotionIntervalMs = p.MotionIntervalMs, ActiveIntervalMs = p.ActiveIntervalMs, + MinConfidence = (float)p.MinConfidence, DetectPerson = p.DetectPerson, + DetectVehicle = p.DetectVehicle, DetectAnimal = p.DetectAnimal, DetectPackage = p.DetectPackage, + DetectMotion = p.DetectMotion, RequireMotionForAI = p.RequireMotionForAI, + MotionThreshold = p.MotionThreshold, YoloModel = p.YoloModel + }; + config[$"{prefix}.profile"] = p?.ExecutionProfileJson ?? JsonSerializer.Serialize(profile); config[$"{prefix}.name"] = camera.Name; if (!string.IsNullOrWhiteSpace(camera.RtspUrl)) config[$"{prefix}.rtsp"] = camera.RtspUrl; diff --git a/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs index 9aec226..cadd36c 100644 --- a/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs +++ b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs @@ -7,6 +7,8 @@ namespace Heimdall.Domain.Entities; public class CameraDetectionProfile { public Guid CameraId { get; private set; } + /// Optional versioned execution contract; null preserves legacy defaults. + public string? ExecutionProfileJson { get; set; } // Object types to detect public bool DetectPerson { get; set; } = true; diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 967ef91..223ca46 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -1,4 +1,5 @@ using Heimdall.Application.Common; +using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data.Interceptors; using Microsoft.AspNetCore.Identity; @@ -11,12 +12,14 @@ namespace Heimdall.Infrastructure.Data; public class AppDbContext : IdentityDbContext, IApplicationDbContext { private readonly AuditInterceptor _auditInterceptor; + private readonly IConfigBroadcastService? _configBroadcast; public AppDbContext( DbContextOptions options, - AuditInterceptor auditInterceptor) : base(options) + AuditInterceptor auditInterceptor, IConfigBroadcastService? configBroadcast = null) : base(options) { _auditInterceptor = auditInterceptor; + _configBroadcast = configBroadcast; } // Domain entities @@ -87,6 +90,23 @@ public class AppDbContext : IdentityDbContext, IApplicat await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false); } + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + ChangeTracker.DetectChanges(); + var invalidate = ChangeTracker.Entries().Any(e => + e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted && + e.Entity is Camera or CameraAssignment or CameraDetectionProfile); + var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (invalidate && _configBroadcast is not null) + { + // Payload-free invalidation: each agent refetches its authorized full snapshot. + // Delivery is best effort; reconnect and periodic resync recover a missed notification. + try { await _configBroadcast.NotifyAllAgentsReload(cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException) { System.Diagnostics.Trace.TraceError("Config invalidation delivery failed: {0}", ex.GetType().Name); } + } + return result; + } + protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); diff --git a/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs b/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs new file mode 100644 index 0000000..2ad3bc6 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261020030000_AddDetectionExecutionProfile.cs @@ -0,0 +1,16 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261020030000_AddDetectionExecutionProfile")] +public sealed class AddDetectionExecutionProfile : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => + migrationBuilder.AddColumn(name: "ExecutionProfileJson", table: "camera_detection_profiles", type: "text", nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) => + migrationBuilder.DropColumn(name: "ExecutionProfileJson", table: "camera_detection_profiles"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 06d9c53..4d649c4 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -900,6 +900,9 @@ namespace Heimdall.Infrastructure.Migrations modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => { + b.Property("ExecutionProfileJson") + .HasColumnType("text"); + b.Property("CameraId") .HasColumnType("uuid"); diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index 2f9408b..ccf2973 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -74,7 +74,7 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct) { - var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, request.Manufacturer, request.Model); + var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, request.Manufacturer, request.Model, request.DetectionProfile); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs b/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs new file mode 100644 index 0000000..47e627b --- /dev/null +++ b/tests/Heimdall.Agent.Tests/DetectionProfileTests.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Heimdall.Agent.Services; +using Heimdall.Application.DTOs; + +namespace Heimdall.Agent.Tests; + +public class DetectionProfileTests +{ + [Fact] + public void FullResync_RemovesOldCamera_AndAppliesProfileInOneNotification() + { + var store = new CameraConfigStore(); + var oldId = Guid.NewGuid(); + var newId = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{oldId}.rtsp", "rtsp://old"); + var changes = 0; + store.Changed += (_, _) => changes++; + store.ReplaceCentral(new Dictionary + { + [$"camera.{newId}.rtsp"] = "rtsp://new", + [$"camera.{newId}.enabled"] = "false", + [$"camera.{newId}.profile"] = JsonSerializer.Serialize(new DetectionProfileDto { MinConfidence = .8f, DetectVehicle = false }) + }); + changes.ShouldBe(1); + var camera = store.Cameras.Single(); + camera.CameraId.ShouldBe(newId); + camera.Enabled.ShouldBeFalse(); + camera.DetectionProfile!.MinConfidence.ShouldBe(.8f); + camera.DetectionProfile.AllowsClass(2).ShouldBeFalse(); + camera.DetectionProfile.AllowsClass(0).ShouldBeTrue(); + store.ReplaceCentral(new Dictionary()); + store.Cameras.ShouldBeEmpty(); + } + + [Fact] + public void InvalidSnapshot_KeepsPreviousConfiguration() + { + var store = new CameraConfigStore(); + var id = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{id}.rtsp", "rtsp://old"); + Should.Throw(() => store.ReplaceCentral(new Dictionary + { [$"camera.{id}.profile"] = JsonSerializer.Serialize(new DetectionProfileDto { Version = 2 }) })); + store.Cameras.Single().RtspUrl.ShouldBe("rtsp://old"); + } + + [Fact] + public void UnsupportedFeatures_AndInvalidThreshold_AreRejected() + { + Should.Throw(() => new DetectionProfileDto { MinConfidence = float.NaN }.Validate()); + Should.Throw(() => new DetectionProfileDto { DetectPackage = true }.Validate()); + Should.Throw(() => new DetectionProfileDto { ZoneX = .8, ZoneWidth = .5 }.Validate()); + } +} diff --git a/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs index cb8b675..78ee120 100644 --- a/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs +++ b/tests/Heimdall.Agent.Tests/SceneStateTrackerTests.cs @@ -46,43 +46,40 @@ public class SceneStateTrackerTests public class FrameMotionDetectorTests { - [Fact] - public void FirstFrame_IsBaseline_NoMotion() + private static byte[] Frame(ImageMagick.IMagickColor color, uint quality = 90) { - var detector = new FrameMotionDetector(); - detector.Detect([1, 2, 3, 4]).ShouldBeFalse(); + using var image = new ImageMagick.MagickImage(color, 64, 64); + image.Quality = quality; + return image.ToByteArray(ImageMagick.MagickFormat.Jpeg); } [Fact] - public void IdenticalFrames_NoMotion() + public void PixelChange_TriggersMotion_AndResetCreatesBaseline() { var detector = new FrameMotionDetector(); - detector.Detect([1, 2, 3, 4]); - detector.Detect([1, 2, 3, 4]).ShouldBeFalse(); - } - - [Fact] - public void MuchLargerFrame_Motion() - { - var detector = new FrameMotionDetector(); - detector.Detect(new byte[100]); - detector.Detect(new byte[200]).ShouldBeTrue(); // +100% size - } - - [Fact] - public void SmallChange_BelowThreshold_NoMotion() - { - var detector = new FrameMotionDetector(thresholdPercent: 20.0); - detector.Detect(new byte[1000]); - detector.Detect(new byte[1100]).ShouldBeFalse(); // +10% < 20% - } - - [Fact] - public void Reset_StartsNewBaseline() - { - var detector = new FrameMotionDetector(); - detector.Detect(new byte[100]); + detector.Detect(Frame(ImageMagick.MagickColors.Black)).ShouldBeFalse(); + detector.Detect(Frame(ImageMagick.MagickColors.White)).ShouldBeTrue(); detector.Reset(); - detector.Detect(new byte[500]).ShouldBeFalse(); // baseline again + detector.Detect(Frame(ImageMagick.MagickColors.Black)).ShouldBeFalse(); + } + + [Fact] + public void EncodingChange_DoesNotTriggerMotion() + { + var detector = new FrameMotionDetector(); + detector.Detect(Frame(ImageMagick.MagickColors.Red, 40)); + detector.Detect(Frame(ImageMagick.MagickColors.Red, 100)).ShouldBeFalse(); + } + + [Fact] + public void Zone_IgnoresChangesOutsideRegion() + { + var detector = new FrameMotionDetector(); + var profile = new Heimdall.Application.DTOs.DetectionProfileDto { ZoneWidth = .5 }; + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 64, 64); + detector.Detect(image.ToByteArray(ImageMagick.MagickFormat.Png), profile); + using var patch = new ImageMagick.MagickImage(ImageMagick.MagickColors.White, 32, 64); + image.Composite(patch, 32, 0, ImageMagick.CompositeOperator.Over); + detector.Detect(image.ToByteArray(ImageMagick.MagickFormat.Png), profile).ShouldBeFalse(); } } diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 50167b9..82d8051 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -94,18 +94,27 @@ public class SnapshotPipelineServiceTests [Fact] public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer() { - var (service, _, _, streams, analyzer) = CreatePipeline(); + var (service, _, store, streams, analyzer) = CreatePipeline(); + var id = Guid.NewGuid(); + store.ReplaceCentral(new Dictionary + { + [$"camera.{id}.enabled"] = "true", + [$"camera.{id}.profile"] = System.Text.Json.JsonSerializer.Serialize(new Heimdall.Application.DTOs.DetectionProfileDto { RequireMotionForAI = false }) + }); + using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 64, 64); await service.StartAsync(CancellationToken.None); try { await streams.SnapshotChannel.Writer.WriteAsync( - new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3])); + new Snapshot(id, DateTime.UtcNow, image.ToByteArray(ImageMagick.MagickFormat.Jpeg))); var deadline = DateTime.UtcNow.AddSeconds(5); - while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline) + while (analyzer.AnalyzedFrameCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); // The frame reached the analyzer — real call, not just a counter. - service.SnapshotsProcessed.ShouldBe(1); + // An unavailable model is never counted as a successful negative analysis. + service.SnapshotsProcessed.ShouldBe(0); + service.AnalysisFailures.ShouldBe(1); analyzer.AnalyzedFrameCount.ShouldBe(1); } finally