diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 90914f5..9afa911 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -64,6 +64,7 @@ builder.Services.AddSingleton(sp => builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/HomeKitMdnsProbe.cs b/src/Heimdall.Agent/Services/HomeKitMdnsProbe.cs new file mode 100644 index 0000000..08f7d08 --- /dev/null +++ b/src/Heimdall.Agent/Services/HomeKitMdnsProbe.cs @@ -0,0 +1,421 @@ +using System.Buffers.Binary; +using System.Net; +using System.Net.Sockets; +using System.Text; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Services; + +/// Parsed HomeKit accessory (camera/doorbell) found via mDNS. +public sealed record HomeKitDevice( + string Ip, + string Name, + string DeviceId, + string Model, + int Category, + bool IsPaired, + int Port); + +/// +/// mDNS/HomeKit discovery probe (multicast). Transposed from Strix +/// pkg/probe/mdns.go (QueryHAP) and go2rtc internal/homekit. +/// Sends a raw DNS PTR query for _hap._tcp.local. to the mDNS +/// multicast group 224.0.0.251:5353, listens ~2 s, parses PTR/SRV/TXT/A +/// replies and keeps accessories with category ci=17 (camera) or +/// ci=18 (doorbell). +/// +/// +/// The listener uses an explicit Task.WhenAny(receive, Task.Delay(...)) +/// window — does NOT apply to async +/// ReceiveAsync (bug réel découvert en prod, fix 491a253). +/// +public sealed class HomeKitMdnsProbe +{ + private const string MulticastAddress = "224.0.0.251"; + private const int MdnsPort = 5353; + private static readonly TimeSpan ListenWindow = TimeSpan.FromSeconds(2); + private static readonly TimeSpan ReplyDelay = TimeSpan.FromMilliseconds(250); + + private readonly ILogger _logger; + + public HomeKitMdnsProbe(ILogger logger) + { + _logger = logger; + } + + /// + /// Run one global multicast probe for HomeKit camera/doorbell accessories. + /// Returns devices deduplicated by IP. Never throws; failures are logged + /// and an empty list is returned (scan must never hang). + /// + public async Task> DiscoverAsync(CancellationToken ct) + { + var devices = new List(); + try + { + using var udp = new UdpClient(AddressFamily.InterNetwork); + udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + udp.Client.Bind(new IPEndPoint(IPAddress.Any, MdnsPort)); + udp.Client.MulticastLoopback = false; + udp.JoinMulticastGroup(IPAddress.Parse(MulticastAddress)); + + // DNS-SD PTR question for _hap._tcp.local. (mDNS: QU with unicast-response bit) + var query = BuildPtrQuery("_hap._tcp.local"); + var multicast = new IPEndPoint(IPAddress.Parse(MulticastAddress), MdnsPort); + + // Send 3 probes (devices sometimes miss the first one). + for (var i = 0; i < 3; i++) + { + await udp.SendAsync(query, multicast, ct).ConfigureAwait(false); + await Task.Delay(ReplyDelay, ct).ConfigureAwait(false); + } + + var collected = new List(); + var listenUntil = DateTime.UtcNow + ListenWindow; + while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil) + { + var receiveTask = udp.ReceiveAsync(ct).AsTask(); + var completed = await Task.WhenAny(receiveTask, Task.Delay(ListenWindow, ct)).ConfigureAwait(false); + if (completed != receiveTask) + break; // no more replies expected + + var result = await receiveTask.ConfigureAwait(false); + var replies = ParsePacket(result.Buffer); + if (replies.Count > 0) + collected.AddRange(replies); + } + + devices = BuildDevices(collected); + if (devices.Count > 0) + _logger.LogInformation("Camera discovery: {Count} HomeKit accessory(ies) via mDNS multicast", devices.Count); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // cancelled + } + catch (Exception ex) + { + _logger.LogWarning(ex, "mDNS/HomeKit multicast probe failed"); + } + + return devices; + } + + // ─── DNS packet building ───────────────────────────────────────── + + private static byte[] BuildPtrQuery(string serviceType) + { + using var ms = new MemoryStream(); + Span scratch = stackalloc byte[8]; + + // Header: ID (random), flags = 0x0000 (QU), QDCOUNT=1. + BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)Random.Shared.Next(0, 0xFFFF)); + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0); + BinaryPrimitives.WriteUInt16BigEndian(scratch[4..], 1); + BinaryPrimitives.WriteUInt16BigEndian(scratch[6..], 0); + ms.Write(scratch); + + WriteDnsName(ms, serviceType); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 12); // QTYPE = PTR + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x8001); // QCLASS = IN + unicast-response + ms.Write(scratch[..4]); + + return ms.ToArray(); + } + + private static void WriteDnsName(MemoryStream ms, string name) + { + foreach (var label in name.TrimEnd('.').Split('.')) + { + if (label.Length == 0 || label.Length > 63) + continue; + ms.WriteByte((byte)label.Length); + ms.Write(Encoding.ASCII.GetBytes(label)); + } + ms.WriteByte(0); + } + + // ─── DNS packet parsing (with compression pointers) ────────────── + + private sealed record MdnsReply( + string Instance, // PTR target instance name (lowercased) + ushort Type, + string? SrvTarget, + int? SrvPort, + IReadOnlyDictionary? Txt, + string? Address); + + private sealed record PacketReader(byte[] Data) + { + private int _pos; + + public int Position + { + get => _pos; + set => _pos = value; + } + + public int Remaining => Data.Length - _pos; + + public ushort ReadUInt16() + { + var v = BinaryPrimitives.ReadUInt16BigEndian(Data.AsSpan(_pos, 2)); + _pos += 2; + return v; + } + + public uint ReadUInt32() + { + var v = BinaryPrimitives.ReadUInt32BigEndian(Data.AsSpan(_pos, 4)); + _pos += 4; + return v; + } + + public byte[] ReadBytes(int count) + { + var b = Data.AsSpan(_pos, count).ToArray(); + _pos += count; + return b; + } + + /// Read a (possibly compressed) DNS name. Returns the name and the + /// position AFTER the name in the original stream (compression pointers + /// never advance the stream position past the pointer itself). + public (string Name, int EndPos) ReadName(int startPos) + { + var labels = new List(); + var pos = startPos; + var jumped = false; + var endPos = startPos; + var guard = 0; + + while (guard++ < 128) + { + if (pos >= Data.Length) + break; + var len = Data[pos]; + if (len == 0) + { + pos++; + if (!jumped) + endPos = pos; + break; + } + if ((len & 0xC0) == 0xC0) + { + if (pos + 1 >= Data.Length) + break; + var pointer = ((len & 0x3F) << 8) | Data[pos + 1]; + if (!jumped) + endPos = pos + 2; + pos = pointer; + jumped = true; + continue; + } + pos++; + if (pos + len > Data.Length) + break; + labels.Add(Encoding.ASCII.GetString(Data, pos, len)); + pos += len; + } + + return (string.Join(".", labels).ToLowerInvariant(), endPos); + } + } + + private static List ParsePacket(byte[] data) + { + var replies = new List(); + try + { + if (data.Length < 12) + return replies; + + var r = new PacketReader(data); + r.Position = 4; // skip ID + flags + var qdCount = r.ReadUInt16(); + var anCount = r.ReadUInt16(); + var nsCount = r.ReadUInt16(); + var arCount = r.ReadUInt16(); + + // Skip questions. + for (var q = 0; q < qdCount; q++) + { + var (_, endPos) = r.ReadName(r.Position); + r.Position = endPos + 4; // QTYPE + QCLASS + } + + var total = anCount + nsCount + arCount; + for (var i = 0; i < total; i++) + { + if (r.Remaining < 10) + break; + + var (name, endPos) = r.ReadName(r.Position); + r.Position = endPos; + var type = r.ReadUInt16(); + var _class = r.ReadUInt16(); + r.ReadUInt32(); // TTL + var rdLength = r.ReadUInt16(); + if (r.Remaining < rdLength) + break; + + var rdataStart = r.Position; + var isCacheFlush = (_class & 0x8000) != 0; + _ = isCacheFlush; + + switch (type) + { + case 12: // PTR + var (ptrName, _) = r.ReadName(rdataStart); + replies.Add(new MdnsReply(ptrName, 12, null, null, null, null)); + break; + case 33: // SRV + var srv = r.ReadBytes(rdLength); + if (srv.Length >= 6) + { + var port = BinaryPrimitives.ReadUInt16BigEndian(srv.AsSpan(4, 2)); + var srvReader = new PacketReader(srv); + srvReader.Position = 6; + var (target, _) = srvReader.ReadName(6); + replies.Add(new MdnsReply(name, 33, target, port, null, null)); + } + break; + case 16: // TXT + var txt = ParseTxt(r.ReadBytes(rdLength)); + replies.Add(new MdnsReply(name, 16, null, null, txt, null)); + break; + case 1: // A + var a = r.ReadBytes(rdLength); + if (a.Length == 4) + replies.Add(new MdnsReply(name, 1, null, null, null, new IPAddress(a).ToString())); + break; + default: + break; + } + // Always advance to the end of this record's rdata so the next + // record parses from the right offset. + r.Position = rdataStart + rdLength; + } + } + catch (Exception ex) + { + // Malformed packet — ignore (mDNS traffic is noisy). + _ = ex; + } + return replies; + } + + private static Dictionary ParseTxt(byte[] data) + { + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + var offset = 0; + while (offset < data.Length) + { + var length = data[offset]; + offset++; + if (length == 0 || offset + length > data.Length) + break; + var entry = Encoding.ASCII.GetString(data, offset, length); + var eq = entry.IndexOf('='); + if (eq > 0) + dict[entry[..eq]] = entry[(eq + 1)..]; + else if (entry.Length > 0) + dict[entry] = ""; + offset += length; + } + return dict; + } + + // ─── Assembly ──────────────────────────────────────────────────── + + /// + /// Group raw replies by instance name and build HomeKit devices. + /// Keeps categories 17 (camera) and 18 (doorbell); sf=1 (already paired) + /// devices are still returned — they are real cameras, just paired. + /// + private static List BuildDevices(List replies) + { + // instance name → TXT / SRV / A records + var byInstance = new Dictionary Txt, string? SrvTarget, int? Port, List Ips)>(StringComparer.OrdinalIgnoreCase); + + foreach (var reply in replies) + { + if (reply.Type == 12) // PTR: instance = target; only the PTR name matters + { + if (!byInstance.ContainsKey(reply.Instance)) + byInstance[reply.Instance] = (new Dictionary(StringComparer.OrdinalIgnoreCase), null, null, []); + continue; + } + + var key = reply.Instance; + if (!byInstance.TryGetValue(key, out var existing)) + { + existing = (new Dictionary(StringComparer.OrdinalIgnoreCase), null, null, []); + byInstance[key] = existing; + } + + if (reply.Type == 16 && reply.Txt is not null) + { + foreach (var (k, v) in reply.Txt) + existing.Txt[k] = v; + } + else if (reply.Type == 33) + { + existing = existing with { SrvTarget = reply.SrvTarget, Port = reply.SrvPort }; + byInstance[key] = existing; + } + else if (reply.Type == 1 && reply.Address is not null && !existing.Ips.Contains(reply.Address)) + { + existing.Ips.Add(reply.Address); + } + } + + var devices = new List(); + var seenIps = new HashSet(StringComparer.Ordinal); + + // A records are named by the SRV target host (cam1.local), not by the + // instance name — build a host → IP map for the SRV target resolution. + var addressByHost = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var reply in replies) + { + if (reply.Type == 1 && reply.Address is not null) + addressByHost[reply.Instance] = reply.Address; + } + + foreach (var (instance, info) in byInstance) + { + if (!int.TryParse(info.Txt.GetValueOrDefault("ci"), out var category)) + continue; + if (category is not (17 or 18)) + continue; // only cameras + doorbells + + // IP: A record of the instance itself, then A record of the SRV + // target host, then any A record seen (best effort). + var ip = info.Ips.FirstOrDefault() + ?? (info.SrvTarget is not null && addressByHost.TryGetValue(info.SrvTarget, out var srvIp) ? srvIp : null) + ?? addressByHost.Values.FirstOrDefault() + ?? ""; + + if (string.IsNullOrEmpty(ip) || !seenIps.Add(ip)) + continue; + + var name = instance.Split('.')[0]; // "Camera-ABCDEF._hap._tcp.local" → "Camera-ABCDEF" + var deviceId = info.Txt.GetValueOrDefault("id") + ?? $"{ip}/{info.Txt.GetValueOrDefault("md", "unknown")}"; + var model = info.Txt.GetValueOrDefault("md") ?? "HomeKit"; + var sf = info.Txt.GetValueOrDefault("sf") ?? "0"; + + devices.Add(new HomeKitDevice( + ip, + name, + deviceId, + model, + category, + IsPaired: sf != "0", + Port: info.Port ?? MdnsPort)); + } + + return devices; + } +} diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index 789bfaa..9593825 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -56,12 +56,17 @@ public sealed class NetworkCameraScanner private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; private readonly ILogger _logger; + private readonly HomeKitMdnsProbe _homeKitProbe; private readonly string? _localIp; private readonly string? _gatewayIp; - public NetworkCameraScanner(ILogger logger) + public NetworkCameraScanner( + ILogger logger, + HomeKitMdnsProbe? homeKitProbe = null) { _logger = logger; + _homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe( + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); var (localIp, gatewayIp) = GetLocalNetworkInfo(); _localIp = localIp; _gatewayIp = gatewayIp; @@ -162,6 +167,12 @@ public sealed class NetworkCameraScanner if (!HasDefinitiveCameraEvidence(device) && !HasCameraPorts(device)) return null; + // HomeKit accessories are proven by the mDNS advertisement (category + // ci=17/18): no RTSP candidates apply — the stream is a HAP session + // (GetImage snapshot test, ticket #67/#65), never a guessed rtsp:// URL. + if (!string.IsNullOrEmpty(device.HomeKitName)) + return device; + // Real ONVIF GetStreamUri URLs (agent enrichment) take priority over // guessed templates: keep them even when the stream test fails — the // camera is already proven by ONVIF, the stream may just need auth. @@ -201,6 +212,50 @@ public sealed class NetworkCameraScanner var devices = new List(); devices.AddRange(await DiscoverOnvifMulticastAsync(credentialPool, ct).ConfigureAwait(false)); devices.AddRange(await DiscoverDvripAsync(ct).ConfigureAwait(false)); + devices.AddRange(await DiscoverHomeKitAsync(ct).ConfigureAwait(false)); + return devices; + } + + /// + /// HomeKit accessory discovery via mDNS multicast (_hap._tcp.local, + /// 224.0.0.251:5353). Only camera (ci=17) and doorbell (ci=18) categories + /// are kept; the HomeKit* fields of the device are filled for the Central + /// ClassifyAgentDevice HomeKit path. + /// + private async Task> DiscoverHomeKitAsync(CancellationToken ct) + { + var devices = new List(); + try + { + var found = await _homeKitProbe.DiscoverAsync(ct).ConfigureAwait(false); + foreach (var accessory in found) + { + devices.Add(new AgentDiscoveredDevice( + Ip: accessory.Ip, + IsReachable: true, + OpenPorts: [accessory.Port], + MacAddress: null, + Vendor: "Apple", + Hostname: accessory.Name, + HttpServerHeader: null, + HttpStatusCode: null, + HttpPort: null, + OnvifDeviceServiceUrl: null, + OnvifName: null, + OnvifHardware: null, + OnvifPort: null, + HomeKitName: accessory.Name, + HomeKitDeviceId: accessory.DeviceId, + HomeKitModel: accessory.Model, + CredentialLabel: null, + StreamUrls: null)); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "HomeKit mDNS discovery failed"); + } + return devices; } diff --git a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs new file mode 100644 index 0000000..42d1c3b --- /dev/null +++ b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs @@ -0,0 +1,236 @@ +using System.Buffers.Binary; +using System.Text; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; + +namespace Heimdall.Agent.Tests; + +public class HomeKitMdnsProbeTests +{ + private static readonly System.Reflection.MethodInfo ParsePacketMethod = typeof(HomeKitMdnsProbe) + .GetMethod("ParsePacket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) + ?? throw new InvalidOperationException("ParsePacket not found"); + + /// Build a minimal mDNS response packet with PTR + SRV + TXT + A records. + private static byte[] BuildMdnsPacket() + { + using var ms = new MemoryStream(); + Span scratch = stackalloc byte[8]; + + // Header: ID=0x1234, flags=0x8400 (response), 0 questions, 4 answers, + // 0 authority, 0 additional (12 octets). + BinaryPrimitives.WriteUInt16BigEndian(scratch, 0x1234); + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x8400); + BinaryPrimitives.WriteUInt16BigEndian(scratch[4..], 0); // QDCOUNT + BinaryPrimitives.WriteUInt16BigEndian(scratch[6..], 4); // ANCOUNT + ms.Write(scratch[..8]); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 0); // NSCOUNT + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0); // ARCOUNT + ms.Write(scratch[..4]); + + // Answer 1: PTR _hap._tcp.local → Camera-ABCDEF._hap._tcp.local + WriteName(ms, "_hap._tcp.local"); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 12); // PTR + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001); // IN + BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 4500); // TTL + ms.Write(scratch); + var ptrName = EncodeName("Camera-ABCDEF._hap._tcp.local"); + BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)ptrName.Length); + ms.Write(scratch[..2]); + ms.Write(ptrName); + + // Answer 2: SRV Camera-ABCDEF._hap._tcp.local → cam-abc.local:8080 + WriteName(ms, "Camera-ABCDEF._hap._tcp.local"); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 33); // SRV + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001); + BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 120); + ms.Write(scratch); + var srvTarget = EncodeName("cam-abc.local"); + var srvRdata = new byte[6 + srvTarget.Length]; + srvRdata[4] = 0x1F; srvRdata[5] = 0x90; // port 8080 big-endian + Array.Copy(srvTarget, 0, srvRdata, 6, srvTarget.Length); + BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)srvRdata.Length); + ms.Write(scratch[..2]); + ms.Write(srvRdata); + + // Answer 3: TXT Camera-ABCDEF._hap._tcp.local → ci=17, id=AA:BB:CC, md=CamModel, sf=0 + WriteName(ms, "Camera-ABCDEF._hap._tcp.local"); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 16); // TXT + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001); + BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 4500); + ms.Write(scratch); + var txtEntries = new List { "ci=17", "id=AA:BB:CC:DD:EE:FF", "md=CamModel", "sf=0" }; + var txtBytes = new List(); + foreach (var entry in txtEntries) + { + var e = Encoding.ASCII.GetBytes(entry); + txtBytes.Add((byte)e.Length); + txtBytes.AddRange(e); + } + BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)txtBytes.Count); + ms.Write(scratch[..2]); + ms.Write(txtBytes.ToArray()); + + // Answer 4: A cam-abc.local → 192.168.1.42 + WriteName(ms, "cam-abc.local"); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 1); // A + BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001); + BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 120); + ms.Write(scratch); + BinaryPrimitives.WriteUInt16BigEndian(scratch, 4); + ms.Write(scratch[..2]); + ms.Write(new byte[] { 192, 168, 1, 42 }); + + return ms.ToArray(); + } + + private static void WriteName(MemoryStream ms, string name) + { + ms.Write(EncodeName(name)); + } + + private static byte[] EncodeName(string name) + { + using var ms = new MemoryStream(); + foreach (var label in name.TrimEnd('.').Split('.')) + { + if (label.Length == 0) continue; + ms.WriteByte((byte)label.Length); + ms.Write(Encoding.ASCII.GetBytes(label)); + } + ms.WriteByte(0); + return ms.ToArray(); + } + + [Fact] + public void ParsePacket_HomeKitCamera_ParsesPtrSrvTxtA() + { + var packet = BuildMdnsPacket(); + var replies = ((System.Collections.IEnumerable)ParsePacketMethod.Invoke(null, [packet])!) + .Cast() + .ToList(); + + replies.Count.ShouldBe(4); + + // PTR + var ptr = replies[0]; + var ptrInstance = (string)ptr.GetType().GetProperty("Instance")!.GetValue(ptr)!; + ptrInstance.ShouldBe("camera-abcdef._hap._tcp.local"); + ((ushort)ptr.GetType().GetProperty("Type")!.GetValue(ptr)!).ShouldBe((ushort)12); + + // SRV + var srv = replies[1]; + ((int?)srv.GetType().GetProperty("SrvPort")!.GetValue(srv)).ShouldBe(8080); + ((string?)srv.GetType().GetProperty("SrvTarget")!.GetValue(srv)).ShouldBe("cam-abc.local"); + + // TXT + var txt = replies[2]; + var txtDict = (System.Collections.Generic.IReadOnlyDictionary)txt.GetType().GetProperty("Txt")!.GetValue(txt)!; + txtDict["ci"].ShouldBe("17"); + txtDict["id"].ShouldBe("AA:BB:CC:DD:EE:FF"); + txtDict["md"].ShouldBe("CamModel"); + txtDict["sf"].ShouldBe("0"); + + // A + var a = replies[3]; + ((string?)a.GetType().GetProperty("Address")!.GetValue(a)).ShouldBe("192.168.1.42"); + } + + [Fact] + public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow() + { + var probe = new HomeKitMdnsProbe(NullLogger.Instance); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + + // In a container without a multicast route this returns [] — it must + // never throw and must terminate within the window. + var devices = await probe.DiscoverAsync(cts.Token); + + devices.ShouldNotBeNull(); + } + + private static readonly System.Reflection.MethodInfo BuildDevicesMethod = typeof(HomeKitMdnsProbe) + .GetMethod("BuildDevices", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) + ?? throw new InvalidOperationException("BuildDevices not found"); + + private static readonly Type MdnsReplyType = typeof(HomeKitMdnsProbe).GetNestedType("MdnsReply", System.Reflection.BindingFlags.NonPublic)!; + + private static object MakeReply( + string instance, ushort type, string? srvTarget = null, int? srvPort = null, + Dictionary? txt = null, string? address = null) + { + return Activator.CreateInstance( + MdnsReplyType, + instance, type, srvTarget, srvPort, (System.Collections.Generic.IReadOnlyDictionary?)txt, address)!; + } + + private static object MakeTypedList(IEnumerable replies) + { + var listType = typeof(System.Collections.Generic.List<>).MakeGenericType(MdnsReplyType); + var list = Activator.CreateInstance(listType)!; + var add = listType.GetMethod("Add")!; + foreach (var reply in replies) + add.Invoke(list, [reply]); + return list; + } + + private static List RunBuildDevices(List replies) + => ((System.Collections.IEnumerable)BuildDevicesMethod.Invoke(null, [MakeTypedList(replies)])!) + .Cast() + .ToList(); + + [Fact] + public void BuildDevices_KeepsCameraAndDoorbell_DedupesByIp() + { + var replies = new List + { + // Camera ci=17 + MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }), + MakeReply("cam1._hap._tcp.local", 33, srvTarget: "cam1.local", srvPort: 8080), + MakeReply("cam1.local", 1, address: "192.168.1.10"), + // Doorbell ci=18 + MakeReply("door1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "18", ["id"] = "BB:22", ["md"] = "DoorOne", ["sf"] = "1" }), + MakeReply("door1._hap._tcp.local", 33, srvTarget: "door1.local", srvPort: 7000), + MakeReply("door1.local", 1, address: "192.168.1.11"), + // Other category ci=5 (light) — must be filtered out + MakeReply("lamp1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "5", ["id"] = "CC:33", ["md"] = "Lamp", ["sf"] = "0" }), + MakeReply("lamp1._hap._tcp.local", 33, srvTarget: "lamp1.local", srvPort: 5000), + MakeReply("lamp1.local", 1, address: "192.168.1.12"), + }; + + var devices = RunBuildDevices(replies); + + devices.Count.ShouldBe(2); + + var cam = devices[0]; + ((string)cam.GetType().GetProperty("Ip")!.GetValue(cam)!).ShouldBe("192.168.1.10"); + ((string)cam.GetType().GetProperty("Name")!.GetValue(cam)!).ShouldBe("cam1"); + ((string)cam.GetType().GetProperty("DeviceId")!.GetValue(cam)!).ShouldBe("AA:11"); + ((string)cam.GetType().GetProperty("Model")!.GetValue(cam)!).ShouldBe("CamOne"); + ((int)cam.GetType().GetProperty("Category")!.GetValue(cam)!).ShouldBe(17); + ((bool)cam.GetType().GetProperty("IsPaired")!.GetValue(cam)!).ShouldBeFalse(); + ((int)cam.GetType().GetProperty("Port")!.GetValue(cam)!).ShouldBe(8080); + + var door = devices[1]; + ((string)door.GetType().GetProperty("Ip")!.GetValue(door)!).ShouldBe("192.168.1.11"); + ((int)door.GetType().GetProperty("Category")!.GetValue(door)!).ShouldBe(18); + ((bool)door.GetType().GetProperty("IsPaired")!.GetValue(door)!).ShouldBeTrue(); + } + + [Fact] + public void BuildDevices_DuplicateInstance_OneDevice() + { + var replies = new List + { + MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }), + MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }), + MakeReply("cam1._hap._tcp.local", 33, srvTarget: "cam1.local", srvPort: 8080), + MakeReply("cam1.local", 1, address: "192.168.1.10"), + }; + + var devices = RunBuildDevices(replies); + + devices.Count.ShouldBe(1); + } +}