using System; 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; using System.Threading; using System.Xml.Linq; using System.Collections.Concurrent; namespace YuncangTrace.LocalService.Services.Hik; /// /// 海康设备连接池 + 通道读取。 /// /// 连接模型(实测结论,见 README/提交说明): /// - NET_DVR_Login_V40 得到的是一个**逻辑会话(UserID)**,SDK 内部维持心跳并在断链后自动重连 /// (NET_DVR_SetReconnect),所以**不要每次请求都登录**; /// - 同一设备可同时存在多个 UserID(实测 0/1/2 三路并发),设备侧上限为 128 个注册用户; /// - 会话空闲 10 分钟自动登出,避免长期占用设备名额; /// - 同一会话的调用用 串行化,避免并发读写同一 UserID。 /// public sealed class HikDeviceService : IDisposable { /// 会话空闲多久后自动登出 private static readonly TimeSpan IdleTimeout = TimeSpan.FromMinutes(10); /// IP 通道配置缓冲区(实测设备返回 50792 字节,留余量) private const int IpParaBufferSize = 60000; /// IP 设备项(NET_DVR_IPDEVINFO)在 IPPARACFG_V40 里的起点/大小 private const int IpDevInfoStart = 84; private const int IpDevInfoSize = 296; /// NET_DVR_GET_PICCFG_V30 输出缓冲区(实测设备返回 7752 字节,留余量) private const int PicCfgBufferSize = 20000; /// PICCFG 结构体里 sChanName 的偏移与长度(DWORD dwSize + char[NAME_LEN=32]) private const int PicCfgNameOffset = 4; private const int PicCfgNameLength = 32; /// /// 通道→IP 设备的映射表(struStreamMode):64 项、每项 496 字节。 /// 实测 84 + 64*296 + 64*496 + 20 = 50792,正好是设备返回的字节数。 /// private const int StreamModeStart = IpDevInfoStart + 64 * IpDevInfoSize; private const int StreamModeSize = 496; private readonly ConcurrentDictionary _sessions = new(StringComparer.OrdinalIgnoreCase); private readonly Timer _sweeper; private bool _disposed; public HikDeviceService() { _sweeper = new Timer(_ => SweepIdleSessions(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); } /// 读取设备通道列表(登录 → 读 IP 接入配置 → 返回)。阻塞调用,调用方放在线程池里跑 /// /// 主数据只走 8000 私有协议(部分摄像头没开 Web/ISAPI 端口); /// 通道名额外用 **8000 会话的 ISAPI 透传** 补一次,拿不到就留空(前端会自己拼「NVR名-通道号」)。 /// public HikChannelsResult GetChannels(string host, int port, string userName, string password) { Validate(host, port, userName, password); var stopwatch = Stopwatch.StartNew(); var key = MakeKey(host, port, userName, password); var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); session.Gate.Wait(); try { var reused = session.UserId >= 0; for (var attempt = 1; ; attempt++) { if (session.UserId < 0) { Login(session, password); reused = false; } try { var result = ReadChannels(session, password); result.userId = session.UserId; result.sessionReused = reused; result.elapsedMs = stopwatch.ElapsedMilliseconds; session.Touch(); return result; } catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) { // 会话可能已经掉了:登出并重登一次 AppLog.Write($"海康会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); CloseSession(session); reused = false; } } } catch { // 登录/取通道彻底失败:把会话从池里摘掉,下次重新来过 if (session.UserId < 0) { _sessions.TryRemove(key, out _); } throw; } finally { session.Gate.Release(); } } /// 当前池中的会话数(排障用) public int SessionCount => _sessions.Values.Count(s => s.UserId >= 0); /// /// 确保已登录并返回 UserID(给实时取流等需要自己发命令的地方用) /// public int EnsureUser(string host, int port, string userName, string password) { Validate(host, port, userName, password); var key = MakeKey(host, port, userName, password); var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); session.Gate.Wait(); try { if (session.UserId < 0) Login(session, password); session.Touch(); return session.UserId; } catch { if (session.UserId < 0) _sessions.TryRemove(key, out _); throw; } finally { session.Gate.Release(); } } /// /// 取设备的「首个数字通道号」(登录时读到的 byStartDChan) /// /// 预览要把它换算成 RTSP 用的 1 起序号:logical = channel - startDigital + 1 /// (本项目设备 32 路模拟 + 32 路数字,数字通道从 33 起 → 通道 33 对应 101 码流)。 /// 会话是池化的,重复调用只会读内存。 /// public int GetStartDigitalChannel(string host, int port, string userName, string password) { Validate(host, port, userName, password); var key = MakeKey(host, port, userName, password); var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); session.Gate.Wait(); try { if (session.UserId < 0) Login(session, password); session.Touch(); var start = session.Device?.StartDigitalChannel ?? 0; return start > 0 ? start : 33; } catch { if (session.UserId < 0) _sessions.TryRemove(key, out _); throw; } finally { session.Gate.Release(); } } /// NET_DVR_GET_TIMECFG 的输出缓冲(NET_DVR_TIME = 24 字节) private const int TimeCfgBufferSize = 24; /// /// 读设备当前时间(8000 私有协议 NET_DVR_GET_TIMECFG,不需要 Web/ISAPI 端口) /// /// 用途:回放是按**设备本地时间**定位的,而扫码时间是**本机时钟**打的。 /// 两边不一致时(现场实测本机慢了 9 秒),录像会整体错位,短回放窗口会直接看不到面单。 /// public DateTime GetDeviceTime(string host, int port, string userName, string password) => GetTime(host, port, userName, password, 0); /// /// 读某个**摄像头自己**的时间(GET_TIMECFG 带通道号)。 /// /// 摄像头画面里烧的 OSD 时间是它自己的时钟,跟录像机是两套时间 —— /// 校时只写录像机的话,OSD 依旧是旧时间。 /// public DateTime GetChannelTime(string host, int port, string userName, string password, int channel) => GetTime(host, port, userName, password, channel); private DateTime GetTime(string host, int port, string userName, string password, int channel) { Validate(host, port, userName, password); var time = DateTime.MinValue; ExecuteWithSession(host, port, userName, password, userId => { var buffer = Marshal.AllocHGlobal(TimeCfgBufferSize); try { Marshal.Copy(new byte[TimeCfgBufferSize], 0, buffer, TimeCfgBufferSize); if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_TIMECFG, channel, buffer, TimeCfgBufferSize, out _)) { var err = HikSdk.NET_DVR_GetLastError(); var who = channel <= 0 ? "设备" : $"通道{channel}"; throw new HikException(err, $"读取{who}时间失败:{HikSdk.DescribeError(err)}"); } var year = Marshal.ReadInt32(buffer, 0); var month = Marshal.ReadInt32(buffer, 4); var day = Marshal.ReadInt32(buffer, 8); var hour = Marshal.ReadInt32(buffer, 12); var minute = Marshal.ReadInt32(buffer, 16); var second = Marshal.ReadInt32(buffer, 20); time = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); } finally { Marshal.FreeHGlobal(buffer); } }); return time; } /// /// 写设备时间(NET_DVR_SET_TIMECFG)。 /// 用于「设置 NVR 的 NTP 后立即生效」:先把 NTP 配置写进去,再直接把设备时间校准到 NTP 时间。 /// public void SetDeviceTime(string host, int port, string userName, string password, DateTime time) => SetTime(host, port, userName, password, 0, time); /// /// 写某个**摄像头自己**的时间(SET_TIMECFG 带通道号,录像机转发给 IPC)。 /// /// 只有摄影头像这样校过,画面里的 OSD 时间才会和录像机对齐; /// 部分前端设备会拒绝校时(第三方 / 关了校时权限),此时抛 。 /// public void SetChannelTime(string host, int port, string userName, string password, int channel, DateTime time) => SetTime(host, port, userName, password, channel, time); private void SetTime(string host, int port, string userName, string password, int channel, DateTime time) { Validate(host, port, userName, password); ExecuteWithSession(host, port, userName, password, userId => { var sdkTime = ToSdkTime(time); var size = Marshal.SizeOf(sdkTime); var buffer = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(sdkTime, buffer, false); if (!HikSdk.NET_DVR_SetDVRConfig(userId, HikSdk.NET_DVR_SET_TIMECFG, channel, buffer, (uint)size)) { var err = HikSdk.NET_DVR_GetLastError(); var who = channel <= 0 ? "设备" : $"通道{channel}"; throw new HikException(err, $"设置{who}时间失败:{HikSdk.DescribeError(err)}"); } } finally { Marshal.FreeHGlobal(buffer); } }); AppLog.Write(channel <= 0 ? $"[hik] 设备时间已写入 {host}:{port}:{time:yyyy-MM-dd HH:mm:ss}" : $"[hik] 通道{channel} 时间已写入 {host}:{port}:{time:yyyy-MM-dd HH:mm:ss}"); } /// /// 写设备时间并**等待设备真正生效**。 /// /// 实测两个坑: /// 1. SET_TIMECFG 返回成功后立刻 GET 可能还是旧值(设备异步应用); /// 2. **写调用本身要 3~4 秒**,而写入的值是调用前就该有的时间 → /// 设备应用时已经「过时」了,原来直接回读永远是 -3~-4 秒。 /// /// 做法:先看当前时间是否已经够准;不准就写一次、量出这次调用的耗时, /// 下一次写入时把这段耗时补偿进去(迭代最多 4 次,直到与目标时间相差 ≤2 秒)。 /// /// 期望的设备时间(绝对时间,调用时刻的值) /// 回读到的设备时间(超时仍未对上就是最后一次读到的值) public DateTime SetDeviceTimeAndConfirm(string host, int port, string userName, string password, DateTime target, int timeoutMs = 20000) { var callStarted = DateTime.Now; var last = target; var lead = TimeSpan.Zero; var deadline = Environment.TickCount64 + Math.Max(timeoutMs, 8000); // 已经够准就不写(避免每次都动设备时钟) try { last = GetDeviceTime(host, port, userName, password); var earlyDiff = (last - target).TotalSeconds; AppLog.Write($"[hik] 校时前检查:设备 {last:HH:mm:ss.fff},目标 {target:HH:mm:ss.fff},差 {earlyDiff:+0.0;-0.0}s"); if (Math.Abs(earlyDiff) <= 1.5) return last; } catch (Exception ex) { AppLog.Write($"[hik] 读取设备时间失败(继续尝试写入):{ex.Message}"); } // 写一次 → 等设备应用完再回读(连续快速写会被设备忽略)→ 差得多就补偿「设备应用延迟」再写一次 for (var attempt = 0; attempt < 3 && Environment.TickCount64 < deadline; attempt++) { var writeValue = target.Add(DateTime.Now - callStarted).Add(lead); SetDeviceTime(host, port, userName, password, writeValue); // 设备应用时间有延迟(实测量约 2.5 秒),等它稳定下来再回读;同时避免连续写入被忽略 Thread.Sleep(2500); try { last = GetDeviceTime(host, port, userName, password); } catch (Exception ex) { AppLog.Write($"[hik] 回读设备时间失败(继续重试):{ex.Message}"); continue; } var expected = target.Add(DateTime.Now - callStarted); var diff = (last - expected).TotalSeconds; AppLog.Write($"[hik] 校时尝试 {attempt + 1}:写入 {writeValue:HH:mm:ss.fff}," + $"回读 {last:HH:mm:ss.fff},期望 {expected:HH:mm:ss.fff},差 {diff:+0.0;-0.0}s,补偿 {lead.TotalSeconds:0.0}s"); if (Math.Abs(diff) <= 1.5) return last; // 设备比期望慢多少,下次写入就把这段延迟补回去(不能用 SDK 调用耗时:它只有几毫秒) lead = lead.Add(TimeSpan.FromSeconds(-diff)); } AppLog.Write($"[hik] 设备时间校准后仍差 {(last - target.Add(DateTime.Now - callStarted)).TotalSeconds:+0.0;-0.0} 秒({host}:{port})"); return last; } /// /// 读录像机的 NTP 配置(走 **8000 私有协议**:NET_DVR_GET_NTPCFG)。 /// public HikNtpConfig GetNtpConfig(string host, int port, string userName, string password) { Validate(host, port, userName, password); HikNtpConfig? config = null; ExecuteWithSession(host, port, userName, password, userId => { var size = Marshal.SizeOf(); var buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(new byte[size], 0, buffer, size); if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_NTPCFG, 0, buffer, (uint)size, out _)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"读取 NTP 配置失败:{HikSdk.DescribeError(err)}"); } var raw = new byte[size]; Marshal.Copy(buffer, raw, 0, size); var end = Array.IndexOf(raw, (byte)0, 0, 64); if (end < 0) end = 64; var server = Encoding.ASCII.GetString(raw, 0, end).Trim(); var interval = BitConverter.ToUInt16(raw, 64); var enabled = raw[66] != 0; config = new HikNtpConfig(server, interval, enabled); } finally { Marshal.FreeHGlobal(buffer); } }); return config!; } /// /// 写录像机的 NTP 配置(NET_DVR_SET_NTPCFG)。 /// /// NTP 服务器(域名或 IP,最多 63 字节 ASCII) /// 同步间隔(分钟,1~1440;设备常见默认 60) public void SetNtpConfig(string host, int port, string userName, string password, string server, int intervalMinutes, bool enabled) { Validate(host, port, userName, password); var text = (server ?? string.Empty).Trim(); if (text.Length == 0) throw new ArgumentException("NTP 服务器不能为空"); if (Encoding.ASCII.GetByteCount(text) > 63) throw new ArgumentException("NTP 服务器地址过长(最多 63 字节)"); var interval = (ushort)Math.Clamp(intervalMinutes, 1, 1440); ExecuteWithSession(host, port, userName, password, userId => { var size = Marshal.SizeOf(); var buffer = Marshal.AllocHGlobal(size); try { // ⚠️ 必须「先读后改再写」: // 本机实测把整个 NET_DVR_NTPPARA 清零后重填(只填 server/interval/enable)会报 err=11, // 因为固件在保留字段里还放了 NTP 端口(读取值里 offset 70 = 0x007B = 123)等数据。 // 原样保留其它字节、只改 sNTPServer / wInterval / byEnable,写入才会成功。 Marshal.Copy(new byte[size], 0, buffer, size); if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_NTPCFG, 0, buffer, (uint)size, out _)) { var readError = HikSdk.NET_DVR_GetLastError(); throw new HikException(readError, $"读取当前 NTP 配置失败:{HikSdk.DescribeError(readError)}"); } var raw = new byte[size]; Marshal.Copy(buffer, raw, 0, size); // sNTPServer[64]:整段清空后写 ASCII(域名的剩余字节保持 0) Array.Clear(raw, 0, 64); Encoding.ASCII.GetBytes(text, 0, text.Length, raw, 0); // WORD wInterval(offset 64)+ BYTE byEnable(offset 66) raw[64] = (byte)(interval & 0xFF); raw[65] = (byte)(interval >> 8); raw[66] = (byte)(enabled ? 1 : 0); Marshal.Copy(raw, 0, buffer, size); if (!HikSdk.NET_DVR_SetDVRConfig(userId, HikSdk.NET_DVR_SET_NTPCFG, 0, buffer, (uint)size)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"设置 NTP 配置失败:{HikSdk.DescribeError(err)}"); } } finally { Marshal.FreeHGlobal(buffer); } }); AppLog.Write($"[hik] NTP 配置已写入 {host}:{port}:{text},间隔 {interval} 分钟,{(enabled ? "启用" : "关闭")}"); } /// /// 抓一帧 JPEG(预览用) /// /// 走 8000 私有协议的 NET_DVR_CaptureJPEGPicture_NEW: /// - 不需要 Web 端口,也不需要解码器(PlayM4),拿到就是可直接给浏览器的 JPEG; /// - 是**海康通道号**(数字通道从 33 起),不是 RTSP 的 1 起序号; /// - 同一 UserID 的抓帧被 串行化,多路预览也不会撞车(只是帧率分摊)。 /// public byte[] CaptureJpeg(string host, int port, string userName, string password, int channel) { Validate(host, port, userName, password); if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); var key = MakeKey(host, port, userName, password); var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); session.Gate.Wait(); try { for (var attempt = 1; ; attempt++) { if (session.UserId < 0) Login(session, password); try { var frame = CaptureOnce(session.UserId, channel); session.Touch(); return frame; } catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) { AppLog.Write($"海康抓帧会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); CloseSession(session); } } } catch { if (session.UserId < 0) _sessions.TryRemove(key, out _); throw; } finally { session.Gate.Release(); } } /// 抓帧缓冲区(4MB 足够 1080p JPEG) private const int JpegBufferSize = 4 * 1024 * 1024; /// /// 云台连续动作(方向 / 变倍 / 聚焦 / 光圈 / 自动扫描) /// /// 走 NET_DVR_PTZControlWithSpeed_Other:只需登录的 UserID + 通道号, /// **不依赖预览句柄**,所以没开预览也能控。 /// /// up / down / left / right / up-left / ... / zoom-in / auto ... /// true = 停止(必须与开始成对调用,否则云台会一直转) /// 1~7(默认 4),部分设备只支持 1~7 public void PtzControl(string host, int port, string userName, string password, int channel, string command, bool stop, int speed = 4) { Validate(host, port, userName, password); if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); if (!HikPtz.Commands.TryGetValue(command ?? string.Empty, out var code)) { throw new ArgumentException($"不支持的云台命令:{command}"); } var finalSpeed = (uint)Math.Clamp(speed <= 0 ? 4 : speed, 1, 7); ExecuteWithSession(host, port, userName, password, userId => { if (!HikSdk.NET_DVR_PTZControlWithSpeed_Other(userId, channel, code, stop ? 1u : 0u, finalSpeed)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"云台控制失败:{HikSdk.DescribeError(err)}"); } }); } /// 预置点:set / goto / clear( 1~256) public void PtzPreset(string host, int port, string userName, string password, int channel, string action, int preset) { Validate(host, port, userName, password); if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); if (!HikPtz.PresetActions.TryGetValue(action ?? string.Empty, out var code)) { throw new ArgumentException($"不支持的预置点操作:{action}"); } if (preset is < 1 or > 256) throw new ArgumentException("预置点编号必须在 1~256 之间"); ExecuteWithSession(host, port, userName, password, userId => { if (!HikSdk.NET_DVR_PTZPreset_Other(userId, channel, code, (uint)preset)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"预置点操作失败:{HikSdk.DescribeError(err)}"); } }); } /// 取登录 UserID 执行一段 SDK 调用(串行化 + 链路错误重登一次) private void ExecuteWithSession(string host, int port, string userName, string password, Action action) { var key = MakeKey(host, port, userName, password); var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); session.Gate.Wait(); try { for (var attempt = 1; ; attempt++) { if (session.UserId < 0) Login(session, password); try { action(session.UserId); session.Touch(); return; } catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) { AppLog.Write($"海康调用会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); CloseSession(session); } } } catch { if (session.UserId < 0) _sessions.TryRemove(key, out _); throw; } finally { session.Gate.Release(); } } /// /// 按时间**下载录像到文件**(走 8000 私有协议:NET_DVR_GetFileByTime_V40) /// /// 与 RTSP 回放的差别: /// - 不需要 554 端口、不需要解码器,设备自己按时间段把录像推下来(比 RTSP 稳,现场防火墙常只开 8000); /// - 落地是设备原始封装(PS),要 mp4 还得用 ffmpeg 转封装; /// - 文件名走 ANSI(SDK 是 char*)→ 这里的 必须是 ASCII 路径, /// 调用方下载完再搬到用户选的中文目录。 /// /// 下载进度 0~100(SDK 的 NET_DVR_GetDownloadPos) public void DownloadByTime(string host, int port, string userName, string password, int channel, DateTime start, DateTime end, string outputPath, int streamType = 0, Action? onProgress = null, CancellationToken ct = default) { Validate(host, port, userName, password); if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); if (end <= start) throw new ArgumentException("结束时间必须晚于开始时间"); HikSdk.EnsureInitialized(); ExecuteWithSession(host, port, userName, password, userId => { var condition = new HikSdk.NET_DVR_PLAYCOND { dwChannel = (uint)channel, struStartTime = ToSdkTime(start), struStopTime = ToSdkTime(end), byStreamType = (byte)streamType, byDownload = 0, byOptimalStreamType = 0, byRes2 = new byte[301], }; var handle = HikSdk.NET_DVR_GetFileByTime_V40(userId, outputPath, ref condition); if (handle < 0) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"按时间下载录像失败:{HikSdk.DescribeError(err)}"); } try { // 录像下载一般 2~5x 实时;留足余量,超时按失败处理(别把界面卡死) var deadline = DateTime.UtcNow.AddSeconds((end - start).TotalSeconds * 2 + 120); var lastPos = -1; var lastSize = 0L; var lastGrowth = DateTime.UtcNow; while (true) { ct.ThrowIfCancellationRequested(); var pos = HikSdk.NET_DVR_GetDownloadPos(handle); if (pos < 0) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"下载中断:{HikSdk.DescribeError(err)}"); } if (pos != lastPos) { onProgress?.Invoke(Math.Min(pos, 100)); lastPos = pos; } // 有些固件(实测本项目这台 NVR)调 GetFileByTime 会「成功返回句柄但一个字节都不推」, // 所以用**文件是否在长**判断真实进度;长时间不增长就快速失败,别让上层干等。 var size = File.Exists(outputPath) ? new FileInfo(outputPath).Length : 0; if (size > lastSize) { lastSize = size; lastGrowth = DateTime.UtcNow; } else if ((DateTime.UtcNow - lastGrowth).TotalSeconds > 5) { if (size == 0) { throw new HikException(uint.MaxValue, "设备没有推送录像数据(该固件可能不支持按时间下载)"); } return; // 有数据且已停止增长 = 拉完了 } if (pos >= 100 && size > 0) return; if (DateTime.UtcNow > deadline) { throw new HikException(uint.MaxValue, "下载超时(设备没有继续推录像)"); } // 短睡,避免把设备问烦;取消时立刻退出 ct.WaitHandle.WaitOne(300); } } finally { HikSdk.NET_DVR_StopGetFile(handle); } }); } /// /// 按时间**拉回放流写文件**(8000 私有协议:NET_DVR_PlayBackByTime + 数据回调) /// /// 这是实测**唯一可用且最快**的回放下载方式: /// - 设备**全速推送**(本项目 2560×1440 主码流约 14 MB/s ≈ 17 倍速), /// 2 分钟素材 7 秒拉完;RTSP 回放是 ~0.7 倍速(30 秒要 40 秒); /// - 落地是原始 PS 流,要 mp4 再用 ffmpeg 转封装( 里做); /// - ⚠️ NET_DVR_GetFileByTime*(直接存文件)在这台固件上不工作,不要用。 /// /// 已接收字节数(总大小未知,界面按 MB 显示) /// /// **第一帧的真实内容时间**(设备本地时间;拿不到为 null)。 /// /// 回放是从「请求时间所在关键帧」开始推的,各通道关键帧位置不同 → /// 同一窗口开始拉的两段录像,第一帧的真实时间会差 0~几秒,合并后画面就错开。 /// 用 NET_DVR_GetPlayBackOsdTime 在第一包数据到达时读一次,即可精确对齐。 /// /// 实际写入字节数 public long PullPlaybackToFile(string host, int port, string userName, string password, int channel, DateTime start, DateTime end, string outputPath, out DateTime? firstOsdTime, Action? onProgress = null, CancellationToken ct = default) { firstOsdTime = null; var osdTime = (DateTime?)null; var osdTried = false; Validate(host, port, userName, password); if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); if (end <= start) throw new ArgumentException("结束时间必须晚于开始时间"); HikSdk.EnsureInitialized(); FileStream? stream = null; var sync = new object(); var written = 0L; // 回调在 SDK 网络线程:只做「拷贝 + 写盘」,不碰 UI HikSdk.PlayDataCallback callback = (_, _, buffer, size, _) => { if (size == 0) return; var chunk = new byte[size]; Marshal.Copy(buffer, chunk, 0, (int)size); lock (sync) { stream?.Write(chunk, 0, (int)size); written += size; } }; try { stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 20, FileOptions.SequentialScan); ExecuteWithSession(host, port, userName, password, userId => { var sdkStart = ToSdkTime(start); var sdkStop = ToSdkTime(end); var handle = HikSdk.NET_DVR_PlayBackByTime(userId, channel, ref sdkStart, ref sdkStop, IntPtr.Zero); if (handle < 0) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"打开回放失败:{HikSdk.DescribeError(err)}"); } try { if (!HikSdk.NET_DVR_SetPlayDataCallBack(handle, callback, IntPtr.Zero)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"设置回放回调失败:{HikSdk.DescribeError(err)}"); } if (!HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStart, 0, IntPtr.Zero)) { var err = HikSdk.NET_DVR_GetLastError(); throw new HikException(err, $"启动回放失败:{HikSdk.DescribeError(err)}"); } // 全速推送:优先看设备给的回放进度(录像中间有断档时,数字节会误判「推完了」) var deadline = DateTime.UtcNow.AddSeconds((end - start).TotalSeconds + 120); var lastSize = 0L; var lastGrowth = DateTime.UtcNow; while (true) { ct.ThrowIfCancellationRequested(); var pos = HikSdk.NET_DVR_GetPlayBackPos(handle); long current; lock (sync) current = written; if (current > lastSize) { lastSize = current; lastGrowth = DateTime.UtcNow; // 第一包数据到手:只试一次读当前帧的 OSD 时间(= 这一路真实内容起点)。 // 读失败就别再试了 —— 这台固件不支持(err=12),每来一包都试会刷满日志 if (!osdTried) { osdTried = true; osdTime = TryReadPlaybackOsdTime(handle); } onProgress?.Invoke(current); } if (pos >= 100) break; if (current > 0 && (DateTime.UtcNow - lastGrowth).TotalSeconds > 5) break; if (current == 0 && (DateTime.UtcNow - lastGrowth).TotalSeconds > 8) { throw new HikException(uint.MaxValue, "设备没有推送回放数据(该时段可能没有录像)"); } if (DateTime.UtcNow > deadline) { throw new HikException(uint.MaxValue, "回放拉流超时"); } ct.WaitHandle.WaitOne(200); } HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStop, 0, IntPtr.Zero); } finally { HikSdk.NET_DVR_StopPlayBack(handle); } }); } finally { lock (sync) { stream?.Flush(); stream?.Dispose(); stream = null; } } firstOsdTime = osdTime; return written; } /// /// 读当前回放帧的 OSD 时间(录像的真实内容时间,设备本地时间) /// 读不到 / 数值明显不合理(年份不在 2000~2100)返回 null。 /// private static DateTime? TryReadPlaybackOsdTime(int handle) { var buffer = Marshal.AllocHGlobal(TimeCfgBufferSize); try { Marshal.Copy(new byte[TimeCfgBufferSize], 0, buffer, TimeCfgBufferSize); if (!HikSdk.NET_DVR_GetPlayBackOsdTime(handle, buffer)) { var err = HikSdk.NET_DVR_GetLastError(); AppLog.Write($"[hik] 读回放 OSD 时间失败:err={err}({HikSdk.DescribeError(err)})"); return null; } var year = Marshal.ReadInt32(buffer, 0); var month = Marshal.ReadInt32(buffer, 4); var day = Marshal.ReadInt32(buffer, 8); var hour = Marshal.ReadInt32(buffer, 12); var minute = Marshal.ReadInt32(buffer, 16); var second = Marshal.ReadInt32(buffer, 20); if (year < 2000 || year > 2100 || month is < 1 or > 12 || day is < 1 or > 31 || hour is < 0 or > 23 || minute is < 0 or > 59 || second is < 0 or > 59) { AppLog.Write($"[hik] 回放 OSD 时间读数异常:{year}-{month}-{day} {hour}:{minute}:{second}"); return null; } return new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); } catch (Exception ex) { AppLog.Write($"[hik] 读回放 OSD 时间失败:{ex.Message}"); return null; } finally { Marshal.FreeHGlobal(buffer); } } /// /// 只探一下「这个通道在 start 时刻的第一帧真实时间」(开一个 3 秒的小回放,读到 OSD 就停)。 /// /// 回放预览用的是 RTSP 实时推流,主机侧拿不到内容时间;这里先用 8000 协议问一次, /// 得到每路真实起点后再按差值推迟出图,几路的画面内容才对得上。 /// public DateTime? ProbePlaybackOsdStart(string host, int port, string userName, string password, int channel, DateTime start, int timeoutMs = 6000) { Validate(host, port, userName, password); HikSdk.EnsureInitialized(); DateTime? osd = null; var gate = new ManualResetEventSlim(false); HikSdk.PlayDataCallback callback = (_, _, _, size, _) => { if (size > 0) gate.Set(); }; ExecuteWithSession(host, port, userName, password, userId => { var sdkStart = ToSdkTime(start); var sdkStop = ToSdkTime(start.AddSeconds(3)); var handle = HikSdk.NET_DVR_PlayBackByTime(userId, channel, ref sdkStart, ref sdkStop, IntPtr.Zero); if (handle < 0) return; try { if (!HikSdk.NET_DVR_SetPlayDataCallBack(handle, callback, IntPtr.Zero)) return; if (!HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStart, 0, IntPtr.Zero)) return; if (!gate.Wait(timeoutMs)) return; // 回调线程刚收到数据,等它落到解码侧一点点再读 Thread.Sleep(60); osd = TryReadPlaybackOsdTime(handle); } finally { HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStop, 0, IntPtr.Zero); HikSdk.NET_DVR_StopPlayBack(handle); } }); gate.Dispose(); return osd; } private static HikSdk.NET_DVR_TIME ToSdkTime(DateTime time) => new() { dwYear = (uint)time.Year, dwMonth = (uint)time.Month, dwDay = (uint)time.Day, dwHour = (uint)time.Hour, dwMinute = (uint)time.Minute, dwSecond = (uint)time.Second, }; /// 抓一帧;分辨率参数按「当前码流 → 720p → D1」降级重试 private static byte[] CaptureOnce(int userId, int channel) { var para = Marshal.AllocHGlobal(4); var buffer = Marshal.AllocHGlobal(JpegBufferSize); try { Marshal.WriteInt16(para, 0, HikSdk.JpegSizeCurrent); Marshal.WriteInt16(para, 2, 2); // 质量:最好 → 较好(枚举:0最好 1较好 2一般 3较差 4差) if (HikSdk.NET_DVR_CaptureJPEGPicture_NEW(userId, channel, para, buffer, JpegBufferSize, out var size) && size > 0) { return CopyFrame(buffer, size); } var firstError = HikSdk.NET_DVR_GetLastError(); // 「用当前分辨率」不被支持时退到固定尺寸(实测部分固件回 17/23) foreach (var sizeHint in new[] { HikSdk.JpegSize720P, HikSdk.JpegSizeD1 }) { Marshal.WriteInt16(para, 0, sizeHint); if (HikSdk.NET_DVR_CaptureJPEGPicture_NEW(userId, channel, para, buffer, JpegBufferSize, out size) && size > 0) { return CopyFrame(buffer, size); } } throw new HikException(firstError, $"抓取画面失败:{HikSdk.DescribeError(firstError)}"); } finally { Marshal.FreeHGlobal(para); Marshal.FreeHGlobal(buffer); } } private static byte[] CopyFrame(IntPtr buffer, uint size) { var bytes = new byte[(int)size]; Marshal.Copy(buffer, bytes, 0, bytes.Length); return bytes; } /// 登出所有会话 public void CloseAll() { foreach (var key in _sessions.Keys.ToList()) { if (!_sessions.TryRemove(key, out var session)) continue; session.Gate.Wait(); try { CloseSession(session); } finally { session.Gate.Release(); session.Gate.Dispose(); } } } private static void Login(Session session, string password) { var userId = HikSdk.Login(session.Host, (ushort)session.Port, session.User, password, out var info); try { session.Device = ParseDeviceInfo(info); } finally { Marshal.FreeHGlobal(info); } session.UserId = userId; session.Touch(); AppLog.Write($"海康登录成功:{session.Host}:{session.Port} 用户={session.User} UserID={userId} 序列号={session.Device?.SerialNumber}"); } private static void CloseSession(Session session) { if (session.UserId >= 0) { try { HikSdk.NET_DVR_Logout(session.UserId); } catch { /* 忽略 */ } AppLog.Write($"海康已登出:{session.Host}:{session.Port} UserID={session.UserId}"); } session.UserId = -1; session.Device = null; } private static void Validate(string host, int port, string userName, string password) { if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("host 不能为空"); if (host.Length > 128) throw new ArgumentException("host 过长"); if (port is <= 0 or > 65535) throw new ArgumentException("port 必须在 1~65535 之间"); if (string.IsNullOrEmpty(userName)) throw new ArgumentException("user 不能为空"); if (string.IsNullOrEmpty(password)) throw new ArgumentException("password 不能为空"); if (userName.Length > 63) throw new ArgumentException("user 过长(最多 63 字节)"); if (password.Length > 63) throw new ArgumentException("password 过长(最多 63 字节)"); // HCNetSDK 的字段是 char[](ANSI),非 ASCII 会按码页转换,跨机器容易错位 —— 直接拦住 foreach (var ch in host + userName + password) { if (ch < 0x20 || ch > 0x7E) throw new ArgumentException("host/user/password 仅支持 ASCII 可见字符"); } } /// /// 会话键:设备 + 用户 + **密码指纹**。 /// 必须带密码指纹 —— 否则「改密码 / 用错密码」会命中已有会话,把错误密码也放过去(实测踩过)。 /// private static string MakeKey(string host, int port, string userName, string password) { var fingerprint = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(password)))[..16]; return $"{host.Trim().ToLowerInvariant()}:{port}|{userName}|{fingerprint}"; } private static bool IsLinkError(uint code) => code is 7 or 8 or 9 or 10 or 11 or 5 or 27; /// 登录返回体(NET_DVR_DEVICEINFO_V40 的前 80 字节为 V30 部分) private static DeviceSnapshot ParseDeviceInfo(IntPtr buffer) { var serialBytes = new byte[48]; Marshal.Copy(buffer, serialBytes, 0, 48); var serial = Encoding.ASCII.GetString(serialBytes).TrimEnd('\0').Trim(); return new DeviceSnapshot { SerialNumber = serial, DiskCount = Marshal.ReadByte(buffer, 50), AnalogChannelCount = Marshal.ReadByte(buffer, 52), StartChannel = Marshal.ReadByte(buffer, 53), DigitalChannelCount = Marshal.ReadByte(buffer, 55) + (Marshal.ReadByte(buffer, 68) << 8), StartDigitalChannel = Marshal.ReadByte(buffer, 66), }; } private static HikChannelsResult ReadChannels(Session session, string password) { var device = session.Device ?? throw new HikException(3, "设备信息缺失(会话状态异常)"); var channels = new List(); string? warning = null; var buffer = Marshal.AllocHGlobal(IpParaBufferSize); try { Marshal.Copy(new byte[IpParaBufferSize], 0, buffer, IpParaBufferSize); Marshal.WriteInt32(buffer, 0, IpParaBufferSize); // dwSize 必须预先填好 var ok = HikSdk.NET_DVR_GetDVRConfig( session.UserId, HikSdk.NET_DVR_GET_IPPARACFG_V40, 0, // ⚠️ 必须传 0,传 -1 会 err=11 buffer, IpParaBufferSize, out var returned); if (!ok || returned < 100) { var err = HikSdk.NET_DVR_GetLastError(); if (IsLinkError(err)) throw new HikException(err, $"读取通道配置失败:{HikSdk.DescribeError(err)}"); warning = $"读取 IP 接入配置失败({HikSdk.DescribeError(err)}),仅返回登录时的通道统计"; } else { var analogCount = Marshal.ReadInt32(buffer, 8); var digitalCount = Marshal.ReadInt32(buffer, 12); var startDigital = Marshal.ReadInt32(buffer, 16); if (analogCount > 0) { for (var i = 0; i < analogCount; i++) { channels.Add(new HikChannelInfo { channel = device.StartChannel + i, type = "analog", enabled = true, }); } } // IP 设备数组是**紧凑**的(未配置的通道被跳过),而预览/回放用的是**真实通道号**。 // 只按数组下标推会错位(现场 IP 通道 19 是空槽,导致 51 以后全部串一位), // 所以优先按 struStreamMode(按通道槽位给 byIPID)来映射。 var mappingOk = CanReadStreamModes(buffer, returned, digitalCount); for (var i = 0; i < digitalCount; i++) { var channel = startDigital + i; bool enabled; IpDeviceEntry? item = null; if (mappingOk) { var offset = StreamModeStart + i * StreamModeSize; enabled = Marshal.ReadByte(buffer, offset + 4) == 1; var ipId = Marshal.ReadByte(buffer, offset + 5); if (enabled && ipId >= 1 && ipId <= 64) { var entry = ReadIpDevice(buffer, ipId - 1); if (entry.Enabled) item = entry; } } else { // 老固件没有这层映射表:退回「顺序对应」 var entry = ReadIpDevice(buffer, i); enabled = entry.Enabled; if (entry.Enabled) item = entry; } channels.Add(new HikChannelInfo { channel = channel, type = "digital", enabled = enabled, ip = item?.Ip, port = item?.Port, user = item?.UserName, }); } } } finally { Marshal.FreeHGlobal(buffer); } // 拿不到配置时用登录信息兜底 if (channels.Count == 0) { for (var i = 0; i < device.AnalogChannelCount; i++) { channels.Add(new HikChannelInfo { channel = device.StartChannel + i, type = "analog", enabled = true }); } for (var i = 0; i < device.DigitalChannelCount; i++) { channels.Add(new HikChannelInfo { channel = device.StartDigitalChannel + i, type = "digital", enabled = false }); } } // 通道名:IP 接入配置里没有名字 → 逐通道读 PICCFG 的 sChanName(走 8000,不需要 Web 端口) TryFillChannelNames(session, password, channels); return new HikChannelsResult { endpoint = $"{session.Host}:{session.Port}", serialNumber = device.SerialNumber, diskCount = device.DiskCount, analogChannelCount = device.AnalogChannelCount, digitalChannelCount = device.DigitalChannelCount, startChannel = device.StartChannel, startDigitalChannel = device.StartDigitalChannel, channels = channels, warning = warning, }; } /// /// 补通道名(best-effort)。 /// /// 主路径:**8000 私有协议**逐通道读 NET_DVR_GET_PICCFG_V30 的 sChanName /// (GBK)—— 不需要设备的 Web/ISAPI 端口,实测 32 路约 250ms,中文名正常。 /// 只有一条都没拿到(极老固件不支持 PICCFG_V30)才退回设备 Web 端口的 ISAPI; /// 全部失败就留空,前端会拼「NVR名-通道号」,不影响其他字段。 /// private static void TryFillChannelNames(Session session, string password, List 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})"); } } /// /// 走 8000 读每个通道的 OSD 名:NET_DVR_GET_PICCFG_V30 头部是 DWORD dwSize + char sChanName[32]。 /// 只查 enabled 的通道(空槽位会回 err=4),任何单通道失败都跳过。 /// private static int FillNamesFromPicCfg(Session session, List 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); } } /// /// 兜底:读设备 ISAPI ContentMgmt/InputProxy/channels(需要设备 Web 端口)。 /// /// - 发请求前先做 500ms TCP 探测,端口没开直接跳过(有些固件只开 8000); /// - 依次试 http://host:80 → https://host:443 → https://host:8443; /// - 先按 IP 匹配,IP 对不上再按 ISAPI 的 id 推(id 从 1 起,对应第几个数字通道)。 /// private static int FillNamesFromIsapi(string host, string userName, string password, List 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(); var byIp = new Dictionary(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; } } /// /// 取 ISAPI 通道列表 XML:按 80(http) → 443(https) → 8443(https) 顺序试, /// 先 TCP 探测端口,连不通直接换下一个(不等待 HTTP 超时)。全部失败返回 null。 /// 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; } /// TCP 端口探测( 内连上就算通) 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; } } /// /// 校验 struStreamMode 映射表能不能用(老固件可能不填这一层)。 /// 判定标准:byEnable 只能 0/1;启用的槽位 byIPID 必须在 1..64。 /// private static bool CanReadStreamModes(IntPtr buffer, uint returned, int digitalCount) { if (digitalCount <= 0 || digitalCount > 64) return false; if (returned < StreamModeStart + digitalCount * StreamModeSize) return false; for (var i = 0; i < digitalCount; i++) { var offset = StreamModeStart + i * StreamModeSize; var enabled = Marshal.ReadByte(buffer, offset + 4); var ipId = Marshal.ReadByte(buffer, offset + 5); if (enabled > 1) return false; if (enabled == 1 && (ipId < 1 || ipId > 64)) return false; } return true; } /// NET_DVR_IPPARACFG_V40.struIPDevInfo[i](每项 296 字节,起点偏移 84) private static IpDeviceEntry ReadIpDevice(IntPtr buffer, int index) { const int ipDeviceStart = IpDevInfoStart; const int ipDeviceSize = IpDevInfoSize; var baseOffset = ipDeviceStart + index * ipDeviceSize; var enabled = Marshal.ReadByte(buffer, baseOffset); // 越界保护:设备返回的缓冲区可能比 64 项小 var ip = ReadAscii(buffer, baseOffset + 116, 16); var port = Marshal.ReadInt16(buffer, baseOffset + 260); var user = ReadAscii(buffer, baseOffset + 4, 32); return new IpDeviceEntry { Enabled = enabled == 1, Ip = ip, Port = port, UserName = user, }; } private static string ReadAscii(IntPtr buffer, int offset, int length) { var bytes = new byte[length]; Marshal.Copy(IntPtr.Add(buffer, offset), bytes, 0, length); var text = Encoding.ASCII.GetString(bytes); var end = text.IndexOf('\0'); return (end >= 0 ? text[..end] : text).Trim(); } private void SweepIdleSessions() { if (_disposed) return; var now = Environment.TickCount64; foreach (var pair in _sessions) { var session = pair.Value; if (now - session.LastUsedTicks < (long)IdleTimeout.TotalMilliseconds) continue; if (!session.Gate.Wait(0)) continue; // 正在被使用,下轮再说 try { if (now - session.LastUsedTicks < (long)IdleTimeout.TotalMilliseconds) continue; CloseSession(session); _sessions.TryRemove(pair.Key, out _); } finally { session.Gate.Release(); } } } public void Dispose() { if (_disposed) return; _disposed = true; _sweeper.Dispose(); try { CloseAll(); } catch { /* 退出阶段忽略 */ } HikSdk.Shutdown(); } private sealed class Session { public Session(string host, int port, string user) { Host = host.Trim(); Port = port; User = user; LastUsedTicks = Environment.TickCount64; } public string Host { get; } public int Port { get; } public string User { get; } public int UserId { get; set; } = -1; public DeviceSnapshot? Device { get; set; } public long LastUsedTicks { get; private set; } /// 同一 UserID 的调用串行化 public SemaphoreSlim Gate { get; } = new(1, 1); public void Touch() => LastUsedTicks = Environment.TickCount64; } private sealed class DeviceSnapshot { public string SerialNumber { get; init; } = string.Empty; public int DiskCount { get; init; } public int AnalogChannelCount { get; init; } public int StartChannel { get; init; } public int DigitalChannelCount { get; init; } public int StartDigitalChannel { get; init; } } private readonly record struct IpDeviceEntry(bool Enabled, string Ip, int Port, string UserName); } /// 一个通道 public sealed class HikChannelInfo { /// 通道号(海康通道号,1 起;数字通道通常从 33 起) public int channel { get; init; } /// analog / digital public string type { get; init; } = string.Empty; public bool enabled { get; init; } /// 设备上的通道名(ISAPI 透传补的;拿不到就是 null,由前端自己拼名字) public string? name { get; set; } /// 数字通道对应的前端 IP(未配置时为 null) public string? ip { get; init; } public int? port { get; init; } public string? user { get; init; } } /// 录像机的 NTP 配置(8000 私有协议读写) /// NTP 服务器(域名或 IP) /// 同步间隔(分钟) /// 是否启用 NTP 校时 public sealed record HikNtpConfig(string Server, int IntervalMinutes, bool Enabled); /// 通道接口返回体 public sealed class HikChannelsResult { public string endpoint { get; init; } = string.Empty; public string serialNumber { get; init; } = string.Empty; public int diskCount { get; init; } public int analogChannelCount { get; init; } public int digitalChannelCount { get; init; } public int startChannel { get; init; } public int startDigitalChannel { get; init; } public List channels { get; init; } = new(); /// 部分数据读取失败时的提示(不影响已返回的通道) public string? warning { get; init; } // 以下由服务层填充 public int userId { get; set; } public bool sessionReused { get; set; } public long elapsedMs { get; set; } }