505 lines
23 KiB
C#
505 lines
23 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services.Scan;
|
||
|
||
/// <summary>设备上的一条 socket 配置(SOCK 段条目)</summary>
|
||
/// <param name="Raw">原始字段(整条写回时用;真机上有设备会把别人的条目清掉,要靠它恢复)</param>
|
||
public sealed record SockEntry(string Name, string Protocol, int LocalPort,
|
||
IReadOnlyDictionary<string, JsonElement>? Raw = null);
|
||
|
||
/// <summary>socket 条目的**运行状态**(CID 10001 才有 `ClientIP`,读配置没有)</summary>
|
||
public sealed record SockState(string Name, string Protocol, string State, string ClientIp)
|
||
{
|
||
/// <summary>设备侧记录的已连客户端 IP 列表(逗号分隔,可能多个)</summary>
|
||
public string[] Clients => ClientIp.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||
}
|
||
|
||
/// <summary>设备侧「给中控用的 TCP 服务」的约定(照抄 AndroidScanCenter 的 TcpServerConfig)</summary>
|
||
public static class SockConfig
|
||
{
|
||
/// <summary>
|
||
/// 设备固件看起来**最多只允许 3 条 SOCK 条目**:真机实测第 4 条写入回 `RC=0`、
|
||
/// 能连上,但 ~1 分钟内会被设备默默丢掉(端口关闭),无限循环。
|
||
/// 所以条目已满时改为「复用一条非保留条目」。
|
||
/// </summary>
|
||
public const int MaxEntries = 3;
|
||
|
||
/// <summary>别人在用的条目名,絶不能动:Android 中控的 `scancenter`、推 WMS 的 `netp`</summary>
|
||
private static readonly string[] Reserved =
|
||
{
|
||
"scancenter",
|
||
"netp",
|
||
};
|
||
|
||
/// <summary>这条条目是不是别人的(保留不动)</summary>
|
||
public static bool IsReserved(string name)
|
||
=> Reserved.Any(item => item.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||
|
||
/// <summary>
|
||
/// 构造一条完整的 SOCK 配置。
|
||
///
|
||
/// ⚠️ SOCK 段是**整条写**的:少传字段等于把那条配置改坏,所以字段集按官方工具原样给全。
|
||
/// 设备按 `Name` 管条目,写我们这条不会动别的条(现场有其他条目:HTTP 推 WMS 等)。
|
||
/// </summary>
|
||
public static Dictionary<string, object> BuildEntry(string name)
|
||
{
|
||
return new Dictionary<string, object>
|
||
{
|
||
["Name"] = string.IsNullOrWhiteSpace(name) ? ScanProtocol.SockName : name,
|
||
["Protocol"] = "TCP-SERVER",
|
||
["LocalPort"] = ScanProtocol.TcpPort,
|
||
["maxAccept"] = 5,
|
||
// 数据源选串口:扫码枪接在设备的 RS232/RS485 口上
|
||
["Rout"] = "uart",
|
||
["BufSize"] = 512,
|
||
["KeepAlive"] = 60,
|
||
["ConnectMode"] = "Always",
|
||
["Timeout"] = 0,
|
||
// 监听模式下 Server/ServerPort 没意义,明确清空,免得设备去连一个莫名其妙的地址
|
||
["Server"] = "",
|
||
["ServerPort"] = 0,
|
||
["StopSerial"] = "",
|
||
["HeartBeatEn"] = 0,
|
||
["HeartBeatTime"] = 0,
|
||
["HeartBeatCode"] = "",
|
||
["RegistMode"] = "Disable",
|
||
["RegistCode"] = "",
|
||
["Security"] = "Disable",
|
||
["SecuKey"] = "",
|
||
["VcomEn"] = 0,
|
||
["VpTag"] = "",
|
||
};
|
||
}
|
||
|
||
/// <summary>我们那条是否就绪:名字对得上、协议是 TCP-SERVER、端口也对(三项都要看)</summary>
|
||
public static bool IsReady(IEnumerable<SockEntry> entries, string name)
|
||
=> entries.Any(item => item.Name.Equals(name, StringComparison.OrdinalIgnoreCase)
|
||
&& item.Protocol.Equals("TCP-SERVER", StringComparison.OrdinalIgnoreCase)
|
||
&& item.LocalPort == ScanProtocol.TcpPort);
|
||
|
||
/// <summary>把设备上现有条目拼成一行(出错时要能看清设备上到底有哪几条)</summary>
|
||
public static string Describe(IEnumerable<SockEntry> entries)
|
||
=> string.Join(" / ", entries.Select(item => $"{item.Name}:{item.Protocol}:{item.LocalPort}"));
|
||
}
|
||
|
||
/// <summary>「确保设备 TCP 服务」的结果</summary>
|
||
public enum TcpServerEnsureKind
|
||
{
|
||
/// <summary>本来就有可用的(不做任何写入)</summary>
|
||
AlreadyReady,
|
||
|
||
/// <summary>新建成功</summary>
|
||
Created,
|
||
|
||
/// <summary>原来有但配置不对,已修正</summary>
|
||
Fixed,
|
||
|
||
/// <summary>读不到设备的 SOCK 段(无应答)</summary>
|
||
ReadFailed,
|
||
|
||
/// <summary>写入失败</summary>
|
||
WriteFailed,
|
||
|
||
/// <summary>写完回读发现还是不对(设备 RC=0 不代表真生效)</summary>
|
||
VerifyFailed,
|
||
}
|
||
|
||
/// <summary>「确保设备 TCP 服务」的结果 + 明细</summary>
|
||
public sealed record TcpServerEnsureResult(TcpServerEnsureKind Kind, string Detail, string SockName = "")
|
||
{
|
||
/// <summary>三条「就绪」的结果都算成功</summary>
|
||
public bool Ok => Kind is TcpServerEnsureKind.AlreadyReady or TcpServerEnsureKind.Created or TcpServerEnsureKind.Fixed;
|
||
|
||
/// <summary>给界面看的一句话</summary>
|
||
public string Message => Kind switch
|
||
{
|
||
TcpServerEnsureKind.AlreadyReady => $"设备 TCP 服务已就绪(端口 {ScanProtocol.TcpPort})",
|
||
TcpServerEnsureKind.Created => $"已在设备上创建 TCP 服务(端口 {ScanProtocol.TcpPort})",
|
||
TcpServerEnsureKind.Fixed => $"已修正设备的 TCP 服务配置(端口 {ScanProtocol.TcpPort})",
|
||
TcpServerEnsureKind.ReadFailed => $"读不到设备 socket 配置:{Detail}",
|
||
TcpServerEnsureKind.WriteFailed => $"写入设备 socket 配置失败:{Detail}",
|
||
_ => $"写入后回读不符(设备上是:{Detail})",
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设备配置写入(JCMD):SOCK 条目读写、落 flash、「确保 TCP 服务」。
|
||
///
|
||
/// 与 <see cref="DeviceScanner"/> 的分工:那边管发现和 SYS 读写,这里补上
|
||
/// 添加通道时必须做的两件事 —— 让设备有一条给中控用的 TCP 服务、把设备名写进设备。
|
||
/// </summary>
|
||
public static class DeviceConfig
|
||
{
|
||
/// <summary>读设备 SOCK 条目(CID 10003 的 SOCK 段;分片会按 `Remain` 续取)</summary>
|
||
public static async Task<List<SockEntry>?> ReadSockEntriesAsync(this DeviceScanner _, string ip,
|
||
CancellationToken ct = default)
|
||
{
|
||
var merged = await ReadSectionAsync(ip, "SOCK", ScanProtocol.CidGetConfig, ct).ConfigureAwait(false);
|
||
if (merged is null) return null;
|
||
|
||
var list = new List<SockEntry>();
|
||
if (merged.Value.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in merged.Value.EnumerateArray())
|
||
{
|
||
if (item.ValueKind != JsonValueKind.Object) continue;
|
||
|
||
var raw = new Dictionary<string, JsonElement>(StringComparer.OrdinalIgnoreCase);
|
||
foreach (var property in item.EnumerateObject()) raw[property.Name] = property.Value.Clone();
|
||
|
||
list.Add(new SockEntry(
|
||
GetString(item, "Name"),
|
||
GetString(item, "Protocol"),
|
||
GetInt(item, "LocalPort"),
|
||
raw));
|
||
}
|
||
}
|
||
return list.Count == 0 ? null : list;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读 SOCK 的**运行状态**(CID 10001)。
|
||
///
|
||
/// 只有这个来源带 `ClientIP` / `State`,用来做「假死」判定:设备断电重启时
|
||
/// TCP 不会发 FIN/RST,中控这侧的 `ReadAsync` 会永久挂住 —— 只能回查设备侧
|
||
/// 还认不认这条连接。
|
||
/// </summary>
|
||
public static async Task<List<SockState>?> ReadSockStatesAsync(this DeviceScanner _, string ip,
|
||
CancellationToken ct = default)
|
||
{
|
||
var merged = await ReadSectionAsync(ip, "SOCK", ScanProtocol.CidGetState, ct).ConfigureAwait(false);
|
||
if (merged is null) return null;
|
||
|
||
var list = new List<SockState>();
|
||
if (merged.Value.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in merged.Value.EnumerateArray())
|
||
{
|
||
if (item.ValueKind != JsonValueKind.Object) continue;
|
||
list.Add(new SockState(
|
||
GetString(item, "SockName").Length > 0 ? GetString(item, "SockName") : GetString(item, "Name"),
|
||
GetString(item, "Protocol"),
|
||
GetString(item, "State"),
|
||
GetString(item, "ClientIP")));
|
||
}
|
||
}
|
||
return list.Count == 0 ? null : list;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 确保设备上有一条「给中控用的 TCP 服务」。没有它这条通道就是死通道(永远连不上)。
|
||
///
|
||
/// 流程与 AndroidScanCenter 一致:读 SOCK → 就绪则不写 → 否则整条写入 → **回读确认**。
|
||
/// 回读不能省:设备 `RC=0` 只代表报文收到了,端口冲突/条目名非法它不报错。
|
||
///
|
||
/// ⚠️ 设备最多只放得下 <see cref="SockConfig.MaxEntries"/> 条(实测第 4 条会被静默丢弃),
|
||
/// 所以条目已满时**复用一条非保留条目**(把它的名字拿去改成我们的 8087),
|
||
/// 实际用的名字通过 <see cref="TcpServerEnsureResult.SockName"/> 返回,调用方要记住它。
|
||
/// </summary>
|
||
/// <param name="preferredName">上次实际用的条目名(已知就直接用,避免又换一个)</param>
|
||
public static async Task<TcpServerEnsureResult> EnsureTcpServerAsync(this DeviceScanner scanner, string ip,
|
||
string? preferredName = null, CancellationToken ct = default)
|
||
{
|
||
var entries = await ReadSockEntriesWithRetryAsync(scanner, ip, ct).ConfigureAwait(false);
|
||
if (entries is null) return new TcpServerEnsureResult(TcpServerEnsureKind.ReadFailed, "设备无应答");
|
||
|
||
var name = string.IsNullOrWhiteSpace(preferredName) ? ScanProtocol.SockName : preferredName.Trim();
|
||
|
||
if (SockConfig.IsReady(entries, name))
|
||
{
|
||
return new TcpServerEnsureResult(TcpServerEnsureKind.AlreadyReady, "", name);
|
||
}
|
||
|
||
var existed = entries.Any(item => item.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||
var reused = string.Empty;
|
||
|
||
if (!existed && entries.Count >= SockConfig.MaxEntries)
|
||
{
|
||
// 条目满了:找一条不是别人的(不是 Android 的 scancenter、不是推 WMS 的 netp)来复用
|
||
var candidate = entries.FirstOrDefault(item => !SockConfig.IsReserved(item.Name));
|
||
if (candidate is null)
|
||
{
|
||
return new TcpServerEnsureResult(TcpServerEnsureKind.VerifyFailed,
|
||
$"设备 socket 条目已满({SockConfig.Describe(entries)}),且没有可复用的条目");
|
||
}
|
||
|
||
name = candidate.Name;
|
||
reused = candidate.Name;
|
||
}
|
||
|
||
AppLog.Write($"[scan] 设备 {ip} 现有 socket 条目:{SockConfig.Describe(entries)};"
|
||
+ (reused.Length > 0
|
||
? $"条目已满,复用「{reused}」改成我们的端口 {ScanProtocol.TcpPort}"
|
||
: existed
|
||
? $"将修复「{name}」条目(端口 {ScanProtocol.TcpPort})"
|
||
: $"将新建「{name}」条目(端口 {ScanProtocol.TcpPort})"));
|
||
|
||
var written = await WriteSectionAsync(ip, "SOCK", SockConfig.BuildEntry(name), ct).ConfigureAwait(false);
|
||
if (!written) return new TcpServerEnsureResult(TcpServerEnsureKind.WriteFailed, "写 SOCK 段失败", name);
|
||
|
||
// 必须落 flash:SET_CONFIG 只改运行态,不落盘的话设备一旦重载/重启就丢,
|
||
// 现象是「刚才还能连,过一会儿就连接被拒」(端口没在监听了)
|
||
if (!await SaveToFlashAsync(ip, ct).ConfigureAwait(false))
|
||
{
|
||
AppLog.Write($"[scan] 设备 {ip} 的 SOCK 配置已生效但未落 flash(重启后会丢)");
|
||
}
|
||
|
||
var after = await ReadSockEntriesWithRetryAsync(scanner, ip, ct).ConfigureAwait(false);
|
||
if (after is null) return new TcpServerEnsureResult(TcpServerEnsureKind.ReadFailed, "写入后回读无应答", name);
|
||
|
||
// ⚠️ 真机踩过的坑:这台设备写 SOCK 段时,偶尔会把**别人的条目一起清掉**
|
||
//(实测把 netp 那条推 WMS 的 HTTP 配置弄没了)。写前已经拿到原始字段,
|
||
// 这里发现丢条就原样写回去,绝不静默把别人的配置吃掉。
|
||
var lost = entries
|
||
.Where(item => !item.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
|
||
.Where(item => after.All(current => !current.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)))
|
||
.ToList();
|
||
|
||
foreach (var item in lost)
|
||
{
|
||
if (item.Raw is null) continue;
|
||
|
||
AppLog.Write($"[scan] ⚠️ 设备 {ip} 把条目「{item.Name}」弄丢了,正在原样写回");
|
||
var restored = await WriteSectionAsync(ip, "SOCK", item.Raw, ct).ConfigureAwait(false);
|
||
AppLog.Write(restored
|
||
? $"[scan] 设备 {ip} 条目「{item.Name}」已写回"
|
||
: $"[scan] 设备 {ip} 条目「{item.Name}」写回失败,请人工检查");
|
||
}
|
||
|
||
if (lost.Count > 0)
|
||
{
|
||
await SaveToFlashAsync(ip, ct).ConfigureAwait(false);
|
||
after = await ReadSockEntriesWithRetryAsync(scanner, ip, ct).ConfigureAwait(false);
|
||
if (after is null) return new TcpServerEnsureResult(TcpServerEnsureKind.ReadFailed, "写回后回读无应答", name);
|
||
}
|
||
|
||
if (!SockConfig.IsReady(after, name))
|
||
{
|
||
return new TcpServerEnsureResult(TcpServerEnsureKind.VerifyFailed, SockConfig.Describe(after), name);
|
||
}
|
||
|
||
return new TcpServerEnsureResult(
|
||
existed || reused.Length > 0 ? TcpServerEnsureKind.Fixed : TcpServerEnsureKind.Created,
|
||
SockConfig.Describe(after),
|
||
name);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 把设备名写进设备(SYS.HostName,UTF-8 支持中文)+ 落 flash。
|
||
///
|
||
/// 实测改完不用重启:读回是新值,广播里也已经是新名。
|
||
/// 落 flash(CID 10017)不能省 —— `SET_CONFIG` 只改运行态,不落盘一次重载就丢。
|
||
/// </summary>
|
||
public static async Task<bool> WriteHostNameAsync(this DeviceScanner scanner, string ip, string name,
|
||
CancellationToken ct = default)
|
||
{
|
||
var trimmed = (name ?? string.Empty).Trim();
|
||
if (trimmed.Length == 0) return true;
|
||
|
||
var patch = new Dictionary<string, object> { ["HostName"] = trimmed };
|
||
if (!await WriteSectionAsync(ip, "SYS", patch, ct).ConfigureAwait(false)) return false;
|
||
|
||
if (!await SaveToFlashAsync(ip, ct).ConfigureAwait(false))
|
||
{
|
||
// 运行态已改成功,只是没落盘 —— 名字已经生效,不算失败,但要在日志里说清楚
|
||
AppLog.Write($"[scan] 设备名 {trimmed} 已生效,但保存到 flash 失败(设备重载后会丢)");
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/// <summary>写任意配置段(CID 10005)。SYS 增量写;SOCK 整条写。</summary>
|
||
public static async Task<bool> WriteSectionAsync(string ip, string section, object patch,
|
||
CancellationToken ct = default)
|
||
{
|
||
var body = JsonSerializer.Serialize(new
|
||
{
|
||
JCMD = 1,
|
||
PL = new Dictionary<string, object> { [section] = patch },
|
||
CID = ScanProtocol.CidSetConfig,
|
||
});
|
||
|
||
var reply = await SendAsync(ip, body, ScanProtocol.CidSetConfig + 1, ct).ConfigureAwait(false);
|
||
AppLog.Write($"[scan] 写设备配置 {ip}({section}):{reply}");
|
||
return reply == 0;
|
||
}
|
||
|
||
/// <summary>把当前配置落 flash(CID 10017 `{"Action":"Set"}`)</summary>
|
||
public static async Task<bool> SaveToFlashAsync(string ip, CancellationToken ct = default)
|
||
{
|
||
var body = "{\"JCMD\":1,\"PL\":{\"Action\":\"Set\"},\"CID\":" + ScanProtocol.CidSaveFlash + "}";
|
||
var reply = await SendAsync(ip, body, ScanProtocol.CidSaveFlash + 1, ct).ConfigureAwait(false);
|
||
AppLog.Write($"[scan] 保存设备配置到 flash {ip}:{reply}");
|
||
return reply == 0;
|
||
}
|
||
|
||
// ---------------- 内部 ----------------
|
||
|
||
/// <summary>读 SOCK 条目,失败重试(现场 UDP 丢包约 6%,一次不回不能当「没有」)</summary>
|
||
private static async Task<List<SockEntry>?> ReadSockEntriesWithRetryAsync(DeviceScanner scanner, string ip,
|
||
CancellationToken ct)
|
||
{
|
||
for (var attempt = 0; attempt < 3; attempt++)
|
||
{
|
||
var entries = await scanner.ReadSockEntriesAsync(ip, ct).ConfigureAwait(false);
|
||
if (entries is not null) return entries;
|
||
try
|
||
{
|
||
await Task.Delay(300, ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// <summary>读配置段(CID 10003)或状态段(CID 10001),分片按 `Remain` 续取后合并。读不到返回 null。</summary>
|
||
private static async Task<JsonElement?> ReadSectionAsync(string ip, string section, int cid,
|
||
CancellationToken ct)
|
||
{
|
||
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\":[\"" + section + "\"],\"CID\":" + cid + "}";
|
||
var payload = ScanProtocol.Utf8(request);
|
||
await udp.SendAsync(payload, payload.Length, new IPEndPoint(address, ScanProtocol.UdpPort))
|
||
.WaitAsync(ct).ConfigureAwait(false);
|
||
|
||
var list = new List<JsonElement>();
|
||
var objects = new Dictionary<string, JsonElement>(StringComparer.OrdinalIgnoreCase);
|
||
var any = false;
|
||
|
||
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; // 超时 / 坏包
|
||
}
|
||
|
||
int nextCid;
|
||
using (doc)
|
||
{
|
||
var root = doc.RootElement;
|
||
if (!root.TryGetProperty("CID", out var cidElement) || !cidElement.TryGetInt32(out var cidValue)) continue;
|
||
if (cidValue != cid + 1 && cidValue != cid + 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(section, out var content))
|
||
{
|
||
any = true;
|
||
if (content.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in content.EnumerateArray()) list.Add(item.Clone());
|
||
}
|
||
else if (content.ValueKind == JsonValueKind.Object)
|
||
{
|
||
foreach (var property in content.EnumerateObject()) objects[property.Name] = property.Value.Clone();
|
||
}
|
||
}
|
||
|
||
var remain = root.TryGetProperty("Remain", out var remainElement)
|
||
&& remainElement.TryGetInt32(out var remainValue) && remainValue == 1;
|
||
if (!remain) break;
|
||
|
||
nextCid = cidValue;
|
||
}
|
||
|
||
var next = "{\"JCMD\":1,\"Remain\":1,\"CID\":" + nextCid + "}";
|
||
var nextPayload = ScanProtocol.Utf8(next);
|
||
await udp.SendAsync(nextPayload, nextPayload.Length, new IPEndPoint(address, ScanProtocol.UdpPort))
|
||
.WaitAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
if (!any) return null;
|
||
|
||
// 数组段(SOCK)与对象段(SYS)合并成一份
|
||
if (list.Count > 0)
|
||
{
|
||
var json = "[" + string.Join(",", list.Select(item => item.GetRawText())) + "]";
|
||
using var merged = JsonDocument.Parse(json);
|
||
return merged.RootElement.Clone();
|
||
}
|
||
|
||
var objJson = "{" + string.Join(",", objects.Select(pair => JsonSerializer.Serialize(pair.Key) + ":" + pair.Value.GetRawText())) + "}";
|
||
using var mergedDoc = JsonDocument.Parse(objJson);
|
||
return mergedDoc.RootElement.Clone();
|
||
}
|
||
|
||
/// <summary>发一条 JCMD 单播并等指定 CID 的回复;返回 RC(-1 = 没回/坏包)</summary>
|
||
private static async Task<int> SendAsync(string ip, string json, int expectedCid, CancellationToken ct)
|
||
{
|
||
if (!IPAddress.TryParse(ip, out var address)) throw new ArgumentException($"IP 不合法:{ip}");
|
||
|
||
using var udp = new UdpClient(AddressFamily.InterNetwork);
|
||
udp.Client.ReceiveTimeout = 2500;
|
||
|
||
var payload = ScanProtocol.Utf8(json);
|
||
await udp.SendAsync(payload, payload.Length, new IPEndPoint(address, ScanProtocol.UdpPort))
|
||
.WaitAsync(ct).ConfigureAwait(false);
|
||
|
||
for (var round = 0; round < 3; round++)
|
||
{
|
||
try
|
||
{
|
||
var buffer = await ScanProtocol.ReceiveWithTimeoutAsync(udp, 2500, ct).ConfigureAwait(false);
|
||
if (buffer is null) return -1; // 超时
|
||
|
||
using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(buffer));
|
||
var root = doc.RootElement;
|
||
if (!root.TryGetProperty("CID", out var cid) || !cid.TryGetInt32(out var cidValue)) continue;
|
||
if (cidValue != expectedCid) continue;
|
||
|
||
return root.TryGetProperty("RC", out var rc) && rc.TryGetInt32(out var rcValue) ? rcValue : -1;
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return -1;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return -1;
|
||
}
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
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 static int GetInt(JsonElement element, string name)
|
||
=> element.TryGetProperty(name, out var value) && value.TryGetInt32(out var number) ? number : 0;
|
||
}
|