feat(discovery): add camera detection pipeline inspired by Strix

Add complete camera discovery and stream testing specification,
Domain entities, enums, DTOs, Application interfaces, and EF Core
configurations for automated ONVIF/mDNS/HTTP/ARP camera detection.

- 4 new enums: CameraDiscoveryMethod, DetectedCameraType,
  StreamProtocol, CameraCapability (flags)
- Camera entity extended with 15+ discovery/test fields
- New entities: CameraDiscoveryResult, DiscoveredStreamUrl
- DTOs: ProbeRequest/Response, StreamTestRequest/Session, etc.
- Interface: ICameraDiscoveryService (8 methods)
- EF Core configurations for all new tables + columns
- Full spec doc: docs/specifications/detection-camera.md (16 sections)
- 145 tests pass, 0 warnings

Inspiré de Strix (github.com/eduard256/Strix) — moteur de
découverte de flux IP supportant 3600+ marques, 100K+ patterns.
This commit is contained in:
Arnaud Dartois committed 2026-07-18 21:15:05 +00:00
1 parent 8c6b2610a0
commit 7e66bb4fbb
16 files changed
+1815 -7

No files matched your search

+975
View File
@@ -0,0 +1,975 @@
# Spécification — Détection & Découverte de Caméras
> **Inspiré de**: [Strix](https://github.com/eduard256/Strix) v2.1 — Moteur de découverte de flux IP
> **Date**: 2026-07-18
> **Statut**: Proposition d'architecture
---
## 1. Résumé Exécutif
Heimdall a besoin d'un système de **découverte automatique de caméras** sur le réseau local
pour remplacer la configuration manuelle actuelle (IP + URL RTSP saisis à la main).
L'architecture s'inspire directement de **Strix** (Go), un moteur de découverte de flux
éprouvé qui supporte 3600+ marques, 100 000+ patterns d'URL et 20 protocoles — mais
réimplémenté en **.NET 10 Clean Architecture** avec une intégration profonde dans l'écosystème
Heimdall (PostgreSQL, Hangfire, SignalR, Blazor).
---
## 2. Pipeline de Découverte
```
┌─────────────────────────────────────────────────────────────────────┐
│ PIPELINE DE DÉCOUVERTE │
│ │
│ 1. SCAN RÉSEAU 2. PROBE DEVICE 3. RECHERCHE DB 4. TEST FLUX │
│ ┌─────────┐ ┌──────────┐ ┌───────────┐ ┌─────────┐ │
│ │ Nmap │────→│ ONVIF │────→│ Heimdall │────→│ RTSP │ │
│ │ ARP │ │ WS-Disc │ │ CamDB │ │ HTTP │ │
│ │ mDNS │ │ HTTP │ │ (brands │ │ ONVIF │ │
│ │ (sous- │ │ mDNS/HAP │ │ + modèles)│ │ profil │ │
│ │ réseau │ │ ARP/OUI │ │ │ │ capture │ │
│ │ local) │ │ (100ms) │ │ │ │ écran │ │
│ └─────────┘ └──────────┘ └───────────┘ └─────────┘ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ SYNTHÈSE │ │
│ │ - IP + MAC + Fabricant + Modèle │ │
│ │ - Protocoles detectés (ONVIF, RTSP, HTTP, HomeKit) │ │
│ │ - URL de flux testées + codecs + résolution │ │
│ │ - Statut (en ligne/hors ligne/type détecté) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ INTÉGRATION HEIMDALL │ │
│ │ - Création automatique de l'entité Camera │ │
│ │ - Sauvegarde des credentials (chiffrés) │ │
│ │ - Envoi config à l'Agent via SignalR │ │
│ │ - Notification UI (Blazor Hub) │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
```
---
## 3. Scan Réseau (NetworkScanner)
### 3.1. Découverte des hôtes
Stratégie progressive avec timeouts agressifs :
| Méthode | Port/Protocole | Timeout | Informations obtenues |
|---------|---------------|---------|----------------------|
| **ARP lookup** (table ARP locale) | Niveau 2 | 5ms | MAC, fabricant via OUI |
| **mDNS multicast** (`_hap._tcp.local`) | UDP 5353 | 1.5s | Caméras HomeKit (nom, modèle, device_id, catégorie) |
| **Ping ICMP** | ICMP | 500ms | Hôte joignable (nécessite `CAP_NET_RAW`) |
| **Scan ports ciblé** | 554,80,443,8080,34567,1935,81,88,8090,5544,10554,7070,7447,3702,8554,8001,8081,51826 | 100ms par port (parallèle 20 workers) | Ports ouverts typiques caméra |
| **WS-Discovery ONVIF** | UDP 3702 (unicast) | 100ms | Détection ONVIF — nom, hardware, XAddrs (URL device_service) |
> **Note**: Le scan réseau est exécuté **uniquement** sur les sous-réseaux configurés
> dans le Site (site.NetworkCidr) par le **Heimdall.Workers** (pas l'Agent).
> Un background job Hangfire planifié (`NetworkScanJob`) lance le scan périodiquement.
### 3.2. Architecture du scan
```
NetworkScanJob (Hangfire)
│
├── NetworkScannerService
│ ├── ArpLookup() → (MAC, Vendor)
│ ├── MulticastMdnsQuery() → (HomeKit cameras)
│ ├── PingSweep(cidr) → list<IP> joignables
│ └── PortScan(ip, ports) → list<int> ports ouverts
│
├── OnvifProbeService
│ └── ProbeDevice(ip) → ONVIFResult (XAddrs, name, hardware)
│
├── HttpProbeService
│ └── Probe(ip, ports) → HTTPResult (status, server header)
│
├── StreamTestService
│ ├── TestRtsp(url, creds) → codecs, résolution, latence, screenshot
│ ├── TestHttp(url, creds) → MJPEG snapshot
│ └── TestOnvifProfile(url) → résolution profils → test RTSP
│
└── DiscoveryResultProcessor
├── MergeResults() → fusionne toutes les données
└── CreateOrUpdateCamera() → persiste l'entité Camera
```
---
## 4. Probe Device (ProbeService)
### 4.1. ONVIF WS-Discovery
Envoi d'un message SOAP `Probe` en UDP unicast sur le port 3702 :
```xml
<?xml version="1.0" ?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<a:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>
<a:MessageID>urn:uuid:{uuid}</a:MessageID>
<a:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>
</s:Header>
<s:Body>
<d:Probe xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery">
<d:Types/>
<d:Scopes/>
</d:Probe>
</s:Body>
</s:Envelope>
```
**Parsing de la réponse** — extraction depuis le XML SOAP :
- `XAddrs` → URL du `device_service` (correction bug `0.0.0.0` → IP réelle)
- `Scopes` → `name`, `hardware` (ex: `onvif://www.onvif.org/name/DS-2CD2032`)
- Port extrait du XAddrs (ou 80 par défaut)
**Résultat**:
```csharp
public record OnvifProbeResult(
string DeviceServiceUrl, // ex: "http://192.168.1.100:8080/onvif/device_service"
int Port, // port du service
string? Name, // nom ONVIF du device
string? Hardware, // modèle matériel
string? Location); // emplacement (optionnel)
```
### 4.2. Détection HomeKit (mDNS/HAP)
**Recherche** : Interrogation multicast `_hap._tcp.local` (PTR) sur UDP 5353.
**Filtre** : Ne conserve que les réponses avec `ci=17` (camera) ou `ci=18` (doorbell).
**Parsing** des enregistrements TXT :
| Clé TXT | Champ | Exemple |
|---------|-------|---------|
| `ci` | Category | `17` (camera), `18` (doorbell) |
| `id` | Device ID | `90:8C:0F:F2:EC:F3` |
| `md` | Model | `HomeKit Camera v2` |
| `sf` | Status Flags | `0` (non paired), `1` (paired) |
| `s#` | SRV port | `51826` ou dynamique |
**Résultat**:
```csharp
public record HomeKitProbeResult(
string Name,
string DeviceId,
string Model,
string Category, // "camera" | "doorbell"
bool IsPaired,
int Port);
```
### 4.3. HTTP Probe
HEAD/GET sur les ports HTTP courants (80, 8080, 443, 81, 88, 8090) :
```csharp
public record HttpProbeResult(
int Port,
int StatusCode,
string? ServerHeader, // ex: "Hikvision-Webs", "DVRDVS-Webs"
bool SupportsDigestAuth);
```
Le `Server` header identifie le fabricant : `Hikvision-Webs` = Hikvision,
`DVRDVS-Webs` = Dahua, `Kguard` = Kguard, etc.
### 4.4. ARP + OUI Lookup
Consultation de la table ARP locale (`/proc/net/arp` ou `ip neigh show`) :
```
192.168.1.100 dev eth0 lladdr c0:56:e3:aa:bb:cc REACHABLE
```
Extraction OUI (3 premiers octets) → lookup dans table SQLite intégrée :
- `C0:56:E3` → `Hikvision`
- `00:23:6A` → `Hikvision`
- `3C:08:F6` → `Dahua`
- `AC:CC:8E` → `Dahua`
- `00:12:1B` → `ACTi`
- `F4:08:8C` → `Reolink`
**Résultat**:
```csharp
public record ArpProbeResult(
string MacAddress,
string? Vendor);
```
### 4.5. Port Scan Ciblé
Scan de 17 ports connus des caméras, en parallèle (20 workers, 100ms timeout par port) :
| Port | Protocole | Usage typique |
|------|-----------|---------------|
| 554 | RTSP | Flux vidéo standard |
| 80 | HTTP | Interface web, MJPEG, API ONVIF |
| 443 | HTTPS | Chiffré |
| 8080 | HTTP | Alternative, API ONVIF |
| 34567 | DVRIP | Dahua/Sofia protocol |
| 1935 | RTMP | Streaming, NVR chinois |
| 3702 | UDP | WS-Discovery ONVIF |
| 8554 | RTSP | Alternative |
| 5544 | RTSP | Alternative |
| 10554 | RTSP | Alternative |
| 81 | HTTP | Alternative |
| 88 | HTTP | Alternative |
| 8090 | HTTP | Alternative |
| 8001 | HTTP | Alternative |
| 8081 | HTTP | Alternative |
| 7070 | HTTP | Alternative |
| 7447 | HTTP | Alternative |
| 51826 | TCP | HomeKit (HAP) |
---
## 5. Recherche Base de Données (CameraDatabase)
### 5.1. Structure de la base
Base SQLite intégrée au Central (téléchargée depuis StrixCamDB ou maintenue localement) :
```sql
-- Marques
CREATE TABLE brands (
brand_id TEXT PRIMARY KEY, -- ex: "hikvision"
brand TEXT NOT NULL -- ex: "Hikvision"
);
-- Patterns d'URL par marque
CREATE TABLE streams (
id INTEGER PRIMARY KEY,
brand_id TEXT NOT NULL REFERENCES brands(brand_id),
url TEXT NOT NULL, -- pattern avec placeholders
protocol TEXT NOT NULL, -- "rtsp", "http", "rtmp", "dvrip", "bubble"
port INTEGER DEFAULT 0 -- 0 = port par défaut du protocole
);
-- Modèles spécifiques
CREATE TABLE stream_models (
stream_id INTEGER REFERENCES streams(id),
model TEXT NOT NULL -- ex: "DS-2CD2032"
);
-- Presets (collections curated)
CREATE TABLE presets (
preset_id TEXT PRIMARY KEY, -- ex: "onvif", "popular-rtsp"
name TEXT NOT NULL
);
CREATE TABLE preset_streams (
preset_id TEXT REFERENCES presets(preset_id),
url TEXT NOT NULL,
protocol TEXT NOT NULL,
port INTEGER DEFAULT 0
);
-- Table OUI pour lookup MAC → Fabricant
CREATE TABLE oui (
mac_prefix TEXT PRIMARY KEY, -- ex: "C056E3"
vendor TEXT NOT NULL
);
```
### 5.2. Types de résultats
| Type | ID | Description | Exemple |
|------|-----|-------------|---------|
| `preset` | `p:{preset_id}` | Collection de patterns (ex: "ONVIF standard") | `p:onvif-global` |
| `brand` | `b:{brand_id}` | Tous les patterns d'une marque | `b:hikvision` |
| `model` | `m:{brand_id}:{model}` | Patterns d'un modèle spécifique | `m:hikvision:DS-2CD2032` |
### 5.3. API Recherche
```csharp
// Recherche textuelle (marque, modèle)
Task<SearchResult[]> SearchAsync(string query, CancellationToken ct);
// Construction des URL de flux à partir d'un ID
Task<StreamUrl[]> BuildStreamsAsync(StreamRequest request, CancellationToken ct);
```
```csharp
public record StreamRequest(
string[] Ids, // IDs de recherche (ex: "b:hikvision", "p:onvif")
string Ip,
string? Username,
string? Password,
int Channel = 0,
int[]? PortFilter = null);
```
**Placeholders supportés** (substitution dans les patterns SQLite) :
| Placeholder | Remplacé par |
|---|---|
| `[CHANNEL]` / `[channel]` | Numéro de canal |
| `[USERNAME]` / `[user]` | Nom d'utilisateur (URL-encoded) |
| `[PASSWORD]` / `[pass]` / `[pwd]` | Mot de passe (URL-encoded) |
| `[IP]` / `[ip]` | Adresse IP |
| `[PORT]` / `[port]` | Port |
| `[WIDTH]` / `[width]` | `640` (défaut) |
| `[HEIGHT]` / `[height]` | `480` (défaut) |
| `[AUTH]` / `[auth]` | Basic auth base64 |
---
## 6. Test de Flux (StreamTester)
### 6.1. Architecture
20 workers parallèles. Chaque worker :
1. Reçoit une URL de flux (pool de workers)
2. Sélectionne le handler selon le protocole
3. Se connecte et négocie (timeout 10s)
4. Capture une image clé (keyframe) → screenshot JPEG
5. Extrait codecs, résolution, latence
6. Retourne le résultat
### 6.2. Protocoles supportés
| Protocole | Handler | Lib .NET | Exemple d'URL |
|-----------|---------|----------|---------------|
| **RTSP** | `RtspHandler` | `LibVLC` / `FFmpeg.Autogen` / `RtspClient` | `rtsp://admin:pass@192.168.1.100/Streaming/Channels/101` |
| **HTTP MJPEG** | `HttpMjpegHandler` | `HttpClient` + `ImageSharp` | `http://admin:pass@192.168.1.100/ISAPI/Streaming/channels/101/picture` |
| **HTTP JPEG** | `HttpJpegHandler` | `HttpClient` | `http://admin:pass@192.168.1.100/ snapshot.jpg` |
| **ONVIF** | `OnvifProfileHandler` | `Onvif.Client` (NuGet) | `onvif://admin:pass@192.168.1.100` |
| **DVRIP** | `DvripHandler` | Implémentation TCP/Sofia | `dvrip://admin:pass@192.168.1.100:34567` |
| **RTMP** | `RtmpHandler` | `FFmpeg.Autogen` | `rtmp://admin:pass@192.168.1.100:1935/live` |
| **HomeKit** | `HomeKitHandler` | HAP lib | `homekit://...?device_id=...&pin=...` |
### 6.3. Résultat de test
```csharp
public record StreamTestResult(
string SourceUrl, // URL testée (credentials masqués dans les logs)
string[] Codecs, // eg. ["H264", "PCMA"]
int Width, // Résolution largeur
int Height, // Résolution hauteur
long LatencyMs, // Latence de connexion
byte[]? ScreenshotJpeg, // Screenshot JPEG (optionnel)
bool IsAlive); // Flux fonctionnel
```
---
## 7. Modèle de Données — Entités Domain
### 7.1. Nouveaux enums
```csharp
// Dans Heimdall.Domain/Enums/
/// <summary>Méthode par laquelle la caméra a été détectée.</summary>
public enum CameraDiscoveryMethod
{
Manual = 0, // Saisie manuelle (actuel)
OnvifWsDiscovery = 1, // WS-Discovery ONVIF
MdnsHomeKit = 2, // mDNS HomeKit
NetworkScan = 3, // Scan réseau générique
HttpProbe = 4, // Détection par en-tête HTTP
ArpProbe = 5, // ARP + OUI
Imported = 6 // Import depuis fichier
}
/// <summary>Protocoles de flux supportés.</summary>
public enum StreamProtocol
{
Rtsp,
Rtsps,
Http,
Https,
Rtmp,
Rtmps,
Dvrip,
Bubble,
HomeKit
}
/// <summary>Type de caméra détecté.</summary>
public enum DetectedCameraType
{
Standard, // Caméra IP standard
HomeKit, // Apple HomeKit
Nvr, // NVR (multiple canaux)
Doorbell, // Sonnette vidéo
Unknown
}
```
### 7.2. Entité Camera — Modifications
```csharp
// Ajouts à Camera.cs existant
// Méthode de découverte
public CameraDiscoveryMethod DiscoveryMethod { get; private set; }
public DetectedCameraType DetectedType { get; private set; }
// MAC + Fabricant (ARP/OUI)
public string? MacAddress { get; private set; }
// Protocoles supportés (flags)
public StreamProtocol SupportedProtocols { get; private set; }
// Réseau
public string? IpAddress { get; private set; } // IP fixe si statique
public int? RtspPort { get; private set; }
public int? HttpPort { get; private set; }
public int? OnvifPort { get; private set; }
// Dernière découverte
public DateTime? LastDiscoveredAt { get; private set; }
// Dernier test de flux
public DateTime? LastStreamTestAt { get; private set; }
public string? LastTestedCodecs { get; private set; } // JSON array
public int? LastTestedWidth { get; private set; }
public int? LastTestedHeight { get; private set; }
public long? LastTestedLatencyMs { get; private set; }
// Nouveaux sous-flux
public string? SubRtspUrl { get; private set; } // Flux secondaire (détection)
// Méthodes
public void SetDiscoveryInfo(
CameraDiscoveryMethod method,
DetectedCameraType type,
string? macAddress,
string ipAddress);
public void SetStreamTestResult(
string? subRtspUrl,
string codecsJson,
int width,
int height,
long latencyMs);
public void SetPorts(
int? rtspPort,
int? httpPort,
int? onvifPort);
```
### 7.3. Nouvelles entités
```csharp
/// <summary>
/// Résultat de probe — stocké temporairement pour le pipeline de découverte.
/// </summary>
public class CameraDiscoveryResult : Entity<Guid>
{
public Guid SiteId { get; private set; }
public string IpAddress { get; private set; }
public string? MacAddress { get; private set; }
public string? Vendor { get; private set; }
public string? Hostname { get; private set; }
public DetectedCameraType DetectedType { get; private set; }
public CameraDiscoveryMethod DiscoveryMethod { get; private set; }
// Résultats des probes
public int[] OpenPorts { get; private set; } = [];
public string? OnvifDeviceServiceUrl { get; private set; }
public string? OnvifName { get; private set; }
public string? OnvifHardware { get; private set; }
public string? HttpServerHeader { get; private set; }
public int? HttpStatusCode { get; private set; }
public bool IsReachable { get; private set; }
// Timestamp
public DateTime ProbedAt { get; private set; } = DateTime.UtcNow;
// Navigation
public Site Site { get; private set; } = null!;
public ICollection<DiscoveredStream> DiscoveredStreams { get; private set; } = [];
}
/// <summary>
/// Flux vidéo découvert lors du test.
/// </summary>
public class DiscoveredStream
{
public Guid Id { get; private set; }
public Guid DiscoveryResultId { get; private set; }
public string Url { get; private set; }
public StreamProtocol Protocol { get; private set; }
public string[] Codecs { get; private set; } = [];
public int Width { get; private set; }
public int Height { get; private set; }
public long LatencyMs { get; private set; }
public bool IsMainStream { get; private set; }
public bool IsAlive { get; private set; }
public CameraDiscoveryResult DiscoveryResult { get; private set; } = null!;
}
```
---
## 8. API REST — Endpoints de Découverte
### 8.1. Probe (découverte initiale)
```
POST /api/discovery/probe
```
```json
{
"siteId": "guid",
"ip": "192.168.1.100",
"subnetCidr": "192.168.1.0/24"
}
```
**Sans IP** → scan du sous-réseau entier :
```
POST /api/discovery/scan
```
```json
{
"siteId": "guid",
"subnetCidr": "192.168.1.0/24",
"timeoutMs": 30000
}
```
### 8.2. Search database
```
GET /api/discovery/search?q=hikvision
```
```json
{
"results": [
{ "type": "brand", "id": "b:hikvision", "name": "Hikvision" },
{ "type": "model", "id": "m:hikvision:DS-2CD2032", "name": "Hikvision: DS-2CD2032" }
]
}
```
### 8.3. Build streams
```
POST /api/discovery/streams
```
```json
{
"ids": ["b:hikvision", "p:onvif"],
"ip": "192.168.1.100",
"username": "admin",
"password": "pass",
"channel": 0
}
```
### 8.4. Test streams
```
POST /api/discovery/test
```
```json
{
"sourceId": "guid",
"streams": [
"rtsp://admin:pass@192.168.1.100/Streaming/Channels/101",
"rtsp://admin:pass@192.168.1.100/Streaming/Channels/102"
]
}
```
**Réponse**:
```json
{
"sessionId": "uuid",
"status": "running",
"total": 2,
"tested": 0
}
```
**Polling** → `GET /api/discovery/test/{sessionId}`
```json
{
"sessionId": "uuid",
"status": "done",
"total": 2,
"tested": 2,
"alive": 2,
"results": [
{
"source": "rtsp://admin:***@192.168.1.100/Streaming/Channels/101",
"codecs": ["H264", "PCMA"],
"width": 1920,
"height": 1080,
"latencyMs": 45,
"screenshotUrl": "/api/discovery/test/{sessionId}/screenshot/0"
}
]
}
```
### 8.5. Add discovered camera
```
POST /api/discovery/confirm
```
```json
{
"siteId": "guid",
"name": "Entrée principale",
"discoveryResultId": "guid",
"mainStreamUrl": "rtsp://admin:pass@192.168.1.100/Streaming/Channels/101",
"subStreamUrl": "rtsp://admin:pass@192.168.1.100/Streaming/Channels/102",
"username": "admin",
"password": "encrypted",
"detectionProfile": { ... }
}
```
---
## 9. Interfaces Application
```csharp
/// <summary>Service de découverte réseau pour les caméras.</summary>
public interface ICameraDiscoveryService
{
// Probe une IP unique → résultats complets
Task<CameraDiscoveryResult> ProbeIpAsync(
Guid siteId, string ip, CancellationToken ct);
// Scan d'un sous-réseau → liste de résultats
Task<IReadOnlyList<CameraDiscoveryResult>> ScanSubnetAsync(
Guid siteId, string cidr, int timeoutMs, CancellationToken ct,
IProgress<ScanProgress>? progress = null);
// Recherche dans la base de caméras
Task<SearchResult[]> SearchDatabaseAsync(string query, CancellationToken ct);
// Construction des URL de flux
Task<string[]> BuildStreamUrlsAsync(
StreamRequest request, CancellationToken ct);
// Test de flux
Task<StreamTestSession> TestStreamsAsync(
Guid sourceId, string[] urls, CancellationToken ct);
// Confirmation et création de la caméra
Task<CameraResponse> ConfirmDiscoveryAsync(
ConfirmDiscoveryRequest request, CancellationToken ct);
}
/// <summary>Test de flux en temps réel.</summary>
public interface IStreamTesterService
{
Task<StreamTestSession> CreateSessionAsync(
string[] urls, CancellationToken ct);
Task<StreamTestSession?> GetSessionAsync(
Guid sessionId, CancellationToken ct);
Task<byte[]?> GetScreenshotAsync(
Guid sessionId, int index, CancellationToken ct);
Task CancelSessionAsync(Guid sessionId, CancellationToken ct);
}
```
---
## 10. Services Infrastructure
### 10.1. NetworkScannerService
```csharp
public class NetworkScannerService : INetworkScannerService
{
// ARP table lookup (multi-plateforme)
Task<ArpResult?> LookupArpAsync(string ip, CancellationToken ct);
// mDNS HomeKit query
Task<MdnsResult?> QueryMdnsAsync(string ip, CancellationToken ct);
// Ping ICMP
Task<bool> PingAsync(string ip, int timeoutMs, CancellationToken ct);
// Port scan parallélisé
Task<int[]> ScanPortsAsync(string ip, int[] ports, int timeoutMs, CancellationToken ct);
// Sweep sous-réseau
IAsyncEnumerable<ScanProgress> SweepSubnetAsync(
string cidr, int timeoutMs, CancellationToken ct);
}
```
### 10.2. OnvifProbeService
```csharp
public class OnvifProbeService : IOnvifProbeService
{
// WS-Discovery unicast probe
Task<OnvifProbeResult?> ProbeDeviceAsync(string ip, int timeoutMs, CancellationToken ct);
// Résolution des profils ONVIF
Task<OnvifProfile[]> GetProfilesAsync(string deviceServiceUrl,
string? username, string? password, CancellationToken ct);
// Obtention de l'URI RTSP pour un profil
Task<string?> GetStreamUriAsync(string deviceServiceUrl,
string profileToken, string? username, string? password, CancellationToken ct);
}
```
### 10.3. StreamTesterService
```csharp
public class StreamTesterService : IStreamTesterService
{
// Pool de workers parallèles (configurable)
// Support: RTSP, HTTP MJPEG/JPEG, ONVIF, RTMP, DVRIP
// Capture de screenshot via FFmpeg ou implémentation pure .NET
// Timeout par flux : 10s
// Session TTL : 30min après completion
}
```
### 10.4. OnvifClient (implémentation SOAP/XML)
```csharp
public class OnvifClient
{
// GetCapabilities()
// GetDeviceInformation() → manufacturer, model, firmware, serial
// GetProfiles() → liste des profils media
// GetStreamUri(token) → URI RTSP pour un profil
// GetServices() → services ONVIF disponibles
// SystemReboot() → si autorisé
// GetHostname() → nom d'hôte configuré
}
```
**NuGet candidates**:
- `Onvif.Client` (community) — basique
- `MJPEGStreamDecoder` — décodage MJPEG (HTTP)
- `FFmpeg.Autogen` — capture d'écran H264/H265 → JPEG
- `SharpPcap` ou `PacketDotNet` — ARP (Linux `CAP_NET_RAW`)
---
## 11. Intégration Workers (Hangfire)
### 11.1. NetworkScanJob
```csharp
/// <summary>Job Hangfire planifié — scanne les sous-réseaux des sites actifs.</summary>
public class NetworkScanJob : IJob
{
// Planifié toutes les 6h par site (cron)
// Découvre les nouvelles caméras
// Met à jour le statut des caméras existantes (Online/Offline)
// Envoie notification SignalR si nouveaux devices
public async Task ExecuteAsync(CancellationToken ct)
{
var sites = await _db.Sites
.Where(s => s.IsActive && !s.IsDeleted)
.ToListAsync(ct);
foreach (var site in sites.Where(s => s.NetworkCidr != null))
{
var discovered = await _discoveryService.ScanSubnetAsync(
site.Id, site.NetworkCidr, 60000, ct);
foreach (var result in discovered.Where(r => r.IsReachable))
{
await _processor.ProcessDiscoveryResultAsync(result, ct);
}
}
}
}
```
### 11.2. CameraHealthCheckJob
```csharp
/// <summary>Job Hangfire — vérifie l'état des flux toutes les 5min.</summary>
public class CameraHealthCheckJob : IJob
{
// Pour chaque caméra Online : ping + RTSP describe (timeout 3s)
// Si échec → marque Offline, notifie
// Si succès après Offline → marque Online, notifie
}
```
### 11.3. StreamTestJob
```csharp
/// <summary>Job Hangfire — test périodique des flux (codecs, résolution).</summary>
public class StreamTestJob : IJob
{
// Planifié quotidiennement
// Re-test des flux découverts automatiquement
// Met à jour les métriques (latence, résolution, codecs)
}
```
---
## 12. Nouveaux Flags Camera (Enum)
```csharp
[Flags]
public enum CameraCapability
{
None = 0,
RtspStreaming = 1 << 0, // RTSP stream
HttpMjpeg = 1 << 1, // MJPEG over HTTP
HttpSnapshot = 1 << 2, // JPEG snapshot
Onvif = 1 << 3, // ONVIF protocol
OnvifPtz = 1 << 4, // PTZ over ONVIF
OnvifAudioIn = 1 << 5, // Audio input
OnvifAudioOut = 1 << 6, // Audio output
HomeKit = 1 << 7, // Apple HomeKit
Dvrip = 1 << 8, // Dahua DVRIP/Sofia
Rtmp = 1 << 9, // RTMP streaming
SubStream = 1 << 10, // Second flux (sous-flux)
}
```
---
## 13. DTOs Application
```csharp
// Request/Response DTOs à ajouter
public record ProbeRequest(Guid SiteId, string Ip);
public record ScanRequest(Guid SiteId, string SubnetCidr, int TimeoutMs = 30000);
public record ProbeResponse(
string Ip,
bool IsReachable,
DetectedCameraType CameraType,
ArpInfo? Arp,
int[] OpenPorts,
OnvifInfo? Onvif,
HttpProbeInfo? Http,
HomeKitInfo? HomeKit,
string[]? MatchedBrands);
public record ArpInfo(string MacAddress, string? Vendor);
public record OnvifInfo(
string DeviceServiceUrl,
int Port,
string? Name,
string? Hardware,
string? Location);
public record HttpProbeInfo(int Port, int StatusCode, string? ServerHeader);
public record HomeKitInfo(
string Name, string DeviceId, string Model,
string Category, bool IsPaired, int Port);
public record StreamTestSession(
Guid SessionId,
string Status, // "running" | "done"
int Total,
int Tested,
int Alive,
StreamTestResult[] Results);
public record ConfirmDiscoveryRequest(
Guid SiteId,
string Name,
Guid DiscoveryResultId,
string MainStreamUrl,
string? SubStreamUrl,
string? Username,
string? Password,
CameraDetectionProfile? DetectionProfile);
```
---
## 14. Sécurité
| Risque | Mitigation |
|--------|-----------|
| **Scan réseau non autorisé** | Limit aux sous-réseaux du Site ; nécessite rôle `Admin` ou `Supervisor` |
| **Credentials en clair dans les logs** | `ICredentialProtector` appliqué systématiquement ; masquage `****` dans logs |
| **WS-Discovery flood** | Rate limiting (10 probes/min/IP) ; timeout 100ms par requête |
| **Données OUI/StrixCamDB** | Base SQLite intégrée, pas d'appels réseau pour la résolution |
| **mDNS spoofing** | Validation de l'IP source ; ne fait pas confiance aux réponses non sollicitées |
| **RTSP brute force** | 3 tentatives max par IP + credentials ; cooldown 60s |
---
## 15. Priorisation & Roadmap
### Phase 1 — Probe & Découverte (🔴 P1)
- [ ] `NetworkScannerService` — ARP lookup, port scan, ping
- [ ] `OnvifProbeService` — WS-Discovery UDP
- [ ] `HttpProbeService` — détection par en-têtes HTTP
- [ ] Entités `CameraDiscoveryResult`, `DiscoveredStream`
- [ ] API `POST /api/discovery/probe` + `POST /api/discovery/scan`
- [ ] Nouveaux champs Camera (DiscoveryMethod, IpAddress, ports, MAC, capabilities)
- [ ] CameraCapability flags enum
### Phase 2 — Base de Données Caméras (🟠 P2)
- [ ] Intégration de la base SQLite StrixCamDB (3600+ marques)
- [ ] Service de recherche `ICameraSearchService`
- [ ] API `GET /api/discovery/search`
- [ ] API `POST /api/discovery/streams` (construction URL)
- [ ] Substitution de placeholders (CHANNEL, USERNAME, IP, etc.)
### Phase 3 — Test de Flux (🟠 P2)
- [ ] `StreamTesterService` — workers parallèles
- [ ] Handlers RTSP, HTTP MJPEG, HTTP snapshot
- [ ] Capture d'écran via FFmpeg
- [ ] API `POST /api/discovery/test` + polling
- [ ] API `GET /api/discovery/test/{id}/screenshot/{index}`
### Phase 4 — Intégration Hangfire (🟡 P3)
- [ ] `NetworkScanJob` — scan planifié des sites
- [ ] `CameraHealthCheckJob` — heartbeat des flux
- [ ] `StreamTestJob` — re-test périodique
- [ ] Notification SignalR vers UI Blazor
### Phase 5 — Fonctionnalités Avancées (🟡 P3)
- [ ] ONVIF profile resolution → RTSP URI extraction
- [ ] HomeKit pairing (`POST /api/discovery/homekit/pair`)
- [ ] DVRIP/Sofia protocol support
- [ ] ONVIF PTZ capabilities detection
- [ ] Export config Frigate/go2rtc
---
## 16. Références
- [Strix](https://github.com/eduard256/Strix) — Moteur de découverte Go (MIT)
- [ONVIF Feature Discovery Spec](https://www.onvif.org/wp-content/uploads/2016/12/ONVIF_Feature_Discovery_Specification_16.07.pdf)
- [ONVIF Core Spec](https://www.onvif.org/specs/core/ONVIF-Core-Specification-v221.pdf) — GetProfiles, GetStreamUri
- [go2rtc](https://github.com/AlexxIT/go2rtc) — Lib de streaming multi-protocole
- [StrixCamDB](https://github.com/eduard256/StrixCamDB) — Base SQLite 3600+ marques, 100K+ patterns
- [Strix HTTP API](https://github.com/eduard256/Strix/blob/main/DEVELOPERS.md) — Référence API REST
- [HAP Spec](https://developer.apple.com/homekit/) — HomeKit Accessory Protocol (mDNS)
- [RFC 6762](https://datatracker.ietf.org/doc/html/rfc6762) — Multicast DNS
- [OUI Database](https://standards-oui.ieee.org/) — IEEE Organizationally Unique Identifier
@@ -14,6 +14,7 @@ public record UpdateCameraRequest(
string? RtspUrl,
CameraStatus? Status);
/// <summary>Camera response including all discovery and stream test metadata.</summary>
public record CameraResponse(
Guid Id,
Guid SiteId,
@@ -22,7 +23,22 @@ public record CameraResponse(
string? Manufacturer,
string? Model,
string? RtspUrl,
string? SubRtspUrl,
CameraStatus Status,
CameraDiscoveryMethod DiscoveryMethod,
DetectedCameraType DetectedType,
CameraCapability Capabilities,
string? IpAddress,
string? MacAddress,
int? RtspPort,
int? HttpPort,
int? OnvifPort,
string? LastTestedCodecs,
int? LastTestedWidth,
int? LastTestedHeight,
long? LastTestedLatencyMs,
DateTime? LastDiscoveredAt,
DateTime? LastStreamTestAt,
bool HasPtz,
bool HasAudio,
bool HasMotionDetection,
@@ -0,0 +1,140 @@
using Heimdall.Domain.Enums;
namespace Heimdall.Application.DTOs;
// ────────────────────────────────────────────────────────────────────
// Probe Requests
// ────────────────────────────────────────────────────────────────────
/// <summary>Probe a single IP address for camera services.</summary>
public record ProbeRequest(Guid SiteId, string Ip);
/// <summary>Scan an entire subnet for cameras.</summary>
public record ScanRequest(Guid SiteId, string SubnetCidr, int TimeoutMs = 30000);
// ────────────────────────────────────────────────────────────────────
// Probe Responses
// ────────────────────────────────────────────────────────────────────
/// <summary>Full probe result for a single IP, combining all detection methods.</summary>
public record ProbeResponse(
string Ip,
bool IsReachable,
DetectedCameraType CameraType,
CameraDiscoveryMethod DiscoveryMethod,
ArpInfo? Arp,
int[] OpenPorts,
OnvifProbeInfo? Onvif,
HttpProbeInfo? Http,
HomeKitProbeInfo? HomeKit,
string[]? MatchedBrands);
/// <summary>ARP table lookup result.</summary>
public record ArpInfo(string MacAddress, string? Vendor);
/// <summary>ONVIF WS-Discovery probe result.</summary>
public record OnvifProbeInfo(
string DeviceServiceUrl,
int Port,
string? Name,
string? Hardware,
string? Location);
/// <summary>HTTP probe result (server header analysis).</summary>
public record HttpProbeInfo(int Port, int StatusCode, string? ServerHeader);
/// <summary>HomeKit / mDNS probe result.</summary>
public record HomeKitProbeInfo(
string Name,
string DeviceId,
string Model,
string Category,
bool IsPaired,
int Port);
// ────────────────────────────────────────────────────────────────────
// Scan Progress
// ────────────────────────────────────────────────────────────────────
/// <summary>Progress update emitted during a subnet scan.</summary>
public record ScanProgress(
int TotalHosts,
int Scanned,
int Discovered,
string? CurrentIp);
// ────────────────────────────────────────────────────────────────────
// Camera Database Search
// ────────────────────────────────────────────────────────────────────
/// <summary>Result from the camera database (preset, brand, or model).</summary>
public record CameraDbEntry(
string Type, // "preset" | "brand" | "model"
string Id, // "p:{id}" | "b:{id}" | "m:{brand}:{model}"
string Name);
/// <summary>Search response.</summary>
public record SearchResponse(CameraDbEntry[] Results);
/// <summary>Build stream URLs from database entries.</summary>
public record StreamBuildRequest(
string[] Ids, // e.g. ["b:hikvision", "p:onvif"]
string Ip,
string? Username,
string? Password,
int Channel = 0,
int[]? PortFilter = null);
/// <summary>Stream build response.</summary>
public record StreamBuildResponse(string[] Streams);
// ────────────────────────────────────────────────────────────────────
// Stream Testing
// ────────────────────────────────────────────────────────────────────
/// <summary>Request to test a set of stream URLs.</summary>
public record StreamTestRequest(string SourceId, string[] Streams);
/// <summary>A tested stream result.</summary>
public record StreamTestResult(
string SourceUrl,
string[] Codecs,
int Width,
int Height,
long LatencyMs,
string? ScreenshotUrl,
bool IsAlive);
/// <summary>The session state for stream testing (polled).</summary>
public record StreamTestSession(
Guid SessionId,
string Status, // "running" | "done"
int Total,
int Tested,
int Alive,
StreamTestResult[] Results);
// ────────────────────────────────────────────────────────────────────
// Confirm Discovery
// ────────────────────────────────────────────────────────────────────
/// <summary>Confirm a discovery result and create a Camera entity.</summary>
public record ConfirmDiscoveryRequest(
Guid SiteId,
string Name,
Guid DiscoveryResultId,
string MainStreamUrl,
string? SubStreamUrl,
string? Username,
string? Password,
CameraDetectionProfileRequest? DetectionProfile);
/// <summary>Inline detection profile during camera creation.</summary>
public record CameraDetectionProfileRequest(
bool DetectPerson = true,
bool DetectVehicle = true,
bool DetectAnimal = false,
bool DetectPackage = false,
bool DetectMotion = true,
bool FaceRecognition = true,
bool LicensePlateRecognition = true);
@@ -0,0 +1,75 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
namespace Heimdall.Application.Services;
/// <summary>
/// Camera discovery service — probes network devices, searches the camera
/// database, builds and tests stream URLs, and creates Camera entities.
/// Inspired by Strix (github.com/eduard256/Strix).
/// </summary>
public interface ICameraDiscoveryService
{
/// <summary>
/// Probe a single IP address using all available methods in parallel
/// (ONVIF WS-Discovery, HTTP, mDNS, ARP, port scan). Returns within ~100ms.
/// </summary>
Task<ServiceResult<ProbeResponse>> ProbeIpAsync(
ProbeRequest request, CancellationToken ct);
/// <summary>
/// Scan an entire subnet for camera devices. Runs port scans in parallel
/// with 20+ workers. Reports progress via IProgress{ScanProgress}.
/// </summary>
Task<ServiceResult<IReadOnlyList<ProbeResponse>>> ScanSubnetAsync(
ScanRequest request, CancellationToken ct,
IProgress<ScanProgress>? progress = null);
/// <summary>
/// Search the built-in camera database (StrixCamDB) by brand, model, or preset.
/// Supports multi-word queries (each word matches independently).
/// </summary>
Task<ServiceResult<SearchResponse>> SearchDatabaseAsync(
string query, CancellationToken ct);
/// <summary>
/// Build full stream URLs from camera database entries, substituting
/// placeholders ([CHANNEL], [USERNAME], [IP], etc.) with actual values.
/// </summary>
Task<ServiceResult<StreamBuildResponse>> BuildStreamUrlsAsync(
StreamBuildRequest request, CancellationToken ct);
/// <summary>
/// Test stream URLs in parallel (20 workers) — connects to each,
/// extracts codecs, resolution, latency, and captures a screenshot.
/// Returns a session ID for polling.
/// </summary>
Task<ServiceResult<StreamTestSession>> TestStreamsAsync(
StreamTestRequest request, CancellationToken ct);
/// <summary>
/// Poll a stream test session for updated results.
/// </summary>
Task<ServiceResult<StreamTestSession>> GetTestSessionAsync(
Guid sessionId, CancellationToken ct);
/// <summary>
/// Get a screenshot from a stream test session.
/// </summary>
Task<byte[]?> GetScreenshotAsync(
Guid sessionId, int index, CancellationToken ct);
/// <summary>
/// Cancel a running stream test session.
/// </summary>
Task<ServiceResult> CancelTestSessionAsync(
Guid sessionId, CancellationToken ct);
/// <summary>
/// Confirm a discovery result — creates a Camera entity with all
/// discovered metadata, credentials (encrypted), and an optional
/// detection profile.
/// </summary>
Task<ServiceResult<CameraResponse>> ConfirmDiscoveryAsync(
ConfirmDiscoveryRequest request, CancellationToken ct);
}
+103 -4
View File
@@ -5,6 +5,7 @@ namespace Heimdall.Domain.Entities;
public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
{
// ── Core ────────────────────────────────────────────────────────
public Guid SiteId { get; private set; }
public Guid? AgentId { get; private set; }
public string Name { get; private set; } = string.Empty;
@@ -13,12 +14,51 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
public string? RtspUrl { get; private set; }
public CameraStatus Status { get; private set; } = CameraStatus.Disabled;
// Capabilities
// ── Discovery ───────────────────────────────────────────────────
/// <summary>How this camera was discovered (manual, ONVIF, mDNS, etc.).</summary>
public CameraDiscoveryMethod DiscoveryMethod { get; private set; } = CameraDiscoveryMethod.Manual;
/// <summary>High-level classification from the probe phase.</summary>
public DetectedCameraType DetectedType { get; private set; } = DetectedCameraType.Standard;
// Network
public string? IpAddress { get; private set; }
public string? MacAddress { get; private set; }
// Ports detected during probe
public int? RtspPort { get; private set; }
public int? HttpPort { get; private set; }
public int? OnvifPort { get; private set; }
// Capabilities flags (bitmask)
public CameraCapability Capabilities { get; private set; } = CameraCapability.None;
/// <summary>Timestamp of the last successful discovery probe.</summary>
public DateTime? LastDiscoveredAt { get; private set; }
// ── Stream test results ─────────────────────────────────────────
/// <summary>Secondary / sub-stream URL (lower resolution for AI detection).</summary>
public string? SubRtspUrl { get; private set; }
/// <summary>Last stream test results (JSON array of codecs).</summary>
public string? LastTestedCodecs { get; private set; }
/// <summary>Resolution of the last successful stream test.</summary>
public int? LastTestedWidth { get; private set; }
public int? LastTestedHeight { get; private set; }
/// <summary>Connection latency in ms (last test).</summary>
public long? LastTestedLatencyMs { get; private set; }
/// <summary>Timestamp of the last stream test.</summary>
public DateTime? LastStreamTestAt { get; private set; }
// ── Legacy capabilities (kept for backward compat) ──────────────
public bool HasPtz { get; private set; }
public bool HasAudio { get; private set; }
public bool HasMotionDetection { get; private set; }
// Audit
// ── Audit ───────────────────────────────────────────────────────
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
@@ -26,7 +66,7 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
public bool IsDeleted { get; private set; }
public DateTime? DeletedAt { get; private set; }
// Navigation
// ── Navigation ──────────────────────────────────────────────────
public Site Site { get; private set; } = null!;
public Agent? Agent { get; private set; }
public CameraCredentials? Credentials { get; private set; }
@@ -34,7 +74,12 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
private Camera() { } // EF Core
public Camera(Guid siteId, string name, string? rtspUrl = null, string? manufacturer = null, string? model = null)
public Camera(
Guid siteId,
string name,
string? rtspUrl = null,
string? manufacturer = null,
string? model = null)
: base(Guid.NewGuid())
{
SiteId = siteId;
@@ -44,6 +89,8 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
Model = model;
}
// ── Behaviour ───────────────────────────────────────────────────
public void AssignAgent(Guid agentId) => AgentId = agentId;
public void Update(string name, string? manufacturer, string? model, string? rtspUrl)
@@ -67,6 +114,58 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
public void SetDetectionProfile(CameraDetectionProfile profile) => DetectionProfile = profile;
/// <summary>
/// Populates discovery-related fields after a successful probe.
/// </summary>
public void SetDiscoveryInfo(
CameraDiscoveryMethod method,
DetectedCameraType type,
string? macAddress,
string ipAddress)
{
DiscoveryMethod = method;
DetectedType = type;
MacAddress = macAddress;
IpAddress = ipAddress;
LastDiscoveredAt = DateTime.UtcNow;
}
/// <summary>
/// Updates known ports from probe results.
/// </summary>
public void SetPorts(int? rtspPort, int? httpPort, int? onvifPort)
{
RtspPort = rtspPort;
HttpPort = httpPort;
OnvifPort = onvifPort;
}
/// <summary>
/// Updates capability bitmask from all probe data.
/// </summary>
public void SetCapabilityFlags(CameraCapability capabilities)
{
Capabilities = capabilities;
}
/// <summary>
/// Records the result of a stream validation test.
/// </summary>
public void SetStreamTestResult(
string? subRtspUrl,
string codecsJson,
int width,
int height,
long latencyMs)
{
SubRtspUrl = subRtspUrl;
LastTestedCodecs = codecsJson;
LastTestedWidth = width;
LastTestedHeight = height;
LastTestedLatencyMs = latencyMs;
LastStreamTestAt = DateTime.UtcNow;
}
public void SoftDelete()
{
IsDeleted = true;
@@ -0,0 +1,120 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// Transient entity representing the outcome of probing a single IP address
/// during the camera discovery pipeline. Retained temporarily for the
/// discovery workflow (probe → search → test → confirm).
/// </summary>
public class CameraDiscoveryResult : Entity<Guid>
{
// ── Identification ──────────────────────────────────────────────
public Guid SiteId { get; private set; }
public Site Site { get; private set; } = null!;
/// <summary>Probed IP address.</summary>
public string IpAddress { get; private set; } = string.Empty;
/// <summary>MAC address from ARP table lookup.</summary>
public string? MacAddress { get; private set; }
/// <summary>Vendor/manufacturer name resolved from OUI.</summary>
public string? Vendor { get; private set; }
/// <summary>Reverse DNS hostname (if resolvable).</summary>
public string? Hostname { get; private set; }
// ── Classification ──────────────────────────────────────────────
/// <summary>Device is reachable on the network.</summary>
public bool IsReachable { get; private set; }
/// <summary>Detected camera type (standard / homekit / nvr / doorbell).</summary>
public DetectedCameraType DetectedType { get; private set; } = DetectedCameraType.Unknown;
/// <summary>Primary discovery method that identified this device.</summary>
public CameraDiscoveryMethod DiscoveryMethod { get; private set; }
// ── Probe results ───────────────────────────────────────────────
/// <summary>Open ports discovered during port scan.</summary>
public int[] OpenPorts { get; private set; } = [];
// ONVIF
public string? OnvifDeviceServiceUrl { get; private set; }
public string? OnvifName { get; private set; }
public string? OnvifHardware { get; private set; }
public int? OnvifPort { get; private set; }
// HTTP
public string? HttpServerHeader { get; private set; }
public int? HttpStatusCode { get; private set; }
public int? HttpPort { get; private set; }
// HomeKit
public bool? IsHomeKitCamera { get; private set; }
public string? HomeKitName { get; private set; }
public string? HomeKitDeviceId { get; private set; }
public string? HomeKitModel { get; private set; }
// ── Status ──────────────────────────────────────────────────────
/// <summary>When this probe was performed.</summary>
public DateTime ProbedAt { get; private set; } = DateTime.UtcNow;
/// <summary>True when this result has been processed (confirmed or rejected).</summary>
public bool IsProcessed { get; private set; }
// ── Navigation ──────────────────────────────────────────────────
public ICollection<DiscoveredStreamUrl> DiscoveredStreams { get; private set; } = [];
private CameraDiscoveryResult() { } // EF Core
public CameraDiscoveryResult(Guid siteId, string ipAddress)
: base(Guid.NewGuid())
{
SiteId = siteId;
IpAddress = ipAddress;
}
// ── Behaviour ───────────────────────────────────────────────────
public void MarkReachable(DetectedCameraType type, CameraDiscoveryMethod method)
{
IsReachable = true;
DetectedType = type;
DiscoveryMethod = method;
}
public void SetOpenPorts(int[] ports) => OpenPorts = ports;
public void SetOnvifResult(string deviceServiceUrl, string? name, string? hardware, int port)
{
OnvifDeviceServiceUrl = deviceServiceUrl;
OnvifName = name;
OnvifHardware = hardware;
OnvifPort = port;
}
public void SetHttpResult(int port, int statusCode, string? serverHeader)
{
HttpPort = port;
HttpStatusCode = statusCode;
HttpServerHeader = serverHeader;
}
public void SetHomeKitResult(string name, string deviceId, string model)
{
IsHomeKitCamera = true;
HomeKitName = name;
HomeKitDeviceId = deviceId;
HomeKitModel = model;
}
public void SetArpInfo(string mac, string? vendor)
{
MacAddress = mac;
Vendor = vendor;
}
public void MarkProcessed() => IsProcessed = true;
}
@@ -0,0 +1,63 @@
using Heimdall.Domain.Enums;
namespace Heimdall.Domain.Entities;
/// <summary>
/// A single stream URL that was tested during the discovery pipeline.
/// Contains the test result (codecs, resolution, latency, screenshot).
/// </summary>
public class DiscoveredStreamUrl
{
public Guid Id { get; private set; }
public Guid DiscoveryResultId { get; private set; }
/// <summary>The full stream URL (credentials may be included).</summary>
public string Url { get; private set; } = string.Empty;
/// <summary>Protocol scheme (rtsp, http, rtmp, dvrip, etc.).</summary>
public StreamProtocol Protocol { get; private set; }
/// <summary>Detected codec names (e.g. ["H264", "PCMA"]).</summary>
public string[] Codecs { get; private set; } = [];
/// <summary>Stream resolution.</summary>
public int Width { get; private set; }
public int Height { get; private set; }
/// <summary>Connection latency in milliseconds.</summary>
public long LatencyMs { get; private set; }
/// <summary>True if the stream is the main (highest-resolution) stream.</summary>
public bool IsMainStream { get; private set; }
/// <summary>True if the stream responded successfully.</summary>
public bool IsAlive { get; private set; }
// Navigation
public CameraDiscoveryResult DiscoveryResult { get; private set; } = null!;
private DiscoveredStreamUrl() { } // EF Core
public DiscoveredStreamUrl(
Guid discoveryResultId,
string url,
StreamProtocol protocol,
string[] codecs,
int width,
int height,
long latencyMs,
bool isMainStream,
bool isAlive)
{
Id = Guid.NewGuid();
DiscoveryResultId = discoveryResultId;
Url = url;
Protocol = protocol;
Codecs = codecs;
Width = width;
Height = height;
LatencyMs = latencyMs;
IsMainStream = isMainStream;
IsAlive = isAlive;
}
}
@@ -0,0 +1,44 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Flags enum describing camera capabilities detected during discovery.
/// Stored as a bitmask in the database.
/// </summary>
[Flags]
public enum CameraCapability
{
None = 0,
/// <summary>RTSP streaming (H264/H265).</summary>
RtspStreaming = 1 << 0,
/// <summary>MJPEG stream over HTTP.</summary>
HttpMjpeg = 1 << 1,
/// <summary>Single JPEG snapshot over HTTP.</summary>
HttpSnapshot = 1 << 2,
/// <summary>ONVIF protocol support (WS-Discovery responded).</summary>
Onvif = 1 << 3,
/// <summary>PTZ control available via ONVIF.</summary>
OnvifPtz = 1 << 4,
/// <summary>Audio input (microphone) available.</summary>
OnvifAudioIn = 1 << 5,
/// <summary>Audio output (speaker) available.</summary>
OnvifAudioOut = 1 << 6,
/// <summary>Apple HomeKit (HAP) support.</summary>
HomeKit = 1 << 7,
/// <summary>Dahua DVRIP / Sofia protocol.</summary>
Dvrip = 1 << 8,
/// <summary>RTMP streaming.</summary>
Rtmp = 1 << 9,
/// <summary>Camera provides a sub-stream (secondary, lower-res stream).</summary>
SubStream = 1 << 10
}
@@ -0,0 +1,28 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Method by which a camera was discovered on the network.
/// </summary>
public enum CameraDiscoveryMethod
{
/// <summary>Manually configured by the user (existing flow).</summary>
Manual = 0,
/// <summary>Discovered via ONVIF WS-Discovery (UDP probe on port 3702).</summary>
OnvifWsDiscovery = 1,
/// <summary>Discovered via mDNS / HomeKit Accessory Protocol (_hap._tcp).</summary>
MdnsHomeKit = 2,
/// <summary>Generic network scan (port scan + ping).</summary>
NetworkScan = 3,
/// <summary>Detected via HTTP server header analysis.</summary>
HttpProbe = 4,
/// <summary>Discovered via ARP table lookup + OUI vendor resolution.</summary>
ArpProbe = 5,
/// <summary>Imported from external file or bulk operation.</summary>
Imported = 6
}
@@ -0,0 +1,23 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// High-level classification of a detected camera's type.
/// Determined during the probe phase based on protocol signatures.
/// </summary>
public enum DetectedCameraType
{
/// <summary>Standard IP camera (RTSP + HTTP).</summary>
Standard = 0,
/// <summary>Apple HomeKit camera / doorbell (HAP over mDNS).</summary>
HomeKit = 1,
/// <summary>NVR / DVR with multiple channels (DVRIP / Sofia protocol).</summary>
Nvr = 2,
/// <summary>Video doorbell (HomeKit or proprietary).</summary>
Doorbell = 3,
/// <summary>Device is reachable but camera type could not be determined.</summary>
Unknown = 4
}
@@ -0,0 +1,18 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Streaming protocols supported by the discovery and test pipeline.
/// Maps directly to the protocol handlers in StreamTesterService.
/// </summary>
public enum StreamProtocol
{
Rtsp,
Rtsps,
Http,
Https,
Rtmp,
Rtmps,
Dvrip,
Bubble,
HomeKit
}
@@ -23,6 +23,10 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
public DbSet<AppSetting> AppSettings => Set<AppSetting>();
public DbSet<AgentSetting> AgentSettings => Set<AgentSetting>();
// Discovery entities
public DbSet<CameraDiscoveryResult> CameraDiscoveryResults => Set<CameraDiscoveryResult>();
public DbSet<DiscoveredStreamUrl> DiscoveredStreams => Set<DiscoveredStreamUrl>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -12,6 +13,7 @@ public class CameraConfiguration : IEntityTypeConfiguration<Camera>
builder.HasKey(c => c.Id);
// ── Core ────────────────────────────────────────────────────
builder.Property(c => c.Name)
.HasMaxLength(200)
.IsRequired()
@@ -33,17 +35,67 @@ public class CameraConfiguration : IEntityTypeConfiguration<Camera>
.IsRequired()
.IsUnicode(false);
// ── Discovery ───────────────────────────────────────────────
builder.Property(c => c.DiscoveryMethod)
.HasConversion<string>()
.HasMaxLength(20)
.IsUnicode(false);
builder.Property(c => c.DetectedType)
.HasConversion<string>()
.HasMaxLength(20)
.IsUnicode(false);
builder.Property(c => c.IpAddress)
.HasMaxLength(45); // IPv6 max length
builder.Property(c => c.MacAddress)
.HasMaxLength(17); // "XX:XX:XX:XX:XX:XX"
builder.Property(c => c.RtspPort);
builder.Property(c => c.HttpPort);
builder.Property(c => c.OnvifPort);
builder.Property(c => c.Capabilities)
.HasConversion<string>()
.HasMaxLength(64)
.IsUnicode(false);
builder.Property(c => c.LastDiscoveredAt);
// ── Stream test ─────────────────────────────────────────────
builder.Property(c => c.SubRtspUrl)
.HasMaxLength(1000)
.IsUnicode(false);
builder.Property(c => c.LastTestedCodecs)
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(c => c.LastTestedWidth);
builder.Property(c => c.LastTestedHeight);
builder.Property(c => c.LastTestedLatencyMs);
builder.Property(c => c.LastStreamTestAt);
// ── Legacy capabilities ─────────────────────────────────────
builder.Property(c => c.HasPtz);
builder.Property(c => c.HasAudio);
builder.Property(c => c.HasMotionDetection);
// ── Audit ───────────────────────────────────────────────────
builder.Property(c => c.CreatedAt)
.HasDefaultValueSql("NOW()");
builder.Property(c => c.UpdatedAt)
.HasDefaultValueSql("NOW()");
// Indexes
// ── Indexes ─────────────────────────────────────────────────
builder.HasIndex(c => c.SiteId);
builder.HasIndex(c => c.AgentId);
builder.HasIndex(c => c.IpAddress);
builder.HasIndex(c => c.MacAddress);
// Relationships
// ── Relationships ───────────────────────────────────────────
builder.HasOne(c => c.Site)
.WithMany(s => s.Cameras)
.HasForeignKey(c => c.SiteId)
@@ -0,0 +1,106 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class CameraDiscoveryResultConfiguration : IEntityTypeConfiguration<CameraDiscoveryResult>
{
public void Configure(EntityTypeBuilder<CameraDiscoveryResult> builder)
{
builder.ToTable("camera_discovery_results");
builder.HasKey(r => r.Id);
// ── Identification ──────────────────────────────────────────
builder.Property(r => r.IpAddress)
.HasMaxLength(45)
.IsRequired()
.IsUnicode(false);
builder.Property(r => r.MacAddress)
.HasMaxLength(17)
.IsUnicode(false);
builder.Property(r => r.Vendor)
.HasMaxLength(100)
.IsUnicode(false);
builder.Property(r => r.Hostname)
.HasMaxLength(255)
.IsUnicode(false);
// ── Classification ──────────────────────────────────────────
builder.Property(r => r.DetectedType)
.HasConversion<string>()
.HasMaxLength(20)
.IsUnicode(false);
builder.Property(r => r.DiscoveryMethod)
.HasConversion<string>()
.HasMaxLength(20)
.IsUnicode(false);
// ── Ports ───────────────────────────────────────────────────
builder.Property(r => r.OpenPorts)
.HasColumnType("integer[]")
.IsUnicode(false);
// ONVIF
builder.Property(r => r.OnvifDeviceServiceUrl)
.HasMaxLength(500)
.IsUnicode(false);
builder.Property(r => r.OnvifName)
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(r => r.OnvifHardware)
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(r => r.OnvifPort);
// HTTP
builder.Property(r => r.HttpServerHeader)
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(r => r.HttpStatusCode);
builder.Property(r => r.HttpPort);
// HomeKit
builder.Property(r => r.HomeKitName)
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(r => r.HomeKitDeviceId)
.HasMaxLength(50)
.IsUnicode(false);
builder.Property(r => r.HomeKitModel)
.HasMaxLength(200)
.IsUnicode(false);
// ── Status ──────────────────────────────────────────────────
builder.Property(r => r.ProbedAt)
.HasDefaultValueSql("NOW()");
// ── Indexes ─────────────────────────────────────────────────
builder.HasIndex(r => r.SiteId);
builder.HasIndex(r => r.IpAddress);
builder.HasIndex(r => r.IsProcessed);
// ── Relationships ───────────────────────────────────────────
builder.HasOne(r => r.Site)
.WithMany()
.HasForeignKey(r => r.SiteId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(r => r.DiscoveredStreams)
.WithOne(ds => ds.DiscoveryResult)
.HasForeignKey(ds => ds.DiscoveryResultId)
.OnDelete(DeleteBehavior.Cascade);
}
}
@@ -0,0 +1,40 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class DiscoveredStreamConfiguration : IEntityTypeConfiguration<DiscoveredStreamUrl>
{
public void Configure(EntityTypeBuilder<DiscoveredStreamUrl> builder)
{
builder.ToTable("discovered_streams");
builder.HasKey(ds => ds.Id);
builder.Property(ds => ds.Url)
.HasMaxLength(2000)
.IsRequired()
.IsUnicode(false);
builder.Property(ds => ds.Protocol)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.IsUnicode(false);
builder.Property(ds => ds.Codecs)
.HasColumnType("text[]")
.IsUnicode(false);
builder.Property(ds => ds.Width);
builder.Property(ds => ds.Height);
builder.Property(ds => ds.LatencyMs);
// Indexes
builder.HasIndex(ds => ds.DiscoveryResultId);
builder.HasIndex(ds => ds.IsAlive);
builder.HasIndex(ds => ds.IsMainStream);
}
}
@@ -107,5 +107,10 @@ public class CameraService : ICameraService
private static CameraResponse MapResponse(Camera c) => new(
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
c.RtspUrl, c.Status, c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
c.RtspUrl, c.SubRtspUrl,
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
}