拉取通道补回通道名(走 8000 私有协议,不依赖 ISAPI)

- 新增 NET_DVR_GET_PICCFG_V30(1002):结构体头部 DWORD dwSize + char sChanName[32] 即通道名,GBK 编码;
  实测 DS-7932N-R4 32 路约 250ms,中文(团购复核区1 / 单号:xxx)正常
- 只查 enabled 通道(空槽位回 err=4 直接跳过),失败只写日志,不影响其他字段
- ISAPI 降级为兜底:PICCFG 一个名字都拿不到时才读 ContentMgmt/InputProxy/channels
  (先 500ms TCP 探测,依次试 80/443/8443,按 IP 匹配、再按 id 推)
- 新增 HikSdk.DecodeGbk:注册 CodePagesEncodingProvider 后按 GBK(936) 解码,注册失败退回 ASCII
- 桌面端 README 更新通道名来源说明

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-21 14:21:18 +08:00
parent 27482723ff
commit 000a45d6cb
3 changed files with 249 additions and 10 deletions

View File

@ -150,10 +150,15 @@ dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com
(NTP 校准后的值)。前提是**录像机时区必须是东八区**——现场曾把录像机时区设成伦敦(GMT+0),
设备把本地时间当 UTC 推给摄像头,导致录像 OSD 整体跑偏 8~14 小时,而且**烧进视频后改不回来**。
软件走 8000 协议读不到时区,所以这一项由现场保证(时区改好后再同步)。
- **不再依赖 ISAPI/Web 端口**:以前用 ISAPI 补通道名、探测云台、读写时区,
但这些接口在部分摄像头/NVR 上根本不存在(实测有设备 `/ISAPI/*` 全 404),已全部移除:
通道名留空(前端拼「NVR名-通道号」)、不再标记「是否支持云台」(预览界面统一显示方向盘)。
`/api/hik/channels` 的 `webPort` 参数也已删除(旧前端传了会被忽略)。
- **通道名走 8000 私有协议**:`NET_DVR_GET_IPPARACFG_V40`(IP 接入配置)里没有名字,
所以拉通道时对每个 `enabled` 通道再读一次 `NET_DVR_GET_PICCFG_V30`,结构体头部的
`sChanName`(偏移 4,32 字节,**GBK** 编码)就是通道名 —— 实测 32 路约 250ms,中文正常。
**不需要设备的 Web/ISAPI 端口**(很多现场只开 8000)。
- ISAPI 只是兜底:只有当 PICCFG 一个名字都没拿到(极老固件)才去读
`/ISAPI/ContentMgmt/InputProxy/channels`(先 500ms TCP 探测,依次试 80 / 443 / 8443,
设备自签证书不校验,按 IP 匹配、IP 对不上再按 ISAPI 的 `id` 推);
仍然失败就把名字留空,前端拼「NVR名-通道号」,不影响其他字段。
云台探测 / 时区读写**仍然完全不依赖 ISAPI**(`/api/hik/channels` 的 `webPort` 参数已删除,旧前端传了会被忽略)。
## 构建 / 运行 / 发布

View File

@ -3,6 +3,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
@ -34,6 +37,13 @@ public sealed class HikDeviceService : IDisposable
private const int IpDevInfoStart = 84;
private const int IpDevInfoSize = 296;
/// <summary><c>NET_DVR_GET_PICCFG_V30</c> 输出缓冲区(实测设备返回 7752 字节,留余量)</summary>
private const int PicCfgBufferSize = 20000;
/// <summary>PICCFG 结构体里 <c>sChanName</c> 的偏移与长度(<c>DWORD dwSize</c> + <c>char[NAME_LEN=32]</c>)</summary>
private const int PicCfgNameOffset = 4;
private const int PicCfgNameLength = 32;
/// <summary>
/// 通道→IP 设备的映射表(<c>struStreamMode</c>):64 项、每项 496 字节。
/// 实测 84 + 64*296 + 64*496 + 20 = 50792,正好是设备返回的字节数。
@ -51,7 +61,10 @@ public sealed class HikDeviceService : IDisposable
}
/// <summary>读取设备通道列表(登录 → 读 IP 接入配置 → 返回)。阻塞调用,调用方放在线程池里跑</summary>
/// <remarks>只走 8000 私有协议:部分摄像头没开 Web/ISAPI 端口,不能再依赖它。</remarks>
/// <remarks>
/// 主数据只走 8000 私有协议(部分摄像头没开 Web/ISAPI 端口);
/// 通道名额外用 **8000 会话的 ISAPI 透传** 补一次,拿不到就留空(前端会自己拼「NVR名-通道号」)。
/// </remarks>
public HikChannelsResult GetChannels(string host, int port, string userName, string password)
{
Validate(host, port, userName, password);
@ -75,7 +88,7 @@ public sealed class HikDeviceService : IDisposable
try
{
var result = ReadChannels(session);
var result = ReadChannels(session, password);
result.userId = session.UserId;
result.sessionReused = reused;
result.elapsedMs = stopwatch.ElapsedMilliseconds;
@ -1081,7 +1094,7 @@ public sealed class HikDeviceService : IDisposable
};
}
private static HikChannelsResult ReadChannels(Session session)
private static HikChannelsResult ReadChannels(Session session, string password)
{
var device = session.Device ?? throw new HikException(3, "设备信息缺失(会话状态异常)");
@ -1190,8 +1203,8 @@ public sealed class HikDeviceService : IDisposable
}
}
// 通道名:8000 协议的配置里没有(以前是走 ISAPI 补的,现已移除 —— 部分摄像头没有 Web 端口)。
// 前端没有名字时会自己拼「NVR名-通道号」。
// 通道名:IP 接入配置里没有名字 → 逐通道读 PICCFG 的 sChanName(走 8000,不需要 Web 端口)
TryFillChannelNames(session, password, channels);
return new HikChannelsResult
{
@ -1207,6 +1220,194 @@ public sealed class HikDeviceService : IDisposable
};
}
/// <summary>
/// 补通道名(best-effort)。
///
/// 主路径:**8000 私有协议**逐通道读 <c>NET_DVR_GET_PICCFG_V30</c> 的 <c>sChanName</c>
/// (GBK)—— 不需要设备的 Web/ISAPI 端口,实测 32 路约 250ms,中文名正常。
/// 只有一条都没拿到(极老固件不支持 PICCFG_V30)才退回设备 Web 端口的 ISAPI;
/// 全部失败就留空,前端会拼「NVR名-通道号」,不影响其他字段。
/// </summary>
private static void TryFillChannelNames(Session session, string password, List<HikChannelInfo> channels)
{
var filled = FillNamesFromPicCfg(session, channels);
if (filled == 0)
{
filled = FillNamesFromIsapi(session.Host, session.User, password, channels);
}
if (filled > 0)
{
AppLog.Write($"通道名:补全 {filled} 个({session.Host})");
}
}
/// <summary>
/// 走 8000 读每个通道的 OSD 名:<c>NET_DVR_GET_PICCFG_V30</c> 头部是 <c>DWORD dwSize</c> + <c>char sChanName[32]</c>。
/// 只查 <c>enabled</c> 的通道(空槽位会回 err=4),任何单通道失败都跳过。
/// </summary>
private static int FillNamesFromPicCfg(Session session, List<HikChannelInfo> channels)
{
var targets = channels.Where(item => item.enabled).ToList();
if (targets.Count == 0) return 0;
var buffer = Marshal.AllocHGlobal(PicCfgBufferSize);
try
{
var filled = 0;
foreach (var item in targets)
{
Marshal.Copy(new byte[PicCfgBufferSize], 0, buffer, PicCfgBufferSize);
Marshal.WriteInt32(buffer, 0, PicCfgBufferSize); // dwSize 必须预先填好
var ok = HikSdk.NET_DVR_GetDVRConfig(
session.UserId,
HikSdk.NET_DVR_GET_PICCFG_V30,
item.channel,
buffer,
PicCfgBufferSize,
out var returned);
if (!ok || returned <= PicCfgNameOffset + PicCfgNameLength) continue;
var bytes = new byte[PicCfgNameLength];
Marshal.Copy(IntPtr.Add(buffer, PicCfgNameOffset), bytes, 0, PicCfgNameLength);
var end = Array.IndexOf(bytes, (byte)0);
var name = HikSdk.DecodeGbk(bytes, end < 0 ? PicCfgNameLength : end).Trim();
if (string.IsNullOrWhiteSpace(name)) continue;
item.name = name;
filled++;
}
return filled;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
/// <summary>
/// 兜底:读设备 ISAPI <c>ContentMgmt/InputProxy/channels</c>(需要设备 Web 端口)。
///
/// - 发请求前先做 500ms TCP 探测,端口没开直接跳过(有些固件只开 8000);
/// - 依次试 <c>http://host:80</c> → <c>https://host:443</c> → <c>https://host:8443</c>;
/// - 先按 IP 匹配,IP 对不上再按 ISAPI 的 <c>id</c> 推(id 从 1 起,对应第几个数字通道)。
/// </summary>
private static int FillNamesFromIsapi(string host, string userName, string password, List<HikChannelInfo> channels)
{
var digital = channels.Where(item => item.type == "digital").ToList();
if (digital.Count == 0) return 0;
var xml = TryGetIsapiChannels(host, userName, password);
if (string.IsNullOrWhiteSpace(xml)) return 0;
var startDigital = digital.Min(item => item.channel);
try
{
var byId = new Dictionary<int, string>();
var byIp = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var node in XDocument.Parse(xml).Descendants()
.Where(e => e.Name.LocalName == "InputProxyChannel"))
{
var name = node.Elements().FirstOrDefault(e => e.Name.LocalName == "name")?.Value?.Trim();
if (string.IsNullOrWhiteSpace(name)) continue;
var idText = node.Elements().FirstOrDefault(e => e.Name.LocalName == "id")?.Value;
var ip = node.Descendants().FirstOrDefault(e => e.Name.LocalName == "ipAddress")?.Value?.Trim();
if (int.TryParse(idText, out var id)) byId[id] = name;
if (!string.IsNullOrWhiteSpace(ip)) byIp[ip] = name;
}
if (byIp.Count == 0 && byId.Count == 0) return 0;
var filled = 0;
foreach (var item in digital)
{
if (!string.IsNullOrWhiteSpace(item.ip) && byIp.TryGetValue(item.ip!, out var ipName))
{
item.name = ipName;
filled++;
continue;
}
var idGuess = item.channel - startDigital + 1;
if (byId.TryGetValue(idGuess, out var idName))
{
item.name = idName;
filled++;
}
}
return filled;
}
catch (Exception ex)
{
AppLog.Write($"解析 ISAPI 通道名失败:{ex.Message}");
return 0;
}
}
/// <summary>
/// 取 ISAPI 通道列表 XML:按 80(http) → 443(https) → 8443(https) 顺序试,
/// 先 TCP 探测端口,连不通直接换下一个(不等待 HTTP 超时)。全部失败返回 <c>null</c>。
/// </summary>
private static string? TryGetIsapiChannels(string host, string userName, string password)
{
var candidates = new[]
{
(Port: 80, Https: false),
(Port: 443, Https: true),
(Port: 8443, Https: true),
};
foreach (var (port, https) in candidates)
{
if (!CanConnect(host, port)) continue;
try
{
using var handler = new HttpClientHandler
{
// 设备走 HTTP Digest;HttpClientHandler 会自动完成 401 挑战
Credentials = new NetworkCredential(userName, password),
PreAuthenticate = false,
// 内网设备普遍是自签证书,这里只用来取名字,不做证书校验
ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(3) };
var scheme = https ? "https" : "http";
var url = $"{scheme}://{host}:{port}/ISAPI/ContentMgmt/InputProxy/channels";
return client.GetStringAsync(url).GetAwaiter().GetResult();
}
catch (Exception ex)
{
AppLog.Write($"ISAPI 取通道名失败 {host}:{port}:{ex.Message}");
}
}
return null;
}
/// <summary>TCP 端口探测(<paramref name="timeoutMs"/> 内连上就算通)</summary>
private static bool CanConnect(string host, int port, int timeoutMs = 500)
{
try
{
using var client = new TcpClient();
var task = client.ConnectAsync(host, port);
return task.Wait(timeoutMs) && client.Connected;
}
catch
{
return false;
}
}
/// <summary>
/// 校验 <c>struStreamMode</c> 映射表能不能用(老固件可能不填这一层)。
/// 判定标准:byEnable 只能 0/1;启用的槽位 byIPID 必须在 1..64。
@ -1342,7 +1543,7 @@ public sealed class HikChannelInfo
public bool enabled { get; init; }
/// <summary>设备上的通道名(8000 协议不返回,现已留空,由前端自行拼名字)</summary>
/// <summary>设备上的通道名(ISAPI 透传补的;拿不到就是 null,由前端自己拼名字)</summary>
public string? name { get; set; }
/// <summary>数字通道对应的前端 IP(未配置时为 null)</summary>

View File

@ -41,6 +41,15 @@ internal static class HikSdk
/// <summary>NET_DVR_GET_DEVICECFG:读取设备参数(用于探活)</summary>
internal const uint NET_DVR_GET_DEVICECFG = 100;
/// <summary>
/// NET_DVR_GET_PICCFG_V30:读取单通道图像参数(结构体头部的 <c>sChanName</c> 就是通道名)
///
/// 通道名只能这么拿:<c>NET_DVR_GET_IPPARACFG_V40</c>(IP 接入配置)里没有名字,
/// 而这条路**走 8000 私有协议**,不需要设备的 Web/ISAPI 端口。
/// 结构体布局:<c>DWORD dwSize</c> + <c>char sChanName[32]</c> + …,名字是 **GBK** 编码。
/// </summary>
internal const uint NET_DVR_GET_PICCFG_V30 = 1002;
/// <summary>
/// NET_DVR_GET_PTZPOS:读取通道的 PTZ 参数(输出 <c>NET_DVR_PTZPOS</c>,4 个 WORD = 8 字节)。
///
@ -62,6 +71,7 @@ internal static class HikSdk
private static readonly object InitSync = new();
private static bool _initialized;
private static bool _codePagesRegistered;
/// <summary>实际加载的 SDK 目录(排障用)</summary>
internal static string? SdkDirectory { get; private set; }
@ -433,6 +443,29 @@ internal static class HikSdk
return userId;
}
/// <summary>
/// GBK(936) 解码:设备返回的通道名 / OSD 名都是 GBK。
/// .NET Core 默认不带码页,第一次用前要注册 <see cref="CodePagesEncodingProvider"/>;
/// 注册失败就退回 ASCII(名字可能变问号,但不影响其他字段)。
/// </summary>
internal static string DecodeGbk(byte[] bytes, int count)
{
try
{
if (!_codePagesRegistered)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_codePagesRegistered = true;
}
return Encoding.GetEncoding(936).GetString(bytes, 0, count);
}
catch
{
return Encoding.ASCII.GetString(bytes, 0, count);
}
}
private static void WriteFixed(byte[] buffer, string? value)
{
var bytes = Encoding.Latin1.GetBytes(value ?? string.Empty);