feat(desktop): 本地 HTTP 服务与扫码通道、扫码记录界面
This commit is contained in:
parent
c3cae69e6e
commit
cb511f33ae
349
desktop/Services/DeviceService.cs
Normal file
349
desktop/Services/DeviceService.cs
Normal file
@ -0,0 +1,349 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面端「设备服务」:把本机当成一台扫码中控(scanner),向服务器上报扫码记录。
|
||||
///
|
||||
/// - **默认关闭**:只有主体管理员在菜单「服务 → 开启设备服务」里手动开启;
|
||||
/// - 开启时调 `POST /api/web/devices/activate`,服务端保证「一个主体只有一台设备在线」,
|
||||
/// 同主体其他设备会被踢下线(旧令牌立即 401);
|
||||
/// - 开启后拿到**长期设备 JWT**,上报走 `POST /api/scan/{channels,records}`;
|
||||
/// - 关闭时调 `POST /api/web/devices/:id/logout` 让令牌立即作废。
|
||||
/// </summary>
|
||||
public sealed class DeviceService
|
||||
{
|
||||
/// <summary>本机上报用的通道 id / 名称(一台电脑就是一个通道)</summary>
|
||||
public const string LocalChannelId = "DESKTOP";
|
||||
public const string LocalChannelName = "本机中控";
|
||||
|
||||
private readonly ApiClient _api;
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Session _session;
|
||||
|
||||
// 扫码记录上报队列:条码先进本地库,后台循环批量推送,**服务器确认后才标记已上传**
|
||||
private readonly SemaphoreSlim _uploadSignal = new(0, 1);
|
||||
private CancellationTokenSource? _uploadCts;
|
||||
private Task? _uploadTask;
|
||||
private int _uploadRetryMs = 1000;
|
||||
|
||||
// 面单一直放在扫码器上时会持续「更新最近扫描时间」(每 1~2 秒一次)——
|
||||
// 这种事件不能每条都写日志,否则一天几万行;同一个 通道+条码 5 分钟记一次。
|
||||
private static readonly ConcurrentDictionary<string, DateTime> TouchedLogAt = new();
|
||||
|
||||
private static bool ShouldLogTouched(string channel, string code)
|
||||
{
|
||||
var key = $"{channel}|{code}";
|
||||
var now = DateTime.Now;
|
||||
|
||||
if (TouchedLogAt.TryGetValue(key, out var last) && now - last < TimeSpan.FromMinutes(5)) return false;
|
||||
|
||||
TouchedLogAt[key] = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
public DeviceService(ApiClient api, AppSettings settings, Session session)
|
||||
{
|
||||
_api = api;
|
||||
_settings = settings;
|
||||
_session = session;
|
||||
}
|
||||
|
||||
/// <summary>上报状态(给界面看的一句话;空串 = 一切正常)</summary>
|
||||
public string UploadStatus { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>是否已开启(本地标记 + 有令牌)</summary>
|
||||
public bool Enabled => _settings.DeviceServiceEnabled && !string.IsNullOrWhiteSpace(_settings.DeviceToken);
|
||||
|
||||
/// <summary>本机 SN(默认机器名,最多 64 字符)</summary>
|
||||
public string Sn
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_settings.DeviceSn)) return _settings.DeviceSn;
|
||||
var name = Environment.MachineName;
|
||||
return string.IsNullOrWhiteSpace(name) ? "PC-DESKTOP" : name.ToUpperInvariant();
|
||||
}
|
||||
set
|
||||
{
|
||||
var text = (value ?? string.Empty).Trim();
|
||||
_settings.DeviceSn = text.Length > 64 ? text[..64] : text;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>当前主体 id(没有主体时 0)</summary>
|
||||
public int SubjectId => _settings.SubjectId;
|
||||
|
||||
/// <summary>当前主体下**除本机以外**的已绑定设备(开启前提示"会被踢掉")</summary>
|
||||
public async Task<IReadOnlyList<ApiDevice>> OtherDevicesAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (SubjectId <= 0) return Array.Empty<ApiDevice>();
|
||||
|
||||
var devices = await _api.DevicesAsync(_session.Token, SubjectId, ct).ConfigureAwait(false);
|
||||
return devices.Where(item => !string.Equals(item.Sn, Sn, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启设备服务:注册本机 → 保存令牌 → 上报通道。
|
||||
/// (踢掉其他设备的确认由界面负责,这里只管干活)
|
||||
/// </summary>
|
||||
/// <exception cref="ApiException">不是管理员 / 网络失败 / 主体到期等,message 可直接显示</exception>
|
||||
public async Task<DeviceActivation> EnableAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (SubjectId <= 0) throw new ApiException("还没有选择主体,请先在「服务 → 切换主体」里选一个");
|
||||
|
||||
var result = await _api.ActivateDeviceAsync(_session.Token, SubjectId, Sn, $"{Environment.MachineName}(本机)", ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
_settings.DeviceServiceEnabled = true;
|
||||
_settings.DeviceId = result.Id;
|
||||
_settings.DeviceSn = result.Sn;
|
||||
_settings.DeviceToken = result.Token;
|
||||
_settings.DeviceRefreshToken = result.RefreshToken;
|
||||
_settings.DeviceTokenExpiresAt = result.ExpiresIn ?? string.Empty;
|
||||
_settings.Save();
|
||||
|
||||
AppLog.Write($"[device] 设备服务已开启:{result.Sn}(id={result.Id},踢下线 {result.Kicked.Count} 台)");
|
||||
|
||||
// 拉起扫码记录上报循环(断网期间的积压会一次性补上去)
|
||||
EnsureUploadLoop();
|
||||
TriggerUpload();
|
||||
|
||||
// 通道不在这里上报:真实通道由 `ScanService` 同步(加了几个扫码通道就报几个)。
|
||||
// 以前这里会补一个 `DESKTOP`「本机中控」占位通道,结果工作台绑定页能看到一个
|
||||
// 永远没数据的假通道;查询也不是扫码,不需要这个通道来"记账"。
|
||||
AppLog.Write("[device] 通道由扫码服务同步(不再上报本机占位通道)");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>上报一批通道(扫码服务的每条通道都同步给服务器,供工作台绑定)</summary>
|
||||
public async Task ReportChannelsAsync(IEnumerable<(string ChannelId, string ChannelName)> channels,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (!Enabled) return;
|
||||
|
||||
var list = channels
|
||||
.Where(item => !string.IsNullOrWhiteSpace(item.ChannelId))
|
||||
.Select(item => (item.ChannelId, string.IsNullOrWhiteSpace(item.ChannelName) ? item.ChannelId : item.ChannelName))
|
||||
.ToList();
|
||||
if (list.Count == 0) return;
|
||||
|
||||
await _api.ReportChannelsAsync(_settings.DeviceToken, list, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>关闭设备服务:让令牌立即作废并清掉本地状态</summary>
|
||||
public async Task DisableAsync(CancellationToken ct = default)
|
||||
{
|
||||
StopUploadLoop();
|
||||
|
||||
var deviceId = _settings.DeviceId;
|
||||
var token = _settings.DeviceToken;
|
||||
|
||||
_settings.DeviceServiceEnabled = false;
|
||||
_settings.DeviceToken = string.Empty;
|
||||
_settings.DeviceRefreshToken = string.Empty;
|
||||
_settings.DeviceTokenExpiresAt = string.Empty;
|
||||
_settings.Save();
|
||||
|
||||
if (deviceId > 0 && token.Length > 0 && SubjectId > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _api.DeactivateDeviceAsync(_session.Token, SubjectId, deviceId, ct).ConfigureAwait(false);
|
||||
AppLog.Write($"[device] 设备服务已关闭(id={deviceId},令牌已作废)");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 关服务不该因为网络问题卡住用户
|
||||
AppLog.Write($"[device] 通知服务器关闭失败(本地已关闭):{ex.Message}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AppLog.Write("[device] 设备服务已关闭(本地)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>换了主体/退出登录:本地状态清掉(不动服务器上的旧设备)</summary>
|
||||
public void ResetLocalState()
|
||||
{
|
||||
StopUploadLoop();
|
||||
|
||||
_settings.DeviceServiceEnabled = false;
|
||||
_settings.DeviceId = 0;
|
||||
_settings.DeviceToken = string.Empty;
|
||||
_settings.DeviceRefreshToken = string.Empty;
|
||||
_settings.DeviceTokenExpiresAt = string.Empty;
|
||||
_settings.Save();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上报一条扫码记录(fire-and-forget 的**入队**版本)。
|
||||
///
|
||||
/// ⚠️ 只在真的"扫了一次码"时调用;**运单查询不要调** ——
|
||||
/// 查询只是看看,记一条 `DESKTOP` 记录会污染扫码记录表(历史要求)。
|
||||
/// 先落本地库,由后台上报循环推给服务器;失败会一直重试,不会丢。
|
||||
/// </summary>
|
||||
public void ReportScan(string code) => ReportOnChannel(LocalChannelId, LocalChannelName, code);
|
||||
|
||||
/// <summary>
|
||||
/// 用指定通道记一条扫码记录。
|
||||
///
|
||||
/// 与 AndroidScanCenter 的 ScanStore + BarcodeReporter 一致:
|
||||
/// ① 先落本地(连续扫描只刷新「最近一次扫描时间」)→ ② 唤醒后台上报循环 →
|
||||
/// ③ 服务器 2xx 确认后才把记录标成已上传,否则按退避重试。
|
||||
///
|
||||
/// **延迟上报**:扫到后 5 分钟没再扫到同一个码才真正上报(见
|
||||
/// <see cref="ScanRecordStore.SettleDelay"/>),上报的是最后一次扫描时间。
|
||||
/// </summary>
|
||||
/// <returns>true = 一次新的扫码事件(连续扫描的重复帧返回 false,界面不用重查)</returns>
|
||||
public bool ReportOnChannel(string channelId, string channelName, string code)
|
||||
{
|
||||
var barcode = (code ?? string.Empty).Trim();
|
||||
if (barcode.Length == 0) return false;
|
||||
|
||||
var channel = string.IsNullOrWhiteSpace(channelId) ? LocalChannelId : channelId;
|
||||
var name = string.IsNullOrWhiteSpace(channelName) ? channel : channelName;
|
||||
|
||||
// 没开设备服务也照样记本地:开起来之后会把积压的自动补上去(断网/未开启期间不丢码)
|
||||
var result = ScanRecordStore.Add(channel, name, barcode, DateTime.Now);
|
||||
if (result.Item is null || result.Kind == ScanAddKind.Repeated) return false;
|
||||
|
||||
if (result.Kind == ScanAddKind.Touched)
|
||||
{
|
||||
if (ShouldLogTouched(channel, barcode))
|
||||
{
|
||||
AppLog.Write($"[scan] 通道 {channel} 扫码:{barcode}(更新最近扫描时间;5 分钟内不再重复记录)");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AppLog.Write($"[scan] 通道 {channel} 扫码:{barcode}(5 分钟未再扫到后上报)");
|
||||
}
|
||||
|
||||
if (!Enabled) return true;
|
||||
EnsureUploadLoop();
|
||||
SignalUpload();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>查服务器上当前中控已登记的通道(用于确认同步)</summary>
|
||||
public Task<HashSet<string>> ChannelsAsync(CancellationToken ct = default)
|
||||
=> _api.ChannelsAsync(_settings.DeviceToken, ct);
|
||||
|
||||
/// <summary>立即触发一次上报(界面的「立即上传」)</summary>
|
||||
public void TriggerUpload()
|
||||
{
|
||||
if (!Enabled) return;
|
||||
EnsureUploadLoop();
|
||||
SignalUpload();
|
||||
}
|
||||
|
||||
/// <summary>开设备服务时把上报循环拉起来(重复调用无影响)</summary>
|
||||
public void EnsureUploadLoop()
|
||||
{
|
||||
if (_uploadTask is { IsCompleted: false }) return;
|
||||
|
||||
_uploadCts = new CancellationTokenSource();
|
||||
_uploadTask = Task.Run(() => UploadLoopAsync(_uploadCts.Token));
|
||||
}
|
||||
|
||||
/// <summary>停上报循环(关服务 / 退出登录)</summary>
|
||||
public void StopUploadLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
_uploadCts?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略
|
||||
}
|
||||
_uploadCts = null;
|
||||
_uploadTask = null;
|
||||
UploadStatus = string.Empty;
|
||||
ScanRecordStore.Flush();
|
||||
}
|
||||
|
||||
private void SignalUpload()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_uploadSignal.CurrentCount == 0) _uploadSignal.Release();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 后台上报循环:有信号或每 30 秒检查一次,把**静默满 5 分钟**的待上传记录攒批推送。
|
||||
///
|
||||
/// 失败时**不标记**那批记录,等退避(1s→2s→5s→10s→30s 封顶)后重发;
|
||||
/// 服务端按 设备+通道+条码+秒 去重、同一运单 24 小时内覆盖成最新时间,
|
||||
/// 所以整批重发不会造成重复落库,也不会把时间改回过去。
|
||||
/// </summary>
|
||||
private async Task UploadLoopAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _uploadSignal.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
while (!ct.IsCancellationRequested && Enabled)
|
||||
{
|
||||
var batch = ScanRecordStore.Pending(50);
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
UploadStatus = string.Empty;
|
||||
break;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var rows = batch.Select(item => (item.ChannelId, item.Code, item.ScannedAt)).ToList();
|
||||
await _api.ReportRecordsAsync(_settings.DeviceToken, rows, ct).ConfigureAwait(false);
|
||||
|
||||
// 服务器已确认:只有这里才把记录标成已上传
|
||||
// (传入上报时的扫描时间:上报期间又扫到的话保持待上传,下一轮带最新时间重发)
|
||||
ScanRecordStore.MarkUploaded(batch.Select(item => (item.Id, item.ScannedAt)));
|
||||
_uploadRetryMs = 1000;
|
||||
UploadStatus = string.Empty;
|
||||
AppLog.Write($"[scan] 已上报扫码 {batch.Count} 条");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UploadStatus = $"上报失败(待上传 {ScanRecordStore.PendingCount()} 条),{_uploadRetryMs / 1000} 秒后重试";
|
||||
AppLog.Write($"[scan] 上报扫码失败({batch.Count} 条,{_uploadRetryMs}ms 后重试):{ex.Message}");
|
||||
try
|
||||
{
|
||||
await Task.Delay(_uploadRetryMs, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
_uploadRetryMs = Math.Min(_uploadRetryMs * 2, 30000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,11 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using YuncangTrace.LocalService.Services.Hik;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
@ -27,14 +30,32 @@ namespace YuncangTrace.LocalService.Services;
|
||||
/// </summary>
|
||||
public sealed class LocalHttpServer : IDisposable
|
||||
{
|
||||
/// <summary>监听端口(前端/插件里写死的 17300)</summary>
|
||||
public const int Port = 17300;
|
||||
/// <summary>监听端口(前端/插件里写死的 17300;可用 <c>YUNCANG_LOCAL_PORT</c> 临时覆盖,便于自测)</summary>
|
||||
public static int Port { get; } = ResolvePort();
|
||||
|
||||
private static int ResolvePort()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("YUNCANG_LOCAL_PORT");
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17300;
|
||||
}
|
||||
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly OrderQueryService _queryService;
|
||||
private readonly HikDeviceService? _hik;
|
||||
private readonly HikStreamService? _stream;
|
||||
private readonly HikFfmpegService? _ffmpeg;
|
||||
private readonly HikPreviewService? _preview;
|
||||
private readonly HikNativePreviewService? _native;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _loop;
|
||||
|
||||
/// <summary>
|
||||
/// 「按运单下载录像」服务(网页查件页也会调)
|
||||
///
|
||||
/// 不注入时为 null → 接口回 503(老版本/没装 ffmpeg 的环境)。
|
||||
/// </summary>
|
||||
public PlaybackDownloadService? PlaybackDownload { get; set; }
|
||||
|
||||
/// <summary>日志回调(服务线程 → UI 线程的桥,UI 那边自己 Dispatcher.Invoke)</summary>
|
||||
public event Action<string>? Log;
|
||||
|
||||
@ -50,9 +71,18 @@ public sealed class LocalHttpServer : IDisposable
|
||||
/// <summary>当前后端地址(由 App 提供,随 `/api/query` 一起返回,排障用)</summary>
|
||||
public Func<string?>? ServerBaseUrlProvider { get; set; }
|
||||
|
||||
public LocalHttpServer(OrderQueryService queryService)
|
||||
public LocalHttpServer(OrderQueryService queryService, HikDeviceService? hik = null)
|
||||
{
|
||||
_queryService = queryService;
|
||||
_hik = hik;
|
||||
|
||||
if (hik is not null)
|
||||
{
|
||||
_stream = new HikStreamService(hik);
|
||||
_ffmpeg = new HikFfmpegService();
|
||||
_preview = new HikPreviewService(hik, _stream, _ffmpeg);
|
||||
_native = new HikNativePreviewService(_stream);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>是否已登录(网页靠它判断要不要唤起登录)</summary>
|
||||
@ -161,6 +191,37 @@ public sealed class LocalHttpServer : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
// 海康设备通道:POST JSON {host,port,user,password} 或 GET ?host=&port=&user=&password=
|
||||
// 走 HCNetSDK 的 8000 私有协议登录,成功后读 IP 接入配置返回通道列表
|
||||
if (path.Equals("/api/hik/channels", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await HandleHikChannelsAsync(request, response).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 海康实时预览:建会话 → MJPEG 拉流 / 单帧快照
|
||||
if (path.StartsWith("/api/hik/preview", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await HandleHikPreviewAsync(request, response, path).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 海康云台:POST /api/hik/ptz(方向/变倍/聚焦/光圈)与 /api/hik/ptz/preset(预置点)
|
||||
if (path.Equals("/api/hik/ptz", StringComparison.OrdinalIgnoreCase) ||
|
||||
path.Equals("/api/hik/ptz/preset", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await HandleHikPtzAsync(request, response, path).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 按运单下载录像:POST /api/playback/download { code }
|
||||
// 网页查件页(/local?code=)用 —— 任何装了本机软件的电脑都能下,存到本机设置的目录
|
||||
if (path.Equals("/api/playback/download", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await HandlePlaybackDownloadAsync(request, response).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false);
|
||||
@ -194,7 +255,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
var result = _queryService.Query(code);
|
||||
var result = (await _queryService.QueryAsync(code).ConfigureAwait(false)).Http;
|
||||
|
||||
if (result.Ok)
|
||||
{
|
||||
@ -216,6 +277,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
{
|
||||
400 => "bad-request",
|
||||
404 => "not-found",
|
||||
401 => "need-login",
|
||||
_ => "error",
|
||||
};
|
||||
|
||||
@ -246,6 +308,10 @@ public sealed class LocalHttpServer : IDisposable
|
||||
<ul>
|
||||
<li><code>/api/query/{运单号}</code> 查询(同时返回服务/登录状态;没登录回 401)</li>
|
||||
<li><code>POST /api/activate-login</code> 把登录窗叫到前台</li>
|
||||
<li><code>POST /api/hik/channels</code> 读取海康设备通道(body:<code>{"host":"192.168.8.241","port":8000,"user":"admin","password":"***"}</code>)</li>
|
||||
<li><code>POST /api/hik/preview</code> 建预览会话(body 同 channels,加 <code>channel</code>)→ 返回 <code>mjpegUrl</code> / <code>snapshotUrl</code> / <code>rtspUrl</code></li>
|
||||
<li><code>POST /api/hik/ptz</code> 云台连续动作(<code>command</code>=up/down/left/right/zoom-in…,<code>stop</code>=true 停止)</li>
|
||||
<li><code>POST /api/hik/ptz/preset</code> 预置点(<code>action</code>=set/goto/clear,<code>preset</code>=1~256)</li>
|
||||
</ul>
|
||||
""";
|
||||
await WriteHtmlAsync(response, 200, html).ConfigureAwait(false);
|
||||
@ -279,6 +345,759 @@ public sealed class LocalHttpServer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按运单下载录像:<c>POST /api/playback/download</c>,body <c>{ "code": "运单号" }</c>
|
||||
///
|
||||
/// 网页查件页(`/local?code=`)用:**任何装了本机软件的电脑**都能查件并下载录像,
|
||||
/// 存到**这台电脑自己设置的目录**(`~/packVideo/年/月/日/`),跟"是不是设备服务器"无关。
|
||||
/// </summary>
|
||||
private async Task HandlePlaybackDownloadAsync(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "请用 POST" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsLoggedIn)
|
||||
{
|
||||
await WriteJsonAsync(response, 401, new
|
||||
{
|
||||
ok = false,
|
||||
state = "need-login",
|
||||
loggedIn = false,
|
||||
message = "本机软件未登录,请先在软件里登录",
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var service = PlaybackDownload;
|
||||
if (service is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 503, new
|
||||
{
|
||||
ok = false,
|
||||
state = "unsupported",
|
||||
message = "本机软件没有启用录像下载(请升级到 1.0.54+)",
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string code;
|
||||
try
|
||||
{
|
||||
using var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8);
|
||||
var body = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
using var document = JsonDocument.Parse(string.IsNullOrWhiteSpace(body) ? "{}" : body);
|
||||
code = ReadJsonString(document.RootElement, "code") ?? string.Empty;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "缺少运单号(code)" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var started = DateTime.UtcNow;
|
||||
Log?.Invoke($"网页请求下载录像:{code}");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await service.DownloadAsync(code.Trim()).ConfigureAwait(false);
|
||||
|
||||
await WriteJsonAsync(response, 200, new
|
||||
{
|
||||
ok = true,
|
||||
state = "ok",
|
||||
code,
|
||||
folder = result.Folder,
|
||||
merged = result.Merged,
|
||||
segments = result.Segments,
|
||||
warnings = result.Warnings,
|
||||
elapsedMs = (int)(DateTime.UtcNow - started).TotalMilliseconds,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
// 「没有可下载的流 / 未登录 / 密码没填」这类,直接把话说清楚
|
||||
await WriteJsonAsync(response, 400, new
|
||||
{
|
||||
ok = false,
|
||||
state = "bad-request",
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"下载录像失败:{ex.Message}");
|
||||
await WriteJsonAsync(response, 500, new
|
||||
{
|
||||
ok = false,
|
||||
state = "error",
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 海康设备通道接口:<c>POST /api/hik/channels</c>(JSON)或 <c>GET /api/hik/channels?host=&port=&user=&password=</c>。
|
||||
///
|
||||
/// 走 HCNetSDK 的 8000 私有协议登录 → 读 <c>NET_DVR_GET_IPPARACFG_V40</c> → 返回通道列表。
|
||||
/// 会话在 <see cref="HikDeviceService"/> 里池化复用,本接口**不会**每次登录。
|
||||
/// </summary>
|
||||
private async Task HandleHikChannelsAsync(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
if (_hik is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string? host = null;
|
||||
string? user = null;
|
||||
string? password = null;
|
||||
var port = 8000;
|
||||
var webPort = 80;
|
||||
|
||||
try
|
||||
{
|
||||
if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (request.ContentLength64 > 8192)
|
||||
{
|
||||
await WriteJsonAsync(response, 413, new { ok = false, message = "请求体过大" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string body;
|
||||
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8))
|
||||
{
|
||||
body = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (body.Trim().Length == 0)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不能为空" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(body);
|
||||
var root = document.RootElement;
|
||||
|
||||
host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip");
|
||||
user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? ReadJsonString(root, "account");
|
||||
password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd");
|
||||
|
||||
if (root.TryGetProperty("port", out var portElement))
|
||||
{
|
||||
if (portElement.ValueKind == JsonValueKind.Number && portElement.TryGetInt32(out var number)) port = number;
|
||||
else if (portElement.ValueKind == JsonValueKind.String && int.TryParse(portElement.GetString(), out var parsed)) port = parsed;
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("webPort", out var webPortElement))
|
||||
{
|
||||
if (webPortElement.ValueKind == JsonValueKind.Number && webPortElement.TryGetInt32(out var webNumber)) webPort = webNumber;
|
||||
else if (webPortElement.ValueKind == JsonValueKind.String && int.TryParse(webPortElement.GetString(), out var webParsed)) webPort = webParsed;
|
||||
}
|
||||
}
|
||||
else if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var query = request.QueryString;
|
||||
host = query["host"] ?? query["ip"];
|
||||
user = query["user"] ?? query["username"];
|
||||
password = query["password"] ?? query["pwd"];
|
||||
if (int.TryParse(query["port"], out var parsed)) port = parsed;
|
||||
if (int.TryParse(query["webPort"], out var parsedWeb)) webPort = parsedWeb;
|
||||
}
|
||||
else
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / GET" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var data = await Task.Run(() => _hik.GetChannels(host ?? string.Empty, port, user ?? string.Empty, password ?? string.Empty, webPort))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
Log?.Invoke($"海康通道读取成功:{data.endpoint},通道 {data.channels.Count} 个,耗时 {data.elapsedMs}ms(会话复用={data.sessionReused})");
|
||||
|
||||
await WriteJsonAsync(response, 200, new
|
||||
{
|
||||
ok = true,
|
||||
state = "ok",
|
||||
data,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false);
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"海康通道读取失败:{ex.Message}");
|
||||
await WriteJsonAsync(response, 502, new
|
||||
{
|
||||
ok = false,
|
||||
state = "hik-error",
|
||||
lastError = ex.ErrorCode,
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"海康通道读取异常:{ex}");
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = "读取通道失败" }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 海康实时预览(`/api/hik/preview*`)
|
||||
///
|
||||
/// 三个动作:
|
||||
/// - <c>POST /api/hik/preview</c>:body `{host, port, user, password, channel, fps?, logicalChannel?}` → 建会话
|
||||
/// - <c>GET /api/hik/preview/snapshot?sid=</c>:单帧 JPEG
|
||||
/// - <c>GET /api/hik/preview/mjpeg?sid=&fps=</c>:<c>multipart/x-mixed-replace</c> 连续帧,浏览器 <c><img></c> 直接能放
|
||||
/// - <c>DELETE /api/hik/preview?sid=</c>:释放会话
|
||||
///
|
||||
/// 为什么用 MJPEG:浏览器不认 RTSP,转 HLS/WebRTC 需要额外转码进程;而
|
||||
/// <c>NET_DVR_CaptureJPEGPicture_NEW</c> 拿到的就是 JPEG,推流侧零依赖。
|
||||
/// </summary>
|
||||
private async Task HandleHikPreviewAsync(HttpListenerRequest request, HttpListenerResponse response, string path)
|
||||
{
|
||||
if (_hik is null || _preview is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var isCreate = path.Equals("/api/hik/preview", StringComparison.OrdinalIgnoreCase);
|
||||
var isClose = path.Equals("/api/hik/preview/close", StringComparison.OrdinalIgnoreCase);
|
||||
var isSnapshot = path.Equals("/api/hik/preview/snapshot", StringComparison.OrdinalIgnoreCase);
|
||||
var isMjpeg = path.Equals("/api/hik/preview/mjpeg", StringComparison.OrdinalIgnoreCase);
|
||||
var isWindow = path.Equals("/api/hik/preview/window", StringComparison.OrdinalIgnoreCase);
|
||||
var isWindowClose = path.Equals("/api/hik/preview/window/close", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isCreate && !isClose && !isSnapshot && !isMjpeg && !isWindow && !isWindowClose)
|
||||
{
|
||||
await WriteJsonAsync(response, 404, new { ok = false, message = "接口不存在" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------- 网页关闭时用 navigator.sendBeacon 释放(只能 POST) ----------
|
||||
if (isClose)
|
||||
{
|
||||
var removed = _preview.Remove(request.QueryString["sid"]);
|
||||
await WriteJsonAsync(response, 200, new { ok = true, removed }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------- 满帧率原生窗口(解码器直接画到窗口,25fps) ----------
|
||||
if (isWindow || isWindowClose)
|
||||
{
|
||||
await HandleHikPreviewWindowAsync(request, response, isWindowClose).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------- 建会话 / 释放会话 ----------
|
||||
if (isCreate)
|
||||
{
|
||||
if (request.HttpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var sidDelete = request.QueryString["sid"];
|
||||
var removed = _preview.Remove(sidDelete);
|
||||
await WriteJsonAsync(response, 200, new { ok = true, removed }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / DELETE" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string host = string.Empty, user = string.Empty, password = string.Empty;
|
||||
var port = 8000;
|
||||
var channel = 0;
|
||||
var fps = 25;
|
||||
int? logicalChannel = null;
|
||||
string? name = null;
|
||||
var streamType = 0; // 0-主码流(默认) 1-子码流
|
||||
var mode = "stream"; // ffmpeg / stream / capture
|
||||
|
||||
try
|
||||
{
|
||||
var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false);
|
||||
if (error is not null)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(body!);
|
||||
var root = document.RootElement;
|
||||
|
||||
host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty;
|
||||
user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? ReadJsonString(root, "account") ?? string.Empty;
|
||||
password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty;
|
||||
name = ReadJsonString(root, "name");
|
||||
|
||||
port = ReadJsonInt(root, "port") ?? 8000;
|
||||
channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0;
|
||||
fps = ReadJsonInt(root, "fps") ?? 25;
|
||||
logicalChannel = ReadJsonInt(root, "logicalChannel");
|
||||
streamType = ReadJsonInt(root, "streamType") ?? 0;
|
||||
|
||||
// mode:ffmpeg(主码流转码)/ stream(SDK 取流解码)/ capture(设备抓帧)
|
||||
var modeText = ReadJsonString(root, "mode");
|
||||
if (!string.IsNullOrWhiteSpace(modeText)) mode = modeText.Trim().ToLowerInvariant();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var session = await Task.Run(() => _preview.Create(host, port, user, password, channel, fps, logicalChannel, name, mode, streamType)).ConfigureAwait(false);
|
||||
|
||||
Log?.Invoke($"预览开始:{session.Host}:{session.Port} 通道 {session.Channel}(码流 {session.StreamId},{session.Fps}fps,{session.Mode},sid={session.Id})");
|
||||
|
||||
await WriteJsonAsync(response, 200, new
|
||||
{
|
||||
ok = true,
|
||||
state = "ok",
|
||||
data = new
|
||||
{
|
||||
sid = session.Id,
|
||||
host = session.Host,
|
||||
port = session.Port,
|
||||
channel = session.Channel,
|
||||
logicalChannel = session.LogicalChannel,
|
||||
streamId = session.StreamId,
|
||||
fps = session.Fps,
|
||||
name = session.Name,
|
||||
// stream/ffmpeg = 可到 25fps;capture = 设备抓帧(约 5fps)
|
||||
mode = session.Mode,
|
||||
streamType = session.StreamType,
|
||||
maxFps = session.Mode == "capture" ? 5 : 25,
|
||||
ffmpegAvailable = _ffmpeg?.IsAvailable ?? false,
|
||||
warning = session.Warning,
|
||||
rtspUrl = session.RtspUrl,
|
||||
mjpegUrl = $"/api/hik/preview/mjpeg?sid={session.Id}",
|
||||
snapshotUrl = $"/api/hik/preview/snapshot?sid={session.Id}",
|
||||
expireAt = session.ExpiresAt.ToString("yyyy-MM-dd HH:mm:ss"),
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"预览建会话失败:{ex.Message}");
|
||||
await WriteJsonAsync(response, 502, new
|
||||
{
|
||||
ok = false,
|
||||
state = "hik-error",
|
||||
lastError = ex.ErrorCode,
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"预览建会话异常:{ex}");
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = "建立预览会话失败" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 以下需要 sid ----------
|
||||
if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var sid = request.QueryString["sid"];
|
||||
var sessionNow = _preview.Get(sid);
|
||||
if (sessionNow is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 404, new
|
||||
{
|
||||
ok = false,
|
||||
state = "session-expired",
|
||||
message = "预览会话不存在或已过期,请重新打开预览",
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSnapshot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var jpeg = await Task.Run(() => _preview.CaptureFrame(sessionNow)).ConfigureAwait(false);
|
||||
response.StatusCode = 200;
|
||||
response.ContentType = "image/jpeg";
|
||||
response.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate";
|
||||
response.ContentLength64 = jpeg.Length;
|
||||
await response.OutputStream.WriteAsync(jpeg).ConfigureAwait(false);
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"预览快照失败:{ex.Message}");
|
||||
await WriteJsonAsync(response, 502, new { ok = false, state = "hik-error", lastError = ex.ErrorCode, message = ex.Message }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await WriteMjpegAsync(request, response, sessionNow).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 连续推 JPEG 帧:<c>multipart/x-mixed-replace</c>
|
||||
///
|
||||
/// 浏览器(Chrome/Edge)对 MJPEG 的 <c><img></c> 支持一直很稳;
|
||||
/// 客户端一关页面写入就会抛 IO 异常,这里直接停止抓帧,避免空转。
|
||||
/// </summary>
|
||||
private async Task WriteMjpegAsync(HttpListenerRequest request, HttpListenerResponse response, HikPreviewSession session)
|
||||
{
|
||||
if (_preview is null) return;
|
||||
|
||||
// 允许浏览器用 ?fps= 临时降/提帧(大屏 10fps 就够,看细节可到 25)
|
||||
var fpsOverride = int.TryParse(request.QueryString["fps"], out var parsed) ? parsed : 0;
|
||||
var fps = Math.Clamp(fpsOverride > 0 ? fpsOverride : session.Fps, 1, 25);
|
||||
var frameInterval = 1000.0 / fps; // 毫秒/帧
|
||||
|
||||
response.StatusCode = 200;
|
||||
response.ContentType = "multipart/x-mixed-replace; boundary=frame";
|
||||
response.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate";
|
||||
response.Headers["Pragma"] = "no-cache";
|
||||
response.SendChunked = true;
|
||||
|
||||
var output = response.OutputStream;
|
||||
var crlf = Encoding.ASCII.GetBytes("\r\n");
|
||||
|
||||
// 按「绝对时间轴」配速(不是每帧之后再睡 40ms):
|
||||
// 抓帧本身约 33ms,若写成 sleep(间隔 - 耗时) 会累积误差,实测只有 ~21fps;绝对时间轴能锁住 25fps。
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
var nextFrameAt = 0.0;
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
// 会话过期(30 分钟没人看)或被 DELETE 掉就收工
|
||||
if (_preview.Get(session.Id) is null) break;
|
||||
|
||||
byte[] jpeg;
|
||||
try
|
||||
{
|
||||
jpeg = await Task.Run(() => _preview.CaptureFrame(session)).ConfigureAwait(false);
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"预览中断:通道 {session.Channel} {ex.Message}");
|
||||
break;
|
||||
}
|
||||
|
||||
// 解码端口刚起来时可能还没出帧,跳过这轮即可(不要断流)
|
||||
if (jpeg.Length == 0)
|
||||
{
|
||||
await Task.Delay(15).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
var header = Encoding.ASCII.GetBytes(
|
||||
$"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {jpeg.Length}\r\n\r\n");
|
||||
|
||||
await output.WriteAsync(header).ConfigureAwait(false);
|
||||
await output.WriteAsync(jpeg).ConfigureAwait(false);
|
||||
await output.WriteAsync(crlf).ConfigureAwait(false);
|
||||
await output.FlushAsync().ConfigureAwait(false);
|
||||
|
||||
nextFrameAt += frameInterval;
|
||||
var delay = nextFrameAt - clock.Elapsed.TotalMilliseconds;
|
||||
if (delay > 0) await Task.Delay((int)Math.Round(delay)).ConfigureAwait(false);
|
||||
else nextFrameAt = clock.Elapsed.TotalMilliseconds; // 已经落后就不追,重新对齐
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 浏览器关掉预览(img 换 src / 关弹窗)→ 写入失败,属于正常结束
|
||||
Log?.Invoke($"预览流结束:通道 {session.Channel}({ex.GetType().Name})");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { response.Abort(); } catch { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读 JSON 请求体(超过 8KB 或为空都算错误)</summary>
|
||||
private static async Task<(string? Body, string? Error)> ReadJsonBodyAsync(HttpListenerRequest request)
|
||||
{
|
||||
if (request.ContentLength64 > 8192) return (null, "请求体过大");
|
||||
|
||||
using var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8);
|
||||
var body = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
if (body.Trim().Length == 0) return (null, "请求体不能为空");
|
||||
|
||||
return (body, null);
|
||||
}
|
||||
|
||||
private static int? ReadJsonInt(JsonElement root, string name)
|
||||
{
|
||||
if (!root.TryGetProperty(name, out var element)) return null;
|
||||
|
||||
if (element.ValueKind == JsonValueKind.Number && element.TryGetInt32(out var number)) return number;
|
||||
if (element.ValueKind == JsonValueKind.String && int.TryParse(element.GetString(), out var parsed)) return parsed;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 满帧率原生窗口:<c>POST /api/hik/preview/window</c> 打开,<c>DELETE ...?wid=</c> 关闭
|
||||
///
|
||||
/// 浏览器内嵌画面必须逐帧转 JPEG,1080p 每帧编码约 140ms(上限约 7fps);
|
||||
/// 这个接口让 PlayM4 直接把画面画到一个原生窗口,能跑满设备帧率(25fps)。
|
||||
/// </summary>
|
||||
private async Task HandleHikPreviewWindowAsync(HttpListenerRequest request, HttpListenerResponse response, bool isClose)
|
||||
{
|
||||
if (_native is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 关窗口:DELETE 或 POST(后者给 navigator.sendBeacon 用,它只能发 POST)
|
||||
if (isClose || request.HttpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var wid = request.QueryString["wid"];
|
||||
var closed = _native.Close(wid);
|
||||
await WriteJsonAsync(response, 200, new { ok = true, closed }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / DELETE" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string host = string.Empty, user = string.Empty, password = string.Empty;
|
||||
var port = 8000;
|
||||
var channel = 0;
|
||||
var streamType = 0;
|
||||
string? name = null;
|
||||
|
||||
try
|
||||
{
|
||||
var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false);
|
||||
if (error is not null)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(body!);
|
||||
var root = document.RootElement;
|
||||
|
||||
host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty;
|
||||
user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? string.Empty;
|
||||
password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty;
|
||||
name = ReadJsonString(root, "name");
|
||||
port = ReadJsonInt(root, "port") ?? 8000;
|
||||
channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0;
|
||||
streamType = ReadJsonInt(root, "streamType") ?? 1;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var preview = _native.Open(host, port, user, password, channel, streamType, name);
|
||||
|
||||
await WriteJsonAsync(response, 200, new
|
||||
{
|
||||
ok = true,
|
||||
state = "ok",
|
||||
data = new
|
||||
{
|
||||
wid = preview.Id,
|
||||
host = preview.Host,
|
||||
channel = preview.Channel,
|
||||
streamType = preview.StreamType,
|
||||
mode = "window",
|
||||
fps = 25,
|
||||
message = "已在本机软件里打开满帧率预览窗口",
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false);
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"满帧率预览失败:{ex.Message}");
|
||||
await WriteJsonAsync(response, 502, new
|
||||
{
|
||||
ok = false,
|
||||
state = "hik-error",
|
||||
lastError = ex.ErrorCode,
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"满帧率预览异常:{ex}");
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = $"打开预览窗口失败:{ex.Message}" }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 云台控制:<c>POST /api/hik/ptz</c> / <c>POST /api/hik/ptz/preset</c>
|
||||
///
|
||||
/// body:<c>{host, port, user, password, channel, command?, stop?, speed?, action?, preset?}</c>
|
||||
/// - <c>command</c>:up/down/left/right/up-left/up-right/down-left/down-right/zoom-in/zoom-out/
|
||||
/// focus-near/focus-far/iris-open/iris-close/auto(自动扫描)
|
||||
/// - <c>stop</c>:true 停止(页面松开按钮时发);方向类是“开始 + 停止”成对调用
|
||||
/// - 预置点:<c>action</c>=set/goto/clear,<c>preset</c>=1~256
|
||||
///
|
||||
/// 走 <c>NET_DVR_PTZControlWithSpeed_Other</c>,不需要开预览也能控。
|
||||
/// </summary>
|
||||
private async Task HandleHikPtzAsync(HttpListenerRequest request, HttpListenerResponse response, string path)
|
||||
{
|
||||
if (_hik is null)
|
||||
{
|
||||
await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string host = string.Empty, user = string.Empty, password = string.Empty;
|
||||
var port = 8000;
|
||||
var channel = 0;
|
||||
var speed = 4;
|
||||
string? command = null;
|
||||
string? action = null;
|
||||
var preset = 0;
|
||||
var stop = false;
|
||||
|
||||
try
|
||||
{
|
||||
var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false);
|
||||
if (error is not null)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(body!);
|
||||
var root = document.RootElement;
|
||||
|
||||
host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty;
|
||||
user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? string.Empty;
|
||||
password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty;
|
||||
command = ReadJsonString(root, "command");
|
||||
action = ReadJsonString(root, "action");
|
||||
port = ReadJsonInt(root, "port") ?? 8000;
|
||||
channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0;
|
||||
speed = ReadJsonInt(root, "speed") ?? 4;
|
||||
preset = ReadJsonInt(root, "preset") ?? 0;
|
||||
|
||||
if (root.TryGetProperty("stop", out var stopElement))
|
||||
{
|
||||
stop = stopElement.ValueKind switch
|
||||
{
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
JsonValueKind.Number => stopElement.TryGetInt32(out var number) && number != 0,
|
||||
JsonValueKind.String => string.Equals(stopElement.GetString(), "true", StringComparison.OrdinalIgnoreCase),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var isPreset = path.EndsWith("/preset", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
if (isPreset)
|
||||
{
|
||||
_hik.PtzPreset(host, port, user, password, channel, action ?? string.Empty, preset);
|
||||
}
|
||||
else
|
||||
{
|
||||
_hik.PtzControl(host, port, user, password, channel, command ?? string.Empty, stop, speed);
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
await WriteJsonAsync(response, 200, new
|
||||
{
|
||||
ok = true,
|
||||
state = "ok",
|
||||
data = new { channel, command, action, preset, stop },
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false);
|
||||
}
|
||||
catch (HikException ex)
|
||||
{
|
||||
Log?.Invoke($"云台操作失败(通道 {channel}):{ex.Message}");
|
||||
await WriteJsonAsync(response, 502, new
|
||||
{
|
||||
ok = false,
|
||||
state = "hik-error",
|
||||
lastError = ex.ErrorCode,
|
||||
message = ex.Message,
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"云台操作异常:{ex}");
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = "云台操作失败" }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ReadJsonString(JsonElement root, string name)
|
||||
=> root.TryGetProperty(name, out var element) && element.ValueKind == JsonValueKind.String
|
||||
? element.GetString()
|
||||
: null;
|
||||
|
||||
/// <summary>CORS + 私有网络访问(PNA)头</summary>
|
||||
private static void WriteCorsHeaders(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
@ -286,7 +1105,8 @@ public sealed class LocalHttpServer : IDisposable
|
||||
var origin = request.Headers["Origin"];
|
||||
response.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(origin) ? "*" : origin;
|
||||
response.Headers["Vary"] = "Origin";
|
||||
response.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
|
||||
// DELETE 用于关闭预览会话;漏了它浏览器预检直接失败(实测现象:关弹窗时 console 报 CORS)
|
||||
response.Headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS";
|
||||
response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Accept";
|
||||
response.Headers["Access-Control-Max-Age"] = "600";
|
||||
|
||||
@ -325,6 +1145,10 @@ public sealed class LocalHttpServer : IDisposable
|
||||
{
|
||||
Stop();
|
||||
_cts?.Dispose();
|
||||
_native?.Dispose();
|
||||
_preview?.Dispose();
|
||||
_ffmpeg?.Dispose();
|
||||
_stream?.Dispose();
|
||||
_listener.Close();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>一次查询的结果(HTTP 层和界面都复用)</summary>
|
||||
/// <param name="Ok">是否查到</param>
|
||||
/// <param name="StatusCode">HTTP 状态码(200 / 400 / 404 / 500)</param>
|
||||
/// <param name="StatusCode">HTTP 状态码(200 / 400 / 401 / 404 / 500)</param>
|
||||
/// <param name="Message">失败原因</param>
|
||||
/// <param name="Data">成功时的数据(**平铺**一个对象,前端按「项目/值」两列直接渲染)</param>
|
||||
public sealed record QueryResult(bool Ok, int StatusCode, string Message, object? Data)
|
||||
@ -20,32 +24,89 @@ public sealed record QueryResult(bool Ok, int StatusCode, string Message, object
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按运单号查信息
|
||||
/// 查询结果的两副面孔
|
||||
///
|
||||
/// ⚠️ **这里是接你们真实数据的地方**:现在返回演示数据(任何 code 都返回同一份)。
|
||||
/// 真实实现通常是:查本地 SQLite / 扫描本地打包视频目录 / 调内部接口,
|
||||
/// 然后把结果按字段平铺返回(前端页面按 key-value 展示,字段随你加)。
|
||||
/// - <see cref="Http"/>:给网页 `/local` 页用的「项目 / 值」扁平字典;
|
||||
/// - <see cref="Query"/>:给桌面端用的结构化对象(校验回放 / 拉流 / 下载都要它)。
|
||||
/// </summary>
|
||||
public sealed record PackQueryOutcome(QueryResult Http, PackQuery? Query);
|
||||
|
||||
/// <summary>
|
||||
/// 按运单号查「回放计划」
|
||||
///
|
||||
/// 数据来自后端 `GET /api/web/pack-query?code=`(**范围限定当前主体**):
|
||||
/// 后端用**扫码当时的工作台快照**算好「去哪个录像机的哪个通道、拉哪一段时间、画面怎么摆」,
|
||||
/// 本机负责展示 + 真正去录像机上校验/拉流。
|
||||
/// </summary>
|
||||
public sealed class OrderQueryService
|
||||
{
|
||||
public QueryResult Query(string? code)
|
||||
private readonly Func<ApiClient?>? _api;
|
||||
private readonly Func<int>? _subjectId;
|
||||
private readonly Func<string?>? _token;
|
||||
|
||||
/// <param name="apiProvider">后端客户端(登录后才有;未登录返回 null,查询会直接回「未登录」)</param>
|
||||
/// <param name="subjectIdProvider">当前主体 id(登录后由设置里取)</param>
|
||||
/// <param name="tokenProvider">当前用户令牌</param>
|
||||
public OrderQueryService(Func<ApiClient?>? apiProvider = null, Func<int>? subjectIdProvider = null,
|
||||
Func<string?>? tokenProvider = null)
|
||||
{
|
||||
_api = apiProvider;
|
||||
_subjectId = subjectIdProvider;
|
||||
_token = tokenProvider;
|
||||
}
|
||||
|
||||
/// <summary>按运单号查回放计划(需要用户令牌 + 当前主体)</summary>
|
||||
public async Task<PackQueryOutcome> QueryAsync(string? code, CancellationToken ct = default)
|
||||
{
|
||||
var value = (code ?? string.Empty).Trim();
|
||||
if (value.Length == 0) return QueryResult.BadRequest("缺少运单号");
|
||||
if (value.Length == 0) return new PackQueryOutcome(QueryResult.BadRequest("缺少运单号"), null);
|
||||
|
||||
// ↓↓↓ 换成真实查询逻辑 ↓↓↓
|
||||
var data = new Dictionary<string, object?>
|
||||
var api = _api?.Invoke();
|
||||
var token = _token?.Invoke();
|
||||
if (api is null || string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
["code"] = value,
|
||||
["orderNo"] = "SO-20261017-001",
|
||||
["channel"] = "CH-1",
|
||||
["printStatus"] = "已打印",
|
||||
["scanTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
|
||||
["videoPath"] = @"D:\video\2026-10-17\demo.mp4",
|
||||
["source"] = "演示数据(请替换 OrderQueryService.Query)",
|
||||
};
|
||||
// ↑↑↑ 换成真实查询逻辑 ↑↑↑
|
||||
return new PackQueryOutcome(QueryResult.Failed("本机软件未登录,无法查询"), null);
|
||||
}
|
||||
|
||||
return QueryResult.Success(data);
|
||||
var subjectId = _subjectId?.Invoke() ?? 0;
|
||||
if (subjectId <= 0) return new PackQueryOutcome(QueryResult.BadRequest("还没有选择主体,无法查询"), null);
|
||||
|
||||
JsonElement data;
|
||||
try
|
||||
{
|
||||
data = await api.PackQueryAsync(token!, subjectId, value, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (ApiException ex)
|
||||
{
|
||||
// 401/403 就是登录态失效,别当成服务器错误
|
||||
var status = ex.StatusCode is 401 or 403 ? 401 : 500;
|
||||
return new PackQueryOutcome(new QueryResult(false, status, ex.Message, null), null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new PackQueryOutcome(QueryResult.Failed(ex.Message), null);
|
||||
}
|
||||
|
||||
var query = PackQuery.Parse(value, data);
|
||||
|
||||
// ⚠️ 不要在这里打完整 JSON:一条记录几 KB,扫码密集时日志一天能到几十 MB。
|
||||
// 只记结论,排障需要细节看后端日志 / 页面。
|
||||
AppLog.Write($"[pack-query] {value} → found={query.Found} reason={query.Reason} "
|
||||
+ $"records={query.Records.Count} streams={query.Streams.Count}");
|
||||
|
||||
if (!query.Found)
|
||||
{
|
||||
// reason:not-found(本主体没扫过)/ foreign(运单存在但属于别的主体)
|
||||
var message = query.Reason == "foreign"
|
||||
? "这个运单号存在,但属于其他主体,当前主体查不到"
|
||||
: query.Hints.FirstOrDefault() ?? "没有查到该运单的扫码记录";
|
||||
return new PackQueryOutcome(QueryResult.NotFound(message), null);
|
||||
}
|
||||
|
||||
// 网页 /local 页吃的是「项目 / 值」(与桌面端共用同一份 ToRows,不会各说一套)
|
||||
var rows = new Dictionary<string, object?>();
|
||||
foreach (var row in query.ToRows()) rows[row.Key] = row.Value;
|
||||
|
||||
return new PackQueryOutcome(QueryResult.Success(rows), query);
|
||||
}
|
||||
}
|
||||
|
||||
301
desktop/Services/PackQuery.cs
Normal file
301
desktop/Services/PackQuery.cs
Normal file
@ -0,0 +1,301 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>摄像头在合成画布上的位置(后端快照里的 layout)</summary>
|
||||
public sealed record PackLayout(int X, int Y, int Width, int Height, int SortNo, int ZIndex);
|
||||
|
||||
/// <summary>一路回放流:去哪个录像机的哪个通道、拉哪一段时间</summary>
|
||||
public sealed record PackStream(
|
||||
int NvrId,
|
||||
string NvrName,
|
||||
string NvrHost,
|
||||
int NvrPort,
|
||||
string NvrUsername,
|
||||
int ChannelNo,
|
||||
int CameraId,
|
||||
string CameraName,
|
||||
int StreamType,
|
||||
PackLayout Layout,
|
||||
int CanvasWidth,
|
||||
int CanvasHeight,
|
||||
DateTimeOffset StartTime,
|
||||
DateTimeOffset EndTime)
|
||||
{
|
||||
public int DurationSec => (int)Math.Round((EndTime - StartTime).TotalSeconds);
|
||||
|
||||
/// <summary>给人看的名字,如「打包台1-通道34(通道34)」</summary>
|
||||
public string DisplayName => string.IsNullOrWhiteSpace(CameraName)
|
||||
? $"通道{ChannelNo}"
|
||||
: $"{CameraName}(通道{ChannelNo})";
|
||||
}
|
||||
|
||||
/// <summary>一条扫码记录的回放计划</summary>
|
||||
public sealed record PackRecord(
|
||||
long Id,
|
||||
DateTimeOffset ScanTime,
|
||||
string ChannelId,
|
||||
string ChannelName,
|
||||
string DeviceSn,
|
||||
string WorkstationName,
|
||||
string WorkstationCode,
|
||||
string Kind,
|
||||
DateTimeOffset? StartTime,
|
||||
DateTimeOffset? EndTime,
|
||||
int DurationSec,
|
||||
IReadOnlyList<PackStream> Streams)
|
||||
{
|
||||
public string KindName => Kind switch
|
||||
{
|
||||
"group" => "团购(扫码时间前后各留余量)",
|
||||
"scatter" => "散单(扫码 = 开始,下一次扫码 = 结束)",
|
||||
_ => "未知工作台类型",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// `GET /api/web/pack-query` 的结构化结果
|
||||
///
|
||||
/// 之前是直接拍成「项目:值」的文本给界面看,做回放校验/预览/下载时不够用,
|
||||
/// 所以解析成强类型:界面显示走 <see cref="Render"/>,拉流走 <see cref="Streams"/>。
|
||||
/// </summary>
|
||||
public sealed record PackQuery(
|
||||
string Code,
|
||||
bool Found,
|
||||
bool Playback,
|
||||
string Reason,
|
||||
IReadOnlyList<string> Hints,
|
||||
IReadOnlyList<PackRecord> Records,
|
||||
IReadOnlyList<DateTimeOffset> UnboundTimes,
|
||||
IReadOnlyList<PackStream> Streams)
|
||||
{
|
||||
/// <summary>
|
||||
/// 拍成「项目 / 值」两列
|
||||
///
|
||||
/// 同一个列表同时喂两边:桌面端拼成多行文本(<see cref="Render"/>),
|
||||
/// 网页 `/local` 页当 key-value 表格渲染 —— 两处显示不会各说一套。
|
||||
/// </summary>
|
||||
public IReadOnlyList<KeyValuePair<string, string>> ToRows()
|
||||
{
|
||||
var rows = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new("运单号", Code),
|
||||
new("扫码记录数", (Records.Count + UnboundTimes.Count).ToString()),
|
||||
};
|
||||
|
||||
if (UnboundTimes.Count > 0)
|
||||
{
|
||||
rows.Add(new("绑定工作台", $"无({string.Join("、", UnboundTimes.Select(FormatTime))})"));
|
||||
}
|
||||
|
||||
for (var i = 0; i < Records.Count; i++)
|
||||
{
|
||||
var record = Records[i];
|
||||
var prefix = Records.Count == 1 ? string.Empty : $"记录 {i + 1} · ";
|
||||
|
||||
rows.Add(new($"{prefix}扫码时间", FormatTime(record.ScanTime)));
|
||||
|
||||
var channel = string.IsNullOrWhiteSpace(record.ChannelName)
|
||||
? $"{record.DeviceSn} / {record.ChannelId}"
|
||||
: $"{record.DeviceSn} / {record.ChannelId}({record.ChannelName})";
|
||||
rows.Add(new($"{prefix}中控 / 通道", channel));
|
||||
|
||||
var workstation = string.IsNullOrWhiteSpace(record.WorkstationCode)
|
||||
? $"{record.WorkstationName} · {record.KindName}"
|
||||
: $"{record.WorkstationName}({record.WorkstationCode})· {record.KindName}";
|
||||
rows.Add(new($"{prefix}工作台", workstation));
|
||||
|
||||
rows.Add(new($"{prefix}回放区间", record.StartTime is not null && record.EndTime is not null
|
||||
? $"{FormatTime(record.StartTime.Value)} ~ {FormatTime(record.EndTime.Value)}({record.DurationSec} 秒)"
|
||||
: "无法确定(见说明)"));
|
||||
|
||||
if (record.Streams.Count == 0)
|
||||
{
|
||||
rows.Add(new($"{prefix}录像机", "—"));
|
||||
rows.Add(new($"{prefix}摄像头", "没有可拉的回放流(工作台没绑摄像头)"));
|
||||
}
|
||||
else
|
||||
{
|
||||
var nvrs = record.Streams
|
||||
.GroupBy(item => $"{item.NvrHost}:{item.NvrPort}")
|
||||
.Select(group => string.IsNullOrWhiteSpace(group.First().NvrName)
|
||||
? group.Key
|
||||
: $"{group.First().NvrName} {group.Key}");
|
||||
rows.Add(new($"{prefix}录像机", string.Join(";", nvrs)));
|
||||
|
||||
var cameras = record.Streams.Select(item =>
|
||||
{
|
||||
var where = item.CanvasWidth <= 0
|
||||
? string.Empty
|
||||
: $"({item.CanvasWidth}×{item.CanvasHeight} @ {item.Layout.X},{item.Layout.Y} "
|
||||
+ $"{item.Layout.Width}×{item.Layout.Height})";
|
||||
return $"通道{item.ChannelNo} {item.CameraName}{where}";
|
||||
});
|
||||
rows.Add(new($"{prefix}摄像头", string.Join(";", cameras)));
|
||||
}
|
||||
}
|
||||
|
||||
// 「通道没绑工作台」已经在上面单独一行说过了,这里不再重复
|
||||
var rest = Hints.Where(item => !item.Contains("没有绑定工作台")).ToList();
|
||||
if (rest.Count > 0) rows.Add(new("说明", string.Join(" ", rest)));
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>拍成多行文本(桌面端文本框用)</summary>
|
||||
public string Render()
|
||||
=> string.Join(Environment.NewLine, ToRows().Select(row => $"{row.Key}:{row.Value}"));
|
||||
|
||||
private static string FormatTime(DateTimeOffset value) => value.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
// ==================== 解析 ====================
|
||||
|
||||
public static PackQuery Parse(string code, JsonElement data)
|
||||
{
|
||||
var found = data.TryGetProperty("found", out var foundElement) && foundElement.ValueKind == JsonValueKind.True;
|
||||
var playback = data.TryGetProperty("playback", out var playbackElement) && playbackElement.ValueKind == JsonValueKind.True;
|
||||
|
||||
var records = new List<PackRecord>();
|
||||
foreach (var item in ReadArray(data, "records"))
|
||||
{
|
||||
var plan = Get(item, "plan");
|
||||
var snapshot = Get(item, "snapshot");
|
||||
var workstation = Get(snapshot, "workstation");
|
||||
|
||||
records.Add(new PackRecord(
|
||||
GetLong(item, "id"),
|
||||
ReadTime(Get(item, "scanTime")) ?? DateTimeOffset.MinValue,
|
||||
GetString(item, "channelId") ?? string.Empty,
|
||||
GetString(item, "channelName") ?? string.Empty,
|
||||
GetString(item, "deviceSn") ?? string.Empty,
|
||||
GetString(workstation, "name") ?? string.Empty,
|
||||
GetString(workstation, "code") ?? string.Empty,
|
||||
GetString(plan, "kind") ?? string.Empty,
|
||||
ReadTime(Get(plan, "startTime")),
|
||||
ReadTime(Get(plan, "endTime")),
|
||||
GetInt(plan, "durationSec"),
|
||||
ReadStreams(ReadArray(plan, "streams"))));
|
||||
}
|
||||
|
||||
var unbound = ReadArray(data, "skipped")
|
||||
.Select(item => ReadTime(Get(item, "scanTime")))
|
||||
.Where(item => item is not null)
|
||||
.Select(item => item!.Value)
|
||||
.ToList();
|
||||
|
||||
return new PackQuery(
|
||||
code,
|
||||
found,
|
||||
playback,
|
||||
GetString(data, "reason") ?? string.Empty,
|
||||
ReadStrings(data, "hints"),
|
||||
records,
|
||||
unbound,
|
||||
ReadStreams(ReadArray(data, "streams")));
|
||||
}
|
||||
|
||||
private static List<PackStream> ReadStreams(IEnumerable<JsonElement> items)
|
||||
{
|
||||
var list = new List<PackStream>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
var layout = Get(item, "layout");
|
||||
var start = ReadTime(Get(item, "startTime"));
|
||||
var end = ReadTime(Get(item, "endTime"));
|
||||
if (start is null || end is null) continue;
|
||||
|
||||
list.Add(new PackStream(
|
||||
GetInt(item, "nvrId"),
|
||||
GetString(item, "nvrName") ?? string.Empty,
|
||||
GetString(item, "nvrHost") ?? string.Empty,
|
||||
GetInt(item, "nvrPort"),
|
||||
GetString(item, "nvrUsername") ?? "admin",
|
||||
GetInt(item, "channelNo"),
|
||||
GetInt(item, "cameraId"),
|
||||
GetString(item, "cameraName") ?? string.Empty,
|
||||
GetInt(item, "streamType"),
|
||||
new PackLayout(
|
||||
GetInt(layout, "x"), GetInt(layout, "y"),
|
||||
GetInt(layout, "width"), GetInt(layout, "height"),
|
||||
GetInt(layout, "sortNo"), GetInt(layout, "zIndex")),
|
||||
GetInt(item, "canvasWidth"),
|
||||
GetInt(item, "canvasHeight"),
|
||||
start.Value,
|
||||
end.Value));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// ==================== JSON 小工具 ====================
|
||||
|
||||
private static JsonElement? Get(JsonElement? element, string property)
|
||||
{
|
||||
if (element is not { ValueKind: JsonValueKind.Object } obj) return null;
|
||||
return obj.TryGetProperty(property, out var value) ? value : null;
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement? element, string property)
|
||||
{
|
||||
var value = Get(element, property);
|
||||
return value is { ValueKind: JsonValueKind.String } ? value.Value.GetString() : null;
|
||||
}
|
||||
|
||||
private static long GetLong(JsonElement? element, string property)
|
||||
{
|
||||
var value = Get(element, property);
|
||||
return value is { ValueKind: JsonValueKind.Number } && value.Value.TryGetInt64(out var number) ? number : 0;
|
||||
}
|
||||
|
||||
private static int GetInt(JsonElement? element, string property)
|
||||
{
|
||||
var value = Get(element, property);
|
||||
if (value is null) return 0;
|
||||
return value.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number => value.Value.TryGetInt32(out var number) ? number : 0,
|
||||
JsonValueKind.String => int.TryParse(value.Value.GetString(), out var parsed) ? parsed : 0,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
private static List<JsonElement> ReadArray(JsonElement? element, string property)
|
||||
{
|
||||
var value = Get(element, property);
|
||||
if (value is null || value.Value.ValueKind != JsonValueKind.Array) return new List<JsonElement>();
|
||||
return value.Value.EnumerateArray().ToList();
|
||||
}
|
||||
|
||||
private static List<string> ReadStrings(JsonElement? element, string property)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (var item in ReadArray(element, property))
|
||||
{
|
||||
if (item.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var text = item.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(text)) list.Add(text!);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>后端给的是 UTC ISO(`2026-10-18T14:09:47.000Z`)</summary>
|
||||
private static DateTimeOffset? ReadTime(JsonElement? element)
|
||||
{
|
||||
if (element is not { ValueKind: JsonValueKind.String }) return null;
|
||||
|
||||
var text = element.Value.GetString();
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
|
||||
if (DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed))
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
380
desktop/Services/Scan/ChannelConnection.cs
Normal file
380
desktop/Services/Scan/ChannelConnection.cs
Normal file
@ -0,0 +1,380 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
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;
|
||||
|
||||
private readonly ScanChannel _channel;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
|
||||
/// <summary>串行化写:下发扫码枪设置要一次写完,不能被重连/其它写方打新</summary>
|
||||
private readonly SemaphoreSlim _writeGate = new(1, 1);
|
||||
|
||||
/// <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 && _channel.Enabled && !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>
|
||||
/// 连上之后立刻把扫码枪配成「连续扫描 + 间隔 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;
|
||||
|
||||
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];
|
||||
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 (_channel.Connected == connected) return;
|
||||
|
||||
_channel.Connected = connected;
|
||||
StateChanged?.Invoke(_channel, connected);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
504
desktop/Services/Scan/DeviceConfig.cs
Normal file
504
desktop/Services/Scan/DeviceConfig.cs
Normal file
@ -0,0 +1,504 @@
|
||||
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;
|
||||
}
|
||||
302
desktop/Services/Scan/DeviceScanner.cs
Normal file
302
desktop/Services/Scan/DeviceScanner.cs
Normal file
@ -0,0 +1,302 @@
|
||||
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>设备 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>
|
||||
private 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
272
desktop/Services/Scan/DiscoveryMonitor.cs
Normal file
272
desktop/Services/Scan/DiscoveryMonitor.cs
Normal file
@ -0,0 +1,272 @@
|
||||
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 口一直听」)。
|
||||
///
|
||||
/// 为什么不能只 bind 48899 被动收:**设备不会主动广播**(实测绑 48899 静听 40 秒,
|
||||
/// 只能收到我们自己发出去的探测包),它只回**探测者**,而且回复发到**发送方的源端口**
|
||||
/// (见 AndroidScanCenter/docs/udp-48899-protocol.md),所以在 48899 上 bind 收不到回复。
|
||||
///
|
||||
/// 所以做法是:**一个 socket 一直开着**,每 <see cref="ProbeIntervalMs"/> 毫秒往
|
||||
/// `255.255.255.255` + 各网段定向广播发一次探测,然后在这**同一个 socket** 上持续收,
|
||||
/// 按 MAC 合并、超过 <see cref="DeviceTimeoutMs"/> 没见过就摘掉。
|
||||
/// 这样界面是「一进来就在刷」的连续感,而不是「扫一轮停 5 秒」的一截一截。
|
||||
/// </summary>
|
||||
public sealed class DiscoveryMonitor : IDisposable
|
||||
{
|
||||
/// <summary>多久探测一次(设备回包通常几十毫秒就回来)</summary>
|
||||
private const int ProbeIntervalMs = 3000;
|
||||
|
||||
/// <summary>多久没再见到就算掉线(比探测间隔大,扛得住偶尔丢包)</summary>
|
||||
private const int DeviceTimeoutMs = 12000;
|
||||
|
||||
private readonly DeviceScanner _scanner = new();
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Dictionary<string, (DiscoveredDevice Device, DateTime LastSeen)> _devices =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private Task? _loop;
|
||||
|
||||
/// <summary>设备列表有变化(新增/更新/掉线)</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>当前看到的设备(按 MAC 排序的快照)</summary>
|
||||
public IReadOnlyList<DiscoveredDevice> Devices
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_devices)
|
||||
{
|
||||
return _devices.Values.Select(item => item.Device)
|
||||
.OrderBy(item => item.Mac, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_loop is not null) return;
|
||||
_loop = Task.Run(() => LoopAsync(_cts.Token));
|
||||
AppLog.Write("[scan] 设备发现已开始(常驻 UDP,每 3 秒探测一次)");
|
||||
}
|
||||
|
||||
private async Task LoopAsync(CancellationToken ct)
|
||||
{
|
||||
using var udp = new UdpClient(AddressFamily.InterNetwork);
|
||||
udp.EnableBroadcast = true;
|
||||
|
||||
var targets = BroadcastTargets();
|
||||
var payload = ScanProtocol.Utf8(ScanProtocol.BroadcastPayload);
|
||||
var nextProbe = DateTime.MinValue;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
|
||||
// 到点就探测一次(同一个 socket 发,回复才会回到这里)
|
||||
if (now >= nextProbe)
|
||||
{
|
||||
foreach (var target in targets)
|
||||
{
|
||||
try
|
||||
{
|
||||
await udp.SendAsync(payload, payload.Length, new IPEndPoint(target, ScanProtocol.UdpPort))
|
||||
.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[scan] 广播到 {target} 失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
nextProbe = now.AddMilliseconds(ProbeIntervalMs);
|
||||
}
|
||||
|
||||
// 一直收:每次最多等 500ms,收完继续等(不关 socket、不留空档)
|
||||
try
|
||||
{
|
||||
UdpReceiveResult? received = null;
|
||||
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
|
||||
{
|
||||
timeout.CancelAfter(500);
|
||||
try
|
||||
{
|
||||
received = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
// 500ms 没包,很正常(没设备回 / 本轮已收完)
|
||||
}
|
||||
}
|
||||
|
||||
if (received is not null) HandleReply(received.Value);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[scan] 收发现回复失败(忽略):{ex.Message}");
|
||||
}
|
||||
|
||||
PruneStale();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>解析一条发现回复(按 MAC 合并;同一条会回多包,无所谓)</summary>
|
||||
private void HandleReply(UdpReceiveResult reply)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
text = Encoding.UTF8.GetString(reply.Buffer);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!text.TrimStart().StartsWith('{')) return;
|
||||
|
||||
string mac;
|
||||
DiscoveredDevice device;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var root = doc.RootElement;
|
||||
if (!root.TryGetProperty("MAC", out var macElement) || macElement.ValueKind != JsonValueKind.String) return;
|
||||
|
||||
mac = (macElement.GetString() ?? string.Empty).Trim().ToUpperInvariant();
|
||||
if (mac.Length == 0) return;
|
||||
|
||||
device = new DiscoveredDevice(
|
||||
mac,
|
||||
reply.RemoteEndPoint.Address.ToString(),
|
||||
GetString(root, "HostName"),
|
||||
GetString(root, "Type"),
|
||||
GetString(root, "Version"),
|
||||
GetString(root, "State"));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var changed = false;
|
||||
|
||||
lock (_devices)
|
||||
{
|
||||
if (!_devices.TryGetValue(mac, out var previous))
|
||||
{
|
||||
_devices[mac] = (device, DateTime.Now);
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 名字/IP/状态变了才算变化(避免每 3 秒都刷一次界面)
|
||||
if (previous.Device.Ip != device.Ip
|
||||
|| previous.Device.HostName != device.HostName
|
||||
|| previous.Device.State != device.State)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
_devices[mac] = (device, DateTime.Now);
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) Changed?.Invoke();
|
||||
}
|
||||
|
||||
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 void PruneStale()
|
||||
{
|
||||
var deadline = DateTime.Now.AddMilliseconds(-DeviceTimeoutMs);
|
||||
var removed = false;
|
||||
|
||||
lock (_devices)
|
||||
{
|
||||
foreach (var mac in _devices.Where(item => item.Value.LastSeen < deadline).Select(item => item.Key).ToList())
|
||||
{
|
||||
_devices.Remove(mac);
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (removed) Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>广播目标:255.255.255.255 + 每块网卡的定向广播地址</summary>
|
||||
private 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 info in nic.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (info.Address.AddressFamily != AddressFamily.InterNetwork) continue;
|
||||
|
||||
var mask = info.IPv4Mask;
|
||||
if (mask is null) continue;
|
||||
|
||||
var ip = info.Address.GetAddressBytes();
|
||||
var m = mask.GetAddressBytes();
|
||||
if (ip.Length != 4 || m.Length != 4) continue;
|
||||
|
||||
var broadcast = new byte[4];
|
||||
for (var i = 0; i < 4; i++) broadcast[i] = (byte)(ip[i] | (m[i] ^ 0xFF));
|
||||
|
||||
var address = new IPAddress(broadcast);
|
||||
if (!targets.Contains(address)) targets.Add(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[scan] 枚举网卡失败(只用 255.255.255.255):{ex.Message}");
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_cts.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略
|
||||
}
|
||||
|
||||
_cts.Dispose();
|
||||
AppLog.Write("[scan] 设备发现已停止");
|
||||
}
|
||||
}
|
||||
255
desktop/Services/Scan/ScanChannel.cs
Normal file
255
desktop/Services/Scan/ScanChannel.cs
Normal file
@ -0,0 +1,255 @@
|
||||
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);
|
||||
}
|
||||
631
desktop/Services/Scan/ScanRecordStore.cs
Normal file
631
desktop/Services/Scan/ScanRecordStore.cs
Normal file
@ -0,0 +1,631 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
/// <summary>
|
||||
/// 一条扫码记录(本地库,也是上报队列的元素)。
|
||||
///
|
||||
/// 与 AndroidScanCenter 的 <c>scan_record</c> 表对应:先落本地、再上报,
|
||||
/// **上报成功(服务器确认)才把 <see cref="Uploaded"/> 置 true**,失败的下一轮重试,
|
||||
/// 所以断网期间的条码不会丢。
|
||||
/// </summary>
|
||||
public sealed class ScanRecordItem
|
||||
{
|
||||
/// <summary>自增序号(= 写入顺序,去重和分页都靠它)</summary>
|
||||
public long Id { get; set; }
|
||||
|
||||
/// <summary>通道号(上报时的 channelId)</summary>
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>通道名(记录用;通道改名后老记录保持当时的名字)</summary>
|
||||
public string ChannelName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>条码</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// **最近一次**扫到这个条码的时间(本地时间)。
|
||||
///
|
||||
/// 连续扫描时同一个码会反复扫到,这里一直刷新成最后一次;
|
||||
/// 停 <see cref="ScanRecordStore.SettleDelay"/> 没再扫到才上报,上报的就是这个时间。
|
||||
/// </summary>
|
||||
public DateTime ScannedAt { get; set; }
|
||||
|
||||
/// <summary>服务器是否已确认收到</summary>
|
||||
public bool Uploaded { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 旧版本「24 小时内重复扫描、不上报」留下的标记(只为兼容历史本地库)。
|
||||
///
|
||||
/// 新规则不再产生这种记录:同一运单在服务器侧只保留一条,
|
||||
/// 后扫到的时间会覆盖前一次,所以这里只为让老记录继续显示成「重复·不上报」。
|
||||
/// </summary>
|
||||
public bool Suppressed { get; set; }
|
||||
|
||||
/// <summary>确认时间</summary>
|
||||
public DateTime? UploadedAt { get; set; }
|
||||
|
||||
/// <summary>上次落盘时的 <see cref="ScannedAt"/>(连续扫描时省得每 80ms 写一次盘)</summary>
|
||||
[JsonIgnore]
|
||||
public DateTime? PersistedScannedAt { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string TimeText => ScannedAt.ToString("MM-dd HH:mm:ss");
|
||||
|
||||
[JsonIgnore]
|
||||
public string UploadText => Uploaded ? "已上传" : Suppressed ? "重复·不上报" : "待上传";
|
||||
|
||||
[JsonIgnore]
|
||||
public string UploadedAtText => UploadedAt is null ? "—" : UploadedAt.Value.ToString("MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>新增/刷新一条扫码记录的结果类型</summary>
|
||||
public enum ScanAddKind
|
||||
{
|
||||
/// <summary>条码为空等非法输入,没落库</summary>
|
||||
Invalid,
|
||||
|
||||
/// <summary>连续扫描:跟该通道上一次是同一个码,只刷新了最近扫描时间,界面不用重查</summary>
|
||||
Repeated,
|
||||
|
||||
/// <summary>新建了一条待上报记录</summary>
|
||||
Created,
|
||||
|
||||
/// <summary>
|
||||
/// 刷新了已有记录的时间:同一个码还有未上报的记录,或已上报的记录被重新激活
|
||||
/// (扫码枪范围大、多个面单轮流被扫到时走这条)。
|
||||
/// </summary>
|
||||
Touched,
|
||||
}
|
||||
|
||||
/// <summary><see cref="ScanRecordStore.Add"/> 的结果</summary>
|
||||
public readonly record struct ScanAddResult(ScanAddKind Kind, ScanRecordItem? Item)
|
||||
{
|
||||
/// <summary>是否是一次「新的扫码事件」(连续扫描的重复帧不算)</summary>
|
||||
public bool IsScanEvent => Kind is ScanAddKind.Created or ScanAddKind.Touched;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 本地扫码记录库(`%LOCALAPPDATA%\YuncangTrace\scan-records.json`)。
|
||||
///
|
||||
/// 为什么要有它(照搬 AndroidScanCenter 的经验):
|
||||
/// - **断网不丢**:条码先落本地,服务器确认后才标记已上传,否则一直重试;
|
||||
/// - **通道回放**:现场要能翻「这台设备刚才扫了什么」,不能只留一条「最近条码」;
|
||||
/// - **连续扫描去重**:同一个码每 ~80ms 报一次,只刷新「最近一次扫到的时间」,
|
||||
/// 不新增记录(所以「A A A B A」记成 A、B 两条,A 的时间是最后一次扫到的时刻);
|
||||
/// - **延迟上报**:扫到后 <see cref="SettleDelay"/>(5 分钟)内没再扫到才进上报队列,
|
||||
/// 上报的是**最后一次**扫描时间。面单一直放在扫码器上时,时间会一直往后刷,
|
||||
/// 直到面单被贴走/拿开,这才是包裹真正离开工作台的时刻;
|
||||
/// - 同一个码在 24 小时内再次扫到时会**复用/重新激活同一条本地记录**(不新增行),
|
||||
/// 5 分钟静默后重新上报,**服务器侧覆盖**原来那条记录的时间和工作台快照
|
||||
/// (不再像旧版本那样「24 小时内重复的不上报」)。
|
||||
///
|
||||
/// 全部操作加锁:调用方既有收条码的连接线程,也有界面线程和上报重试线程。
|
||||
/// </summary>
|
||||
public static class ScanRecordStore
|
||||
{
|
||||
/// <summary>每个通道最多保留多少条(不封顶的话文件会一直长;删最旧的)</summary>
|
||||
private const int MaxPerChannel = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// 延迟上报的静默窗口:扫到后这么久没再扫到同一个码,才允许上报。
|
||||
/// 连续扫描时每次扫到都会把时间往后推,所以上报的是「最后一次扫描」。
|
||||
/// </summary>
|
||||
public static readonly TimeSpan SettleDelay = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>
|
||||
/// 同一运单在本地复用同一条记录的窗口(与后端的合并窗口一致:24 小时)。
|
||||
///
|
||||
/// 已上报的记录又被扫到(扫码枪范围大、两个面单轮流被扫)时,
|
||||
/// **重新激活这一条**而不是新增一行,避免同一个运单在本地堆出多条;
|
||||
/// 超过 24 小时再扫,才算一条新的记录。
|
||||
/// </summary>
|
||||
public static readonly TimeSpan MergeWindow = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>连续扫描时最多多久落一次盘(本地库是整文件重写,不能每 80ms 写一次)</summary>
|
||||
private static readonly TimeSpan PersistInterval = TimeSpan.FromSeconds(30);
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static List<ScanRecordItem> _items = new();
|
||||
private static long _nextId = 1;
|
||||
private static bool _loaded;
|
||||
private static DateTime _loadedWriteTime = DateTime.MinValue;
|
||||
private static bool _dirty;
|
||||
private static DateTime _lastSaveAt = DateTime.MinValue;
|
||||
private static Timer? _flushTimer;
|
||||
|
||||
/// <summary>记录有变化(新增 / 标记已上传 / 清空),界面据此刷新</summary>
|
||||
public static event Action? Changed;
|
||||
|
||||
/// <summary>
|
||||
/// 扫码记录**上报成功**(服务器已确认)。参数 = 这批记录里新上传的条码(已去重)。
|
||||
///
|
||||
/// 桌面端用它来补一次「扫码时查不到(还没上报)→ 上报成功后自动重查」。
|
||||
/// </summary>
|
||||
public static event Action<IReadOnlyList<string>>? Uploaded;
|
||||
|
||||
private static string Dir => AgentPaths.DataRoot;
|
||||
|
||||
private static string FilePath => AgentPaths.RecordsFile;
|
||||
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
/// <summary>读盘(只读一次;读不到就当空库,绝不抛)</summary>
|
||||
private static void EnsureLoaded()
|
||||
{
|
||||
if (_loaded)
|
||||
{
|
||||
// 服务模式:后台服务是**写入方**,桌面端只读展示 → 文件变了就重新加载
|
||||
if (AgentPaths.MachineMode && !AgentPaths.IsServiceProcess) ReloadIfChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
LoadFromDisk();
|
||||
}
|
||||
|
||||
private static void LoadFromDisk()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
_items = new List<ScanRecordItem>();
|
||||
_nextId = 1;
|
||||
_loadedWriteTime = DateTime.MinValue;
|
||||
return;
|
||||
}
|
||||
|
||||
var list = JsonSerializer.Deserialize<List<ScanRecordItem>>(File.ReadAllText(FilePath), Options);
|
||||
if (list is null) return;
|
||||
|
||||
_items = list.Where(item => !string.IsNullOrWhiteSpace(item.Code)).ToList();
|
||||
foreach (var item in _items) item.PersistedScannedAt = item.ScannedAt;
|
||||
_nextId = _items.Count == 0 ? 1 : _items.Max(item => item.Id) + 1;
|
||||
_loadedWriteTime = File.GetLastWriteTimeUtc(FilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[scan] 读取扫码记录失败(按空库继续):{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>别的进程(后台服务)写过文件了就重新加载(只在服务模式的桌面端调用)</summary>
|
||||
private static void ReloadIfChanged()
|
||||
{
|
||||
DateTime writeTime;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return;
|
||||
writeTime = File.GetLastWriteTimeUtc(FilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (writeTime == _loadedWriteTime) return;
|
||||
|
||||
_dirty = false;
|
||||
LoadFromDisk();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记一条扫码记录。
|
||||
///
|
||||
/// - 连续扫描(跟该通道上一条是同一个码、且还没上报)→ 只刷新 <see cref="ScanRecordItem.ScannedAt"/>,
|
||||
/// 返回 <see cref="ScanAddKind.Repeated"/>(界面不用重查,避免刷屏);
|
||||
/// - 同一个码还有一条没上报的记录(例如 A B A)→ 刷新那条的时间,返回 <see cref="ScanAddKind.Touched"/>;
|
||||
/// - 同一个码 24 小时内**已经上报过**、现在又被扫到(扫码枪范围大 / 两个面单轮流被扫)→
|
||||
/// **重新激活原来那条**(不新增行),静默 5 分钟后再上报覆盖服务器记录;
|
||||
/// - 其它情况新建一条记录。
|
||||
/// </summary>
|
||||
public static ScanAddResult Add(string channelId, string channelName, string code, DateTime scannedAt)
|
||||
{
|
||||
var key = (channelId ?? string.Empty).Trim();
|
||||
var text = (code ?? string.Empty).Trim();
|
||||
if (key.Length == 0 || text.Length == 0) return new ScanAddResult(ScanAddKind.Invalid, null);
|
||||
|
||||
ScanAddResult result;
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
var name = (channelName ?? string.Empty).Trim();
|
||||
var windowStart = scannedAt - MergeWindow;
|
||||
|
||||
// 连续扫描:同一个码每 ~80ms 报一次,只把时间刷到最新
|
||||
var last = _items.LastOrDefault(item => item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
if (last is not null && last.Code.Equals(text, StringComparison.Ordinal))
|
||||
{
|
||||
if (!last.Uploaded && !last.Suppressed)
|
||||
{
|
||||
Touch(last, scannedAt, name);
|
||||
result = new ScanAddResult(ScanAddKind.Repeated, last);
|
||||
}
|
||||
else if (last.ScannedAt > windowStart)
|
||||
{
|
||||
// 已经上报过、24 小时内又被扫到 → 重新激活这一条(不再新增本地行)
|
||||
Reopen(last, scannedAt, name);
|
||||
result = new ScanAddResult(ScanAddKind.Touched, last);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = new ScanAddResult(ScanAddKind.Created, Create(key, name, text, scannedAt));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 同一个码中途又扫到(A B A):优先刷新那条还没上报的记录,
|
||||
// 避免同一个包裹在界面上堆出多条。
|
||||
var pending = _items.LastOrDefault(item =>
|
||||
item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase)
|
||||
&& item.Code.Equals(text, StringComparison.Ordinal)
|
||||
&& !item.Uploaded
|
||||
&& !item.Suppressed);
|
||||
|
||||
if (pending is not null)
|
||||
{
|
||||
Touch(pending, scannedAt, name);
|
||||
result = new ScanAddResult(ScanAddKind.Touched, pending);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 已经上报过的同一条码(24 小时内)→ 重新激活原来那条,
|
||||
// 静默 5 分钟后再上报,后端会覆盖成最新扫描时间 + 工作台快照。
|
||||
var uploaded = _items
|
||||
.Where(item => item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase)
|
||||
&& item.Code.Equals(text, StringComparison.Ordinal)
|
||||
&& item.ScannedAt > windowStart)
|
||||
.OrderByDescending(item => item.ScannedAt)
|
||||
.ThenByDescending(item => item.Id)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (uploaded is not null)
|
||||
{
|
||||
Reopen(uploaded, scannedAt, name);
|
||||
result = new ScanAddResult(ScanAddKind.Touched, uploaded);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = new ScanAddResult(ScanAddKind.Created, Create(key, name, text, scannedAt));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SaveThrottled();
|
||||
if (result.IsScanEvent) Changed?.Invoke();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>新建一条待上报记录(调用方已加锁)</summary>
|
||||
private static ScanRecordItem Create(string channelId, string channelName, string code, DateTime scannedAt)
|
||||
{
|
||||
var added = new ScanRecordItem
|
||||
{
|
||||
Id = _nextId++,
|
||||
ChannelId = channelId,
|
||||
ChannelName = channelName,
|
||||
Code = code,
|
||||
ScannedAt = scannedAt,
|
||||
Uploaded = false,
|
||||
Suppressed = false,
|
||||
};
|
||||
_items.Add(added);
|
||||
TrimChannel(channelId);
|
||||
_dirty = true;
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把记录的「最近扫描时间」刷新到最新(调用方已加锁)。
|
||||
/// 落盘做 30 秒节流:连续扫描时内存里每次都要更新,但没必要每 80ms 重写整个文件。
|
||||
/// </summary>
|
||||
private static void Touch(ScanRecordItem item, DateTime scannedAt, string channelName)
|
||||
{
|
||||
item.ScannedAt = scannedAt;
|
||||
if (!string.IsNullOrWhiteSpace(channelName)) item.ChannelName = channelName;
|
||||
|
||||
if (item.PersistedScannedAt is null
|
||||
|| scannedAt - item.PersistedScannedAt.Value >= PersistInterval)
|
||||
{
|
||||
_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新激活一条**已上报**(或旧规则标记为重复)的记录(调用方已加锁)。
|
||||
///
|
||||
/// 扫码枪范围太大时,两个面单会轮流被扫:A 刚上报完、过一会儿又被扫到。
|
||||
/// 这时不新增本地行,而是把原来那条改回「待上传」并刷新时间,
|
||||
/// 静默 5 分钟后再上报 —— 后端会把同一条记录覆盖成最新扫描时间。
|
||||
/// </summary>
|
||||
private static void Reopen(ScanRecordItem item, DateTime scannedAt, string channelName)
|
||||
{
|
||||
item.ScannedAt = scannedAt;
|
||||
if (!string.IsNullOrWhiteSpace(channelName)) item.ChannelName = channelName;
|
||||
item.Uploaded = false;
|
||||
item.UploadedAt = null;
|
||||
item.Suppressed = false;
|
||||
_dirty = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 可以上报的一批(按写入顺序,头进头出)。
|
||||
///
|
||||
/// **默认只返回静默满 <see cref="SettleDelay"/>(5 分钟)的记录**:扫到后 5 分钟内又扫到同一个码,
|
||||
/// <see cref="ScanRecordItem.ScannedAt"/> 会被刷新,这条就继续等,不会提前上报。
|
||||
/// </summary>
|
||||
public static List<ScanRecordItem> Pending(int limit) => Pending(limit, SettleDelay);
|
||||
|
||||
/// <summary>可以上报的一批(指定静默窗口;调试/测试可传 <see cref="TimeSpan.Zero"/>)</summary>
|
||||
public static List<ScanRecordItem> Pending(int limit, TimeSpan settle)
|
||||
{
|
||||
var cutoff = DateTime.Now - settle;
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _items
|
||||
.Where(item => !item.Uploaded && !item.Suppressed && item.ScannedAt <= cutoff)
|
||||
.OrderBy(item => item.Id)
|
||||
.Take(limit)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>待上报条数(含还在静默期的记录;不含旧版本标记的重复记录)</summary>
|
||||
public static int PendingCount()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _items.Count(item => !item.Uploaded && !item.Suppressed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>已经静默满 5 分钟、可以真正上报的条数</summary>
|
||||
public static int ReadyCount()
|
||||
{
|
||||
var cutoff = DateTime.Now - SettleDelay;
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _items.Count(item => !item.Uploaded && !item.Suppressed && item.ScannedAt <= cutoff);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>这个条码是否有「还没上报」的本地记录(桌面端用来提示“等待上报后自动查询”)</summary>
|
||||
public static bool HasPending(string code)
|
||||
{
|
||||
var text = (code ?? string.Empty).Trim();
|
||||
if (text.Length == 0) return false;
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _items.Any(item => !item.Uploaded && !item.Suppressed && item.Code.Equals(text, StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>某通道(null/空 = 全部)最近的记录,新的一头在前</summary>
|
||||
public static List<ScanRecordItem> Recent(string? channelId, int limit = 500)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
var query = _items.AsEnumerable();
|
||||
if (!string.IsNullOrWhiteSpace(channelId))
|
||||
{
|
||||
query = query.Where(item => item.ChannelId.Equals(channelId.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
return query.OrderByDescending(item => item.Id).Take(limit).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页取记录(新的一头在前)
|
||||
///
|
||||
/// 本地库每通道最多 5000 条,全塞进 ListView 会卡;界面按页取(默认 200 条/页)。
|
||||
/// </summary>
|
||||
/// <param name="channelId">null/空 = 全部通道</param>
|
||||
/// <param name="page">页码,0 起</param>
|
||||
/// <param name="pageSize">每页条数(<=0 时按 200)</param>
|
||||
/// <returns>当前页记录 / 总条数(用于算页数)</returns>
|
||||
public static (List<ScanRecordItem> Items, int Total) Page(string? channelId, int page, int pageSize = 200)
|
||||
{
|
||||
if (pageSize <= 0) pageSize = 200;
|
||||
if (page < 0) page = 0;
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
var query = _items.AsEnumerable();
|
||||
if (!string.IsNullOrWhiteSpace(channelId))
|
||||
{
|
||||
query = query.Where(item => item.ChannelId.Equals(channelId.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
var ordered = query.OrderByDescending(item => item.Id).ToList();
|
||||
var total = ordered.Count;
|
||||
var items = ordered.Skip(page * pageSize).Take(pageSize).ToList();
|
||||
return (items, total);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>总条数 / 待上传条数(界面统计用;含还在 5 分钟静默期的记录)</summary>
|
||||
public static (int Total, int Pending) Stats()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return (_items.Count, _items.Count(item => !item.Uploaded && !item.Suppressed));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务器确认收到:标记为已上传(**只在拿到成功响应后调用**)。
|
||||
///
|
||||
/// 传入每条记录**上报时**的扫描时间:如果上报期间又扫到了同一个码
|
||||
/// (<see cref="ScanRecordItem.ScannedAt"/> 已经更新),这条保持「待上传」,
|
||||
/// 下一轮会带着最新时间再上报一次,避免最新时间被这次成功回执覆盖掉。
|
||||
/// </summary>
|
||||
public static void MarkUploaded(IEnumerable<(long Id, DateTime ScannedAt)> uploaded)
|
||||
{
|
||||
var map = uploaded.GroupBy(item => item.Id).ToDictionary(group => group.Key, group => group.First().ScannedAt);
|
||||
if (map.Count == 0) return;
|
||||
|
||||
var codes = new List<string>();
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
var now = DateTime.Now;
|
||||
var marked = 0;
|
||||
foreach (var item in _items.Where(item => map.ContainsKey(item.Id) && !item.Uploaded))
|
||||
{
|
||||
if (item.ScannedAt != map[item.Id]) continue; // 上报期间又扫到,保持待上传
|
||||
item.Uploaded = true;
|
||||
item.UploadedAt = now;
|
||||
marked++;
|
||||
if (!codes.Contains(item.Code)) codes.Add(item.Code);
|
||||
}
|
||||
if (marked == 0) return;
|
||||
_dirty = true;
|
||||
}
|
||||
|
||||
SaveThrottled();
|
||||
Changed?.Invoke();
|
||||
if (codes.Count > 0) Uploaded?.Invoke(codes);
|
||||
}
|
||||
|
||||
/// <summary>清空(channelId 为空 = 清全部)</summary>
|
||||
public static int Clear(string? channelId = null)
|
||||
{
|
||||
int removed;
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
if (string.IsNullOrWhiteSpace(channelId))
|
||||
{
|
||||
removed = _items.Count;
|
||||
_items = new List<ScanRecordItem>();
|
||||
}
|
||||
else
|
||||
{
|
||||
var key = channelId.Trim();
|
||||
removed = _items.RemoveAll(item => item.ChannelId.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
if (removed == 0) return 0;
|
||||
_dirty = true;
|
||||
}
|
||||
|
||||
Save(force: true);
|
||||
Changed?.Invoke();
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>强制落盘(退出前调用)</summary>
|
||||
public static void Flush()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
EnsureLoaded();
|
||||
// 连续扫描时 ScannedAt 可能还没到落盘间隔 → 退出前把最新的也写下去
|
||||
if (!_dirty && _items.All(item => item.PersistedScannedAt == item.ScannedAt)) return;
|
||||
}
|
||||
Save(force: true);
|
||||
}
|
||||
|
||||
/// <summary>每个通道的超额部分(最旧的)删掉</summary>
|
||||
private static void TrimChannel(string channelId)
|
||||
{
|
||||
var mine = _items.Where(item => item.ChannelId.Equals(channelId, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(item => item.Id)
|
||||
.ToList();
|
||||
if (mine.Count <= MaxPerChannel) return;
|
||||
|
||||
var drop = new HashSet<long>(mine.Skip(MaxPerChannel).Select(item => item.Id));
|
||||
_items.RemoveAll(item => drop.Contains(item.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写盘节流:连续扫码时不要每条都整表重写(最多 2 秒一次)。
|
||||
/// ⚠️ 被节流掉的那次**必须补写**,否则「已上传」标记会丢在内存里 ——
|
||||
/// 重启后记录又变回待上传(虽然服务端会去重,但状态就是错的)。
|
||||
/// </summary>
|
||||
private static void SaveThrottled()
|
||||
{
|
||||
bool wait;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!_dirty) return; // 连续扫描只刷了时间、还没到落盘间隔 → 不用写
|
||||
wait = (DateTime.Now - _lastSaveAt).TotalSeconds < 2;
|
||||
}
|
||||
|
||||
if (wait)
|
||||
{
|
||||
ScheduleDelayedFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
Save(force: false);
|
||||
}
|
||||
|
||||
/// <summary>被节流后补一次写盘(只排一个定时器,不堆积)</summary>
|
||||
private static void ScheduleDelayedFlush()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (_flushTimer is not null) return;
|
||||
|
||||
_flushTimer = new Timer(_ =>
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_flushTimer?.Dispose();
|
||||
_flushTimer = null;
|
||||
}
|
||||
Save(force: false);
|
||||
}, null, 2200, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save(bool force)
|
||||
{
|
||||
string json;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!_dirty && !force) return;
|
||||
if (!force && (DateTime.Now - _lastSaveAt).TotalSeconds < 2) return;
|
||||
|
||||
json = JsonSerializer.Serialize(_items, Options);
|
||||
foreach (var item in _items) item.PersistedScannedAt = item.ScannedAt;
|
||||
_dirty = false;
|
||||
_lastSaveAt = DateTime.Now;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Dir);
|
||||
var temp = FilePath + ".tmp";
|
||||
File.WriteAllText(temp, json);
|
||||
File.Copy(temp, FilePath, overwrite: true);
|
||||
File.Delete(temp);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[scan] 保存扫码记录失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
664
desktop/Services/Scan/ScanService.cs
Normal file
664
desktop/Services/Scan/ScanService.cs
Normal file
@ -0,0 +1,664 @@
|
||||
using System;
|
||||
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;
|
||||
|
||||
// 看门狗:设备断电重启时 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;
|
||||
}
|
||||
|
||||
/// <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>读通道配置</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>();
|
||||
|
||||
foreach (var device in devices)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(device.Ip)) continue;
|
||||
|
||||
var channel = Channels.FirstOrDefault(item => item.Mac.Equals(device.Mac, StringComparison.OrdinalIgnoreCase));
|
||||
if (channel is null || 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 (changed.Count == 0) return;
|
||||
|
||||
SaveChannels();
|
||||
Changed?.Invoke();
|
||||
|
||||
foreach (var channel in changed)
|
||||
{
|
||||
if (Running && channel.Enabled) 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>
|
||||
/// 切换某条通道的扫码枪静音(与 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="stage">进度文案回调(界面显示用)</param>
|
||||
public async Task<AddChannelResult> AddChannelAsync(string mac, string name, string ip, int number,
|
||||
string? reportedHostName = null, Action<string>? stage = null, CancellationToken ct = default)
|
||||
{
|
||||
var key = (mac ?? string.Empty).Trim().ToUpperInvariant();
|
||||
var trimmed = (name ?? 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 (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,
|
||||
Number = wanted,
|
||||
TcpPort = ScanProtocol.TcpPort,
|
||||
SockName = ensure.SockName,
|
||||
Enabled = true,
|
||||
};
|
||||
Channels.Add(channel);
|
||||
SaveChannels();
|
||||
Changed?.Invoke();
|
||||
RequestChannelSync();
|
||||
|
||||
if (Running) StartConnection(channel);
|
||||
|
||||
var message = $"通道 {channel.Number}「{channel.DisplayName}」已添加{ensure.Message}{patchNote}";
|
||||
return new AddChannelResult(channel, true, message, ensure.Kind);
|
||||
}
|
||||
|
||||
/// <summary>删除通道</summary>
|
||||
public void RemoveChannel(ScanChannel channel)
|
||||
{
|
||||
StopConnection(channel);
|
||||
Channels.Remove(channel);
|
||||
SaveChannels();
|
||||
Changed?.Invoke();
|
||||
RequestChannelSync();
|
||||
}
|
||||
|
||||
/// <summary>启用 / 停用通道</summary>
|
||||
public void SetEnabled(ScanChannel channel, bool enabled)
|
||||
{
|
||||
channel.Enabled = enabled;
|
||||
SaveChannels();
|
||||
|
||||
if (enabled && Running) StartConnection(channel);
|
||||
else StopConnection(channel);
|
||||
|
||||
Changed?.Invoke();
|
||||
RequestChannelSync();
|
||||
}
|
||||
|
||||
/// <summary>启动扫码服务:连接所有启用的通道 + (后台)同步通道列表到服务器</summary>
|
||||
public Task StartAsync()
|
||||
{
|
||||
Load();
|
||||
Running = true;
|
||||
|
||||
foreach (var channel in Channels.Where(item => item.Enabled)) StartConnection(channel);
|
||||
|
||||
RequestChannelSync();
|
||||
EnsureWatchdog();
|
||||
AppLog.Write($"[scan] 扫码服务已启动,通道 {Channels.Count(item => item.Enabled)} 个");
|
||||
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();
|
||||
|
||||
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` **回查确认**)。
|
||||
///
|
||||
/// 不用手动点:添加 / 删除 / 启用停用 都会调 <see cref="RequestChannelSync"/>,
|
||||
/// 后台循环一直重试到服务器确实有这批通道为止(断网、服务器重启都不用手管)。
|
||||
/// </summary>
|
||||
public void RequestChannelSync()
|
||||
{
|
||||
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.Where(item => item.Enabled)
|
||||
.Select(item => (item.ChannelId, item.DisplayName))
|
||||
.ToList();
|
||||
|
||||
if (local.Count == 0)
|
||||
{
|
||||
SetSyncStatus("当前没有启用的通道");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _device.ReportChannelsAsync(local, 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;
|
||||
SetSyncStatus($"通道已同步({local.Count} 个)");
|
||||
AppLog.Write($"[scan] 通道已同步到服务器并确认:{local.Count} 个");
|
||||
return;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"服务器上还缺通道 {string.Join('/', missing)}");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
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);
|
||||
|
||||
if (added) Barcode?.Invoke(channel, code);
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>添加通道的结果(<see cref="Channel"/> 为空表示失败,<see cref="Message"/> 是给用户看的一句话)</summary>
|
||||
public sealed record AddChannelResult(
|
||||
ScanChannel? Channel,
|
||||
bool Ok,
|
||||
string Message,
|
||||
TcpServerEnsureKind EnsureKind = TcpServerEnsureKind.AlreadyReady);
|
||||
51
desktop/Services/Scan/ScannerCommands.cs
Normal file
51
desktop/Services/Scan/ScannerCommands.cs
Normal file
@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
/// <summary>
|
||||
/// 扫码枪的设置指令(照搬 AndroidScanCenter 的 <c>ScannerCommands</c>,来源:设备商
|
||||
/// 《网口配置-文档介绍-V4.0》第 14 页「串口指令表」)。
|
||||
///
|
||||
/// ⚠️ 这些指令发给的是**扫码枪**,不是网口设备:我们通过已有的 TCP 连接写进去,
|
||||
/// 设备按 `Rout=uart` 透传到串口。
|
||||
///
|
||||
/// ⚠️ 静音那两条是 **10 字节**(其余 9 字节),**不要**按 9 字节去"凑"长度,
|
||||
/// 校验位也照抄,改错了设备会静默丢弃(现象是"发了没反应")。
|
||||
/// </summary>
|
||||
public static class ScannerCommands
|
||||
{
|
||||
/// <summary>触发模式 → 连续扫描:扫码枪自己一直扫,不用主机触发</summary>
|
||||
public static readonly byte[] TriggerContinuous =
|
||||
{ 0x07, 0xC6, 0x04, 0x08, 0x00, 0x8A, 0x04, 0xFE, 0x99 };
|
||||
|
||||
/// <summary>识读间隔 → 0s:连扫时两条之间不等待</summary>
|
||||
public static readonly byte[] IntervalZero =
|
||||
{ 0x07, 0xC6, 0x04, 0x08, 0x00, 0x89, 0x00, 0xFE, 0x9E };
|
||||
|
||||
/// <summary>
|
||||
/// 静音 → 使能:扫到码不蜂鸣。
|
||||
/// 参数是「静音」,0x01 = 使能(安静)、0x00 = 禁止(照旧响)—— 是**反的**。
|
||||
/// </summary>
|
||||
public static readonly byte[] MuteOn =
|
||||
{ 0x08, 0xC6, 0x04, 0x08, 0x00, 0xF2, 0x0C, 0x01, 0xFE, 0x27 };
|
||||
|
||||
/// <summary>静音 → 禁止:恢复蜂鸣</summary>
|
||||
public static readonly byte[] MuteOff =
|
||||
{ 0x08, 0xC6, 0x04, 0x08, 0x00, 0xF2, 0x0C, 0x00, 0xFE, 0x28 };
|
||||
|
||||
/// <summary>
|
||||
/// 连上之后按顺序下发的设置(9 + 9 + 10 = 28 字节,一次写完)。
|
||||
///
|
||||
/// 为什么放在"连上时"而不是做成一个按钮:这些是**扫码枪**的状态,
|
||||
/// 枪自己断电重启就丢了;而连接每重建一次都会走这里,等于自动兜住。
|
||||
/// 静音取**通道记住的值**(不是固定值),否则每次重连都会把人的设置覆盖掉
|
||||
/// —— 现场看到的现象就是"设了过一会儿自己又响了"。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<byte[]> StartupSequence(bool muted) => new[]
|
||||
{
|
||||
TriggerContinuous,
|
||||
IntervalZero,
|
||||
muted ? MuteOn : MuteOff,
|
||||
};
|
||||
}
|
||||
42
desktop/Views/AddChannelWindow.xaml
Normal file
42
desktop/Views/AddChannelWindow.xaml
Normal file
@ -0,0 +1,42 @@
|
||||
<Window x:Class="YuncangTrace.LocalService.AddChannelWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="添加通道"
|
||||
Height="420" Width="460"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
FontSize="13">
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="10" Margin="18" Padding="18">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="添加扫码通道" FontSize="15" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="DeviceText" DockPanel.Dock="Top" FontSize="12"
|
||||
Foreground="{StaticResource MutedBrush}" Margin="0,4,0,12" TextWrapping="Wrap" />
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,14,0,0">
|
||||
<Button Content="取消" Padding="14,5" IsCancel="True" Click="Cancel_Click" />
|
||||
<Button Content="添加" Padding="14,5" Margin="8,0,0,0" IsDefault="True"
|
||||
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
|
||||
Cursor="Hand" Click="Ok_Click" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel>
|
||||
<TextBlock Text="通道号" FontWeight="SemiBold" Margin="0,0,0,4" />
|
||||
<ComboBox x:Name="NumberBox" DisplayMemberPath="Label" Height="28" Padding="6,3" />
|
||||
<TextBlock Text="通道号是现场认工位的号,删掉的号不会被自动复用;已占用的号会标注占用者"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,4,0,14" TextWrapping="Wrap" />
|
||||
|
||||
<TextBlock Text="设备名" FontWeight="SemiBold" Margin="0,0,0,4" />
|
||||
<TextBox x:Name="NameBox" Height="28" Padding="6,3" VerticalContentAlignment="Center"
|
||||
MaxLength="32" />
|
||||
<TextBlock Text="会写入设备本身(HostName)并落盘,设备面板和其他上位机看到的都是这个名字;留空则用设备自报名"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,4,0,14" TextWrapping="Wrap" />
|
||||
|
||||
<TextBlock x:Name="HintText" FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
TextWrapping="Wrap" Text="添加时会先检查并确保设备上有给中控用的 TCP 服务(桌面端自己的条目与端口,不占 Android 那个)" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Window>
|
||||
90
desktop/Views/AddChannelWindow.xaml.cs
Normal file
90
desktop/Views/AddChannelWindow.xaml.cs
Normal file
@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 「添加通道」弹窗:设置**通道号**与**设备名**(与 AndroidScanCenter 的添加流程一致)。
|
||||
///
|
||||
/// - 通道号是本地概念(现场认工位用),被占用的号照样列出来、只标注谁占着
|
||||
/// —— 直接藏掉的话现场看到「怎么就没有 3 号」还得来问一遍;
|
||||
/// - 设备名会写进设备本身(SYS.HostName),默认填设备自报的名字。
|
||||
/// </summary>
|
||||
public partial class AddChannelWindow : Window
|
||||
{
|
||||
/// <summary>下拉框选项(带占用标注)</summary>
|
||||
public sealed class NumberOption
|
||||
{
|
||||
public int Number { get; init; }
|
||||
public string Label { get; init; } = string.Empty;
|
||||
public bool Taken { get; init; }
|
||||
}
|
||||
|
||||
private readonly IReadOnlyList<ScanChannel> _channels;
|
||||
|
||||
public AddChannelWindow(DiscoveredDevice device, IReadOnlyList<ScanChannel> channels)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_channels = channels;
|
||||
|
||||
var reported = (device.HostName ?? string.Empty).Trim();
|
||||
DeviceText.Text = reported.Length == 0
|
||||
? $"{device.Mac} · {device.Ip} · {device.Model}"
|
||||
: $"{reported}({device.Mac} · {device.Ip} · {device.Model})";
|
||||
|
||||
// 默认名:设备自报的 HostName(通常就是工位名),没有就用 MAC
|
||||
var defaultName = reported.Length == 0 ? device.Mac : reported;
|
||||
NameBox.Text = defaultName;
|
||||
|
||||
var suggested = ChannelStore.NextNumber(channels);
|
||||
var options = new List<NumberOption>();
|
||||
for (var number = 1; number <= ChannelStore.MaxNumber; number++)
|
||||
{
|
||||
var owner = ChannelStore.FindByNumber(channels, number);
|
||||
options.Add(new NumberOption
|
||||
{
|
||||
Number = number,
|
||||
Taken = owner is not null,
|
||||
Label = owner is null ? number.ToString() : $"{number}(已被「{owner.DisplayName}」占用)",
|
||||
});
|
||||
}
|
||||
NumberBox.ItemsSource = options;
|
||||
NumberBox.SelectedItem = options.FirstOrDefault(item => item.Number == suggested) ?? options[0];
|
||||
|
||||
HintText.Text = $"添加时会先检查并确保设备上有给中控用的 TCP 服务(条目 {ScanProtocol.SockName}、端口 {ScanProtocol.TcpPort},"
|
||||
+ "与 Android 中控的 8086 分开),设备名有变化会写入设备并落盘";
|
||||
}
|
||||
|
||||
/// <summary>用户选的通道号(确定后有值)</summary>
|
||||
public int ChannelNumber { get; private set; }
|
||||
|
||||
/// <summary>用户填的设备名(确定后有值,可能为空 = 用设备自报名)</summary>
|
||||
public string ChannelName { get; private set; } = string.Empty;
|
||||
|
||||
private void Ok_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (NumberBox.SelectedItem is not NumberOption option)
|
||||
{
|
||||
MessageBox.Show(this, "请先选择通道号", "添加通道", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
// 已被占用:只提示、不关框,用户可以接着选(与 AndroidScanCenter 一致)
|
||||
if (option.Taken)
|
||||
{
|
||||
MessageBox.Show(this, $"通道号 {option.Number} 已经被占用了,请换一个号", "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
ChannelNumber = option.Number;
|
||||
ChannelName = (NameBox.Text ?? string.Empty).Trim();
|
||||
DialogResult = true;
|
||||
}
|
||||
|
||||
private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
}
|
||||
82
desktop/Views/ScanRecordsView.xaml
Normal file
82
desktop/Views/ScanRecordsView.xaml
Normal file
@ -0,0 +1,82 @@
|
||||
<UserControl x:Class="YuncangTrace.LocalService.Views.ScanRecordsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI" FontSize="13">
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 后台服务绑定的主体与当前主体不一致时由 MainWindow 显示 -->
|
||||
<Border x:Name="NoticeBar" Grid.Row="0" Background="#FFF7E6" BorderBrush="#F0D9A8"
|
||||
BorderThickness="1" CornerRadius="6" Padding="10,7" Margin="0,0,0,8"
|
||||
Visibility="Collapsed">
|
||||
<TextBlock x:Name="NoticeText" TextWrapping="Wrap" FontSize="12" Foreground="#8A5A00" />
|
||||
</Border>
|
||||
|
||||
<!-- 标题行:筛选 + 状态 + 按钮(与其他页签一致,全都挤在标题行上) -->
|
||||
<DockPanel Grid.Row="1" Margin="0,0,0,8" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="扫码记录" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Margin="12,0,0,0">
|
||||
<ComboBox x:Name="ChannelFilter" Width="170" Height="26" Padding="6,2"
|
||||
DisplayMemberPath="Label" SelectionChanged="ChannelFilter_SelectionChanged" />
|
||||
<Button x:Name="UploadButton" Content="立即上传" Padding="10,3" Margin="8,0,0,0"
|
||||
Click="Upload_Click" />
|
||||
<Button x:Name="ClearButton" Content="清空" Padding="10,3" Margin="8,0,0,0" Click="Clear_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="StatusText" DockPanel.Dock="Right" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Right" TextTrimming="CharacterEllipsis"
|
||||
Text="—" />
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="2" Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="8">
|
||||
<ListView x:Name="RecordList" BorderThickness="0" SelectionMode="Single">
|
||||
<ListView.View>
|
||||
<GridView>
|
||||
<GridViewColumn Header="时间" Width="130" DisplayMemberBinding="{Binding TimeText}" />
|
||||
<GridViewColumn Header="通道" Width="150" DisplayMemberBinding="{Binding ChannelName}" />
|
||||
<GridViewColumn Header="号" Width="46" DisplayMemberBinding="{Binding ChannelId}" />
|
||||
<GridViewColumn Header="条码" Width="300" DisplayMemberBinding="{Binding Code}" />
|
||||
<GridViewColumn Header="上传" Width="80" DisplayMemberBinding="{Binding UploadText}" />
|
||||
<GridViewColumn Header="确认时间" Width="130" DisplayMemberBinding="{Binding UploadedAtText}" />
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
</ListView>
|
||||
</Border>
|
||||
|
||||
<!-- 分页条:本地每通道最多 5000 条,一次全渲染会卡 -->
|
||||
<DockPanel Grid.Row="3" Margin="0,8,0,0" LastChildFill="False">
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal">
|
||||
<Button x:Name="FirstButton" Content="首页" Padding="10,3" Click="First_Click" />
|
||||
<Button x:Name="PrevButton" Content="上一页" Padding="10,3" Margin="6,0,0,0" Click="Prev_Click" />
|
||||
<TextBlock x:Name="PageText" Text="第 1 / 1 页" VerticalAlignment="Center"
|
||||
Margin="12,0,12,0" Foreground="{StaticResource MutedBrush}" />
|
||||
<Button x:Name="NextButton" Content="下一页" Padding="10,3" Margin="0,0,6,0" Click="Next_Click" />
|
||||
<Button x:Name="LastButton" Content="末页" Padding="10,3" Click="Last_Click" />
|
||||
|
||||
<TextBox x:Name="JumpBox" Width="64" Height="26" Padding="6,2" Margin="12,0,0,0"
|
||||
VerticalContentAlignment="Center" KeyDown="JumpBox_KeyDown"
|
||||
ToolTip="输入页码后回车" />
|
||||
<Button Content="跳转" Padding="10,3" Margin="6,0,0,0" Click="Jump_Click" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="每页" VerticalAlignment="Center" Foreground="{StaticResource MutedBrush}"
|
||||
Margin="0,0,6,0" />
|
||||
<ComboBox x:Name="PageSizeBox" Width="80" Height="26" Padding="6,2"
|
||||
SelectionChanged="PageSizeBox_SelectionChanged">
|
||||
<ComboBoxItem Content="100" />
|
||||
<ComboBoxItem Content="200" />
|
||||
<ComboBoxItem Content="500" />
|
||||
<ComboBoxItem Content="1000" />
|
||||
</ComboBox>
|
||||
<TextBlock Text="条" VerticalAlignment="Center" Foreground="{StaticResource MutedBrush}"
|
||||
Margin="6,0,0,0" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
296
desktop/Views/ScanRecordsView.xaml.cs
Normal file
296
desktop/Views/ScanRecordsView.xaml.cs
Normal file
@ -0,0 +1,296 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 「扫码记录」页签(对应 AndroidScanCenter 的「通道回放」):
|
||||
/// 看本机落了哪些条码、**服务器确认了没有**。
|
||||
///
|
||||
/// 记录先写本地库(`scan-records.json`),上报成功(服务器 2xx)才标成「已上传」,
|
||||
/// 所以这里也是断网期间「有没有丢码」的唯一凭证。
|
||||
/// </summary>
|
||||
public partial class ScanRecordsView : UserControl
|
||||
{
|
||||
private readonly ScanService _scan;
|
||||
private readonly ObservableCollection<ScanRecordItem> _rows = new();
|
||||
|
||||
/// <summary>上传状态/条数会自己变(后台重试),定时刷一下界面</summary>
|
||||
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromSeconds(1) };
|
||||
|
||||
private bool _suppressFilterChange;
|
||||
private bool _suppressPageSizeChange;
|
||||
|
||||
/// <summary>当前页码(0 起)</summary>
|
||||
private int _page;
|
||||
|
||||
/// <summary>每页条数(默认 200:本地每通道最多 5000 条,全渲染会卡)</summary>
|
||||
private int _pageSize = 200;
|
||||
|
||||
/// <summary>当前页签名(用来判断「要不要重建列表」,避免每秒刷新把滚动/选中冲掉)</summary>
|
||||
private string _pageSignature = string.Empty;
|
||||
|
||||
/// <summary>下拉框选项:全部 + 每个通道</summary>
|
||||
public sealed class ChannelOption
|
||||
{
|
||||
public string? ChannelId { get; init; }
|
||||
public string Label { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
public ScanRecordsView(ScanService scan)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_scan = scan;
|
||||
RecordList.ItemsSource = _rows;
|
||||
|
||||
// 默认 200 条/页;直接设 SelectedIndex 会触发 SelectionChanged,
|
||||
// 那时 _scan 刚赋好、但其它控件不一定就绪 → 先抑制一下
|
||||
_suppressPageSizeChange = true;
|
||||
PageSizeBox.SelectedIndex = 1;
|
||||
_suppressPageSizeChange = false;
|
||||
|
||||
// 与扫码通道页一致:**不随页签切换停用功能**,事件与定时刷新一直挂着
|
||||
_scan.Changed += OnStoreChanged;
|
||||
ScanRecordStore.Changed += OnStoreChanged;
|
||||
_timer.Start();
|
||||
|
||||
Loaded += (_, _) =>
|
||||
{
|
||||
RefreshFilters();
|
||||
Refresh();
|
||||
};
|
||||
|
||||
_timer.Tick += (_, _) => Refresh();
|
||||
}
|
||||
|
||||
/// <summary>后台服务绑定的主体与当前主体不一致时的提示(null / 空 = 隐藏)</summary>
|
||||
public void SetNotice(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
NoticeText.Text = string.Empty;
|
||||
NoticeBar.Visibility = Visibility.Collapsed;
|
||||
return;
|
||||
}
|
||||
|
||||
NoticeText.Text = text;
|
||||
NoticeBar.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
// 事件只用来同步通道下拉(通道增删),列表本身交给定时器 ——
|
||||
// 连续扫码时 Changed 会一条一触发,每次都重建 500 行没必要
|
||||
private void OnStoreChanged() => Dispatcher.Invoke(RefreshFilters);
|
||||
|
||||
/// <summary>通道下拉:新增/删除通道后跟着变(保持当前选中)</summary>
|
||||
private void RefreshFilters()
|
||||
{
|
||||
var current = (ChannelFilter.SelectedItem as ChannelOption)?.ChannelId;
|
||||
|
||||
var options = new List<ChannelOption> { new() { ChannelId = null, Label = "全部通道" } };
|
||||
options.AddRange(_scan.Channels
|
||||
.OrderBy(item => item.Number)
|
||||
.Select(item => new ChannelOption
|
||||
{
|
||||
ChannelId = item.ChannelId,
|
||||
Label = $"{item.Number} · {item.DisplayName}",
|
||||
}));
|
||||
|
||||
_suppressFilterChange = true;
|
||||
ChannelFilter.ItemsSource = options;
|
||||
ChannelFilter.SelectedItem = options.FirstOrDefault(item => item.ChannelId == current) ?? options[0];
|
||||
_suppressFilterChange = false;
|
||||
}
|
||||
|
||||
private void ChannelFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (_suppressFilterChange) return;
|
||||
_page = 0; // 换通道回到第一页
|
||||
_pageSignature = string.Empty;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>重画列表 + 状态行(按页取,不再一次塞 500 条)</summary>
|
||||
private void Refresh()
|
||||
{
|
||||
var selected = (ChannelFilter.SelectedItem as ChannelOption)?.ChannelId;
|
||||
|
||||
var (items, total) = ScanRecordStore.Page(selected, _page, _pageSize);
|
||||
var pages = Math.Max((total + _pageSize - 1) / _pageSize, 1);
|
||||
|
||||
// 页码越界(清空/删除后)→ 回到最后一页
|
||||
if (_page >= pages)
|
||||
{
|
||||
_page = pages - 1;
|
||||
(items, total) = ScanRecordStore.Page(selected, _page, _pageSize);
|
||||
}
|
||||
|
||||
// 只有「这一页的内容真的变了」才重建,避免 1 秒定时器把滚动位置和选中项冲掉
|
||||
var signature = $"{selected}|{_page}|{_pageSize}|{total}|{items.Count}|"
|
||||
+ (items.Count == 0 ? "0" : $"{items[0].Id}-{items[^1].Id}-{items.Count(item => item.Uploaded)}");
|
||||
|
||||
if (signature != _pageSignature)
|
||||
{
|
||||
_pageSignature = signature;
|
||||
|
||||
var selectedId = (RecordList.SelectedItem as ScanRecordItem)?.Id;
|
||||
|
||||
_rows.Clear();
|
||||
foreach (var item in items) _rows.Add(item);
|
||||
|
||||
// 尽量保持选中项(同一页时)
|
||||
if (selectedId is not null)
|
||||
{
|
||||
var again = _rows.FirstOrDefault(item => item.Id == selectedId);
|
||||
if (again is not null) RecordList.SelectedItem = again;
|
||||
}
|
||||
}
|
||||
|
||||
PageText.Text = $"第 {_page + 1} / {pages} 页 · 共 {total} 条";
|
||||
|
||||
FirstButton.IsEnabled = _page > 0;
|
||||
PrevButton.IsEnabled = _page > 0;
|
||||
NextButton.IsEnabled = _page < pages - 1;
|
||||
LastButton.IsEnabled = _page < pages - 1;
|
||||
|
||||
var scope = selected is null
|
||||
? "全部通道"
|
||||
: _scan.Channels.FirstOrDefault(channel => channel.ChannelId == selected)?.DisplayName ?? selected;
|
||||
|
||||
var (allTotal, pending) = ScanRecordStore.Stats();
|
||||
var ready = ScanRecordStore.ReadyCount();
|
||||
var status = $"{scope}:共 {total} 条 · 全部 {allTotal} 条 · 待上传 {pending} 条";
|
||||
if (pending > ready) status += $"({pending - ready} 条静默中,满 5 分钟自动上报)";
|
||||
|
||||
if (IsAgentMode)
|
||||
{
|
||||
var agent = AgentFiles.LoadStatus();
|
||||
if (!string.IsNullOrWhiteSpace(agent?.UploadStatus)) status += $" · {agent.UploadStatus}";
|
||||
if (agent?.Running == false) status += " · 后台服务未运行";
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(_scan.UploadStatus))
|
||||
{
|
||||
status += $" · {_scan.UploadStatus}";
|
||||
}
|
||||
|
||||
StatusText.Text = status;
|
||||
UploadButton.IsEnabled = pending > 0;
|
||||
}
|
||||
|
||||
// ---------------- 分页 ----------------
|
||||
|
||||
private void First_Click(object sender, RoutedEventArgs e) => GoToPage(0);
|
||||
|
||||
private void Prev_Click(object sender, RoutedEventArgs e) => GoToPage(_page - 1);
|
||||
|
||||
private void Next_Click(object sender, RoutedEventArgs e) => GoToPage(_page + 1);
|
||||
|
||||
private void Last_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var selected = (ChannelFilter.SelectedItem as ChannelOption)?.ChannelId;
|
||||
var (_, total) = ScanRecordStore.Page(selected, 0, _pageSize);
|
||||
var pages = Math.Max((total + _pageSize - 1) / _pageSize, 1);
|
||||
GoToPage(pages - 1);
|
||||
}
|
||||
|
||||
private void Jump_Click(object sender, RoutedEventArgs e) => JumpToInput();
|
||||
|
||||
private void JumpBox_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Enter) JumpToInput();
|
||||
}
|
||||
|
||||
/// <summary>跳页:没在范围里的值由 Refresh 里的越界回退处理</summary>
|
||||
private void JumpToInput()
|
||||
{
|
||||
var text = (JumpBox.Text ?? string.Empty).Trim();
|
||||
JumpBox.Text = string.Empty;
|
||||
|
||||
if (!int.TryParse(text, out var number) || number <= 0) return;
|
||||
GoToPage(number - 1);
|
||||
}
|
||||
|
||||
private void GoToPage(int page)
|
||||
{
|
||||
if (page < 0) return;
|
||||
_page = page;
|
||||
_pageSignature = string.Empty; // 强制重建
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void PageSizeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (_suppressPageSizeChange) return;
|
||||
if (PageSizeBox.SelectedItem is not ComboBoxItem item) return;
|
||||
if (!int.TryParse(item.Content?.ToString(), out var size) || size <= 0) return;
|
||||
|
||||
_pageSize = size;
|
||||
_page = 0;
|
||||
_pageSignature = string.Empty;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>当前是否「后台服务收码」模式(本进程只展示,写入靠服务)</summary>
|
||||
private static bool IsAgentMode => AgentPaths.MachineMode && !AgentPaths.IsServiceProcess;
|
||||
|
||||
private void Upload_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ScanRecordStore.PendingCount() == 0)
|
||||
{
|
||||
StatusText.Text = "没有待上传的记录";
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsAgentMode)
|
||||
{
|
||||
AgentFiles.QueueCommand(command => command.TriggerUploadAt = DateTime.UtcNow);
|
||||
StatusText.Text = "已通知后台服务上传,稍等…";
|
||||
return;
|
||||
}
|
||||
|
||||
if (ScanRecordStore.ReadyCount() == 0)
|
||||
{
|
||||
StatusText.Text = "记录还在 5 分钟静默期(等最后一次扫描后再上报),稍后会自动上传";
|
||||
return;
|
||||
}
|
||||
|
||||
_scan.TriggerUpload();
|
||||
StatusText.Text = "已请求上传,稍等…";
|
||||
}
|
||||
|
||||
private void Clear_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var selected = (ChannelFilter.SelectedItem as ChannelOption)?.ChannelId;
|
||||
var scope = selected is null ? "全部通道" : $"通道 {selected}";
|
||||
var pending = ScanRecordStore.PendingCount();
|
||||
|
||||
var hint = pending > 0 ? $"\n\n注意:还有 {pending} 条没上传,清掉就找不回来了。" : string.Empty;
|
||||
if (MessageBox.Show(Window.GetWindow(this)!, $"确定清空{scope}的扫码记录?{hint}", "清空扫码记录",
|
||||
MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) return;
|
||||
|
||||
if (IsAgentMode)
|
||||
{
|
||||
AgentFiles.QueueCommand(command =>
|
||||
{
|
||||
command.ClearRecordsAt = DateTime.UtcNow;
|
||||
command.ClearChannelId = selected;
|
||||
});
|
||||
StatusText.Text = "已通知后台服务清空,稍等…";
|
||||
return;
|
||||
}
|
||||
|
||||
var removed = ScanRecordStore.Clear(selected);
|
||||
StatusText.Text = $"已清空 {removed} 条";
|
||||
_page = 0;
|
||||
_pageSignature = string.Empty;
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
104
desktop/Views/ScanTabView.xaml
Normal file
104
desktop/Views/ScanTabView.xaml
Normal file
@ -0,0 +1,104 @@
|
||||
<UserControl x:Class="YuncangTrace.LocalService.Views.ScanTabView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI" FontSize="13">
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="160" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 后台服务绑定的主体与当前主体不一致时由 MainWindow 显示 -->
|
||||
<Border x:Name="NoticeBar" Grid.Row="0" Background="#FFF7E6" BorderBrush="#F0D9A8"
|
||||
BorderThickness="1" CornerRadius="6" Padding="10,7" Margin="0,0,0,8"
|
||||
Visibility="Collapsed">
|
||||
<TextBlock x:Name="NoticeText" TextWrapping="Wrap" FontSize="12" Foreground="#8A5A00" />
|
||||
</Border>
|
||||
|
||||
<!-- 通道列表(状态 + 按钮都在标题行) -->
|
||||
<Border Grid.Row="1" Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="8">
|
||||
<DockPanel>
|
||||
<DockPanel DockPanel.Dock="Top" Margin="2,0,0,6" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="扫码通道" FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Margin="12,0,0,0">
|
||||
<Button x:Name="ReconnectButton" Content="重连全部" Padding="10,3" Click="Reconnect_Click" />
|
||||
<Button x:Name="ToggleButton" Content="停用" Padding="10,3" Margin="8,0,0,0" Click="Toggle_Click" />
|
||||
<Button x:Name="MuteButton" Content="静音" Padding="10,3" Margin="8,0,0,0" Click="Mute_Click" />
|
||||
<Button x:Name="ConfigButton" Content="读取设备配置" Padding="10,3" Margin="8,0,0,0" Click="ReadConfig_Click" />
|
||||
<Button x:Name="RawCommandButton" Content="串口指令…" Padding="10,3" Margin="8,0,0,0" Click="RawCommand_Click" />
|
||||
<Button x:Name="RemoveButton" Content="删除通道" Padding="10,3" Margin="8,0,0,0" Click="Remove_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="ChannelStatusText" DockPanel.Dock="Right" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Right" TextTrimming="CharacterEllipsis"
|
||||
Text="通道 = 一台扫码设备;收到条码会自动上报到服务器" />
|
||||
</DockPanel>
|
||||
<ListView x:Name="ChannelList" BorderThickness="0" SelectionMode="Single"
|
||||
SelectionChanged="ChannelList_SelectionChanged">
|
||||
<ListView.View>
|
||||
<GridView>
|
||||
<GridViewColumn Header="号" Width="46" DisplayMemberBinding="{Binding Number}" />
|
||||
<GridViewColumn Header="名称" Width="150" DisplayMemberBinding="{Binding DisplayName}" />
|
||||
<GridViewColumn Header="MAC" Width="130" DisplayMemberBinding="{Binding Mac}" />
|
||||
<GridViewColumn Header="IP" Width="120" DisplayMemberBinding="{Binding LastIp}" />
|
||||
<GridViewColumn Header="状态" Width="70" DisplayMemberBinding="{Binding StateText}" />
|
||||
<GridViewColumn Header="静音" Width="70" DisplayMemberBinding="{Binding MuteText}" />
|
||||
<GridViewColumn Header="最近条码" Width="220" DisplayMemberBinding="{Binding LastCode}" />
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
</ListView>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 发现到的设备(状态 + 按钮都在标题行) -->
|
||||
<DockPanel Grid.Row="2" Margin="0,10,0,6" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="发现到的设备(局域网 UDP 48899)" FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Margin="12,0,0,0">
|
||||
<ToggleButton x:Name="DiscoverToggle" Content="开始扫描" Padding="10,3" Click="Discover_Toggle" />
|
||||
<Button x:Name="AddButton" Content="添加为通道" Padding="10,3" Margin="8,0,0,0" Click="Add_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="DiscoverStatusText" DockPanel.Dock="Right" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Right" TextTrimming="CharacterEllipsis"
|
||||
Text="未开始扫描" />
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="3" Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="8">
|
||||
<ListView x:Name="DeviceList" BorderThickness="0" SelectionMode="Single">
|
||||
<ListView.View>
|
||||
<GridView>
|
||||
<GridViewColumn Header="设备名" Width="140" DisplayMemberBinding="{Binding HostName}" />
|
||||
<GridViewColumn Header="IP" Width="130" DisplayMemberBinding="{Binding Ip}" />
|
||||
<GridViewColumn Header="MAC" Width="130" DisplayMemberBinding="{Binding Mac}" />
|
||||
<GridViewColumn Header="型号" Width="90" DisplayMemberBinding="{Binding Model}" />
|
||||
<GridViewColumn Header="版本" Width="90" DisplayMemberBinding="{Binding Version}" />
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
</ListView>
|
||||
</Border>
|
||||
|
||||
<!-- 设备配置 -->
|
||||
<Border Grid.Row="4" Background="#F8FAFC" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="10" Margin="0,8,0,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.Column="0">
|
||||
<TextBlock Text="设备配置(选中通道后点「读取设备配置」)" FontWeight="SemiBold" Margin="0,0,0,6" />
|
||||
<TextBlock x:Name="ConfigText" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap"
|
||||
Text="—" FontFamily="Consolas, Microsoft YaHei UI" FontSize="12" />
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1" VerticalAlignment="Bottom">
|
||||
<Button x:Name="RestartButton" Content="重启设备" Padding="12,4" Click="Restart_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
488
desktop/Views/ScanTabView.xaml.cs
Normal file
488
desktop/Views/ScanTabView.xaml.cs
Normal file
@ -0,0 +1,488 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Threading;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 「扫码通道」页签(桌面端开启扫码服务后才显示):
|
||||
/// 通道列表 / 设备发现 / 设备配置,收码与上报由 <see cref="ScanService"/> 负责。
|
||||
/// </summary>
|
||||
public partial class ScanTabView : UserControl
|
||||
{
|
||||
private readonly ScanService _scan;
|
||||
private readonly ObservableCollection<ChannelRow> _rows = new();
|
||||
|
||||
/// <summary>发现到的**全部**设备(含已添加的);显示时再按通道过滤</summary>
|
||||
private readonly ObservableCollection<DiscoveredDevice> _allDevices = new();
|
||||
|
||||
/// <summary>界面上显示的设备(已排除已添加为通道的)</summary>
|
||||
private readonly ObservableCollection<DiscoveredDevice> _devices = new();
|
||||
|
||||
/// <summary>服务模式:后台服务写的状态(在线/离线、最近条码)</summary>
|
||||
private readonly DispatcherTimer _agentTimer = new() { Interval = TimeSpan.FromSeconds(1) };
|
||||
private AgentStatus? _agentStatus;
|
||||
private DateTime _agentStatusAt;
|
||||
|
||||
private static bool IsAgentMode => AgentPaths.MachineMode && !AgentPaths.IsServiceProcess;
|
||||
|
||||
public ScanTabView(ScanService scan)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_scan = scan;
|
||||
ChannelList.ItemsSource = _rows;
|
||||
DeviceList.ItemsSource = _devices;
|
||||
|
||||
// 事件**一直挂着**,不在 Unloaded 里退订:
|
||||
// TabControl 切页签、窗口隐藏到托盘都会触发 Unloaded,退订的话界面就再也不刷新
|
||||
// (真机踩过:连接明明是好的,界面永远停在“离线”)。
|
||||
// 切页签也**不停发现**——开关打开就该一直发现,直到用户自己关。
|
||||
_scan.Changed += OnScanChanged;
|
||||
_scan.DiscoveredChanged += OnDiscoveredChanged;
|
||||
|
||||
Loaded += (_, _) => Refresh();
|
||||
|
||||
if (IsAgentMode)
|
||||
{
|
||||
_agentTimer.Tick += (_, _) => ApplyAgentStatus();
|
||||
_agentTimer.Start();
|
||||
}
|
||||
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>后台服务绑定的主体与当前主体不一致时的提示(null / 空 = 隐藏)</summary>
|
||||
public void SetNotice(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
NoticeText.Text = string.Empty;
|
||||
NoticeBar.Visibility = Visibility.Collapsed;
|
||||
return;
|
||||
}
|
||||
|
||||
NoticeText.Text = text;
|
||||
NoticeBar.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务模式:把后台服务写的运行状态盖到本地通道对象上(服务才是真正连设备的那一方)。
|
||||
/// 发现列表也读服务写的 agent-discovered.json。
|
||||
/// </summary>
|
||||
private void ApplyAgentStatus()
|
||||
{
|
||||
var status = AgentFiles.LoadStatus();
|
||||
if (status is null) return;
|
||||
|
||||
if (status.UpdatedAt == _agentStatusAt) return; // 没变化不用重画
|
||||
_agentStatusAt = status.UpdatedAt;
|
||||
_agentStatus = status;
|
||||
|
||||
foreach (var channel in _scan.Channels)
|
||||
{
|
||||
var runtime = status.Channels.FirstOrDefault(item =>
|
||||
item.Mac.Equals(channel.Mac, StringComparison.OrdinalIgnoreCase));
|
||||
if (runtime is null)
|
||||
{
|
||||
channel.Connected = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
channel.Connected = runtime.Connected;
|
||||
if (!string.IsNullOrWhiteSpace(runtime.LastIp)) channel.LastIp = runtime.LastIp;
|
||||
channel.LastCode = runtime.LastCode;
|
||||
channel.LastCodeAt = runtime.LastCodeAt;
|
||||
}
|
||||
|
||||
var discovered = AgentFiles.LoadDiscovered();
|
||||
_allDevices.Clear();
|
||||
foreach (var item in discovered)
|
||||
{
|
||||
_allDevices.Add(new DiscoveredDevice(item.Mac, item.Ip, item.HostName, item.Model, item.Firmware, "online"));
|
||||
}
|
||||
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>服务模式的通道状态行(数据来自 agent-status.json)</summary>
|
||||
private string BuildAgentStatusText()
|
||||
{
|
||||
var status = _agentStatus ?? AgentFiles.LoadStatus();
|
||||
if (status is null) return "后台扫码服务状态未知(还没写入 agent-status.json)";
|
||||
|
||||
if (!status.Running)
|
||||
{
|
||||
return "后台扫码服务未运行"
|
||||
+ (string.IsNullOrWhiteSpace(status.LastError) ? "" : $":{status.LastError}");
|
||||
}
|
||||
|
||||
var online = _rows.Count(item => item.StateText == "在线");
|
||||
var text = $"后台服务运行中 · 通道 {_rows.Count} 个(在线 {online})";
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(status.ChannelSyncStatus)) text += $" · {status.ChannelSyncStatus}";
|
||||
if (!string.IsNullOrWhiteSpace(status.UploadStatus)) text += $" · {status.UploadStatus}";
|
||||
else if (status.PendingRecords > 0) text += $" · 待上传 {status.PendingRecords} 条扫码记录";
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>列表行(界面显示用)</summary>
|
||||
public sealed class ChannelRow
|
||||
{
|
||||
public int Number { get; init; }
|
||||
public string DisplayName { get; init; } = string.Empty;
|
||||
public string Mac { get; init; } = string.Empty;
|
||||
public string LastIp { get; init; } = string.Empty;
|
||||
public string StateText { get; init; } = string.Empty;
|
||||
public string MuteText { get; init; } = string.Empty;
|
||||
public string LastCode { get; init; } = string.Empty;
|
||||
public ScanChannel Source { get; init; } = null!;
|
||||
}
|
||||
|
||||
private void OnScanChanged()
|
||||
{
|
||||
Dispatcher.Invoke(Refresh);
|
||||
}
|
||||
|
||||
/// <summary>选中项变了:同步按钮文案/可用性</summary>
|
||||
private void ChannelList_SelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateSelectionButtons();
|
||||
|
||||
private void UpdateSelectionButtons()
|
||||
{
|
||||
var current = ChannelList.SelectedItem as ChannelRow;
|
||||
ToggleButton.Content = current is not null && current.Source.Enabled ? "停用" : "启用";
|
||||
MuteButton.Content = current is not null && current.Source.Muted ? "恢复蜂鸣" : "静音";
|
||||
MuteButton.IsEnabled = current is not null;
|
||||
}
|
||||
|
||||
/// <summary>重新渲染通道列表(保持选中项)</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
var selected = (ChannelList.SelectedItem as ChannelRow)?.Source.Mac;
|
||||
|
||||
_rows.Clear();
|
||||
foreach (var channel in _scan.Channels.OrderBy(item => item.Number))
|
||||
{
|
||||
_rows.Add(new ChannelRow
|
||||
{
|
||||
Number = channel.Number,
|
||||
DisplayName = channel.DisplayName,
|
||||
Mac = channel.Mac,
|
||||
LastIp = channel.LastIp,
|
||||
StateText = !channel.Enabled ? "已停用" : channel.Connected ? "在线" : "离线",
|
||||
MuteText = channel.Muted ? "静音" : "—",
|
||||
LastCode = string.IsNullOrEmpty(channel.LastCode)
|
||||
? "—"
|
||||
: $"{channel.LastCode}({channel.LastCodeAt:HH:mm:ss})",
|
||||
Source = channel,
|
||||
});
|
||||
}
|
||||
|
||||
if (selected is not null)
|
||||
{
|
||||
var hit = _rows.FirstOrDefault(item => item.Source.Mac.Equals(selected, StringComparison.OrdinalIgnoreCase));
|
||||
if (hit is not null) ChannelList.SelectedItem = hit;
|
||||
}
|
||||
|
||||
UpdateSelectionButtons();
|
||||
|
||||
var status = IsAgentMode
|
||||
? BuildAgentStatusText()
|
||||
: _scan.Running
|
||||
? $"扫码服务运行中 · 通道 {_rows.Count} 个(在线 {_rows.Count(item => item.StateText == "在线")})"
|
||||
: "扫码服务未启动(菜单「服务 → 开启设备服务」后自动启动)";
|
||||
|
||||
// 同步/上报都是后台自动重试的,把它的状态摊在同一行里,别让人以为需要手动点
|
||||
if (!IsAgentMode)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_scan.ChannelSyncStatus)) status += $" · {_scan.ChannelSyncStatus}";
|
||||
if (!string.IsNullOrWhiteSpace(_scan.UploadStatus)) status += $" · {_scan.UploadStatus}";
|
||||
else
|
||||
{
|
||||
var (_, pending) = ScanRecordStore.Stats();
|
||||
if (pending > 0) status += $" · 待上传 {pending} 条扫码记录";
|
||||
}
|
||||
}
|
||||
|
||||
ChannelStatusText.Text = status;
|
||||
|
||||
ApplyDeviceFilter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按当前通道列表过滤发现结果:**已经添加为通道的设备不再显示**。
|
||||
///
|
||||
/// 显示集合与「发现到的全集」分开存:删掉通道后不用重新扫一轮,那台设备自己会回到列表里。
|
||||
/// </summary>
|
||||
private void ApplyDeviceFilter()
|
||||
{
|
||||
var added = new HashSet<string>(_scan.Channels.Select(item => item.Mac), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
_devices.Clear();
|
||||
foreach (var device in _allDevices.Where(item => !added.Contains(item.Mac)))
|
||||
{
|
||||
_devices.Add(device);
|
||||
}
|
||||
|
||||
var hidden = _allDevices.Count - _devices.Count;
|
||||
if (IsAgentMode)
|
||||
{
|
||||
DiscoverStatusText.Text = (_devices.Count == 0
|
||||
? (hidden > 0 ? $"后台服务扫描中…(发现的 {hidden} 台都已添加为通道)" : "后台服务扫描中…")
|
||||
: $"后台服务扫描中… 未添加 {_devices.Count} 台" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : ""));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_scan.Monitoring)
|
||||
{
|
||||
DiscoverStatusText.Text = _devices.Count == 0
|
||||
? (hidden > 0 ? $"正在扫描…(发现的 {hidden} 台都已添加为通道)" : "正在扫描…")
|
||||
: $"正在扫描… 未添加 {_devices.Count} 台" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : "");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_allDevices.Count == 0)
|
||||
{
|
||||
DiscoverStatusText.Text = "未开始扫描";
|
||||
return;
|
||||
}
|
||||
|
||||
DiscoverStatusText.Text = _devices.Count == 0
|
||||
? (hidden > 0 ? $"发现的 {hidden} 台都已添加为通道" : "未发现设备")
|
||||
: $"发现 {_devices.Count} 台未添加的设备" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : "");
|
||||
}
|
||||
|
||||
/// <summary>扫描开关:打开后**常驻发现**(每 3 秒探测一次、socket 一直开着收),直到用户手工停止</summary>
|
||||
private void Discover_Toggle(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (IsAgentMode)
|
||||
{
|
||||
DiscoverToggle.IsChecked = true;
|
||||
ChannelStatusText.Text = "服务模式下设备发现由后台服务常驻执行";
|
||||
return;
|
||||
}
|
||||
|
||||
if (DiscoverToggle.IsChecked == true)
|
||||
{
|
||||
DiscoverToggle.Content = "停止扫描";
|
||||
_scan.StartDiscovery();
|
||||
}
|
||||
else
|
||||
{
|
||||
DiscoverToggle.Content = "开始扫描";
|
||||
_scan.StopDiscovery();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>发现列表变了:整表替换成服务里的当前快照(已按 MAC 去重、已踢掉掉线设备)</summary>
|
||||
private void OnDiscoveredChanged() => Dispatcher.Invoke(() =>
|
||||
{
|
||||
var latest = _scan.DiscoveredDevices;
|
||||
|
||||
_allDevices.Clear();
|
||||
foreach (var device in latest) _allDevices.Add(device);
|
||||
|
||||
ApplyDeviceFilter();
|
||||
});
|
||||
|
||||
private async void Add_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DeviceList.SelectedItem is not DiscoveredDevice device)
|
||||
{
|
||||
MessageBox.Show(Window.GetWindow(this)!, "请先在下面的列表里选中一台设备", "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
// 先让用户定通道号 + 设备名(与 AndroidScanCenter 的添加流程一致)
|
||||
var dialog = new AddChannelWindow(device, _scan.Channels) { Owner = Window.GetWindow(this) };
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
|
||||
AddButton.IsEnabled = false;
|
||||
AddChannelWindow_ShowStage($"正在添加通道 {dialog.ChannelNumber}…");
|
||||
try
|
||||
{
|
||||
var result = await _scan.AddChannelAsync(
|
||||
device.Mac, dialog.ChannelName, device.Ip, dialog.ChannelNumber, device.HostName,
|
||||
stage => Dispatcher.Invoke(() => AddChannelWindow_ShowStage(stage)));
|
||||
|
||||
Refresh();
|
||||
ChannelStatusText.Text = result.Message;
|
||||
|
||||
if (!result.Ok)
|
||||
{
|
||||
MessageBox.Show(Window.GetWindow(this)!, result.Message, "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsAgentMode)
|
||||
{
|
||||
ChannelStatusText.Text = result.Message + "(已保存,后台服务会自动重连)";
|
||||
}
|
||||
else if (!_scan.Running)
|
||||
{
|
||||
MessageBox.Show(Window.GetWindow(this)!,
|
||||
$"{result.Message}\n\n开启「服务 → 开启设备服务」后才会开始连接设备收码。",
|
||||
"添加通道", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
_scan.RequestChannelSync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ChannelStatusText.Text = $"添加通道失败:{ex.Message}";
|
||||
MessageBox.Show(Window.GetWindow(this)!, $"添加通道失败:{ex.Message}", "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
AddButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>添加通道过程中的进度文案(回到界面线程再写控件)</summary>
|
||||
private void AddChannelWindow_ShowStage(string text)
|
||||
{
|
||||
ChannelStatusText.Text = text;
|
||||
}
|
||||
|
||||
private void Toggle_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
|
||||
_scan.SetEnabled(row.Source, !row.Source.Enabled);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 静音 / 恢复蜂鸣:只存本地 + 让这条连接重走一遍(连上时整条设置下发)。
|
||||
/// 已经断开的通道也能设 —— 下次连上自动生效。
|
||||
/// </summary>
|
||||
private void Mute_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
|
||||
var muted = !row.Source.Muted;
|
||||
_scan.SetMuted(row.Source, muted);
|
||||
Refresh();
|
||||
|
||||
ChannelStatusText.Text = muted
|
||||
? $"通道 {row.Number}「{row.DisplayName}」已设为静音(重新下发设置中)"
|
||||
: $"通道 {row.Number}「{row.DisplayName}」已恢复蜂鸣(重新下发设置中)";
|
||||
}
|
||||
|
||||
private void Remove_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
if (MessageBox.Show(Window.GetWindow(this)!, $"确定删除通道「{row.DisplayName}」?", "删除通道",
|
||||
MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) return;
|
||||
|
||||
_scan.RemoveChannel(row.Source);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private async void Reconnect_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (IsAgentMode)
|
||||
{
|
||||
AgentFiles.QueueCommand(command => command.ReloadChannelsAt = DateTime.UtcNow);
|
||||
ChannelStatusText.Text = "已通知后台服务重新连接全部通道";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_scan.Running)
|
||||
{
|
||||
ChannelStatusText.Text = "扫码服务未启动,先开启「服务 → 开启设备服务」";
|
||||
return;
|
||||
}
|
||||
|
||||
ReconnectButton.IsEnabled = false;
|
||||
try
|
||||
{
|
||||
_scan.Stop();
|
||||
await _scan.StartAsync();
|
||||
Refresh();
|
||||
ChannelStatusText.Text = "已重新连接全部通道";
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReconnectButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 串口指令调试:直接把 HEX 字节透传给扫码枪(静音指令对不上枪型号时现场自己试)。
|
||||
/// </summary>
|
||||
private async void RawCommand_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
|
||||
var dialog = new ScannerCommandWindow(row.Source) { Owner = Window.GetWindow(this) };
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
|
||||
var ok = await _scan.SendCommandAsync(row.Source, dialog.Payload);
|
||||
ChannelStatusText.Text = ok
|
||||
? $"已向通道 {row.Number} 的扫码枪下发 {dialog.Payload.Length} 字节"
|
||||
: "该通道当前未连接,指令没发出去";
|
||||
}
|
||||
|
||||
private async void ReadConfig_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
if (string.IsNullOrWhiteSpace(row.Source.LastIp))
|
||||
{
|
||||
ConfigText.Text = "该通道还没有 IP,先扫描一次设备";
|
||||
return;
|
||||
}
|
||||
|
||||
ConfigText.Text = "正在读取…";
|
||||
try
|
||||
{
|
||||
var config = await _scan.ReadConfigAsync(row.Source.LastIp);
|
||||
ConfigText.Text = config is null
|
||||
? "读取失败(设备不支持 / 不在线)"
|
||||
: $"设备名:{config.HostName}\n"
|
||||
+ $"网络:{(config.DhcpEn ? "DHCP" : "静态")} {config.IpAddr} / {config.Mask} / 网关 {config.GateWay} / DNS {config.Dns}\n"
|
||||
+ $"登录:{config.User} / {config.Password}";
|
||||
ChannelStatusText.Text = $"已读取 {row.Source.LastIp} 的配置";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ConfigText.Text = $"读取失败:{ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private async void Restart_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ChannelList.SelectedItem is not ChannelRow row) return;
|
||||
if (string.IsNullOrWhiteSpace(row.Source.LastIp))
|
||||
{
|
||||
ConfigText.Text = "该通道还没有 IP,先扫描一次设备";
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show(Window.GetWindow(this)!,
|
||||
$"重启设备「{row.DisplayName}」({row.Source.LastIp})?\n\n设备上会短暂断连,稍后自动重连。",
|
||||
"重启设备", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) return;
|
||||
|
||||
try
|
||||
{
|
||||
var ok = await _scan.RestartAsync(row.Source.LastIp);
|
||||
ConfigText.Text = ok ? "已下发重启命令(设备可能延迟几十秒才真正复位)" : "重启命令下发失败";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ConfigText.Text = $"重启失败:{ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
41
desktop/Views/ScannerCommandWindow.xaml
Normal file
41
desktop/Views/ScannerCommandWindow.xaml
Normal file
@ -0,0 +1,41 @@
|
||||
<Window x:Class="YuncangTrace.LocalService.ScannerCommandWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="串口指令"
|
||||
Height="400" Width="520"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
FontSize="13">
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="10" Margin="18" Padding="18">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="给扫码枪发串口指令" FontSize="15" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="DeviceText" DockPanel.Dock="Top" FontSize="12"
|
||||
Foreground="{StaticResource MutedBrush}" Margin="0,4,0,10" TextWrapping="Wrap" />
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,12,0,0">
|
||||
<Button Content="取消" Padding="14,5" IsCancel="True" Click="Cancel_Click" />
|
||||
<Button Content="发送" Padding="14,5" Margin="8,0,0,0" IsDefault="True"
|
||||
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
|
||||
Cursor="Hand" Click="Ok_Click" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel>
|
||||
<TextBlock Text="指令(十六进制,空格分隔)" FontWeight="SemiBold" Margin="0,0,0,4" />
|
||||
<TextBox x:Name="HexBox" Height="120" Padding="6,4" AcceptsReturn="True"
|
||||
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12"
|
||||
VerticalScrollBarVisibility="Auto" />
|
||||
<TextBlock FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,6,0,0" TextWrapping="Wrap"
|
||||
Text="通过设备已有的 TCP 连接写进去,设备会透传到串口(Rout=uart)。下面几条是常用指令,点一下即可填入:" />
|
||||
<WrapPanel Margin="0,6,0,0">
|
||||
<Button Content="静音(0x01)" Padding="8,2" Margin="0,0,8,6" Click="MuteOn_Click" />
|
||||
<Button Content="恢复蜂鸣(0x00)" Padding="8,2" Margin="0,0,8,6" Click="MuteOff_Click" />
|
||||
<Button Content="连续扫描" Padding="8,2" Margin="0,0,8,6" Click="Continuous_Click" />
|
||||
<Button Content="识别间隔 0s" Padding="8,2" Margin="0,0,8,6" Click="Interval_Click" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Window>
|
||||
68
desktop/Views/ScannerCommandWindow.xaml.cs
Normal file
68
desktop/Views/ScannerCommandWindow.xaml.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 「串口指令」调试窗:把任意 HEX 字节透传给扫码枪。
|
||||
///
|
||||
/// 为什么需要它:静音/触发模式这类设置是**扫码枪**的,指令以厂商提供的为准;
|
||||
/// 现场换了一批枪时指令集可能不同,有一个能直接发字节的地方,比重新发版快得多。
|
||||
/// </summary>
|
||||
public partial class ScannerCommandWindow : Window
|
||||
{
|
||||
public ScannerCommandWindow(ScanChannel channel)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
DeviceText.Text = $"{channel.Number} · {channel.DisplayName}({channel.Mac} · {channel.LastIp})"
|
||||
+ (channel.Connected ? " · 在线" : " · 离线(连上后才能发)");
|
||||
|
||||
// 预填当前静音状态对应的指令,方便对照试
|
||||
HexBox.Text = ToHex(channel.Muted ? ScannerCommands.MuteOn : ScannerCommands.MuteOff);
|
||||
}
|
||||
|
||||
/// <summary>要发送的字节(确定后有值)</summary>
|
||||
public byte[] Payload { get; private set; } = Array.Empty<byte>();
|
||||
|
||||
private static string ToHex(byte[] bytes) => string.Join(' ', bytes.Select(b => b.ToString("X2")));
|
||||
|
||||
private void Ok_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var text = (HexBox.Text ?? string.Empty).Replace("0x", string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
var tokens = text.Split(new[] { ' ', ',', '\r', '\n', '\t', '-' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var bytes = new byte[tokens.Length];
|
||||
for (var i = 0; i < tokens.Length; i++)
|
||||
{
|
||||
if (!byte.TryParse(tokens[i], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out bytes[i]))
|
||||
{
|
||||
MessageBox.Show(this, $"第 {i + 1} 个字节不是合法十六进制:{tokens[i]}", "串口指令",
|
||||
MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (bytes.Length == 0)
|
||||
{
|
||||
MessageBox.Show(this, "请先填写要发送的指令", "串口指令", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
Payload = bytes;
|
||||
DialogResult = true;
|
||||
}
|
||||
|
||||
private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
|
||||
private void MuteOn_Click(object sender, RoutedEventArgs e) => HexBox.Text = ToHex(ScannerCommands.MuteOn);
|
||||
|
||||
private void MuteOff_Click(object sender, RoutedEventArgs e) => HexBox.Text = ToHex(ScannerCommands.MuteOff);
|
||||
|
||||
private void Continuous_Click(object sender, RoutedEventArgs e) => HexBox.Text = ToHex(ScannerCommands.TriggerContinuous);
|
||||
|
||||
private void Interval_Click(object sender, RoutedEventArgs e) => HexBox.Text = ToHex(ScannerCommands.IntervalZero);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user