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; /// 局域网里发现到的一台扫码设备(UDP 48899 广播回复) public sealed record DiscoveredDevice(string Mac, string Ip, string HostName, string Model, string Version, string State) { public string Display => $"{HostName}({(string.IsNullOrEmpty(Ip) ? "?" : Ip)} · {Mac} · {Model})"; } /// 设备 SYS 段配置(JCMD 10003 读回) public sealed record DeviceSysConfig( string HostName, string IpAddr, string Mask, string GateWay, string Dns, bool DhcpEn, string User, string Password) { public string Display => $"{HostName} · {(DhcpEn ? "DHCP" : "静态")} {IpAddr}"; } /// /// 设备发现与 JCMD 配置(从 AndroidScanCenter 的 DeviceScanner 移植到桌面端)。 /// /// 要点(见 AndroidScanCenter/docs/udp-48899-protocol.md): /// - 往 `255.255.255.255:48899`(以及各网段的定向广播)发**明文 JSON**, /// 设备的回复会回到**发送方的源端口**,所以必须**同一个 socket** 收发, /// **不能**绑 48899 去收; /// - 按 **MAC 去重**(一台设备会因为收到多个广播而回多个包); /// - JCMD 配置/重启走 **UDP 单播到设备 IP:48899**,`{"JCMD":1,"CID":...}`, /// `RC=0` 为成功;升级前不要发 `DO_RELOAD`(会把改动抹掉)。 /// public sealed class DeviceScanner { private static readonly TimeSpan ReplyWait = TimeSpan.FromSeconds(1.6); /// 广播发现设备(每块网卡各广播一次) public async Task> DiscoverAsync(CancellationToken ct = default) { var devices = new Dictionary(StringComparer.OrdinalIgnoreCase); using var udp = new UdpClient(AddressFamily.InterNetwork); udp.EnableBroadcast = true; var targets = BroadcastTargets(); var payload = ScanProtocol.Utf8(ScanProtocol.BroadcastPayload); foreach (var target in targets) { try { await udp.SendAsync(payload, payload.Length, new IPEndPoint(target, ScanProtocol.UdpPort)) .WaitAsync(ct).ConfigureAwait(false); } catch (Exception ex) { AppLog.Write($"[scan] 广播到 {target} 失败:{ex.Message}"); } } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(ReplyWait); while (!timeout.IsCancellationRequested) { try { var received = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false); var text = Encoding.UTF8.GetString(received.Buffer); if (!text.TrimStart().StartsWith('{')) continue; using var doc = JsonDocument.Parse(text); var root = doc.RootElement; if (!root.TryGetProperty("MAC", out var macElement) || macElement.ValueKind != JsonValueKind.String) continue; var mac = (macElement.GetString() ?? string.Empty).Trim().ToUpperInvariant(); if (mac.Length == 0) continue; devices[mac] = new DiscoveredDevice( mac, received.RemoteEndPoint.Address.ToString(), GetString(root, "HostName"), GetString(root, "Type"), GetString(root, "Version"), GetString(root, "State")); } catch (OperationCanceledException) { break; } catch (Exception ex) { AppLog.Write($"[scan] 解析发现回复失败:{ex.Message}"); } } AppLog.Write($"[scan] 发现 {devices.Count} 台设备"); return devices.Values.OrderBy(item => item.Mac, StringComparer.Ordinal).ToList(); } /// 读设备 SYS 配置(CID 10003;`Remain=1` 时用响应 CID 续取) public async Task ReadSysConfigAsync(string ip, CancellationToken ct = default) { if (!IPAddress.TryParse(ip, out var address)) throw new ArgumentException($"IP 不合法:{ip}"); using var udp = new UdpClient(AddressFamily.InterNetwork); udp.Client.ReceiveTimeout = 2500; var request = "{\"JCMD\":1,\"PL\":[\"SYS\"],\"CID\":" + ScanProtocol.CidGetConfig + "}"; var payload = ScanProtocol.Utf8(request); await udp.SendAsync(payload, payload.Length, new IPEndPoint(address, ScanProtocol.UdpPort)) .WaitAsync(ct).ConfigureAwait(false); var all = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var round = 0; round < 4; round++) { JsonDocument doc; try { var buffer = await ScanProtocol.ReceiveWithTimeoutAsync(udp, 2500, ct).ConfigureAwait(false); if (buffer is null) break; // 超时 var text = Encoding.UTF8.GetString(buffer); if (!text.TrimStart().StartsWith('{')) continue; doc = JsonDocument.Parse(text); } catch (OperationCanceledException) { break; } catch (Exception) { break; // 超时 / 坏包:结束 } using (doc) { var root = doc.RootElement; if (!root.TryGetProperty("CID", out var cid) || !cid.TryGetInt32(out var cidValue)) continue; if (cidValue != ScanProtocol.CidGetConfig + 1 && cidValue != ScanProtocol.CidGetConfig + 2) continue; var rc = root.TryGetProperty("RC", out var rcElement) && rcElement.TryGetInt32(out var rcValue) ? rcValue : -1; if (rc != 0) break; if (root.TryGetProperty("PL", out var pl) && pl.ValueKind == JsonValueKind.Object && pl.TryGetProperty("SYS", out var sys) && sys.ValueKind == JsonValueKind.Object) { foreach (var property in sys.EnumerateObject()) { all[property.Name] = property.Value.Clone(); } } var remain = root.TryGetProperty("Remain", out var remainElement) && remainElement.TryGetInt32(out var remainValue) && remainValue == 1; if (!remain) break; // 没取完:用响应 CID 续取 var next = "{\"JCMD\":1,\"Remain\":1,\"CID\":" + cidValue + "}"; var nextPayload = ScanProtocol.Utf8(next); await udp.SendAsync(nextPayload, nextPayload.Length, new IPEndPoint(address, ScanProtocol.UdpPort)) .WaitAsync(ct).ConfigureAwait(false); } } if (all.Count == 0) return null; return new DeviceSysConfig( GetString(all, "HostName"), GetString(all, "IpAddr"), GetString(all, "Mask"), GetString(all, "GateWay"), GetString(all, "Dns"), GetInt(all, "DhcpEn") == 1, GetString(all, "User"), GetString(all, "Password")); } /// /// 写设备 SYS 配置(CID 10005,**增量**:只传要改的字段) /// /// ⚠️ 切 DHCP 会把 `IpAddr/Mask/GateWay` 清成 0.0.0.0;改回静态必须三个一起写。 /// 写完**不要**发 `DO_RELOAD`(会把改动抹掉),想立刻生效用 `RestartAsync`。 /// public Task WriteSysConfigAsync(string ip, IReadOnlyDictionary patch, CancellationToken ct = default) => DeviceConfig.WriteSectionAsync(ip, "SYS", patch, ct); /// 重启设备(CID 20003;实测会延后几十秒到几分钟才真正复位) public async Task RestartAsync(string ip, CancellationToken ct = default) { if (!IPAddress.TryParse(ip, out var address)) throw new ArgumentException($"IP 不合法:{ip}"); using var udp = new UdpClient(AddressFamily.InterNetwork); udp.Client.ReceiveTimeout = 2000; var payload = ScanProtocol.Utf8("{\"JCMD\":1,\"CID\":" + ScanProtocol.CidDoRestart + "}"); await udp.SendAsync(payload, payload.Length, new IPEndPoint(address, ScanProtocol.UdpPort)) .WaitAsync(ct).ConfigureAwait(false); try { var buffer = await ScanProtocol.ReceiveWithTimeoutAsync(udp, 2000, ct).ConfigureAwait(false); if (buffer is null) { AppLog.Write($"[scan] 重启设备 {ip}:无应答"); return false; } using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(buffer)); var root = doc.RootElement; var rc = root.TryGetProperty("RC", out var rcElement) && rcElement.TryGetInt32(out var rcValue) ? rcValue : -1; AppLog.Write($"[scan] 重启设备 {ip}:RC={rc}"); return rc == 0; } catch (Exception ex) { AppLog.Write($"[scan] 重启设备失败 {ip}:{ex.Message}"); return false; } } /// 广播目标:255.255.255.255 + 每块网卡的定向广播地址 internal static List BroadcastTargets() { var targets = new List { IPAddress.Broadcast }; try { foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) continue; if (nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; foreach (var unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.AddressFamily != AddressFamily.InterNetwork) continue; if (unicast.IPv4Mask is null) continue; var address = unicast.Address.GetAddressBytes(); var mask = unicast.IPv4Mask.GetAddressBytes(); if (address.Length != 4 || mask.Length != 4) continue; var broadcast = new byte[4]; for (var i = 0; i < 4; i++) broadcast[i] = (byte)(address[i] | (mask[i] ^ 255)); var target = new IPAddress(broadcast); if (!targets.Contains(target)) targets.Add(target); } } } catch (Exception ex) { AppLog.Write($"[scan] 枚举网卡失败:{ex.Message}"); } return targets; } private static string GetString(JsonElement element, string property) { if (!element.TryGetProperty(property, out var value)) return string.Empty; return value.ValueKind switch { JsonValueKind.String => (value.GetString() ?? string.Empty).Trim(), JsonValueKind.Number => value.ToString(), _ => string.Empty, }; } private static string GetString(IReadOnlyDictionary map, string key) => map.TryGetValue(key, out var value) ? RawText(value) : string.Empty; private static string RawText(JsonElement value) => value.ValueKind switch { JsonValueKind.String => (value.GetString() ?? string.Empty).Trim(), JsonValueKind.Number => value.ToString(), _ => string.Empty, }; private static int GetInt(IReadOnlyDictionary map, string key) { if (!map.TryGetValue(key, out var value)) return 0; return value.ValueKind switch { JsonValueKind.Number => value.TryGetInt32(out var number) ? number : 0, JsonValueKind.String => int.TryParse(value.GetString(), out var parsed) ? parsed : 0, _ => 0, }; } }