packServer/desktop/Services/Scan/DiscoveryMonitor.cs

273 lines
9.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services.Scan;
/// <summary>
/// 常驻的设备发现(真正的「开着 UDP 口一直听」)。
///
/// 为什么不能只 bind 48899 被动收:**设备不会主动广播**(实测绑 48899 静听 40 秒,
/// 只能收到我们自己发出去的探测包),它只回**探测者**,而且回复发到**发送方的源端口**
/// (见 AndroidScanCenter/docs/udp-48899-protocol.md),所以在 48899 上 bind 收不到回复。
///
/// 所以做法是:**一个 socket 一直开着**,每 <see cref="ProbeIntervalMs"/> 毫秒往
/// `255.255.255.255` + 各网段定向广播发一次探测,然后在这**同一个 socket** 上持续收,
/// 按 MAC 合并、超过 <see cref="DeviceTimeoutMs"/> 没见过就摘掉。
/// 这样界面是「一进来就在刷」的连续感,而不是「扫一轮停 5 秒」的一截一截。
/// </summary>
public sealed class DiscoveryMonitor : IDisposable
{
/// <summary>多久探测一次(设备回包通常几十毫秒就回来)</summary>
private const int ProbeIntervalMs = 3000;
/// <summary>多久没再见到就算掉线(比探测间隔大,扛得住偶尔丢包)</summary>
private const int DeviceTimeoutMs = 12000;
private readonly DeviceScanner _scanner = new();
private readonly CancellationTokenSource _cts = new();
private readonly Dictionary<string, (DiscoveredDevice Device, DateTime LastSeen)> _devices =
new(StringComparer.OrdinalIgnoreCase);
private Task? _loop;
/// <summary>设备列表有变化(新增/更新/掉线)</summary>
public event Action? Changed;
/// <summary>当前看到的设备(按 MAC 排序的快照)</summary>
public IReadOnlyList<DiscoveredDevice> Devices
{
get
{
lock (_devices)
{
return _devices.Values.Select(item => item.Device)
.OrderBy(item => item.Mac, StringComparer.Ordinal)
.ToList();
}
}
}
public void Start()
{
if (_loop is not null) return;
_loop = Task.Run(() => LoopAsync(_cts.Token));
AppLog.Write("[scan] 设备发现已开始(常驻 UDP,每 3 秒探测一次)");
}
private async Task LoopAsync(CancellationToken ct)
{
using var udp = new UdpClient(AddressFamily.InterNetwork);
udp.EnableBroadcast = true;
var targets = BroadcastTargets();
var payload = ScanProtocol.Utf8(ScanProtocol.BroadcastPayload);
var nextProbe = DateTime.MinValue;
while (!ct.IsCancellationRequested)
{
var now = DateTime.Now;
// 到点就探测一次(同一个 socket 发,回复才会回到这里)
if (now >= nextProbe)
{
foreach (var target in targets)
{
try
{
await udp.SendAsync(payload, payload.Length, new IPEndPoint(target, ScanProtocol.UdpPort))
.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
AppLog.Write($"[scan] 广播到 {target} 失败:{ex.Message}");
}
}
nextProbe = now.AddMilliseconds(ProbeIntervalMs);
}
// 一直收:每次最多等 500ms,收完继续等(不关 socket、不留空档)
try
{
UdpReceiveResult? received = null;
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
timeout.CancelAfter(500);
try
{
received = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
// 500ms 没包,很正常(没设备回 / 本轮已收完)
}
}
if (received is not null) HandleReply(received.Value);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
AppLog.Write($"[scan] 收发现回复失败(忽略):{ex.Message}");
}
PruneStale();
}
}
/// <summary>解析一条发现回复(按 MAC 合并;同一条会回多包,无所谓)</summary>
private void HandleReply(UdpReceiveResult reply)
{
string text;
try
{
text = Encoding.UTF8.GetString(reply.Buffer);
}
catch
{
return;
}
if (!text.TrimStart().StartsWith('{')) return;
string mac;
DiscoveredDevice device;
try
{
using var doc = JsonDocument.Parse(text);
var root = doc.RootElement;
if (!root.TryGetProperty("MAC", out var macElement) || macElement.ValueKind != JsonValueKind.String) return;
mac = (macElement.GetString() ?? string.Empty).Trim().ToUpperInvariant();
if (mac.Length == 0) return;
device = new DiscoveredDevice(
mac,
reply.RemoteEndPoint.Address.ToString(),
GetString(root, "HostName"),
GetString(root, "Type"),
GetString(root, "Version"),
GetString(root, "State"));
}
catch
{
return;
}
var changed = false;
lock (_devices)
{
if (!_devices.TryGetValue(mac, out var previous))
{
_devices[mac] = (device, DateTime.Now);
changed = true;
}
else
{
// 名字/IP/状态变了才算变化(避免每 3 秒都刷一次界面)
if (previous.Device.Ip != device.Ip
|| previous.Device.HostName != device.HostName
|| previous.Device.State != device.State)
{
changed = true;
}
_devices[mac] = (device, DateTime.Now);
}
}
if (changed) Changed?.Invoke();
}
private static string GetString(JsonElement element, string name)
=> element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
? value.GetString() ?? string.Empty
: string.Empty;
private void PruneStale()
{
var deadline = DateTime.Now.AddMilliseconds(-DeviceTimeoutMs);
var removed = false;
lock (_devices)
{
foreach (var mac in _devices.Where(item => item.Value.LastSeen < deadline).Select(item => item.Key).ToList())
{
_devices.Remove(mac);
removed = true;
}
}
if (removed) Changed?.Invoke();
}
/// <summary>广播目标:255.255.255.255 + 每块网卡的定向广播地址</summary>
private static List<IPAddress> BroadcastTargets()
{
var targets = new List<IPAddress> { IPAddress.Broadcast };
try
{
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus != OperationalStatus.Up) continue;
if (nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var info in nic.GetIPProperties().UnicastAddresses)
{
if (info.Address.AddressFamily != AddressFamily.InterNetwork) continue;
var mask = info.IPv4Mask;
if (mask is null) continue;
var ip = info.Address.GetAddressBytes();
var m = mask.GetAddressBytes();
if (ip.Length != 4 || m.Length != 4) continue;
var broadcast = new byte[4];
for (var i = 0; i < 4; i++) broadcast[i] = (byte)(ip[i] | (m[i] ^ 0xFF));
var address = new IPAddress(broadcast);
if (!targets.Contains(address)) targets.Add(address);
}
}
}
catch (Exception ex)
{
AppLog.Write($"[scan] 枚举网卡失败(只用 255.255.255.255):{ex.Message}");
}
return targets;
}
public void Dispose()
{
try
{
_cts.Cancel();
}
catch
{
// 忽略
}
_cts.Dispose();
AppLog.Write("[scan] 设备发现已停止");
}
}