256 lines
10 KiB
C#
256 lines
10 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services.Scan;
|
||
|
||
/// <summary>
|
||
/// 一条扫码通道 = 一台已纳入管理的扫码设备(原 AndroidScanCenter 的 Channel)。
|
||
///
|
||
/// 绑定键是 **MAC**(设备 DHCP,IP 会变),`LastIp` 只是「最后一次见到」的缓存。
|
||
/// 通道**不再区分团购/散单**——团散在「工作台」上区分。
|
||
/// </summary>
|
||
public sealed class ScanChannel
|
||
{
|
||
/// <summary>设备 MAC(12 位十六进制,大写)</summary>
|
||
public string Mac { get; set; } = string.Empty;
|
||
|
||
/// <summary>通道号(添加时分配最小空号,之后固定;上报时就是 channelId)</summary>
|
||
public int Number { get; set; }
|
||
|
||
/// <summary>显示名(默认取设备 HostName,可改)</summary>
|
||
public string Name { get; set; } = string.Empty;
|
||
|
||
/// <summary>最后一次见到的 IP</summary>
|
||
public string LastIp { get; set; } = string.Empty;
|
||
|
||
/// <summary>设备 TCP 端口(设备当服务端;桌面端用 8087,避开 Android 中控的 8086)</summary>
|
||
public int TcpPort { get; set; } = ScanProtocol.TcpPort;
|
||
|
||
/// <summary>
|
||
/// 设备上我们实际用的 SOCK 条目名。
|
||
///
|
||
/// 默认是 <see cref="ScanProtocol.SockName"/>(packcenter);但设备最多只能放 3 条条目,
|
||
/// 满了时会**复用一条非保留条目**(把它的名字拿去改成 8087),那时这里记的就是被复用的名字。
|
||
/// </summary>
|
||
public string SockName { get; set; } = string.Empty;
|
||
|
||
/// <summary>是否启用(停用就不连、不上报)</summary>
|
||
public bool Enabled { get; set; } = true;
|
||
|
||
/// <summary>扫码枪是否静音(现场偏好,暂只记录)</summary>
|
||
public bool Muted { get; set; }
|
||
|
||
public long AddedAtMs { get; set; } = DateTimeOffset.Now.ToUnixTimeMilliseconds();
|
||
|
||
// ---------------- 运行时状态(不落盘) ----------------
|
||
|
||
/// <summary>TCP 连接状态</summary>
|
||
[System.Text.Json.Serialization.JsonIgnore]
|
||
public bool Connected { get; set; }
|
||
|
||
/// <summary>最近一条条码</summary>
|
||
[System.Text.Json.Serialization.JsonIgnore]
|
||
public string LastCode { get; set; } = string.Empty;
|
||
|
||
/// <summary>最近条码时间</summary>
|
||
[System.Text.Json.Serialization.JsonIgnore]
|
||
public DateTime? LastCodeAt { get; set; }
|
||
|
||
[System.Text.Json.Serialization.JsonIgnore]
|
||
public string DisplayName => string.IsNullOrWhiteSpace(Name) ? (string.IsNullOrEmpty(Mac) ? "(未知)" : Mac) : Name.Trim();
|
||
|
||
/// <summary>上报给服务端的 channelId(用通道号,稳定且短)</summary>
|
||
[System.Text.Json.Serialization.JsonIgnore]
|
||
public string ChannelId => Number.ToString();
|
||
}
|
||
|
||
/// <summary>通道配置读写(普通模式 `%LOCALAPPDATA%\YuncangTrace\channels.json`;服务模式 `%ProgramData%\YuncangTrace\channels.json`)</summary>
|
||
public static class ChannelStore
|
||
{
|
||
private static string Dir => AgentPaths.DataRoot;
|
||
|
||
private static string FilePath => AgentPaths.ChannelsFile;
|
||
|
||
private static readonly JsonSerializerOptions Options = new()
|
||
{
|
||
WriteIndented = true,
|
||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
};
|
||
|
||
/// <summary>读通道列表(读不到返回空列表,绝不抛)</summary>
|
||
public static List<ScanChannel> Load()
|
||
{
|
||
try
|
||
{
|
||
if (!File.Exists(FilePath)) return new List<ScanChannel>();
|
||
|
||
var list = JsonSerializer.Deserialize<List<ScanChannel>>(File.ReadAllText(FilePath), Options)
|
||
?? new List<ScanChannel>();
|
||
|
||
NormalizeNumbers(list);
|
||
MigratePort(list);
|
||
return list;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[scan] 读取通道配置失败:{ex.Message}");
|
||
return new List<ScanChannel>();
|
||
}
|
||
}
|
||
|
||
/// <summary>保存通道列表(只落盘持久字段,运行时状态由 JsonIgnore 排除)</summary>
|
||
public static void Save(IEnumerable<ScanChannel> channels)
|
||
{
|
||
try
|
||
{
|
||
Directory.CreateDirectory(Dir);
|
||
File.WriteAllText(FilePath, JsonSerializer.Serialize(channels.ToList(), Options));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[scan] 保存通道配置失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>老数据/缺号的数据补齐通道号(分配最小空号,删掉的不复用)</summary>
|
||
private static void NormalizeNumbers(List<ScanChannel> list)
|
||
{
|
||
var used = new HashSet<int>(list.Where(item => item.Number > 0).Select(item => item.Number));
|
||
foreach (var channel in list.Where(item => item.Number <= 0))
|
||
{
|
||
var number = 1;
|
||
while (used.Contains(number)) number++;
|
||
channel.Number = number;
|
||
used.Add(number);
|
||
}
|
||
}
|
||
|
||
/// <summary>分配最小的空号</summary>
|
||
public static int NextNumber(IEnumerable<ScanChannel> channels)
|
||
{
|
||
var used = new HashSet<int>(channels.Select(item => item.Number));
|
||
var number = 1;
|
||
while (used.Contains(number)) number++;
|
||
return number;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 旧配置里存的是 8086(早期跟 Android 中控共用的端口)→ 改成桌面端自己的端口。
|
||
/// 改了之后设备上还没这条条目,靠「连不上时自愈」自动建。
|
||
/// </summary>
|
||
private static void MigratePort(List<ScanChannel> list)
|
||
{
|
||
var migrated = list.Where(item => item.TcpPort != ScanProtocol.TcpPort).ToList();
|
||
if (migrated.Count == 0) return;
|
||
|
||
foreach (var channel in migrated)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 端口 {channel.TcpPort} → {ScanProtocol.TcpPort}(不再与 Android 中控的 8086 共用)");
|
||
channel.TcpPort = ScanProtocol.TcpPort;
|
||
}
|
||
|
||
Save(list);
|
||
}
|
||
|
||
/// <summary>通道号上限(与原中控一致:现场是工位号,量级几十)</summary>
|
||
public const int MaxNumber = 50;
|
||
|
||
/// <summary>某个号是否已被别的通道占用(<paramref name="exceptMac"/> 用于「改自己」时排除自己)</summary>
|
||
public static ScanChannel? FindByNumber(IEnumerable<ScanChannel> channels, int number, string? exceptMac = null)
|
||
{
|
||
return channels.FirstOrDefault(item => item.Number == number
|
||
&& (exceptMac is null || !item.Mac.Equals(exceptMac, StringComparison.OrdinalIgnoreCase)));
|
||
}
|
||
}
|
||
|
||
/// <summary>扫码链路用到的常量(与设备固件一致)</summary>
|
||
public static class ScanProtocol
|
||
{
|
||
/// <summary>UDP 发现 / JCMD 端口(设备监听)</summary>
|
||
public const int UdpPort = 48899;
|
||
|
||
/// <summary>
|
||
/// 设备侧 TCP 监听端口(设备当服务端,把串口数据推给连上来的人)。
|
||
///
|
||
/// ⚠️ 不用 8086:那是 Android 中控(条目 `scancenter`)在用的。同一台设备上
|
||
/// 两条连接都往串口写,设置会互相覆盖(Android 那边重连时会把静音顶掉)。
|
||
/// 桌面端用**自己的条目名 + 自己的端口**,互不干扰。
|
||
/// </summary>
|
||
public const int TcpPort = 8087;
|
||
|
||
/// <summary>广播报文(`ConnectMode` 必须是 Forbidden:只发现,不改设备服务器配置)</summary>
|
||
public const string BroadcastPayload =
|
||
"{\"Agent\":0,\"Type\":\"EP_Tool\",\"PasswordEn\":0,\"ServPort\":0,\"Version\":\"3.1.3f\","
|
||
+ "\"ConnectMode\":\"Forbidden\",\"Zone\":\"EPort\",\"ServEn\":1,\"ServAddr\":\"0.0.0.0\",\"ClientEn\":0}";
|
||
|
||
// JCMD 命令号
|
||
/// <summary>读配置(10003→10004)</summary>
|
||
public const int CidGetConfig = 10003;
|
||
|
||
/// <summary>读运行状态(10001→10002):只有它回来的 SOCK 条目才带 `ClientIP`</summary>
|
||
public const int CidGetState = 10001;
|
||
|
||
/// <summary>写配置(10005→10006,增量;SOCK 段是整条写)</summary>
|
||
public const int CidSetConfig = 10005;
|
||
|
||
/// <summary>把配置落 flash(10017→10018):不落盘的话一次重载就丢(原中控已实测)</summary>
|
||
public const int CidSaveFlash = 10017;
|
||
|
||
public const int CidDoRestart = 20003;
|
||
|
||
/// <summary>桌面端自己的 SOCK 条目名(不能跟 Android 的 `scancenter` 重名)</summary>
|
||
public const string SockName = "packcenter";
|
||
|
||
/// <summary>条码合法性(与原中控一致:去空白后 4~64 位,不含控制字符)</summary>
|
||
public static string? CleanBarcode(string? raw)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(raw)) return null;
|
||
|
||
// 设备每 ~0.7s 推一帧 `04 D0 00 00 FF 2C`:控制字节会被当分帧清掉,
|
||
// 但结尾那个 0x2C(',')是可打印字符,会粘在紧接着的条码前面,
|
||
// 现场出现的就是 `,6901028011778`。条码本体不会以非字母数字开头/结尾,
|
||
// 所以首尾的非字母数字一律削掉(**中间的保留**,GS1 内部可能有 `-` `/`)。
|
||
var text = raw.Trim();
|
||
text = System.Text.RegularExpressions.Regex.Replace(text, "^[^0-9A-Za-z]+", string.Empty);
|
||
text = System.Text.RegularExpressions.Regex.Replace(text, "[^0-9A-Za-z]+$", string.Empty);
|
||
|
||
if (text.Length is < 4 or > 64) return null;
|
||
if (text.Any(ch => char.IsControl(ch))) return null;
|
||
return text;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 收一个 UDP 包,带**真实超时**。
|
||
///
|
||
/// ⚠️ `UdpClient.Client.ReceiveTimeout` 只对**同步** `Receive` 生效,
|
||
/// `ReceiveAsync` 完全不看它 —— 设备不回应时会一直挂着(自愈/读配置就卡死在那里)。
|
||
/// </summary>
|
||
/// <returns>收到返回字节;超时返回 null(调用方据此当“没应答”处理)</returns>
|
||
public static async Task<byte[]?> ReceiveWithTimeoutAsync(UdpClient udp, int timeoutMs,
|
||
CancellationToken ct = default)
|
||
{
|
||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||
cts.CancelAfter(timeoutMs);
|
||
|
||
try
|
||
{
|
||
var received = await udp.ReceiveAsync(cts.Token).ConfigureAwait(false);
|
||
return received.Buffer;
|
||
}
|
||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||
{
|
||
return null; // 超时
|
||
}
|
||
}
|
||
|
||
/// <summary>UTF-8 无 BOM 字节(UDP/TCP 报文都用它)</summary>
|
||
public static byte[] Utf8(string text) => new UTF8Encoding(false).GetBytes(text);
|
||
}
|