IPCamera.cs 19.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Asa.CameraFactory;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;

namespace Asa.HIK
{
    /// <summary>
    /// 网络监控摄像机
    /// </summary>
    public class IPCamera : ICamera
    {
        private List<LoginInfo> info;

        /// <summary>
        /// 网络监控摄像机
        /// </summary>
        /// <param name="configPath"></param>
        /// <param name="logName"></param>
        public IPCamera(string configPath, string logName = "HIK.IPCamera")
        {
            info = new List<LoginInfo>();
            GetConfig(configPath);
            if (!string.IsNullOrWhiteSpace(logName))
                Log.Load(logName);
        }

        /// <summary>
        /// 相机名称
        /// </summary>
        public string[] Name
        {
            get
            {
                string[] str = new string[info.Count];
                for (int i = 0; i < str.Length; i++)
                    str[i] = info[i].Name;
                return str;
            }
        }

        /// <summary>
        /// 相机总数
        /// </summary>
        public int Count
        {
            get
            {
                int count = 0;
                for (int i = 0; i < info.Count; i++)
                    if (info[i].ID >= 0) count++;
                return count;
            }
        }

        /// <summary>
        /// 相机是否打开
        /// </summary>
        public bool[] IsOpen
        {
            get
            {
                bool[] rtn = new bool[info.Count];
                for (int i = 0; i < rtn.Length; i++)
                    rtn[i] = info[i].Handle >= 0;
                return rtn;
            }

        }

        /// <summary>
        /// 图像分辨率
        /// </summary>
        public Size[] Size { private set; get; }

        /// <summary>
        /// 相机获取到的图像
        /// </summary>
        public Bitmap Image { private set; get; }

        /// <summary>
        /// 预览控件
        /// </summary>
        public IntPtr Preview { set; get; } = IntPtr.Zero;



        /// <summary>
        /// 加载
        /// </summary>
        /// <returns></returns>
        public bool Load()
        {
            try
            {
                bool rtn = API.NET_DVR_Init();
                Size = new Size[info.Count];
                for (int i = 0; i < info.Count; i++)
                    LoginDevice(i);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Load", ex);
                return false;
            }
        }

        /// <summary>
        /// 释放所有
        /// </summary>
        public void Dispose()
        {
            for (int i = 0; i < info.Count; i++)
                LogoutDevice(i);
            API.NET_DVR_Cleanup();
        }

        /// <summary>
        /// 打开所有摄像机
        /// </summary>
        /// <returns></returns>
        public bool OpenAll()
        {
            bool rtn = false;
            for (int i = 0; i < info.Count; i++)
            {
                rtn = OpenDevice(i);
                if (!rtn) break;
            }
            return rtn;
        }

        /// <summary>
        /// 关闭所有摄像机
        /// </summary>
        public void CloseAll()
        {
            for (int i = 0; i < info.Count; i++)
                CloseDevice(i);
        }

        /// <summary>
        /// 打开摄像机
        /// </summary>
        /// <param name="cameraIndex"></param>
        /// <returns></returns>
        public bool Open(int cameraIndex)
        {
            return OpenDevice(cameraIndex);
        }

        /// <summary>
        /// 关闭摄像机
        /// </summary>
        /// <param name="cameraIndex"></param>
        public void Close(int cameraIndex)
        {
            CloseDevice(cameraIndex);
        }

        /// <summary>
        /// 抓取所有摄像机一张图像
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public bool GrabOne(out Bitmap[] bmp)
        {
            bmp = new Bitmap[info.Count];
            bool rtn = false;
            for (int i = 0; i < info.Count; i++)
            {
                rtn = GrabDevice(i, out bmp[i]);
                if (!rtn) break;
            }
            return rtn;
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex)
        {
            bool rtn = GrabDevice(cameraIndex, out Bitmap bmp);
            Image = bmp;
            return rtn;
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <param name="bmp">Bitmap图像</param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out Bitmap bmp)
        {
            return GrabDevice(cameraIndex, out bmp);
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraName">相机名称</param>
        /// <param name="bmp">Bitmap图像</param>
        /// <returns></returns>
        public bool GrabOne(string cameraName, out Bitmap bmp)
        {
            bmp = null;
            int index = info.FindIndex(match => match.Name == cameraName);
            if (index == -1) return false;
            return GrabDevice(index, out bmp);
        }

        /// <summary>
        /// 抓取一张图像字节
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <param name="buff">图像字节数组</param>
        /// <param name="format"></param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out byte[] buff, out PixelFormat format)
        {
            return GrabDevice(cameraIndex, out buff, out format);
        }

        /// <summary>
        /// 抓取一张图像指针
        /// </summary>
        /// <param name="cameraIndex"></param>
        /// <param name="handle"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out IntPtr handle, out PixelFormat format)
        {
            return GrabDevice(cameraIndex, out handle, out format);
        }









        private bool LoginDevice(int idx)
        {
            try
            {
                API.NET_DVR_USER_LOGIN_INFO loginInfo = new();
                API.NET_DVR_DEVICEINFO_V40 deviceInfo = new();

                //设备IP地址或者域名
                byte[] byIP = Encoding.Default.GetBytes(info[idx].IP);
                loginInfo.sDeviceAddress = new byte[129];
                byIP.CopyTo(loginInfo.sDeviceAddress, 0);

                //设备用户名
                byte[] byUserName = Encoding.Default.GetBytes(info[idx].User);
                loginInfo.sUserName = new byte[64];
                byUserName.CopyTo(loginInfo.sUserName, 0);

                //设备密码
                byte[] byPassword = Encoding.Default.GetBytes(info[idx].Password);
                loginInfo.sPassword = new byte[64];
                byPassword.CopyTo(loginInfo.sPassword, 0);

                //设备服务端口号
                loginInfo.wPort = (ushort)info[idx].Port;

                //注册回调函数
                API.LOGINRESULTCALLBACK loginCall = new(LoginCallBack);
                loginInfo.cbLoginResult = loginCall;

                //是否异步登录
                loginInfo.bUseAsynLogin = false;

                //登录设备
                info[idx].ID = API.NET_DVR_Login_V40(ref loginInfo, ref deviceInfo);
                if (info[idx].ID < 0)
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("Load {0} failed, error code {1}", info[idx].IP, err));
                    return false;
                }
                else
                {
                    int n = Array.FindIndex(deviceInfo.struDeviceV30.sSerialNumber, s => s == 0);
                    info[idx].SerialNumber = Encoding.UTF8.GetString(deviceInfo.struDeviceV30.sSerialNumber, 0, n);
                    Log.Info(string.Format("Load {0} OK", info[idx].IP));
                    return true;
                }
            }
            catch(Exception ex)
            {
                Log.Error("LoginDevice", ex);
                return false;
            }
        }

        private void LogoutDevice(int idx)
        {
            try
            {
                bool rtn = API.NET_DVR_Logout(info[idx].ID);
                if (rtn)
                {
                    info[idx].ID = -1;
                    info[idx].Handle = -1;
                    Log.Info(string.Format("Dispose {0} OK", info[idx].IP));
                }
                else
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("Dispose {0} failed, error code {1}", info[idx].IP, err));
                }
            }
            catch (Exception ex)
            {
                Log.Error("LogoutDevice", ex);
            }

        }

        private bool OpenDevice(int idx)
        {
            try
            {
                API.NET_DVR_PREVIEWINFO lpPreviewInfo = new();
                if (Preview != IntPtr.Zero)
                    lpPreviewInfo.hPlayWnd = Preview;  //预览窗口
                lpPreviewInfo.lChannel = 1;         //预览的设备通道
                lpPreviewInfo.dwStreamType = 0;     //码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推
                lpPreviewInfo.dwLinkMode = 0;       //连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4-RTP/RTSP,5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true;      //0- 非阻塞取流,1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 1;  //播放库播放缓冲区最大缓冲帧数
                lpPreviewInfo.byProtoType = 0;
                lpPreviewInfo.byPreviewMode = 0;

                API.REALDATACALLBACK RealData = new(RealDataCallBack);  //预览实时流回调函数
                IntPtr pUser = new();//用户数据

                //打开预览
                info[idx].Handle = API.NET_DVR_RealPlay_V40(info[idx].ID, ref lpPreviewInfo, null/*RealData*/, pUser);
                if (info[idx].Handle < 0)
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("Open {0} failed, error code {1}", info[idx].IP, err));
                    return false;
                }
                else
                {
                    Log.Info(string.Format("Open {0} OK", info[idx].IP));
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.Error("OpenDevice", ex);
                return false;
            }
        }

        private void CloseDevice(int idx)
        {
            try
            {
                bool rtn = API.NET_DVR_StopRealPlay(info[idx].Handle);
                if (rtn)
                {
                    info[idx].Handle = -1;
                    Log.Info(string.Format("Close {0} OK", info[idx].IP));
                }
                else
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("Close {0} failed, error code {1}", info[idx].IP, err));
                }
            }
            catch (Exception ex)
            {
                Log.Error("CloseDevice", ex);
            }

        }

        private bool GrabDevice(int idx, out Bitmap bmp)
        {
            bmp = null;

            try
            {
                //bmp,需要指定hPlayWnd
                //string path = AppDomain.CurrentDomain.BaseDirectory + "IPCamera.bmp";
                //bool rtn = API.NET_DVR_CapturePicture(info[idx].Handle, path);

                //jpg
                //string path = AppDomain.CurrentDomain.BaseDirectory + info[idx].Name + ".jpg";
                string path = System.IO.Path.GetTempFileName();

                API.NET_DVR_JPEGPARA lpJpegPara = new()
                {
                    wPicQuality = 0,  //图像质量
                    wPicSize = 0xff   //Auto使用当前码流分辨率
                };
                bool rtn = API.NET_DVR_CaptureJPEGPicture(info[idx].ID, 1, ref lpJpegPara, path);

                if (rtn)
                {
                    System.IO.FileStream fs = new(path, System.IO.FileMode.Open);
                    byte[] array = new byte[fs.Length];
                    fs.Read(array, 0, array.Length);
                    System.IO.MemoryStream ms = new(array);
                    bmp = new Bitmap(System.Drawing.Image.FromStream(ms));
                    Size[idx] = new Size(bmp.Width, bmp.Height);
                    fs.Dispose();
                    System.IO.File.Delete(path);
                    Log.Info(string.Format("GrabOne {0} OK", info[idx].IP));
                }
                else
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("GrabOne {0} failed, error code {1}", info[idx].IP, err));
                }
                return rtn;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private bool GrabDevice(int idx, out byte[] buff, out PixelFormat format)
        {
            buff = null;
            format = PixelFormat.Undefined;

            try
            {
                //jpg
                string path = AppDomain.CurrentDomain.BaseDirectory + "IPCamera.jpg";
                API.NET_DVR_JPEGPARA lpJpegPara = new()
                {
                    wPicQuality = 0,  //图像质量
                    wPicSize = 0xff   //Auto使用当前码流分辨率
                };
                bool rtn = API.NET_DVR_CaptureJPEGPicture(info[idx].ID, 1, ref lpJpegPara, path);

                if (rtn)
                {
                    Bitmap bmp = new(path);
                    System.IO.MemoryStream ms = new();
                    bmp.Save(ms, ImageFormat.Bmp);
                    buff = ms.GetBuffer();
                    format = bmp.PixelFormat;
                    Size[idx] = new Size(bmp.Width, bmp.Height);
                    ms.Close();
                    bmp.Dispose();
                    System.IO.File.Delete(path);
                    Log.Info(string.Format("GrabOne {0} OK", info[idx].IP));
                }
                else
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("GrabOne {0} failed, error code {1}", info[idx].IP, err));
                }
                return rtn;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private bool GrabDevice(int idx, out IntPtr handle, out PixelFormat format)
        {
            handle = IntPtr.Zero;
            format = PixelFormat.Undefined;

            try
            {
                //jpg
                string path = AppDomain.CurrentDomain.BaseDirectory + "IPCamera.jpg";
                API.NET_DVR_JPEGPARA lpJpegPara = new()
                {
                    wPicQuality = 0,  //图像质量
                    wPicSize = 0xff   //Auto使用当前码流分辨率
                };
                bool rtn = API.NET_DVR_CaptureJPEGPicture(info[idx].ID, 1, ref lpJpegPara, path);

                if (rtn)
                {
                    Bitmap bmp = new(path);
                    System.IO.MemoryStream ms = new();
                    bmp.Save(ms, ImageFormat.Bmp);
                    byte[] buff = ms.GetBuffer();
                 
                    //handle = Marshal.AllocHGlobal(buff.Length);
                    //Marshal.Copy(buff, 0, handle, buff.Length);
                    handle = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
                    format = bmp.PixelFormat;
                    Size[idx] = new Size(bmp.Width, bmp.Height);
                    ms.Close();
                    bmp.Dispose();
                    System.IO.File.Delete(path);
                    Log.Info(string.Format("GrabOne {0} OK", info[idx].IP));
                }
                else
                {
                    uint err = API.NET_DVR_GetLastError();
                    Log.Info(string.Format("GrabOne {0} failed, error code {1}", info[idx].IP, err));
                }
                return rtn;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private void LoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
        {
            //string strLoginCallBack = "登录设备,lUserID:" + lUserID + ",dwResult:" + dwResult;

            //if (dwResult == 0)
            //{
            //    uint iErrCode = API.NET_DVR_GetLastError();
            //    strLoginCallBack = strLoginCallBack + ",错误号:" + iErrCode;
            //}

            ////下面代码注释掉也会崩溃
            //if (InvokeRequired)
            //{
            //    object[] paras = new object[2];
            //    paras[0] = strLoginCallBack;
            //    paras[1] = lpDeviceInfo;
            //    labelLogin.BeginInvoke(new UpdateTextStatusCallback(UpdateClientList), paras);
            //}
            //else
            //{
            //    //创建该控件的主线程直接更新信息列表 
            //    UpdateClientList(strLoginCallBack, lpDeviceInfo);
            //}

        }

        private void RealDataCallBack(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser)
        {
            //if (dwBufSize > 0)
            //{
            //    byte[] sData = new byte[dwBufSize];
            //    Marshal.Copy(pBuffer, sData, 0, (Int32)dwBufSize);

            //    string str = "实时流数据.ps";
            //    FileStream fs = new FileStream(str, FileMode.Create);
            //    int iLen = (int)dwBufSize;
            //    fs.Write(sData, 0, iLen);
            //    fs.Close();
            //}
        }

        private void GetConfig(string path)
        {
            string json = System.IO.File.ReadAllText(path);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new();
            Dictionary<string, object> dic = (Dictionary<string, object>)serializer.DeserializeObject(json);

            if (dic.TryGetValue("HIKIPCamera", out object value))
            {
                object[] obj = (object[])value;
                for (int i = 0; i < obj.Length; i++)
                {
                    Dictionary<string, object> param = (Dictionary<string, object>)obj[i];
                    LoginInfo item = new();
                    if (param.TryGetValue("Name", out value))
                        item.Name = value.ToString();
                    if (param.TryGetValue("IP", out value))
                        item.IP = value.ToString();
                    if (param.TryGetValue("User", out value))
                        item.User = value.ToString();
                    if (param.TryGetValue("Pwd", out value))
                        item.Password = value.ToString();
                    if (param.TryGetValue("Port", out value))
                        item.Port = Convert.ToInt32(value);
                    info.Add(item);
                }
            }
        }

    }
}