桌面端
- 新增 LocalWsServer(ws://127.0.0.1:17301):hello / ping / get_channels /
start_preview / stop_preview / open_window / close_window / ptz / ptz_preset,
一条连接可同时推多路 JPEG 帧(帧头带 sid);慢命令并发派发,云台命令按连接串行,
页面断开自动清理会话与满帧率窗口
- LocalHttpServer 删除预览(MJPEG/快照/满帧率窗口)、/api/hik/channels、/api/hik/ptz*,
HTTP 17300 只保留 /api/query/{code}、/api/activate-login、/api/playback/download,
其余 POST 统一回 404 并提示已迁到 WS;不再依赖 HCNetSDK
- App 自行组装 HikStreamService -> HikPreviewService + HikNativePreviewService 注入 WS
- 后台服务加固:框架依赖(开发版)安装/启动时自动写服务环境变量 DOTNET_ROOT,
避免 LocalSystem 找不到用户目录里的 .NET 8 而报「后台服务启动超时」
前端
- 新增 api/localWs.ts(连接/断线/请求-响应/二进制帧分发),补 getChannels / openWindow /
closeWindow / ptz / ptzPreset
- CamerasView 预览只走 WS(保留「唤起本机软件 -> 等待 -> 提示安装」兜底),
满帧率窗口、云台、预置点改走 WS
- NvrsView 拉取通道改走 WS(连不上时自动唤起一次再重试)
- CameraLayoutCanvas 合成画面 4 路改 WS 推帧
- 删除 createHikPreview/closeHikPreview*/openHikWindow/closeHikWindow*/ptzControl/ptzPreset
与 isLocalServiceAlive/waitForLocalService
其他
- 移除 cameras.has_ptz(迁移 20261019233000)与相关接口/字段/UI
- 通道号按 struStreamMode 映射(IP 通道空槽导致 51 之后整体错位)
- 扫码 24 小时内只保留最后一次扫描(后上报时间更新时覆盖)
- 清理历史 DESKTOP 占位通道(迁移 20261019230000)
- README / desktop README 补 17301 与 WS 接口说明,修正已删除的 /api/health 描述
381 lines
14 KiB
C#
381 lines
14 KiB
C#
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 && !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();
|
||
}
|
||
}
|