- 后端:新增 workstationConfigOf 与 GET /api/scanner/workstations,只下发绑定了本机通道的工作台及其摄像头与 NVR 凭据 - 桌面:新增 WorkstationOsdService/OsdText——扫码命中即写「摄像头名 + 单号」,单号不变不重写,连续 60s 未识别恢复工作台名;单线程写队列、失败退避、配置移除的摄像头还原一次 - 桌面:HikDeviceService.SetChannelOsdName 读-改-写 + 回读校验(GBK、31 字节、按字符边界截断) - 修复 build.ps1 / test-update.ps1 丢失 UTF-8 BOM,PowerShell 5.1 按 GBK 解析中文注释导致语法错误 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1087 lines
48 KiB
C#
1087 lines
48 KiB
C#
using System;
|
||
using System.Collections.Concurrent;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services.Scan;
|
||
|
||
/// <summary>
|
||
/// 扫码服务(从 AndroidScanCenter 移植到桌面端):管通道配置 + TCP 收码 + 上报服务器。
|
||
///
|
||
/// - 只有**设备服务开启**(主体管理员)并且扫码服务启动时才真正连设备;
|
||
/// - 每条通道一条 TCP 连接,收到条码 → 过滤 → 交给 <see cref="DeviceService"/> 上报;
|
||
/// - 通道也上报给服务器(`POST /api/scan/channels`),施工时在「工作台」里绑定通道(团散在工作台区分)。
|
||
/// </summary>
|
||
public sealed class ScanService
|
||
{
|
||
private readonly DeviceService _device;
|
||
private readonly DeviceScanner _scanner = new();
|
||
private readonly Dictionary<string, ChannelConnection> _connections = new(StringComparer.OrdinalIgnoreCase);
|
||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||
|
||
// 通道自动同步:任何变动 → 唤醒后台循环 → 推上去 + 回查确认,失败退避重试直到成功
|
||
private readonly SemaphoreSlim _syncSignal = new(0, 1);
|
||
private CancellationTokenSource? _syncCts;
|
||
private Task? _syncTask;
|
||
private int _syncRetryMs = 1000;
|
||
|
||
/// <summary>下一次推送是否用「全量对账」语义(添加/删除通道时置 true,成功后清掉)</summary>
|
||
private volatile bool _syncReplace;
|
||
|
||
// 看门狗:设备断电重启时 TCP 不发 FIN,read 会永久挂住 → 定期回查设备侧 ClientIP
|
||
private CancellationTokenSource? _watchdogCts;
|
||
private Task? _watchdogTask;
|
||
|
||
/// <summary>每个通道上次自愈的时间(每台设备 60 秒最多查一次)</summary>
|
||
private readonly Dictionary<string, DateTime> _lastHealAt = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
/// <summary>每个通道上次写「连不上/自愈」日志的时间(离线设备不要每 60 秒刷屏)</summary>
|
||
private readonly Dictionary<string, DateTime> _healLogAt = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
/// <summary>常驻发现(开关打开时才有)</summary>
|
||
private DiscoveryMonitor? _monitor;
|
||
|
||
/// <summary>发现列表变了(新增/更新/掉线)</summary>
|
||
public event Action? DiscoveredChanged;
|
||
|
||
/// <summary>是否正在持续发现</summary>
|
||
public bool Monitoring => _monitor is not null;
|
||
|
||
/// <summary>当前发现到的设备</summary>
|
||
public IReadOnlyList<DiscoveredDevice> DiscoveredDevices
|
||
=> _monitor?.Devices ?? Array.Empty<DiscoveredDevice>();
|
||
|
||
/// <summary>打开「扫描」:常驻 UDP(每 3 秒探测、一直收),不是扫一轮停一会儿</summary>
|
||
public void StartDiscovery()
|
||
{
|
||
if (_monitor is not null) return;
|
||
|
||
_monitor = new DiscoveryMonitor();
|
||
_monitor.Changed += OnDiscoveredChanged;
|
||
_monitor.Start();
|
||
OnDiscoveredChanged();
|
||
}
|
||
|
||
/// <summary>关掉「扫描」</summary>
|
||
public void StopDiscovery()
|
||
{
|
||
if (_monitor is null) return;
|
||
|
||
_monitor.Changed -= OnDiscoveredChanged;
|
||
_monitor.Dispose();
|
||
_monitor = null;
|
||
DiscoveredChanged?.Invoke();
|
||
}
|
||
|
||
private void OnDiscoveredChanged()
|
||
{
|
||
// 顺手把已有通道的 IP 刷新一下(DHCP 换地址就能立刻重连到新地址)
|
||
ApplyDiscoveredIps(_monitor?.Devices ?? Array.Empty<DiscoveredDevice>());
|
||
DiscoveredChanged?.Invoke();
|
||
}
|
||
|
||
public ScanService(DeviceService device)
|
||
{
|
||
_device = device;
|
||
LabelScan = new LabelScanMonitor(device, (channelId, code, wsType, afterAbsence) =>
|
||
ReportCameraScanAsync(channelId, ChannelNameOf(channelId), code, wsType, afterAbsence));
|
||
// 工作台 OSD 字幕:扫码/识别命中 → 写「摄像头名 + 运单号」,1 分钟没扫 → 还原工作台名
|
||
Osd = new WorkstationOsdService(device);
|
||
ScanActivity += (channelId, code, at) => Osd.OnScanActivity(channelId, code, at);
|
||
// 扫码枪那条路也要按「通道 → 工作台类型」决定记录规则(散单取第一次、团购取最后一次)
|
||
device.ChannelModeOf = LabelScan.ModeOf;
|
||
// 主体续期/恢复后补一次通道对账(暂停期间通道变动不会推上去)
|
||
_device.SubjectResumed += () => RequestChannelSync();
|
||
}
|
||
|
||
/// <summary>通道显示名(面单摄像头识别结果落本地记录时用;查不到就用通道号)</summary>
|
||
private string ChannelNameOf(string channelId)
|
||
{
|
||
var key = (channelId ?? string.Empty).Trim();
|
||
// 虚拟通道(面单摄像头自己用的 `CAM-<工作台id>`)不在本机通道列表里,名字从面单配置里取
|
||
var labelName = LabelScan.ChannelNameOf(key);
|
||
if (!string.IsNullOrWhiteSpace(labelName)) return labelName;
|
||
|
||
var channel = Channels.FirstOrDefault(item => item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||
return channel?.DisplayName ?? key;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 面单识别配置的拉取/对账层(**只拉配置,不做识别**)。
|
||
/// 服务启动时自动拉一次 + 每 5 分钟兜底;收到 `labelScan.refresh` 时立即拉。
|
||
/// </summary>
|
||
public LabelScanMonitor LabelScan { get; }
|
||
|
||
/// <summary>工作台 OSD 字幕(摄像头名 + 运单号 → 录像机通道名)</summary>
|
||
public WorkstationOsdService Osd { get; }
|
||
|
||
/// <summary>通道同步状态(给界面看的一句话)</summary>
|
||
public string ChannelSyncStatus { get; private set; } = string.Empty;
|
||
|
||
/// <summary>扫码记录上报状态(空串 = 没有积压、也没报错)</summary>
|
||
public string UploadStatus => _device.UploadStatus;
|
||
|
||
/// <summary>立即把积压的扫码记录推一次</summary>
|
||
public void TriggerUpload() => _device.TriggerUpload();
|
||
|
||
/// <summary>通道列表引用(配置页/主界面共用一份,改完调 <see cref="SaveChannels"/>)</summary>
|
||
public List<ScanChannel> Channels { get; private set; } = new();
|
||
|
||
/// <summary>扫码服务是否已启动</summary>
|
||
public bool Running { get; private set; }
|
||
|
||
/// <summary>通道状态变化(界面刷新用)</summary>
|
||
public event Action? Changed;
|
||
|
||
/// <summary>
|
||
/// 收到一条**新**条码(连续扫描时同一个码只报一次)。
|
||
///
|
||
/// 落本地记录、延迟上报、同步通道都在本类内部完成,订阅者只用于"提示/展示"。
|
||
/// ⚠️ **不要用这个事件去查运单**:扫码和运单查询是两条独立链路,
|
||
/// 历史上就是在这里自动查了一次,用户看到的是"没点查询,打包查询却一直在自动查"。
|
||
/// 运单查询只允许用户主动发起(输入框回车 / 点查询 / 协议叫醒)。
|
||
/// </summary>
|
||
public event Action<ScanChannel, string>? Barcode;
|
||
|
||
/// <summary>
|
||
/// 任意一次命中(扫码枪 + 面单识别,**含连续重复命中**):`(channelId, code, at)`。
|
||
///
|
||
/// 只给「在扫什么」这类轻量状态用(例如工作台 OSD 字幕的 60 秒在场计时):
|
||
/// 在扫码/识别线程上同步触发,订阅者**不能**做耗时操作(写设备、发请求都不行)。
|
||
/// </summary>
|
||
public event Action<string, string, DateTime>? ScanActivity;
|
||
|
||
/// <summary>读通道配置</summary>
|
||
public void Load()
|
||
{
|
||
Channels = ChannelStore.Load();
|
||
}
|
||
|
||
/// <summary>存通道配置</summary>
|
||
public void SaveChannels()
|
||
{
|
||
ChannelStore.Save(Channels);
|
||
}
|
||
|
||
/// <summary>发现局域网设备(UDP 48899 广播);顺手把已有通道的 IP 刷新成最新</summary>
|
||
public async Task<IReadOnlyList<DiscoveredDevice>> DiscoverAsync(CancellationToken ct = default)
|
||
{
|
||
var devices = await _scanner.DiscoverAsync(ct).ConfigureAwait(false);
|
||
ApplyDiscoveredIps(devices);
|
||
return devices;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设备 DHCP 换 IP 后必须重连:通道靠 MAC 绑定,`LastIp` 只是缓存,
|
||
/// 不刷新的话会一直重连一个旧地址(Android 侧 `Connection#setIp` 就是干这个的)。
|
||
///
|
||
/// 顺带把设备型号补进通道配置:老通道(本次改动前添加的)没有型号,
|
||
/// 发现到之后就知道它是不是「安卓扫描通道」。
|
||
/// </summary>
|
||
private void ApplyDiscoveredIps(IReadOnlyList<DiscoveredDevice> devices)
|
||
{
|
||
var changed = new List<ScanChannel>();
|
||
var metadataChanged = false;
|
||
|
||
foreach (var device in devices)
|
||
{
|
||
var channel = Channels.FirstOrDefault(item => item.Mac.Equals(device.Mac, StringComparison.OrdinalIgnoreCase));
|
||
if (channel is null) continue;
|
||
|
||
var model = (device.Model ?? string.Empty).Trim();
|
||
if (model.Length > 0 && !channel.Model.Equals(model, StringComparison.Ordinal))
|
||
{
|
||
channel.Model = model;
|
||
metadataChanged = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(device.Ip) || channel.LastIp.Equals(device.Ip, StringComparison.Ordinal)) continue;
|
||
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 设备 IP 变了:{channel.LastIp} → {device.Ip},重新连接");
|
||
channel.LastIp = device.Ip;
|
||
changed.Add(channel);
|
||
}
|
||
|
||
if (!metadataChanged && changed.Count == 0) return;
|
||
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
|
||
foreach (var channel in changed)
|
||
{
|
||
if (Running) StartConnection(channel);
|
||
}
|
||
}
|
||
|
||
/// <summary>给某条通道的扫码枪发一串原始字节(调试用,走设备透传)</summary>
|
||
public async Task<bool> SendCommandAsync(ScanChannel channel, byte[] payload)
|
||
{
|
||
if (!_connections.TryGetValue(channel.Mac, out var connection)) return false;
|
||
return await connection.SendRawAsync(payload).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>面单摄像头的「在场」状态:同一张面单一直摆在拍摄区时只算一次进入,记录时间取**第一次**识别</summary>
|
||
private sealed class CameraPresence
|
||
{
|
||
/// <summary>这张面单的时间(首次识别时刻,写进记录后**永不刷新**)</summary>
|
||
public DateTime? ScanTime { get; set; }
|
||
|
||
public DateTime LastHitAt { get; set; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// 多久没有新的识别命中,就认为面单已经离开了拍摄区。
|
||
///
|
||
/// 直接复用识别线程的 <see cref="LabelScanWorker.RepackAbsence"/>:**判定「面单离开」只有这一个阈值**,
|
||
/// 两处各写一个的话会出现「算重新进去了、但时间没更新」的漏洞。
|
||
///
|
||
/// 注意在场状态是**按「通道|条码」**记的,所以换一张新面单永远是新建记录、不受这个值影响;
|
||
/// 它只决定「同一张面单」重新被识别时算不算新的一次进入(要不要重新上报/播报 + 时间要不要更新)。
|
||
/// </summary>
|
||
private static readonly TimeSpan CameraPresenceGap = LabelScanWorker.RepackAbsence;
|
||
|
||
/// <summary>首次识别时间的保留时长(与后端 24 小时合并窗口一致)</summary>
|
||
private static readonly TimeSpan CameraPresenceTtl = TimeSpan.FromHours(24);
|
||
|
||
private readonly Dictionary<string, CameraPresence> _cameraPresence = new(StringComparer.OrdinalIgnoreCase);
|
||
private readonly object _cameraPresenceGate = new();
|
||
|
||
/// <summary>待通知安卓播报的条码(按通道只保留最新一条:播报是「叮」一声,旧的无意义)</summary>
|
||
private readonly ConcurrentDictionary<string, string> _pendingNotices = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
/// <summary>后台播报泵是否在跑(0/1,避免每条命中都起一个任务)</summary>
|
||
private int _noticePumpRunning;
|
||
|
||
/// <summary>
|
||
/// 面单摄像头识别到一条条码:**先落待上报记录(立即上报),再通知安卓端播报(等回执)**。
|
||
///
|
||
/// 与扫码枪的区别(摄像头场景:面单放进拍摄区 → 开始打包 → 打包完才取走):
|
||
/// 1. **取第一次识别的时间**,不用「最后一次命中」——面单会在视野里停留很久;
|
||
/// 2. **写入即上报**,不等 5 秒静默:一进面单区就要能把录像定位到那一刻;
|
||
/// 3. 同一张面单在视野里的重复帧**什么都不做**(不改时间、不重复上报、不重复播报);
|
||
/// 4. 面单一直摆着、中途出现识别空档(手挡/移位/反光)→ **仍算同一轮打包,时间不前移**;
|
||
/// 只有「画面里连 45 秒没有任何条码」之后重新识别到(真的拿走再放回,例如装错了重新打包)
|
||
/// 才用**这次**的时间。
|
||
///
|
||
/// 不能用「这中间通道上又扫过别的包裹」当判据:两张面单轮流进入视野就会命中,
|
||
/// 但那两张都没离开过,属于误判(现场就是因此把打包时间推后了)。
|
||
///
|
||
/// **团购工作台不一样**(`wsType = 2`):和扫码枪同一套规则 —— 静默 5 秒后上报、
|
||
/// 时间取**最后一次**命中(见 <see cref="ScanRecordStore.Add"/>)。
|
||
///
|
||
/// 记录与通知解耦:**记录永远写**(与通道类型、安卓是否在线、设备服务是否开启无关),
|
||
/// 通知失败只体现在 <see cref="CameraScanResult.Notified"/>。
|
||
/// </summary>
|
||
/// <param name="wsType">1 散单(取第一次 + 立即上报)/ 2 团购(静默 5 秒取最后一次)/ 0 未知按散单</param>
|
||
/// <param name="afterAbsence">
|
||
/// 这张面单是从「画面里连一段时间没有任何条码」之后重新出现的 —— 即真的被拿走再放回来
|
||
/// (装错了重新打包)。为 true 时记录时间用**这次**的,否则沿用本轮首次识别时间。
|
||
/// </param>
|
||
public async Task<CameraScanResult> ReportCameraScanAsync(string channelId, string channelName, string code,
|
||
int wsType = 1, bool afterAbsence = false)
|
||
{
|
||
var key = (channelId ?? string.Empty).Trim();
|
||
var text = (code ?? string.Empty).Trim();
|
||
if (key.Length == 0 || text.Length == 0) return new CameraScanResult(false, false);
|
||
|
||
var now = DateTime.Now;
|
||
// 连续命中也算「还在扫」:OSD 字幕靠它续 60 秒在场计时(不重写文本)
|
||
RaiseScanActivity(key, text);
|
||
var presenceKey = $"{key}|{text}";
|
||
bool firstInView;
|
||
DateTime? knownScanTime = null;
|
||
|
||
lock (_cameraPresenceGate)
|
||
{
|
||
PruneCameraPresence(now);
|
||
|
||
if (_cameraPresence.TryGetValue(presenceKey, out var presence))
|
||
{
|
||
// 还在视野里(距上次命中没超过 Gap)→ 只刷新命中时间,其余什么都不做
|
||
firstInView = now - presence.LastHitAt > CameraPresenceGap;
|
||
presence.LastHitAt = now;
|
||
knownScanTime = presence.ScanTime;
|
||
}
|
||
else
|
||
{
|
||
firstInView = true;
|
||
_cameraPresence[presenceKey] = new CameraPresence { LastHitAt = now };
|
||
}
|
||
}
|
||
|
||
if (wsType == 2)
|
||
{
|
||
return await ReportGroupBuyCameraScanAsync(key, channelName, text, now, presenceKey, firstInView).ConfigureAwait(false);
|
||
}
|
||
|
||
if (!firstInView) return new CameraScanResult(false, false, knownScanTime);
|
||
|
||
// ⚠️ 同一轮打包内重新识别到同一张面单时,时间必须是**最初那次**:
|
||
// 面单一直摆在拍摄区,中间被手挡住/移位一会儿就可能出现识别空档,
|
||
// 若用 now 就会把打包时间整体往后推(实测出现过「开始打包 30 秒之后」)。
|
||
var recordAt = ResolveCameraScanTime(now, knownScanTime, afterAbsence);
|
||
|
||
// ① 记录:时间固定取第一次识别(AddCamera 内部 24 小时复用同一条,不会新增行)
|
||
var added = ScanRecordStore.AddCamera(key, channelName, text, recordAt);
|
||
|
||
// 记录里那条的时间才是唯一真值(命中已有记录时就是当初那次的时间),
|
||
// 界面/上报都以它为准,所以面单一直不拿走也不会越刷越新
|
||
var scanTime = added.Item?.ScannedAt ?? now;
|
||
lock (_cameraPresenceGate)
|
||
{
|
||
if (_cameraPresence.TryGetValue(presenceKey, out var presence)) presence.ScanTime = scanTime;
|
||
}
|
||
|
||
if (added.IsScanEvent)
|
||
{
|
||
// 立即上报(不等静默窗口;未开启设备服务时只留在本地队列)
|
||
_device.TriggerUpload();
|
||
var channel = Channels.FirstOrDefault(item => item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||
if (channel is not null) Barcode?.Invoke(channel, text);
|
||
Changed?.Invoke();
|
||
}
|
||
|
||
// ② 通知安卓端播报「扫码成功」:**丢后台,不等回执**。
|
||
// 回执只是让安卓「叮」一声,等它会把面单摄像头的解码循环堵住
|
||
// (实测 1200ms×2 次重试 → 8fps 的画面在管道里堆到 2.6 秒,拿到的是几秒前的帧)。
|
||
QueueScanNotice(key, text);
|
||
|
||
return new CameraScanResult(added.IsScanEvent, false, scanTime);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 团购工作台的面单摄像头识别结果:**和扫码枪同一套规则** —— 记录时间取最后一次命中,
|
||
/// 静默 <see cref="ScanRecordStore.SettleDelay"/>(5 秒)没再认出同一个码才进上报队列。
|
||
///
|
||
/// 播报仍然只在「刚进入视野」时发一次(码可能在视野里停很久,不能每帧都播)。
|
||
/// </summary>
|
||
/// <summary>团购工作台的识别结果:**同步完成**(不再等安卓回执,播报丢后台)</summary>
|
||
private Task<CameraScanResult> ReportGroupBuyCameraScanAsync(
|
||
string channelId,
|
||
string channelName,
|
||
string code,
|
||
DateTime now,
|
||
string presenceKey,
|
||
bool firstInView)
|
||
{
|
||
if (!firstInView)
|
||
{
|
||
// 还在视野里:刷新「最后一次」时间,静默窗口重新计时(与扫码枪连续扫描一致)
|
||
var touched = ScanRecordStore.Add(channelId, channelName, code, now);
|
||
lock (_cameraPresenceGate)
|
||
{
|
||
if (_cameraPresence.TryGetValue(presenceKey, out var presence)) presence.ScanTime = touched.Item?.ScannedAt ?? now;
|
||
}
|
||
if (touched.IsScanEvent) Changed?.Invoke();
|
||
return Task.FromResult(new CameraScanResult(touched.IsScanEvent, false, touched.Item?.ScannedAt));
|
||
}
|
||
|
||
var added = ScanRecordStore.Add(channelId, channelName, code, now);
|
||
var scanTime = added.Item?.ScannedAt ?? now;
|
||
lock (_cameraPresenceGate)
|
||
{
|
||
if (_cameraPresence.TryGetValue(presenceKey, out var presence)) presence.ScanTime = scanTime;
|
||
}
|
||
|
||
if (added.IsScanEvent)
|
||
{
|
||
var channel = Channels.FirstOrDefault(item => item.ChannelId.Equals(channelId, StringComparison.OrdinalIgnoreCase));
|
||
if (channel is not null) Barcode?.Invoke(channel, code);
|
||
Changed?.Invoke();
|
||
}
|
||
|
||
// 团购也要播报,但只是「出现了」这一下;后续重复命中不再播。同样丢后台不等回执。
|
||
QueueScanNotice(channelId, code);
|
||
return Task.FromResult(new CameraScanResult(added.IsScanEvent, false, scanTime));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 把「通知安卓播报」丢到后台执行,扫码流不等回执。
|
||
///
|
||
/// 同一通道只保留**最新一条**:播报就是「叮」一声,排队等旧的没有意义,
|
||
/// 这样即使安卓一直不回执,队列也不会无限增长。
|
||
/// </summary>
|
||
public void QueueScanNotice(string channelId, string code)
|
||
{
|
||
var key = (channelId ?? string.Empty).Trim();
|
||
if (key.Length == 0 || string.IsNullOrWhiteSpace(code)) return;
|
||
|
||
_pendingNotices[key] = code;
|
||
StartNoticePump();
|
||
}
|
||
|
||
/// <summary>后台播报泵:串行消化 <see cref="_pendingNotices"/>,自身异常不影响扫码流</summary>
|
||
private void StartNoticePump()
|
||
{
|
||
if (Interlocked.CompareExchange(ref _noticePumpRunning, 1, 0) != 0) return;
|
||
|
||
_ = Task.Run(async () =>
|
||
{
|
||
try
|
||
{
|
||
while (!_pendingNotices.IsEmpty)
|
||
{
|
||
foreach (var key in _pendingNotices.Keys.ToList())
|
||
{
|
||
if (!_pendingNotices.TryRemove(key, out var code)) continue;
|
||
try
|
||
{
|
||
await NotifyScanSuccessAsync(key, code).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[scan] 通知安卓播报失败:{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
Interlocked.Exchange(ref _noticePumpRunning, 0);
|
||
// 收尾瞬间可能又进来一条,补拉一次泵
|
||
if (!_pendingNotices.IsEmpty) StartNoticePump();
|
||
}
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 决定这条面单记录该用哪个时间。
|
||
///
|
||
/// 判据只有一个:**面单有没有真的离开过画面**(<paramref name="afterAbsence"/>,
|
||
/// 由识别线程按「画面里连一段时间没有任何条码」得出)。
|
||
///
|
||
/// - 没离开(面单一直摆着,中途被手挡住/移位/反光):**沿用最初那次**。
|
||
/// 否则打包时间会被推后 —— 现场实测出现过「变成开始打包 30 秒之后」,录像定位整体偏移;
|
||
/// - 真的离开又回来(装错了重新打包、20 分钟后重新称重发现装错再包一遍):用**这次**的时间。
|
||
///
|
||
/// 为什么不再用「这中间通道上又扫过别的包裹」当判据:两张面单轮流进入视野就会命中,
|
||
/// 但那两张面单都没离开过,属于误判。
|
||
/// </summary>
|
||
internal static DateTime ResolveCameraScanTime(DateTime now, DateTime? knownScanTime, bool afterAbsence)
|
||
{
|
||
if (afterAbsence) return now;
|
||
if (knownScanTime is DateTime firstSeen && now >= firstSeen) return firstSeen;
|
||
return now;
|
||
}
|
||
|
||
/// <summary>清掉 24 小时没再出现过的在场记录(防止字典无限增长)</summary>
|
||
private void PruneCameraPresence(DateTime now)
|
||
{
|
||
if (_cameraPresence.Count == 0) return;
|
||
|
||
var stale = _cameraPresence
|
||
.Where(pair => now - pair.Value.LastHitAt > CameraPresenceTtl)
|
||
.Select(pair => pair.Key)
|
||
.ToList();
|
||
foreach (var key in stale) _cameraPresence.Remove(key);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 通知某条通道的安卓设备「扫码成功」(让它播报语音),并等它回执。
|
||
///
|
||
/// **只对安卓扫描通道发**:网口扫码枪/中控盒没有语音能力,收到也无事可做。
|
||
/// 返回 false 只表示「没确认收到」,不是错误 —— 记录已在 <see cref="ReportCameraScanAsync"/> 里落好。
|
||
/// </summary>
|
||
public async Task<bool> NotifyScanSuccessAsync(string channelId, string code)
|
||
{
|
||
var key = (channelId ?? string.Empty).Trim();
|
||
if (key.Length == 0) return false;
|
||
|
||
var channel = Channels.FirstOrDefault(item =>
|
||
item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase)
|
||
|| item.Mac.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||
if (channel is null || !channel.IsAndroidStation) return false;
|
||
if (!_connections.TryGetValue(channel.Mac, out var connection)) return false;
|
||
|
||
return await connection.SendScanNoticeAsync(code).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 切换某条通道的扫码枪静音(与 AndroidScanCenter 一致):
|
||
/// **只存本地 + 让这条连接重新走一遍**,不在现有 socket 上补写指令 ——
|
||
/// 连上时会按最新值把「连续扫描 + 间隔 0 + 静音」整条下发。
|
||
/// </summary>
|
||
public void SetMuted(ScanChannel channel, bool muted)
|
||
{
|
||
if (channel.Muted == muted) return;
|
||
|
||
channel.Muted = muted;
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
|
||
if (_connections.TryGetValue(channel.Mac, out var connection))
|
||
{
|
||
// 设备当前没通也不怕:下次连上时按记住的值下发
|
||
connection.RequestReconnect("扫码枪设置变更,主动重连");
|
||
AppLog.Write($"[scan] 通道 {channel.Number}「{channel.DisplayName}」" + (muted ? "已设为静音" : "已恢复蜂鸣") + ",正在重新下发设置");
|
||
}
|
||
else
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number}「{channel.DisplayName}」" + (muted ? "已设为静音" : "已恢复蜂鸣") + "(设备未连通,连上后自动生效)");
|
||
}
|
||
}
|
||
|
||
public Task<DeviceSysConfig?> ReadConfigAsync(string ip, CancellationToken ct = default)
|
||
=> _scanner.ReadSysConfigAsync(ip, ct);
|
||
|
||
public Task<bool> WriteConfigAsync(string ip, IReadOnlyDictionary<string, object> patch, CancellationToken ct = default)
|
||
=> _scanner.WriteSysConfigAsync(ip, patch, ct);
|
||
|
||
/// <summary>确保设备上有一条给中控用的 TCP 服务(没有它这条通道永远收不到码)</summary>
|
||
public Task<TcpServerEnsureResult> EnsureTcpServerAsync(string ip, string? preferredName = null,
|
||
CancellationToken ct = default)
|
||
=> _scanner.EnsureTcpServerAsync(ip, preferredName, ct);
|
||
|
||
/// <summary>把设备名写进设备(SYS.HostName + 落 flash)</summary>
|
||
public Task<bool> WriteHostNameAsync(string ip, string name, CancellationToken ct = default)
|
||
=> _scanner.WriteHostNameAsync(ip, name, ct);
|
||
|
||
public Task<bool> RestartAsync(string ip, CancellationToken ct = default)
|
||
=> _scanner.RestartAsync(ip, ct);
|
||
|
||
/// <summary>
|
||
/// 添加通道(按 MAC 去重)。
|
||
///
|
||
/// 顺序与 AndroidScanCenter 一致,且**先配设备、后落本地**:
|
||
/// ① 确保设备有 TCP-SERVER 服务(失败就整个失败,本地什么都不写);
|
||
/// ② 设备名与设备自报的不一样就写进设备(失败不阻断,只影响设备面板/其他上位机看到的叫法);
|
||
/// ③ 才把通道写进本地配置并开始连。
|
||
/// 回滚本地行不通:中间设备名可能已经写上去了,回滚只能回一半。
|
||
/// </summary>
|
||
/// <param name="number">指定通道号(<=0 或被占用时退回最小空号)</param>
|
||
/// <param name="model">设备型号(UDP 发现应答的 Type/CustomerID;AndroidStation = 安卓扫描通道)</param>
|
||
/// <param name="stage">进度文案回调(界面显示用)</param>
|
||
public async Task<AddChannelResult> AddChannelAsync(string mac, string name, string ip, int number,
|
||
string? reportedHostName = null, string? model = null, Action<string>? stage = null, CancellationToken ct = default)
|
||
{
|
||
var key = (mac ?? string.Empty).Trim().ToUpperInvariant();
|
||
var trimmed = (name ?? string.Empty).Trim();
|
||
var deviceModel = (model ?? string.Empty).Trim();
|
||
|
||
// 已存在:只更新名字/IP/型号/通道号,不重配设备
|
||
var existing = Channels.FirstOrDefault(item => item.Mac.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||
if (existing is not null)
|
||
{
|
||
existing.LastIp = string.IsNullOrWhiteSpace(ip) ? existing.LastIp : ip;
|
||
if (trimmed.Length > 0) existing.Name = trimmed;
|
||
if (deviceModel.Length > 0) existing.Model = deviceModel;
|
||
if (number > 0 && ChannelStore.FindByNumber(Channels, number, existing.Mac) is null) existing.Number = number;
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
if (Running) StartConnection(existing);
|
||
return new AddChannelResult(existing, true, "该设备已在通道列表里,已更新名称/通道号");
|
||
}
|
||
|
||
// ① 设备 TCP 服务(失败直接中止)
|
||
stage?.Invoke("正在检查设备 TCP 服务…");
|
||
var ensure = await EnsureTcpServerAsync(ip, null, ct).ConfigureAwait(false);
|
||
if (!ensure.Ok) return new AddChannelResult(null, false, ensure.Message);
|
||
|
||
// ② 设备名(可选,失败不阻断)
|
||
var patchNote = string.Empty;
|
||
if (trimmed.Length > 0 && !trimmed.Equals((reportedHostName ?? string.Empty).Trim(), StringComparison.Ordinal))
|
||
{
|
||
stage?.Invoke($"正在把设备名「{trimmed}」写入设备…");
|
||
var ok = await WriteHostNameAsync(ip, trimmed, ct).ConfigureAwait(false);
|
||
if (!ok) patchNote = "(设备名写入失败,不影响收码)";
|
||
}
|
||
|
||
// ③ 落本地
|
||
var wanted = number > 0 && ChannelStore.FindByNumber(Channels, number) is null
|
||
? number
|
||
: ChannelStore.NextNumber(Channels);
|
||
var channel = new ScanChannel
|
||
{
|
||
Mac = key,
|
||
Name = trimmed.Length > 0 ? trimmed : key,
|
||
LastIp = ip,
|
||
Model = deviceModel,
|
||
Number = wanted,
|
||
TcpPort = ScanProtocol.TcpPort,
|
||
SockName = ensure.SockName,
|
||
};
|
||
Channels.Add(channel);
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
RequestChannelSync(replace: true);
|
||
|
||
if (Running) StartConnection(channel);
|
||
|
||
var message = $"通道 {channel.Number}「{channel.DisplayName}」已添加{ensure.Message}{patchNote}";
|
||
return new AddChannelResult(channel, true, message, ensure.Kind);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 改已添加通道的名字(不用先删再添加)。
|
||
///
|
||
/// - 本机先落盘并同步服务器:`POST /api/scan/channels` 按 `channelId` 更新 `channelName`,
|
||
/// 所以这里用普通推送(**不用** `replace`,改名不涉及删通道);
|
||
/// - <paramref name="writeToDevice"/> 为 true 时顺手写设备 `SYS.HostName`(与添加通道一致),
|
||
/// 写失败**不回滚**本机改名:设备名只影响设备面板/其他上位机看到的叫法,不影响收码;
|
||
/// - 名字没变就不推服务器,只按需补写设备名。
|
||
/// </summary>
|
||
public async Task<RenameChannelResult> RenameChannelAsync(ScanChannel channel, string name, bool writeToDevice,
|
||
Action<string>? stage = null, CancellationToken ct = default)
|
||
{
|
||
var trimmed = (name ?? string.Empty).Trim();
|
||
if (trimmed.Length == 0) return new RenameChannelResult(false, "通道名不能为空");
|
||
|
||
var oldName = channel.DisplayName;
|
||
var renamed = !trimmed.Equals((channel.Name ?? string.Empty).Trim(), StringComparison.Ordinal);
|
||
|
||
if (renamed)
|
||
{
|
||
channel.Name = trimmed;
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
RequestChannelSync();
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 改名:「{oldName}」→「{trimmed}」");
|
||
}
|
||
|
||
var note = string.Empty;
|
||
if (writeToDevice)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(channel.LastIp))
|
||
{
|
||
note = "(不知道该设备 IP,设备名没写入)";
|
||
}
|
||
else
|
||
{
|
||
stage?.Invoke($"正在把设备名「{trimmed}」写入设备…");
|
||
var ok = await WriteHostNameAsync(channel.LastIp, trimmed, ct).ConfigureAwait(false);
|
||
note = ok ? ",并已写入设备" : "(设备名写入失败,不影响收码)";
|
||
}
|
||
}
|
||
|
||
var message = renamed
|
||
? $"通道 {channel.Number} 已改名:「{oldName}」→「{trimmed}」{note}"
|
||
: $"通道 {channel.Number} 名称未变{note}";
|
||
return new RenameChannelResult(true, message);
|
||
}
|
||
|
||
/// <summary>删除通道</summary>
|
||
public void RemoveChannel(ScanChannel channel)
|
||
{
|
||
StopConnection(channel);
|
||
Channels.Remove(channel);
|
||
SaveChannels();
|
||
Changed?.Invoke();
|
||
// 全量对账:服务器会软删这条通道并解绑工作台
|
||
RequestChannelSync(replace: true);
|
||
}
|
||
|
||
/// <summary>启动扫码服务:连接所有通道 + (后台)同步通道列表到服务器</summary>
|
||
public Task StartAsync()
|
||
{
|
||
Load();
|
||
Running = true;
|
||
|
||
foreach (var channel in Channels) StartConnection(channel);
|
||
|
||
RequestChannelSync();
|
||
EnsureWatchdog();
|
||
LabelScan.Start(); // 面单识别配置:启动拉一次 + 每 5 分钟兜底
|
||
Osd.Start(); // 工作台 OSD:启动拉一次 + 每 1 分钟兜底
|
||
AppLog.Write($"[scan] 扫码服务已启动,通道 {Channels.Count} 个");
|
||
Changed?.Invoke();
|
||
return Task.CompletedTask;
|
||
}
|
||
|
||
/// <summary>停止扫码服务(断开所有连接)</summary>
|
||
public void Stop()
|
||
{
|
||
Running = false;
|
||
foreach (var connection in _connections.Values.ToList()) connection.Stop();
|
||
_connections.Clear();
|
||
|
||
try
|
||
{
|
||
_syncCts?.Cancel();
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
_syncCts = null;
|
||
_syncTask = null;
|
||
|
||
try
|
||
{
|
||
_watchdogCts?.Cancel();
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
_watchdogCts = null;
|
||
_watchdogTask = null;
|
||
|
||
StopDiscovery();
|
||
LabelScan.Stop();
|
||
Osd.Stop();
|
||
|
||
AppLog.Write("[scan] 扫码服务已停止");
|
||
Changed?.Invoke();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 看门狗(每 30 秒):连接看着在线但**很久没收到字节**时,回查设备侧还认不认这条连接。
|
||
///
|
||
/// 设备断电重启时 TCP 层不会发 FIN/RST,中控这侧阻塞的 `ReadAsync` 会永久挂住,
|
||
/// 既不报断开也不重连 —— 只有回查设备侧 `SOCK.ClientIP`(CID 10001)才能发现。
|
||
/// </summary>
|
||
private void EnsureWatchdog()
|
||
{
|
||
if (_watchdogTask is { IsCompleted: false }) return;
|
||
|
||
_watchdogCts = new CancellationTokenSource();
|
||
_watchdogTask = Task.Run(() => WatchdogLoopAsync(_watchdogCts.Token));
|
||
}
|
||
|
||
private async Task WatchdogLoopAsync(CancellationToken ct)
|
||
{
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
try
|
||
{
|
||
await Task.Delay(TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
|
||
foreach (var connection in _connections.Values.ToList())
|
||
{
|
||
var channel = connection.Channel;
|
||
if (!channel.Connected) continue;
|
||
|
||
// 设备平时一直在推帧(~0.7s 一帧),20 秒一个字节都没有就可疑了
|
||
if ((DateTime.Now - connection.LastRxAt).TotalSeconds < 20) continue;
|
||
|
||
try
|
||
{
|
||
var states = await _scanner.ReadSockStatesAsync(channel.LastIp, ct).ConfigureAwait(false);
|
||
|
||
// ⚠️ 读不到(UDP 完全没应答)= 设备已断电/断网/离线。
|
||
// 以前这里「读不到就不断言」,结果设备真离线了界面还一直是「在线」
|
||
// (设备断电时 TCP 不发 FIN,本地 socket 一直挂着)。
|
||
if (states is null)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number}({channel.DisplayName})设备无应答"
|
||
+ $"({channel.LastIp} 已 {Math.Round((DateTime.Now - connection.LastRxAt).TotalSeconds)}s 没数据),判为离线并重连");
|
||
connection.RequestReconnect("设备无应答(疑似断电/离线)");
|
||
continue;
|
||
}
|
||
|
||
var name = string.IsNullOrWhiteSpace(channel.SockName) ? ScanProtocol.SockName : channel.SockName;
|
||
var mine = states.FirstOrDefault(item =>
|
||
item.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||
|
||
// 设备能应答、但我们那条条目不见了:说明设备重载/配置被改,重连让它自愈
|
||
if (mine is null)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 设备上已没有「{name}」条目,强制重连(会自愈)");
|
||
connection.RequestReconnect($"设备上已没有「{name}」条目");
|
||
continue;
|
||
}
|
||
|
||
if (mine.Clients.Any(ip => ip.Equals(connection.LocalIp, StringComparison.Ordinal))) continue;
|
||
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 设备侧已不认这条连接"
|
||
+ $"(ClientIP=[{mine.ClientIp}],本机 {connection.LocalIp}),强制重连");
|
||
connection.RequestReconnect($"设备侧已不认这条连接(ClientIP=[{mine.ClientIp}])");
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 假死检查失败(忽略):{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 把通道列表同步到服务器(`POST /api/scan/channels` 之后再用 `GET` **回查确认**)。
|
||
///
|
||
/// `replace = true` = 全量对账(添加/删除通道时用):服务器会软删本中控下不在列表里的旧通道,
|
||
/// 并解绑对应工作台绑定(通道列表存在本地,与本机设备是否在线无关)。
|
||
///
|
||
/// 不用手动点:添加 / 删除 都会调 <see cref="RequestChannelSync"/>,
|
||
/// 后台循环一直重试到服务器确实有这批通道为止(断网、服务器重启都不用手管)。
|
||
/// </summary>
|
||
public void RequestChannelSync(bool replace = false)
|
||
{
|
||
if (replace) _syncReplace = true;
|
||
EnsureSyncLoop();
|
||
try
|
||
{
|
||
if (_syncSignal.CurrentCount == 0) _syncSignal.Release();
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
}
|
||
|
||
private void EnsureSyncLoop()
|
||
{
|
||
if (_syncTask is { IsCompleted: false }) return;
|
||
|
||
_syncCts = new CancellationTokenSource();
|
||
_syncTask = Task.Run(() => SyncLoopAsync(_syncCts.Token));
|
||
}
|
||
|
||
private async Task SyncLoopAsync(CancellationToken ct)
|
||
{
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
try
|
||
{
|
||
// 只等信号:**不靠超时**。以前写成 WaitAsync(30s) + 无条件推送,
|
||
// 结果每 30 秒就往服务器重推一次通道、刷一条日志(看起来像“一直在重连”)。
|
||
await _syncSignal.WaitAsync(ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
|
||
await PushChannelsUntilConfirmedAsync(ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
/// <summary>推一次 + 回查确认;不成功就退避重试,直到服务器真的有这批通道</summary>
|
||
private async Task PushChannelsUntilConfirmedAsync(CancellationToken ct)
|
||
{
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
if (!_device.Enabled)
|
||
{
|
||
SetSyncStatus("设备服务未开启,通道等开启后再同步");
|
||
return;
|
||
}
|
||
|
||
var local = Channels
|
||
.Select(item => (item.ChannelId, item.DisplayName))
|
||
.ToList();
|
||
|
||
// replace = 全量对账:本地通道列表就是全部(设备离线不影响通道配置),
|
||
// 推空列表也合法 —— 表示通道已巨部删除,服务器要跟着删。
|
||
var replace = _syncReplace;
|
||
|
||
if (local.Count == 0 && !replace)
|
||
{
|
||
SetSyncStatus("当前没有通道");
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
await _device.ReportChannelsAsync(local, replace, ct).ConfigureAwait(false);
|
||
|
||
// 服务器回查:确保它真的收到了(POST 成功≠入库成功,例如主体变更/令牌失效)
|
||
var remote = await _device.ChannelsAsync(ct).ConfigureAwait(false);
|
||
var missing = local.Where(item => !remote.Contains(item.ChannelId)).Select(item => item.ChannelId).ToList();
|
||
|
||
if (missing.Count == 0)
|
||
{
|
||
_syncRetryMs = 1000;
|
||
if (replace) _syncReplace = false;
|
||
SetSyncStatus($"通道已同步({local.Count} 个)");
|
||
AppLog.Write($"[scan] 通道已同步到服务器并确认:{local.Count} 个" + (replace ? "(全量对账)" : ""));
|
||
return;
|
||
}
|
||
|
||
throw new InvalidOperationException($"服务器上还缺通道 {string.Join('/', missing)}");
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return;
|
||
}
|
||
catch (ApiException ex) when (ex.IsSubjectUnavailable)
|
||
{
|
||
// 主体过期/停用:不进入退避重试(否则每 30 秒撞一次墙),等续期事件再同步
|
||
SetSyncStatus("主体已到期/停用,通道同步暂停(恢复后自动重试)");
|
||
AppLog.Write($"[scan] 通道同步暂停:{ex.Message}");
|
||
return;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
SetSyncStatus($"通道同步失败,{_syncRetryMs / 1000} 秒后重试");
|
||
AppLog.Write($"[scan] 通道同步失败({_syncRetryMs}ms 后重试):{ex.Message}");
|
||
try
|
||
{
|
||
await Task.Delay(_syncRetryMs, ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return;
|
||
}
|
||
_syncRetryMs = Math.Min(_syncRetryMs * 2, 30000);
|
||
}
|
||
}
|
||
}
|
||
|
||
private void SetSyncStatus(string status)
|
||
{
|
||
if (ChannelSyncStatus == status) return;
|
||
ChannelSyncStatus = status;
|
||
Changed?.Invoke();
|
||
}
|
||
|
||
private void StartConnection(ScanChannel channel)
|
||
{
|
||
StopConnection(channel);
|
||
if (string.IsNullOrWhiteSpace(channel.LastIp)) return;
|
||
|
||
var connection = new ChannelConnection(channel);
|
||
connection.Barcode += OnBarcode;
|
||
connection.StateChanged += (_, _) => Changed?.Invoke();
|
||
connection.HealNeeded += healChannel => _ = HealAsync(healChannel);
|
||
_connections[channel.Mac] = connection;
|
||
connection.Start();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 自愈:连不上时回查设备上我们那条 TCP 服务(`packcenter / TCP-SERVER / 8087`)还在不在,
|
||
/// 被删了/被改了就重建(照搬 AndroidScanCenter 的 <c>healIfNeeded</c>)。
|
||
///
|
||
/// 只在「连不上」时查(连得上就不动设备配置),每台设备 60 秒最多查一次。
|
||
/// </summary>
|
||
private async Task HealAsync(ScanChannel channel)
|
||
{
|
||
if (!Running || !_device.Enabled) return;
|
||
if (string.IsNullOrWhiteSpace(channel.LastIp)) return;
|
||
|
||
var now = DateTime.Now;
|
||
if (_lastHealAt.TryGetValue(channel.Mac, out var last) && (now - last).TotalSeconds < 60) return;
|
||
_lastHealAt[channel.Mac] = now;
|
||
|
||
// 离线设备每 60 秒会自愈一次;日志只在第一次 / 每 10 分钟记一遍
|
||
var shouldLog = !_healLogAt.TryGetValue(channel.Mac, out var lastLog)
|
||
|| (now - lastLog).TotalMinutes >= 10;
|
||
if (shouldLog) _healLogAt[channel.Mac] = now;
|
||
|
||
try
|
||
{
|
||
if (shouldLog)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 连不上({channel.LastIp}),回查设备的 TCP 服务…");
|
||
}
|
||
|
||
var result = await _scanner.EnsureTcpServerAsync(channel.LastIp, channel.SockName).ConfigureAwait(false);
|
||
|
||
if (shouldLog || result.Ok)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 自愈:{result.Message}");
|
||
}
|
||
|
||
if (result.Ok)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(result.SockName) && result.SockName != channel.SockName)
|
||
{
|
||
channel.SockName = result.SockName;
|
||
SaveChannels();
|
||
}
|
||
|
||
if (_connections.TryGetValue(channel.Mac, out var connection))
|
||
{
|
||
connection.RequestReconnect("设备 TCP 服务已就绪,立即重连");
|
||
}
|
||
}
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
// 忽略
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (shouldLog)
|
||
{
|
||
AppLog.Write($"[scan] 通道 {channel.Number} 自愈失败(稍后再试):{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
|
||
private void StopConnection(ScanChannel channel)
|
||
{
|
||
if (!_connections.TryGetValue(channel.Mac, out var existing)) return;
|
||
|
||
try
|
||
{
|
||
existing.Stop();
|
||
existing.Dispose();
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
_connections.Remove(channel.Mac);
|
||
channel.Connected = false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 收到条码。
|
||
///
|
||
/// ⚠️ 连续扫描模式下同一个码每 ~80ms 报一次:
|
||
/// - 记录库只把「最近扫描时间」刷到最新,不新增记录;
|
||
/// - 这里只在**新扫码事件**(换了条码 / 已上报过的码又扫到)时通知界面,
|
||
/// 否则订阅者会被连续扫描刷屏。订阅者**只能做展示**,不能据此发起运单查询。
|
||
/// 真正的上报在扫到后 5 秒没再扫到同一个码时才做(时间取最后一次扫描)。
|
||
/// </summary>
|
||
private void OnBarcode(ScanChannel channel, string code)
|
||
{
|
||
var added = _device.ReportOnChannel(channel.ChannelId, channel.DisplayName, code);
|
||
|
||
// 连续扫描(~80ms 一次)也会走到这里:OSD 只续计时,不会重写
|
||
RaiseScanActivity(channel.ChannelId, code);
|
||
|
||
if (added) Barcode?.Invoke(channel, code);
|
||
Changed?.Invoke();
|
||
}
|
||
|
||
/// <summary>触发 <see cref="ScanActivity"/>;订阅者异常绝不影响扫码主链路</summary>
|
||
private void RaiseScanActivity(string channelId, string code)
|
||
{
|
||
var handlers = ScanActivity;
|
||
if (handlers is null) return;
|
||
|
||
try
|
||
{
|
||
handlers(channelId, code, DateTime.Now);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[scan] 扫码活动事件处理失败(通道 {channelId}):{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>添加通道的结果(<see cref="Channel"/> 为空表示失败,<see cref="Message"/> 是给用户看的一句话)</summary>
|
||
public sealed record AddChannelResult(
|
||
ScanChannel? Channel,
|
||
bool Ok,
|
||
string Message,
|
||
TcpServerEnsureKind EnsureKind = TcpServerEnsureKind.AlreadyReady);
|
||
|
||
/// <summary>改通道名的结果(<see cref="Message"/> 是给用户看的一句话)</summary>
|
||
public sealed record RenameChannelResult(bool Ok, string Message);
|
||
|
||
/// <summary>
|
||
/// 面单摄像头识别结果的处理结果。
|
||
///
|
||
/// <see cref="NewScan"/> 只影响界面是否重查;<see cref="Notified"/> 只表示「安卓端有没有收到播报通知」,
|
||
/// **不代表记录是否入队** —— 记录一定已写入待上报队列。
|
||
///
|
||
/// <see cref="ScanTime"/> 是这条记录**真正的时间**:第一次识别到的那一刻,
|
||
/// 面单不拿走也不会变(界面显示「首次识别」用它,不能用当前的命中时间)。
|
||
/// </summary>
|
||
/// <summary>面单摄像头识别结果(<paramref name="Notified"/> 恒为 false:播报已改为后台异步,不再等回执)</summary>
|
||
public sealed record CameraScanResult(bool NewScan, bool Notified, DateTime? ScanTime = null);
|