packServer/desktop/Services/Scan/DeviceScanner.cs
liufumingren f8aa4c4899 feat(工作台): 成员扫码登入、面单摄像头与虚拟通道
- 工作台成员扫码登入:workstation_login_records 记录谁在什么时候登入/下线了哪台工作台,
  超时(团购 1h / 散单 30min)由 schedule/workstation_idle_offline 自动下线;
  运单查询的 packers 取当时的登入成员
- 面单摄像头识别:workstation_cameras.is_label_camera + service/label_scan 下发本机该跑的识别配置,
  设备端(桌面端 LabelScan 工作线程)按配置做面单识别并上报
- 虚拟通道 CAM-<工作台id>:工作台没接扫码枪时,面单摄像头那一路顶替扫码枪上报,records 规则按 ws_type 区分
- 桌面端:新增 LabelScanMonitor/LabelScanWorker/ScanDeviceKind 与面单预览页,扫描通道支持改名,静默窗口 5s

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-29 17:19:24 +08:00

309 lines
12 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 48899 广播回复)</summary>
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})";
/// <summary>是否安卓扫码通道(AndroidStation)</summary>
public bool IsAndroidStation => ScanDeviceKind.IsAndroidStation(Model);
/// <summary>界面上的类型标注</summary>
public string KindText => ScanDeviceKind.Describe(Model);
}
/// <summary>设备 SYS 段配置(JCMD 10003 读回)</summary>
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}";
}
/// <summary>
/// 设备发现与 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`(会把改动抹掉)。
/// </summary>
public sealed class DeviceScanner
{
private static readonly TimeSpan ReplyWait = TimeSpan.FromSeconds(1.6);
/// <summary>广播发现设备(每块网卡各广播一次)</summary>
public async Task<IReadOnlyList<DiscoveredDevice>> DiscoverAsync(CancellationToken ct = default)
{
var devices = new Dictionary<string, DiscoveredDevice>(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();
}
/// <summary>读设备 SYS 配置(CID 10003;`Remain=1` 时用响应 CID 续取)</summary>
public async Task<DeviceSysConfig?> 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<string, JsonElement>(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"));
}
/// <summary>
/// 写设备 SYS 配置(CID 10005,**增量**:只传要改的字段)
///
/// ⚠️ 切 DHCP 会把 `IpAddr/Mask/GateWay` 清成 0.0.0.0;改回静态必须三个一起写。
/// 写完**不要**发 `DO_RELOAD`(会把改动抹掉),想立刻生效用 `RestartAsync`。
/// </summary>
public Task<bool> WriteSysConfigAsync(string ip, IReadOnlyDictionary<string, object> patch,
CancellationToken ct = default)
=> DeviceConfig.WriteSectionAsync(ip, "SYS", patch, ct);
/// <summary>重启设备(CID 20003;实测会延后几十秒到几分钟才真正复位)</summary>
public async Task<bool> 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;
}
}
/// <summary>广播目标:255.255.255.255 + 每块网卡的定向广播地址</summary>
internal 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 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<string, JsonElement> 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<string, JsonElement> 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,
};
}
}