- 新增 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>
557 lines
23 KiB
C#
557 lines
23 KiB
C#
using System;
|
||
using System.IO;
|
||
using System.Runtime.InteropServices;
|
||
using System.Text;
|
||
|
||
namespace YuncangTrace.LocalService.Services.Hik;
|
||
|
||
/// <summary>
|
||
/// 海康「设备网络 SDK(HCNetSDK)」的 P/Invoke 声明与初始化。
|
||
///
|
||
/// 只覆盖本项目需要的最小集合:<c>NET_DVR_Login_V40</c>(走 8000 私有协议)、
|
||
/// <c>NET_DVR_GetDVRConfig</c>(读 IP 通道配置)、<c>NET_DVR_Logout</c>。
|
||
///
|
||
/// ⚠️ 关键约束(都踩过):
|
||
/// 1. **必须 x64**:desktop 本身是 x64 进程,SDK 只能用 Win64 包(32 位会加载失败);
|
||
/// 2. **必须 SetDllDirectory**:HCNetSDK.dll 依赖同目录的 HCCore.dll 与 <c>HCNetSDKCom\</c> 组件,
|
||
/// 不指定目录会 DLL 找不到 → <c>NET_DVR_Init</c> 直接失败;
|
||
/// 3. **结构体要按字节对齐**:<see cref="NET_DVR_USER_LOGIN_INFO"/> 的 <c>Marshal.SizeOf</c> 必须为 416,
|
||
/// 少一个填充字节密码就会读错位;
|
||
/// 4. **密码传明文**:MD5/RSA 是 SDK 与设备内部的挑战应答,应用层传明文(实测传 MD5 必然 err=1)。
|
||
/// </summary>
|
||
internal static class HikSdk
|
||
{
|
||
private const string Dll = "HCNetSDK.dll";
|
||
|
||
/// <summary>NET_DVR_GET_IPPARACFG_V40:读取 IP 接入配置(含 IP 通道列表)</summary>
|
||
internal const uint NET_DVR_GET_IPPARACFG_V40 = 1062;
|
||
|
||
/// <summary>NET_DVR_GET_TIMECFG:读取设备时间(输出 NET_DVR_TIME,24 字节)</summary>
|
||
internal const uint NET_DVR_GET_TIMECFG = 118;
|
||
|
||
/// <summary>NET_DVR_SET_TIMECFG:写入设备时间(输入 NET_DVR_TIME)</summary>
|
||
internal const uint NET_DVR_SET_TIMECFG = 119;
|
||
|
||
/// <summary>NET_DVR_GET_NTPCFG:读取 NTP 配置(输出 NET_DVR_NTPPARA,126 字节)</summary>
|
||
internal const uint NET_DVR_GET_NTPCFG = 224;
|
||
|
||
/// <summary>NET_DVR_SET_NTPCFG:写入 NTP 配置(输入 NET_DVR_NTPPARA)</summary>
|
||
internal const uint NET_DVR_SET_NTPCFG = 225;
|
||
|
||
/// <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 字节)。
|
||
///
|
||
/// 文档写明是「获取 IP 快球 PTZ 参数」:**非云台通道通常返回失败**(err=17/23)。
|
||
/// 拉取通道时已不再调用(预览界面统一显示云台方向盘,不再标记「是否支持云台」)。
|
||
/// </summary>
|
||
internal const uint NET_DVR_GET_PTZPOS = 293;
|
||
|
||
/// <summary>
|
||
/// NET_DVR_JPEGPARA.wPicSize 常用值
|
||
///
|
||
/// <c>0xFF</c> = 用当前码流分辨率(部分老固件不支持,会回 err=17/23,调用方需降级重试)。
|
||
/// </summary>
|
||
internal const byte JpegSizeCurrent = 0xFF;
|
||
|
||
internal const byte JpegSize720P = 0x0B;
|
||
|
||
internal const byte JpegSizeD1 = 0x02;
|
||
|
||
private static readonly object InitSync = new();
|
||
private static bool _initialized;
|
||
private static bool _codePagesRegistered;
|
||
|
||
/// <summary>实际加载的 SDK 目录(排障用)</summary>
|
||
internal static string? SdkDirectory { get; private set; }
|
||
|
||
/// <summary>设备网络 SDK 的登录参数结构体(Win64 下 sizeof = 416)</summary>
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
internal struct NET_DVR_USER_LOGIN_INFO
|
||
{
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 129)] public byte[] sDeviceAddress;
|
||
public byte byUseTransport;
|
||
public ushort wPort;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sUserName;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sPassword;
|
||
public IntPtr cbLoginResult;
|
||
public IntPtr pUser;
|
||
public int bUseAsynLogin;
|
||
public byte byProxyType;
|
||
public byte byUseUTCTime;
|
||
public byte byLoginMode;
|
||
public byte byHttps;
|
||
public int iProxyID;
|
||
public byte byVerifyMode;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 119)] public byte[] byRes3;
|
||
}
|
||
|
||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||
private static extern bool SetDllDirectory(string lpPathName);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
private static extern bool NET_DVR_Init();
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
private static extern bool NET_DVR_Cleanup();
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern uint NET_DVR_GetLastError();
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
private static extern bool NET_DVR_SetConnectTime(uint dwWaitTime, uint dwTryTimes);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
private static extern bool NET_DVR_SetReconnect(uint dwInterval, int bEnableRecon);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
private static extern int NET_DVR_Login_V40(ref NET_DVR_USER_LOGIN_INFO pLoginInfo, IntPtr lpDeviceInfo);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_Logout(int lUserID);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_GetDVRConfig(
|
||
int lUserID,
|
||
uint dwCommand,
|
||
int lChannel,
|
||
IntPtr lpOutBuffer,
|
||
uint dwOutBufferSize,
|
||
out uint lpBytesReturned);
|
||
|
||
/// <summary>写设备配置(如 <c>NET_DVR_SET_NTPCFG</c>);<paramref name="lpInBuffer"/> 指向命令对应的结构体</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_SetDVRConfig(
|
||
int lUserID,
|
||
uint dwCommand,
|
||
int lChannel,
|
||
IntPtr lpInBuffer,
|
||
uint dwInBufferSize);
|
||
|
||
/// <summary>
|
||
/// 从设备抓一帧 JPEG(走 8000 私有协议,**不需要** ISAPI/Web 端口)
|
||
///
|
||
/// 预览就是靠它按 fps 连续抓帧、再以 MJPEG 推给浏览器;不需要解码器,也不需要转码进程。
|
||
/// <c>lpJpegPara</c> 指向 <c>NET_DVR_JPEGPARA</c>(WORD wPicSize + WORD wPicQuality,4 字节)。
|
||
/// </summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_CaptureJPEGPicture_NEW(
|
||
int lUserID,
|
||
int lChannel,
|
||
IntPtr lpJpegPara,
|
||
IntPtr sJpegPicBuffer,
|
||
uint dwPicSize,
|
||
out uint lpSizeReturned);
|
||
|
||
/// <summary>
|
||
/// 实时预览信息(HCNetSDK.h 的 <c>NET_DVR_PREVIEWINFO</c>,x64 下 sizeof = 288)
|
||
///
|
||
/// 头文件**没有** <c>#pragma pack</c>,所以按自然对齐声明:<c>hPlayWnd</c> 前有 4 字节填充。
|
||
/// </summary>
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
internal struct NET_DVR_PREVIEWINFO
|
||
{
|
||
public int lChannel;
|
||
public uint dwStreamType; // 0-主码流 1-子码流 2-第三码流
|
||
public uint dwLinkMode; // 0-TCP
|
||
public IntPtr hPlayWnd; // 0 = 只要数据、不显示
|
||
public uint bBlocked;
|
||
public uint bPassbackRecord;
|
||
public byte byPreviewMode;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] byStreamID;
|
||
public byte byProtoType;
|
||
public byte byRes1;
|
||
public byte byVideoCodingType;
|
||
public uint dwDisplayBufNum;
|
||
public byte byNPQMode;
|
||
public byte byRecvMetaData;
|
||
public byte byDataType;
|
||
public byte byReconnect;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 212)] public byte[] byRes;
|
||
}
|
||
|
||
/// <summary>实时流数据回调(dwDataType:1-系统头,2-流数据)</summary>
|
||
internal delegate void RealDataCallback(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern int NET_DVR_RealPlay_V40(
|
||
int lUserID,
|
||
ref NET_DVR_PREVIEWINFO lpPreviewInfo,
|
||
RealDataCallback? fRealDataCallBack_V30,
|
||
IntPtr pUser);
|
||
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_StopRealPlay(int lRealHandle);
|
||
|
||
/// <summary>
|
||
/// 云台连续动作(不依赖预览句柄,直接用登录的 UserID + 通道号)
|
||
///
|
||
/// <paramref name="dwStop"/>:0=开始,1=停止。云台必须“开始 + 停止”成对调用,否则会一直转。
|
||
/// </summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_PTZControlWithSpeed_Other(
|
||
int lUserID,
|
||
int lChannel,
|
||
uint dwPTZCommand,
|
||
uint dwStop,
|
||
uint dwSpeed);
|
||
|
||
/// <summary>预置点:设置 / 调用 / 删除(<c>dwPTZPresetCmd</c> 见 <see cref="HikPtz"/>)</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_PTZPreset_Other(
|
||
int lUserID,
|
||
int lChannel,
|
||
uint dwPTZPresetCmd,
|
||
uint dwPresetIndex);
|
||
|
||
// ==================== 按时间下载录像(走 8000 私有协议) ====================
|
||
|
||
/// <summary>HCNetSDK 的 <c>NET_DVR_TIME</c>(sizeof = 24)</summary>
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
internal struct NET_DVR_TIME
|
||
{
|
||
public uint dwYear;
|
||
public uint dwMonth;
|
||
public uint dwDay;
|
||
public uint dwHour;
|
||
public uint dwMinute;
|
||
public uint dwSecond;
|
||
}
|
||
|
||
/// <summary>
|
||
/// HCNetSDK 的 <c>NET_DVR_NTPPARA</c>(sizeof = 126)
|
||
///
|
||
/// <code>
|
||
/// BYTE sNTPServer[64]; // 域名/IP,ASCII
|
||
/// WORD wInterval; // 同步间隔(分钟)
|
||
/// BYTE byEnable; // 0-关闭 1-启用
|
||
/// BYTE byRes[59];
|
||
/// </code>
|
||
/// </summary>
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
internal struct NET_DVR_NTPPARA
|
||
{
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sNTPServer;
|
||
public ushort wInterval;
|
||
public byte byEnable;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 59)] public byte[] byRes;
|
||
}
|
||
|
||
/// <summary>
|
||
/// HCNetSDK 的 <c>NET_DVR_PLAYCOND</c>(sizeof = 356)
|
||
///
|
||
/// <code>
|
||
/// DWORD dwChannel; NET_DVR_TIME struStartTime; NET_DVR_TIME struStopTime;
|
||
/// BYTE byStreamType; BYTE byDownload; BYTE byOptimalStreamType; BYTE byRes2[301];
|
||
/// </code>
|
||
/// </summary>
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
internal struct NET_DVR_PLAYCOND
|
||
{
|
||
public uint dwChannel;
|
||
public NET_DVR_TIME struStartTime;
|
||
public NET_DVR_TIME struStopTime;
|
||
public byte byStreamType; // 0-主码流 1-子码流
|
||
public byte byDownload; // 0-下载(存文件)1-回放(需解码器)
|
||
public byte byOptimalStreamType;
|
||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 301)] public byte[] byRes2;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 按时间把录像**下载到文件**(8000 私有协议,不需要 554 / 不需要解码器)
|
||
///
|
||
/// 返回值是文件句柄(>0 成功,-1 失败用 <see cref="NET_DVR_GetLastError"/> 查原因)。
|
||
/// 下载出来的是设备原始封装(PS),要 mp4 得再用 ffmpeg 转封装。
|
||
/// </summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern int NET_DVR_GetFileByTime_V40(
|
||
int lUserID,
|
||
[MarshalAs(UnmanagedType.LPStr)] string sSavedFileName,
|
||
ref NET_DVR_PLAYCOND pDownloadCond);
|
||
|
||
/// <summary>下载进度(0~100,-1 表示失败)</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern int NET_DVR_GetDownloadPos(int lFileHandle);
|
||
|
||
/// <summary>停止下载并释放句柄</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_StopGetFile(int lFileHandle);
|
||
|
||
// ==================== 按时间**回放取流**(8000 私有协议,全速推送) ====================
|
||
|
||
/// <summary><c>NET_DVR_PlayBackControl</c> 控制码</summary>
|
||
internal const uint PlayStart = 1;
|
||
|
||
internal const uint PlayStop = 2;
|
||
|
||
internal const uint PlayPause = 3;
|
||
|
||
internal const uint PlayFast = 5;
|
||
|
||
internal const uint PlayNormal = 7;
|
||
|
||
/// <summary>回放数据回调(<paramref name="dwDataType"/>:1 系统头,2 流数据)</summary>
|
||
internal delegate void PlayDataCallback(int lPlayHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize,
|
||
IntPtr pUser);
|
||
|
||
/// <summary>
|
||
/// 按时间打开回放(通道号用**海康通道号**,如 34)
|
||
///
|
||
/// ⚠️ 实测:这条接口是**全速推送**的,不按实时速率 —— 本项目设备 2 分钟主码流素材
|
||
/// 约 7 秒就推完(≈14 MB/s,17 倍速),所以下载录像不用再 `PlayFast`。
|
||
/// 相比之下 <c>NET_DVR_GetFileByTime*</c> 在这台固件上直接不工作(err 17 / 0 字节)。
|
||
/// </summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern int NET_DVR_PlayBackByTime(
|
||
int lUserID,
|
||
int lChannel,
|
||
ref NET_DVR_TIME lpStartTime,
|
||
ref NET_DVR_TIME lpStopTime,
|
||
IntPtr hWnd);
|
||
|
||
/// <summary>回放数据回调(<paramref name="hWnd"/> 传 0 时必须设,否则没有数据)</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_SetPlayDataCallBack(
|
||
int lPlayHandle,
|
||
PlayDataCallback? fPlayDataCallBack,
|
||
IntPtr pUser);
|
||
|
||
/// <summary>回放控制(开始 / 停止 / 暂停 / 快放…),<paramref name="dwControlCode"/> 见常量</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_PlayBackControl(
|
||
int lPlayHandle,
|
||
uint dwControlCode,
|
||
uint dwInValue,
|
||
IntPtr lpOutValue);
|
||
|
||
/// <summary>停止回放并释放句柄</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_StopPlayBack(int lPlayHandle);
|
||
|
||
/// <summary>回放进度(0~100;-1 失败)。判「推完」用它,比数字节稳</summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern int NET_DVR_GetPlayBackPos(int lPlayHandle);
|
||
|
||
/// <summary>
|
||
/// 取**当前回放帧对应的 OSD 时间**(输出 <c>NET_DVR_TIME</c>,24 字节)。
|
||
///
|
||
/// 这是录像的真实内容时间(录像机回放时间轴),不是"会话相对时间"——
|
||
/// 多路对齐只有靠它才能精确到秒:各路从哪个关键帧起播、晚了多少,读一次就知道。
|
||
/// </summary>
|
||
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
|
||
internal static extern bool NET_DVR_GetPlayBackOsdTime(int lPlayHandle, IntPtr lpOsdTime);
|
||
|
||
/// <summary>初始化 SDK(幂等)。找不到 HCNetSDK.dll 时抛 <see cref="HikException"/></summary>
|
||
internal static void EnsureInitialized()
|
||
{
|
||
lock (InitSync)
|
||
{
|
||
if (_initialized) return;
|
||
|
||
var dir = ResolveSdkDirectory()
|
||
?? throw new HikException(uint.MaxValue,
|
||
"未找到 HCNetSDK.dll:请把海康 Win64 SDK 的「库文件」目录放到程序目录下的 native\\HCNetSDK\\," +
|
||
"或设置环境变量 YUNCANG_HIKSDK_DIR 指向该目录");
|
||
|
||
SetDllDirectory(dir);
|
||
|
||
// 组件(HCNetSDKCom)里的 DLL 由 HCCore 自行 LoadLibrary,补齐 PATH 更稳
|
||
var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
|
||
if (path.IndexOf(dir, StringComparison.OrdinalIgnoreCase) < 0)
|
||
{
|
||
Environment.SetEnvironmentVariable("PATH", dir + Path.PathSeparator + path);
|
||
}
|
||
|
||
if (!NET_DVR_Init())
|
||
{
|
||
throw new HikException(NET_DVR_GetLastError(), "HCNetSDK 初始化失败(NET_DVR_Init)");
|
||
}
|
||
|
||
// 3 秒连接超时、2 次重试;断链后 5 秒重连(SDK 默认 30 秒,这里更快恢复)
|
||
NET_DVR_SetConnectTime(3000, 2);
|
||
NET_DVR_SetReconnect(5000, 1);
|
||
|
||
SdkDirectory = dir;
|
||
_initialized = true;
|
||
AppLog.Write($"HCNetSDK 已初始化:{dir}");
|
||
}
|
||
}
|
||
|
||
/// <summary>停用 SDK(进程退出时调用)</summary>
|
||
internal static void Shutdown()
|
||
{
|
||
lock (InitSync)
|
||
{
|
||
if (!_initialized) return;
|
||
try { NET_DVR_Cleanup(); } catch { /* 退出阶段忽略 */ }
|
||
_initialized = false;
|
||
}
|
||
}
|
||
|
||
/// <summary>登录设备,返回 UserID(>=0);失败抛异常。调用方负责 FreeHGlobal(deviceInfo)</summary>
|
||
internal static int Login(string host, ushort port, string userName, string password, out IntPtr deviceInfo)
|
||
{
|
||
EnsureInitialized();
|
||
|
||
var info = new NET_DVR_USER_LOGIN_INFO
|
||
{
|
||
sDeviceAddress = new byte[129],
|
||
sUserName = new byte[64],
|
||
sPassword = new byte[64],
|
||
byRes3 = new byte[119],
|
||
byUseTransport = 0,
|
||
wPort = port,
|
||
bUseAsynLogin = 0,
|
||
byProxyType = 0,
|
||
byUseUTCTime = 0,
|
||
byLoginMode = 0, // 0 = 私有协议(走 8000);1 = ISAPI 登录模式(本项目不用)
|
||
byHttps = 0, // 0 = 不套 TLS
|
||
iProxyID = -1, // 不使用代理时必须为 -1(填 0 新固件会报参数错误 17,实测)
|
||
byVerifyMode = 0,
|
||
};
|
||
|
||
// 用 Latin1 保证 1 字符 = 1 字节,不会像 UTF-8 那样把非 ASCII 撑成多字节错位
|
||
WriteFixed(info.sDeviceAddress, host);
|
||
WriteFixed(info.sUserName, userName);
|
||
WriteFixed(info.sPassword, password);
|
||
|
||
// 设备信息结构体(NET_DVR_DEVICEINFO_V40)比较大,给足空间;给小了会报参数错误 17
|
||
const int infoSize = 4096;
|
||
deviceInfo = Marshal.AllocHGlobal(infoSize);
|
||
Marshal.Copy(new byte[infoSize], 0, deviceInfo, infoSize);
|
||
|
||
var userId = NET_DVR_Login_V40(ref info, deviceInfo);
|
||
if (userId < 0)
|
||
{
|
||
var err = NET_DVR_GetLastError();
|
||
Marshal.FreeHGlobal(deviceInfo);
|
||
deviceInfo = IntPtr.Zero;
|
||
throw new HikException(err, $"登录设备失败:{DescribeError(err)}");
|
||
}
|
||
|
||
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);
|
||
var count = Math.Min(bytes.Length, buffer.Length - 1);
|
||
Array.Copy(bytes, 0, buffer, 0, count);
|
||
}
|
||
|
||
private static string? ResolveSdkDirectory()
|
||
{
|
||
var candidates = new[]
|
||
{
|
||
Environment.GetEnvironmentVariable("YUNCANG_HIKSDK_DIR"),
|
||
Path.Combine(AppContext.BaseDirectory, "native", "HCNetSDK"),
|
||
Path.Combine(AppContext.BaseDirectory, "native"),
|
||
// 兜底:有些部署(历史安装包)把运行库直接放在 exe 同级的 HCNetSDK 目录
|
||
Path.Combine(AppContext.BaseDirectory, "HCNetSDK"),
|
||
AppContext.BaseDirectory,
|
||
};
|
||
|
||
foreach (var dir in candidates)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(dir)) continue;
|
||
try
|
||
{
|
||
if (File.Exists(Path.Combine(dir, Dll))) return Path.GetFullPath(dir);
|
||
}
|
||
catch
|
||
{
|
||
// 路径非法就跳过
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/// <summary>常见错误码的中文描述(对照 HCNetSDK.h)</summary>
|
||
internal static string DescribeError(uint code) => code switch
|
||
{
|
||
0 => "成功",
|
||
1 => "用户名或密码错误(密码必须传明文)",
|
||
2 => "权限不足",
|
||
3 => "SDK 未初始化",
|
||
4 => "通道号错误",
|
||
5 => "连接到设备的客户端个数超过最大",
|
||
6 => "设备版本不匹配",
|
||
7 => "连接设备失败(IP/端口不通或设备未开机)",
|
||
8 => "网络发送失败",
|
||
9 => "网络接收失败",
|
||
10 => "网络接收超时",
|
||
11 => "网络数据错误",
|
||
12 => "调用次序错误",
|
||
13 => "无此权限",
|
||
14 => "命令执行超时",
|
||
15 => "串口号错误",
|
||
16 => "报警端口错误",
|
||
17 => "参数错误(检查登录参数,如代理序号 / 结构体大小)",
|
||
18 => "通道状态异常",
|
||
19 => "没有硬盘",
|
||
20 => "硬盘号错误",
|
||
21 => "硬盘已满",
|
||
22 => "硬盘出错",
|
||
23 => "设备不支持",
|
||
24 => "设备忙",
|
||
25 => "设备修改不成功",
|
||
26 => "密码格式不正确",
|
||
27 => "硬盘正在格式化",
|
||
47 => "用户不存在",
|
||
72 => "账号被锁定",
|
||
73 => "账号已过期",
|
||
74 => "账号已禁用",
|
||
76 => "该用户有权限的设备数量超过最大值",
|
||
251 => "密码为风险密码(设备拒绝)",
|
||
1231 => "初始密码未修改,功能受限",
|
||
_ => $"未知错误({code})",
|
||
};
|
||
}
|
||
|
||
/// <summary>海康 SDK 调用异常(<see cref="ErrorCode"/> 为 NET_DVR_GetLastError 的原值)</summary>
|
||
public sealed class HikException : Exception
|
||
{
|
||
public HikException(uint errorCode, string message) : base(message)
|
||
{
|
||
ErrorCode = errorCode;
|
||
}
|
||
|
||
/// <summary>NET_DVR_GetLastError 返回码(非 SDK 错误时用 0xFFFFFFFF)</summary>
|
||
public uint ErrorCode { get; }
|
||
}
|