diff --git a/src/Heimdall.Api/Hubs/EventsHub.cs b/src/Heimdall.Api/Hubs/EventsHub.cs
new file mode 100644
index 0000000..28c9ef3
--- /dev/null
+++ b/src/Heimdall.Api/Hubs/EventsHub.cs
@@ -0,0 +1,76 @@
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.SignalR;
+
+namespace Heimdall.Api.Hubs;
+
+///
+/// SignalR hub for real-time camera events pushed to the web UI.
+/// Connected clients receive new events instantly (motion, person, vehicle, etc.)
+/// without polling.
+///
+[Authorize(AuthenticationSchemes = "JwtBearer")]
+public class EventsHub : Hub
+{
+ private readonly ILogger _logger;
+
+ public EventsHub(ILogger logger) => _logger = logger;
+
+ ///
+ /// Clients call this to join a group-filtered event feed (e.g., per site).
+ ///
+ public async Task JoinSiteEvents(string siteId)
+ {
+ if (!Guid.TryParse(siteId, out _))
+ {
+ await Clients.Caller.SendAsync("Error", "Invalid siteId format");
+ return;
+ }
+ await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
+ _logger.LogDebug("Client {ConnectionId} joined site events group {SiteId}", Context.ConnectionId, siteId);
+ }
+
+ ///
+ /// Clients call this to leave a group-filtered event feed.
+ ///
+ public async Task LeaveSiteEvents(string siteId)
+ {
+ if (!Guid.TryParse(siteId, out _)) return;
+ await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
+ }
+
+ public override async Task OnConnectedAsync()
+ {
+ _logger.LogDebug("Client connected to events hub: {ConnectionId}", Context.ConnectionId);
+ await base.OnConnectedAsync();
+ }
+
+ public override async Task OnDisconnectedAsync(Exception? exception)
+ {
+ _logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId);
+ await base.OnDisconnectedAsync(exception);
+ }
+}
+
+///
+/// Sends SignalR notifications when new camera events are created.
+/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
+///
+public class EventBroadcastService : IEventBroadcastService
+{
+ private readonly IHubContext _hubContext;
+ private readonly ILogger _logger;
+
+ public EventBroadcastService(IHubContext hubContext, ILogger logger)
+ {
+ _hubContext = hubContext;
+ _logger = logger;
+ }
+
+ public async Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default)
+ {
+ _logger.LogDebug("Broadcasting new event: {EventId} type={Type} camera={CameraId}", ev.Id, ev.Type, ev.CameraId);
+ await _hubContext.Clients.All.SendAsync("EventCreated", ev, ct);
+ }
+}
diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs
index 564542b..6499b4d 100644
--- a/src/Heimdall.Api/Program.cs
+++ b/src/Heimdall.Api/Program.cs
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.RateLimiting;
using Scalar.AspNetCore;
using Heimdall.Api.Filters;
using Heimdall.Application;
+using Heimdall.Application.Services;
using Heimdall.Infrastructure;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Data;
@@ -61,6 +62,7 @@ else
}
builder.Services.AddSignalR();
+builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddOpenApi();
@@ -261,5 +263,6 @@ app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub("/hubs/config");
+app.MapHub("/hubs/events");
app.Run();
diff --git a/src/Heimdall.Application/Services/IEventBroadcastService.cs b/src/Heimdall.Application/Services/IEventBroadcastService.cs
new file mode 100644
index 0000000..111575a
--- /dev/null
+++ b/src/Heimdall.Application/Services/IEventBroadcastService.cs
@@ -0,0 +1,13 @@
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+///
+/// Broadcasts camera events to connected clients (SignalR / WebSocket).
+/// Implemented in the API layer; referenced by Infrastructure for decoupled
+/// notification after event creation.
+///
+public interface IEventBroadcastService
+{
+ Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default);
+}
diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs
index 2307997..6658b59 100644
--- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs
+++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs
@@ -4,6 +4,7 @@ using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
@@ -11,13 +12,16 @@ namespace Heimdall.Infrastructure.Services;
public sealed class CameraEventService : ICameraEventService
{
private readonly IDbContextFactory _dbFactory;
+ private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
public CameraEventService(
IDbContextFactory dbFactory,
+ IServiceProvider serviceProvider,
ILogger logger)
{
_dbFactory = dbFactory;
+ _serviceProvider = serviceProvider;
_logger = logger;
}
@@ -40,6 +44,21 @@ public sealed class CameraEventService : ICameraEventService
"Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}",
ev.Id, ev.Type, ev.Confidence, ev.CameraId);
+ // Fire-and-forget broadcast to connected SignalR clients
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ using var scope = _serviceProvider.CreateScope();
+ var broadcast = scope.ServiceProvider.GetRequiredService();
+ await broadcast.NotifyEventCreated(MapResponse(ev));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Failed to broadcast event {EventId}", ev.Id);
+ }
+ }, CancellationToken.None);
+
return ServiceResult.Success(MapResponse(ev));
}
diff --git a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs
index 7b7faae..fbdfb6f 100644
--- a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs
+++ b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs
@@ -15,6 +15,7 @@ public class CameraEventServiceTests
{
private readonly IDbContextFactory _dbFactory;
private readonly ILogger _logger = Substitute.For>();
+ private readonly IServiceProvider _serviceProvider = Substitute.For();
public CameraEventServiceTests()
{
@@ -47,7 +48,7 @@ public class CameraEventServiceTests
[Fact]
public async Task CreateAsync_ValidRequest_ReturnsEvent()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var result = await service.CreateAsync(new CreateCameraEventRequest(
@@ -63,7 +64,7 @@ public class CameraEventServiceTests
[Fact]
public async Task CreateAsync_UnknownCamera_ReturnsNotFound()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var result = await service.CreateAsync(new CreateCameraEventRequest(
Guid.NewGuid(), EventType.MotionDetected, 0.9, null, null, null),
CancellationToken.None);
@@ -75,7 +76,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetByIdAsync_ExistingId_ReturnsEvent()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new CreateCameraEventRequest(
@@ -90,7 +91,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetByIdAsync_UnknownId_ReturnsNotFound()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var result = await service.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
@@ -99,7 +100,7 @@ public class CameraEventServiceTests
[Fact]
public async Task QueryAsync_FilterByType_ReturnsFiltered()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -118,7 +119,7 @@ public class CameraEventServiceTests
[Fact]
public async Task QueryAsync_FilterByMinConfidence_ReturnsFiltered()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.95, null, null, null), CancellationToken.None);
@@ -135,7 +136,7 @@ public class CameraEventServiceTests
[Fact]
public async Task DeleteAsync_ExistingEvent_RemovesIt()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -150,7 +151,7 @@ public class CameraEventServiceTests
[Fact]
public async Task AttachSnapshotAsync_ExistingEvent_UpdatesSnapshot()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -171,7 +172,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetRecentByCameraAsync_ReturnsLatest()
{
- var service = new CameraEventService(_dbFactory, _logger);
+ var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
for (int i = 0; i < 5; i++)