之前的判定是「本机连不上 NVR 才走 B」,导致同 LAN 多台机器各连各的, 录像机并发登录数照样被打满,设备管理服务的会话池闲置。 选路(StreamGateway) - 新增 StreamGateway:广播询问(带 NVR 地址)→ 有应答就用它, 没有才本机直连;结果缓存 15 秒(含"没找到"的负结果) - 转发失败时 Invalidate,下次重新探测 - 广播询问带 nvrHosts:对端实测连不上该 NVR 就不应答 校验走设备管理服务 - B 侧新增 POST /check,复用 HikPlaybackService.CheckAsync (真拉一小段,语义与桌面端本地校验一致) - 桌面端校验改为优先交给设备管理服务;服务无响应则降级本机并重新探测 - 并发上限 4,避免多台查询机同时校验把 NVR 打满 下载走设备管理服务 - PlaybackDownloadService 去掉 CanReachNvrAsync 判定,改用 StreamGateway - 服务端(hik-worker)自身不装网关,永远本地执行 其他 - 边端端口支持 YUNCANG_EDGE_UDP_PORT / YUNCANG_EDGE_HTTP_PORT 覆盖 (同机并行跑两个实例测试时用,与 YUNCANG_LOCAL_WS_PORT 同思路) - SDK 校验路径不数帧(返回 -1),界面只在有帧数时显示"试拉 N 帧" - 顺带修复:下载临时文件名未对 CameraName 做 Sanitize, 摄像头名含 ? : * 等字符时会整段下载失败 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
140 lines
5.4 KiB
C#
140 lines
5.4 KiB
C#
using System;
|
||
using System.Buffers.Binary;
|
||
using System.IO;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>
|
||
/// 服务主进程 ↔ <c>--hik-worker</c> 子进程的管道协议。
|
||
///
|
||
/// 为什么单独开子进程跑海康:HCNetSDK 是原生库,**访问越界会直接杀掉进程**
|
||
/// (0xC0000005),放主进程里等于把扫码收码/上报一起带走。
|
||
/// 隔离后 worker 崩了只需重启它,扫码链路无感。
|
||
///
|
||
/// 传输格式:<c>[4 字节小端长度][UTF-8 JSON]</c>。
|
||
/// 选命名管道而不是本机端口:不占端口、管道断开即知对端已死、ACL 天然限制访问者。
|
||
/// </summary>
|
||
public sealed record HikWorkerRequest(string Id, string Op, JsonElement? Payload)
|
||
{
|
||
public static HikWorkerRequest Create(string op, object? payload = null)
|
||
{
|
||
var element = payload is null
|
||
? (JsonElement?)null
|
||
: JsonSerializer.SerializeToElement(payload, HikWorkerJson.Options);
|
||
return new HikWorkerRequest(Guid.NewGuid().ToString("N"), op, element);
|
||
}
|
||
}
|
||
|
||
/// <summary>worker 的响应;<see cref="Data"/> 由调用方按 <see cref="Op"/> 自行反序列化</summary>
|
||
public sealed record HikWorkerResponse(string Id, bool Ok, string? Error, JsonElement? Data);
|
||
|
||
/// <summary>管道消息的读写(长度前缀 + JSON),两端共用</summary>
|
||
public static class HikWorkerPipe
|
||
{
|
||
/// <summary>管道名(服务单实例,固定名即可)</summary>
|
||
public const string PipeName = "YuncangTrace.HikWorker";
|
||
|
||
/// <summary>单条消息上限(流计划带十几个通道也远小于这个值)</summary>
|
||
private const int MaxMessageBytes = 8 * 1024 * 1024;
|
||
|
||
public static async Task WriteAsync<T>(Stream stream, T payload, CancellationToken ct)
|
||
{
|
||
var json = JsonSerializer.SerializeToUtf8Bytes(payload, HikWorkerJson.Options);
|
||
var header = new byte[4];
|
||
BinaryPrimitives.WriteInt32LittleEndian(header, json.Length);
|
||
|
||
await stream.WriteAsync(header, ct).ConfigureAwait(false);
|
||
await stream.WriteAsync(json, ct).ConfigureAwait(false);
|
||
await stream.FlushAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>读一条消息;对端正常关闭返回 null</summary>
|
||
public static async Task<T?> ReadAsync<T>(Stream stream, CancellationToken ct) where T : class
|
||
{
|
||
var header = new byte[4];
|
||
if (!await ReadExactAsync(stream, header, ct).ConfigureAwait(false)) return null;
|
||
|
||
var length = BinaryPrimitives.ReadInt32LittleEndian(header);
|
||
if (length is <= 0 or > MaxMessageBytes)
|
||
{
|
||
throw new InvalidDataException($"管道消息长度非法:{length}");
|
||
}
|
||
|
||
var buffer = new byte[length];
|
||
if (!await ReadExactAsync(stream, buffer, ct).ConfigureAwait(false))
|
||
{
|
||
throw new EndOfStreamException("管道消息被截断");
|
||
}
|
||
|
||
return JsonSerializer.Deserialize<T>(buffer, HikWorkerJson.Options);
|
||
}
|
||
|
||
private static async Task<bool> ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct)
|
||
{
|
||
var offset = 0;
|
||
while (offset < buffer.Length)
|
||
{
|
||
var read = await stream.ReadAsync(buffer.AsMemory(offset), ct).ConfigureAwait(false);
|
||
if (read == 0) return offset > 0 ? throw new EndOfStreamException("管道消息被截断") : false;
|
||
offset += read;
|
||
}
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/// <summary>统一的序列化选项(两端必须一致,否则时间/枚举会解析出偏差)</summary>
|
||
public static class HikWorkerJson
|
||
{
|
||
public static readonly JsonSerializerOptions Options = new()
|
||
{
|
||
PropertyNameCaseInsensitive = true,
|
||
// 中文警告/错误直接可读,不转 \uXXXX
|
||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
};
|
||
}
|
||
|
||
/// <summary>worker 支持的操作名(两端共用,避免拼错)</summary>
|
||
public static class HikWorkerOps
|
||
{
|
||
/// <summary>自检:返回 SDK / ffmpeg 是否就绪、录像根目录</summary>
|
||
public const string Probe = "probe";
|
||
|
||
/// <summary>按流计划下载并合并</summary>
|
||
public const string Download = "download";
|
||
|
||
/// <summary>优雅退出</summary>
|
||
public const string Shutdown = "shutdown";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 局域网发现用的端口(与 17300/17301 同族,但独立进程独立端口)。
|
||
///
|
||
/// - <see cref="UdpQuery"/>:收桌面端的广播询问(**询问-应答**,不是主动公告);
|
||
/// - <see cref="Http"/>:取流健康端点,桌面端用一次 TCP 连接就能判定"是否同 LAN"。
|
||
/// </summary>
|
||
public static class HikWorkerPorts
|
||
{
|
||
/// <summary>可用 <c>YUNCANG_EDGE_UDP_PORT</c> 临时覆盖(同机并行跑两个实例测试时用)</summary>
|
||
public static int UdpQuery { get; } = Resolve("YUNCANG_EDGE_UDP_PORT", 17310);
|
||
|
||
/// <summary>可用 <c>YUNCANG_EDGE_HTTP_PORT</c> 临时覆盖</summary>
|
||
public static int Http { get; } = Resolve("YUNCANG_EDGE_HTTP_PORT", 17311);
|
||
|
||
private static int Resolve(string name, int fallback)
|
||
{
|
||
var raw = Environment.GetEnvironmentVariable(name);
|
||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : fallback;
|
||
}
|
||
}
|
||
|
||
/// <summary>局域网询问/应答的报文(两端共用)</summary>
|
||
public static class HikWorkerDiscovery
|
||
{
|
||
public const string QueryType = "edge.query";
|
||
public const string ReplyType = "edge.reply";
|
||
}
|
||
|