packServer/desktop/Services/Scan/ChannelConnection.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

549 lines
21 KiB
C#
Raw Permalink 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.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services.Scan;
/// <summary>
/// 一条通道的 TCP 长连接(从 AndroidScanCenter 的 ChannelConnections 移植)。
///
/// **方向是「设备当服务端、中控当客户端」**:设备在我们的 SOCK 条目端口(默认 8087)上监听,
/// 把串口(扫码枪)的数据推给连上来的人。所以这里为每条通道建一条**出向**连接,
/// 断了自动重连;读到的每一行就是一条条码。
///
/// 在线状态以**这条连接**为准(UDP 只说明「设备在网上」)。
/// </summary>
public sealed class ChannelConnection : IDisposable
{
private const int ConnectTimeoutMs = 4000;
private const int ReconnectMs = 5000;
/// <summary>单行上限(字节):不带分隔符时也要能吐出去</summary>
private const int MaxLineBytes = 256;
/// <summary>控制帧起始字节(RS):桌面端 → 设备 / 设备 → 桌面端共用,不会出现在条码里</summary>
private const byte ControlMark = 0x1E;
/// <summary>单条控制帧上限(异常数据保护)</summary>
private const int MaxControlBytes = 2048;
/// <summary>
/// 等安卓端确认「扫码成功通知」的超时(设备就在同一局域网,正常 10ms 级)。
/// 这个等待现在跑在**后台播报泵**里,不再占用面单摄像头的解码循环,所以可以给足余量,
/// 让重连/网络抖动时也能补上这一声。
/// </summary>
private const int ScanNoticeAckTimeoutMs = 1200;
/// <summary>通知重试次数(含首次):第一次没回执就再发一次,避免单包丢失被判失败</summary>
private const int ScanNoticeAttempts = 2;
private readonly ScanChannel _channel;
private readonly CancellationTokenSource _cts = new();
/// <summary>串行化写:下发扫码枪设置要一次写完,不能被重连/其它写方打新</summary>
private readonly SemaphoreSlim _writeGate = new(1, 1);
/// <summary>等待设备回执的「扫码成功通知」:id → 完成源(设备的 ack 帧来兑现)</summary>
private readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> _scanNotices = new();
/// <summary>当前连接(静音切换时要主动关掉它,让循环重新连并重新下发设置)</summary>
private TcpClient? _client;
/// <summary>提前唤醒重连等待(改设置时不必要干等 5 秒)</summary>
private readonly SemaphoreSlim _wake = new(0, 1);
/// <summary>本次断开的原因(我们自己要求重连时写,日志里不能写成连接失败)</summary>
private string? _manualReason;
/// <summary>收到一条条码</summary>
public event Action<ScanChannel, string>? Barcode;
/// <summary>连接状态变了(true=已连上)</summary>
public event Action<ScanChannel, bool>? StateChanged;
/// <summary>连续重连多次都不行:上报给上层去「自愈」(回查/补建设备的 TCP 服务条目)</summary>
public event Action<ScanChannel>? HealNeeded;
public ChannelConnection(ScanChannel channel)
{
_channel = channel;
}
public ScanChannel Channel => _channel;
/// <summary>本机在这条连接上的源 IP(设备侧 `ClientIP` 应该等于它,心跳用)</summary>
public string LocalIp { get; private set; } = string.Empty;
/// <summary>最后一次收到字节的时刻(有数据 = 连接肯定是活的)</summary>
public DateTime LastRxAt { get; private set; } = DateTime.Now;
/// <summary>启动后台循环(连上→读→断→重连)</summary>
public void Start()
{
_ = Task.Run(() => LoopAsync(_cts.Token));
}
public void Stop()
{
try
{
_cts.Cancel();
}
catch
{
// 忽略
}
SetState(false);
}
/// <summary>
/// 强制重连(改静音用)。
///
/// 不在现有 socket 上补写一条静音指令,而是**关掉连接、让循环重新走一遍**:
/// 设置只存在通道配置里一个真值来源,连上时由 <see cref="ApplyScannerSettingsAsync"/> 整体下发。
/// 否则「字节发出去了但扫码枪没执行」时无法判断(Android 侧实测撞过)。
/// </summary>
public void RequestReconnect(string reason = "本地请求重连")
{
_manualReason = reason;
try
{
_client?.Dispose();
}
catch
{
// 忽略
}
try
{
if (_wake.CurrentCount == 0) _wake.Release();
}
catch
{
// 忽略
}
}
private async Task LoopAsync(CancellationToken ct)
{
var attempts = 0;
while (!ct.IsCancellationRequested && !string.IsNullOrWhiteSpace(_channel.LastIp))
{
TcpClient? client = null;
var reason = string.Empty;
try
{
client = new TcpClient { NoDelay = true };
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
timeout.CancelAfter(ConnectTimeoutMs);
await client.ConnectAsync(_channel.LastIp, _channel.TcpPort, timeout.Token).ConfigureAwait(false);
}
_client = client;
// ⚠️ IPv4 也可能以 `::ffff:192.168.11.56` 形式给出(双栈 socket),
// 不归一化的话跟设备侧 `ClientIP`(纯 IPv4)永远对不上(看门狗会误判为假死)
var ep = client.Client.LocalEndPoint as System.Net.IPEndPoint;
LocalIp = ep is null
? string.Empty
: (ep.Address.IsIPv4MappedToIPv6 ? ep.Address.MapToIPv4() : ep.Address).ToString();
LastRxAt = DateTime.Now;
SetState(true);
AppLog.Write(attempts == 0
? $"[scan] 通道 {_channel.Number}({_channel.DisplayName})已连接 {_channel.LastIp}:{_channel.TcpPort}"
: $"[scan] 通道 {_channel.Number}({_channel.DisplayName})重连成功(第 {attempts} 次){_channel.LastIp}:{_channel.TcpPort}");
// 连上就按通道记住的静音值把整条扫码枪设置(连扫 + 间隔 0 + 静音)下发一遍
await ApplyScannerSettingsAsync(client, ct).ConfigureAwait(false);
reason = await ReadLoopAsync(client, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// 真的是被停掉(关服务/删通道/换地址)
break;
}
catch (OperationCanceledException)
{
// ⚠️ 连接超时也会抛 OperationCanceledException(来自上面的 timeout CTS)。
// 之前没区分,被当成「取消」直接 break —— 循环静默死掉,
// 界面一直离线、日志一条不打、再也不重连。
reason = $"连接超时({ConnectTimeoutMs}ms 内没建起来)";
}
catch (Exception ex)
{
reason = "连接失败:" + ex.Message;
}
finally
{
_client = null;
SetState(false);
try
{
client?.Dispose();
}
catch
{
// 忽略
}
}
if (ct.IsCancellationRequested) break;
if (_manualReason is not null)
{
reason = _manualReason;
_manualReason = null;
}
// 连接真断了才记一条(以前只有「已连接」没「断开」,出问题看不出到底是断还是没连)
attempts++;
// 长时间离线时别每 5 秒刷一行:前 3 次都记,之后每 10 次记一次
if (attempts <= 3 || attempts % 10 == 0)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 断开({reason}),{ReconnectMs / 1000} 秒后重连"
+ (attempts > 1 ? $";已重连 {attempts} 次" : string.Empty));
}
// 连续连不上(第 3 次、之后每 10 次):让上层回查设备那条 TCP 服务还在不在
if (attempts == 3 || attempts % 10 == 0)
{
HealNeeded?.Invoke(_channel);
}
if (ct.IsCancellationRequested) break;
try
{
// 可选「被提前唤醒」:改设置时不用干等满 5 秒
await _wake.WaitAsync(ReconnectMs, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
AppLog.Write($"[scan] 通道 {_channel.Number} 重连循环结束(服务停止 / 通道被删除)");
}
/// <summary>
/// 直接给扫码枪发一串字节(调试用):走设备的 TCP→串口 透传。
/// 返回 false 表示当前没连上。
/// </summary>
public async Task<bool> SendRawAsync(byte[] payload)
{
var client = _client;
if (client is null || payload.Length == 0) return false;
try
{
var stream = client.GetStream();
await _writeGate.WaitAsync().ConfigureAwait(false);
try
{
await stream.WriteAsync(payload).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
}
finally
{
_writeGate.Release();
}
AppLog.Write($"[scan] 通道 {_channel.Number} 已下发串口指令 {payload.Length} 字节:"
+ BitConverter.ToString(payload).Replace('-', ' '));
return true;
}
catch (Exception ex)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 下发串口指令失败:{ex.Message}");
return false;
}
}
/// <summary>
/// 给**安卓扫码端**下发一条「扫码成功」通知,并**等待它的回执**。
///
/// 为什么必须确认:现场要让操作员听到播报,通知丢了就静默失败;
/// 只有设备回了 <c>{"cmd":"ack","id":...}</c> 才算成功(超时重发一次)。
///
/// 为什么只给安卓通道发:网口扫码枪/中控盒**没有语音能力**,收到也没有事情可做,
/// 还会被透传到枪的串口,所以这类通道一律不发。
///
/// ⚠️ 这是**通知**,不是上报:条码本身已经写进待上报队列(见
/// <c>ScanService.ReportCameraScanAsync</c>),本方法失败**不影响记录**。
///
/// 帧格式 <c>0x1E + UTF-8 JSON + '\n'</c>:以 0x1E 开头,
/// 和 9/10 字节的扫码枪设置指令、普通条码行都不会冲突;设备回执用同样的帧格式。
/// </summary>
/// <returns>true = 设备已确认收到(会播报)</returns>
public async Task<bool> SendScanNoticeAsync(string code)
{
if (!_channel.IsAndroidStation || string.IsNullOrWhiteSpace(code)) return false;
for (var attempt = 1; attempt <= ScanNoticeAttempts; attempt++)
{
var client = _client;
if (client is null) return false;
var id = Guid.NewGuid().ToString("N")[..12];
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_scanNotices[id] = completion;
try
{
var payload = JsonSerializer.SerializeToUtf8Bytes(new { cmd = "scan", id, code });
var frame = BuildControlFrame(payload);
var stream = client.GetStream();
await _writeGate.WaitAsync().ConfigureAwait(false);
try
{
await stream.WriteAsync(frame).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
}
finally
{
_writeGate.Release();
}
var acked = await completion.Task.WaitAsync(TimeSpan.FromMilliseconds(ScanNoticeAckTimeoutMs))
.ConfigureAwait(false);
if (acked)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 安卓端已确认播报:{code}");
return true;
}
}
catch (TimeoutException)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 安卓端没回执(第 {attempt}/{ScanNoticeAttempts} 次):{code}");
}
catch (Exception ex)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 通知安卓端失败(不影响上报):{ex.Message}");
return false;
}
finally
{
_scanNotices.TryRemove(id, out _);
}
}
AppLog.Write($"[scan] 通道 {_channel.Number} 通知未确认(记录已入队,不影响上报):{code}");
return false;
}
/// <summary>拼一条控制帧:0x1E + JSON + '\n'</summary>
private static byte[] BuildControlFrame(byte[] payload)
{
var frame = new byte[payload.Length + 2];
frame[0] = ControlMark;
Buffer.BlockCopy(payload, 0, frame, 1, payload.Length);
frame[^1] = (byte)'\n';
return frame;
}
/// <summary>设备的控制帧(目前只有 <c>{"cmd":"ack","id":...}</c>):兑现等待中的通知</summary>
private void HandleControlFrame(byte[] json)
{
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (!root.TryGetProperty("cmd", out var cmd) || cmd.ValueKind != JsonValueKind.String) return;
if (!string.Equals(cmd.GetString(), "ack", StringComparison.OrdinalIgnoreCase)) return;
var id = root.TryGetProperty("id", out var idElement) && idElement.ValueKind == JsonValueKind.String
? idElement.GetString()
: null;
if (string.IsNullOrEmpty(id)) return;
if (_scanNotices.TryGetValue(id, out var completion)) completion.TrySetResult(true);
}
catch (Exception ex)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 控制帧解析失败:{ex.Message}");
}
}
/// <summary>连接断开时让所有等待回执的通知立刻失败(不要干等超时)</summary>
private void FailPendingScanNotices()
{
foreach (var pair in _scanNotices)
{
pair.Value.TrySetResult(false);
}
_scanNotices.Clear();
}
/// <summary>
/// 连上之后立刻把扫码枪配成「连续扫描 + 间隔 0s + 静音状态」(9 + 9 + 10 = 28 字节一次写完)。
///
/// 写失败**不当作连接失败**:设置没配上顶多是不出数据,连接本身还是要留着。
/// </summary>
private async Task ApplyScannerSettingsAsync(TcpClient client, CancellationToken ct)
{
try
{
var stream = client.GetStream();
await _writeGate.WaitAsync(ct).ConfigureAwait(false);
try
{
foreach (var command in ScannerCommands.StartupSequence(_channel.Muted))
{
await stream.WriteAsync(command, ct).ConfigureAwait(false);
}
await stream.FlushAsync(ct).ConfigureAwait(false);
}
finally
{
_writeGate.Release();
}
AppLog.Write($"[scan] 通道 {_channel.Number} 已下发扫码枪设置:连续扫描 + 间隔 0s + "
+ (_channel.Muted ? "静音" : "蜂鸣"));
}
catch (Exception ex)
{
AppLog.Write($"[scan] 通道 {_channel.Number} 下发扫码枪设置失败(不影响收码):{ex.Message}");
}
}
/// <summary>
/// 读数据:按 CR/LF 分行,超长也先吐出来;返回断开原因(给日志用)。
///
/// ⚠️ 真机(E10C 1.41.1)实测:设备每 ~0.7s 会往已连上的客户端推一帧
/// <c>04 D0 00 00 FF 2C</c>(6 字节二进制,无 CR/LF)。这些字节如果照抄进行缓冲,
/// 会攒到 256 字节才吐,期间真扫码枪那行条码会被**粘在后面一起丢掉**。
/// 所以这里只累积 **可打印 ASCII**:遇到控制字符/高位字节就把当前行清空(当作帧分隔),
/// 条码(Code128/EAN 等)本来就是纯 ASCII,不受影响。
/// </summary>
private async Task<string> ReadLoopAsync(TcpClient client, CancellationToken ct)
{
var stream = client.GetStream();
var buffer = new byte[1024];
var pending = new MemoryStream();
var noiseBytes = 0;
var noiseLogged = false;
// 正在收控制帧时的缓冲(0x1E 开头);null = 当前不在控制帧里
MemoryStream? control = null;
try
{
while (!ct.IsCancellationRequested)
{
var read = await stream.ReadAsync(buffer, ct).ConfigureAwait(false);
if (read <= 0) return "设备关闭了连接"; // 对端关了
LastRxAt = DateTime.Now;
for (var i = 0; i < read; i++)
{
var b = buffer[i];
// 控制帧(安卓端的 ack):和条码混在同一条 TCP 里,按 0x1E .. CR/LF 收
if (control is not null)
{
if (b is (byte)'\n' or (byte)'\r')
{
if (control.Length > 0) HandleControlFrame(control.ToArray());
control = null;
}
else if (control.Length < MaxControlBytes)
{
control.WriteByte(b);
}
else
{
control = null; // 超长丢帧
}
continue;
}
if (b == ControlMark)
{
control = new MemoryStream(256);
continue;
}
if (b is (byte)'\n' or (byte)'\r')
{
Flush(pending);
continue;
}
if (b < 0x20 || b > 0x7E)
{
// 二进制噪声(设备心跳帧):丢掉已攒的半行,继续
pending.SetLength(0);
noiseBytes++;
if (!noiseLogged && noiseBytes >= 6)
{
noiseLogged = true;
AppLog.Write($"[scan] 通道 {_channel.Number} 收到设备二进制帧,已忽略(非条码)");
}
continue;
}
pending.WriteByte(b);
if (pending.Length >= MaxLineBytes) Flush(pending);
}
}
return "已停止";
}
catch (OperationCanceledException)
{
return "已停止";
}
catch (Exception ex)
{
// 设备断电重启时常见:Connection reset by peer / 对方强制关闭
return ex.InnerException?.Message ?? ex.Message;
}
}
private void Flush(MemoryStream pending)
{
if (pending.Length == 0) return;
var text = Encoding.UTF8.GetString(pending.ToArray());
pending.SetLength(0);
var code = ScanProtocol.CleanBarcode(text);
if (code is null) return;
_channel.LastCode = code;
_channel.LastCodeAt = DateTime.Now;
Barcode?.Invoke(_channel, code);
}
private void SetState(bool connected)
{
if (!connected) FailPendingScanNotices(); // 断了就别让通知干等超时
if (_channel.Connected == connected) return;
_channel.Connected = connected;
StateChanged?.Invoke(_channel, connected);
}
public void Dispose()
{
Stop();
_cts.Dispose();
}
}