| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701 |
- using Cognex.VisionPro;
- using CSScripting;
- using Microsoft.Win32;
- using MvCamCtrl.NET;
- using MvCamCtrl.NET.CameraParams;
- using NPOI.SS.Formula.Functions;
- using NPOI.Util;
- using NPOI.XSSF.Model;
- using OpenCvSharp.Dnn;
- using Org.BouncyCastle.Asn1.Tsp;
- using OxyPlot;
- using Sdcb.OpenVINO;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Media.Media3D;
- using TeamAAS_VP;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Interfaces;
- using TeamAAS_VP.Models;
- namespace TeamAAS_VP.Core.Cameras
- {
- public class MvCamera : ICamera, INotifyPropertyChanged
- {
- #region 字段
- private Thread m_hReceiveThread;
- // 用于序列化对同一相机实例的操作,防止同一实例被并发操作
- private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
- // 用于保护状态变量(例如 IsGrabbing)的并发访问
- private readonly object _stateLock = new object();
- #endregion
- #region 属性
- public CameraBrand CameraBrand { get => CameraBrand.HikRobot_MVS; }
- public string Name { get; private set; }
- public Guid ID { get; private set; }
- public int Index { get; set; }
- public string ManufacturerName { get; private set; }
- public bool IsFindByIp { get; private set; }
- public string ModelName { get; private set; }
- public string SerialNumber { get; private set; }
- public string CameraIp { get; private set; }
- public CameraType CameraType { get; private set; }
- MvCameraAcqTool.MvCameraAcqTool mvCameraAcq;
- public MyCamera.MV_CC_DEVICE_INFO CameraInfo { get; private set; }
- public UInt32 ImageWidth { get; private set; }
- public UInt32 ImageHeight { get; private set; }
- public MvGvspPixelType PixelType { get; private set; }
- private bool _IsGrabbing;
- /// <summary>
- /// 正在采集
- /// </summary>
- public bool IsGrabbing
- {
- get { return _IsGrabbing; }
- private set { SetProperty(ref _IsGrabbing, value); }
- }
- private ICogImage _Image;
- public ICogImage Image
- {
- get { return _Image; }
- private set { SetProperty(ref _Image, value); }
- }
- public bool IsConnected { get; private set; }
- private bool IsHaveCamera = false;
- /// <summary>
- /// 采集用时
- /// </summary>
- public TimeSpan TotalTime { get; private set; }
- /// <summary>
- /// 错误信息
- /// </summary>
- public string ErrorMessage { get; private set; }
- #endregion
- #region 事件
- public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
- public event Action<Guid, bool> CameraConnectChangedEvent;
- #endregion
- public MvCamera(Guid id, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
- {
- ID = id;
- Name = serialNumber;
- Index = index;
- CameraIp = cameraip;
- SerialNumber = serialNumber;
- IsFindByIp = isFindByIp;
- mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
- MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
- mvCameraAcq.EnumDeivce(ref stDeviceList);
- MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
- for (int i = 0; i < stDeviceList.nDeviceNum; i++)
- {
- device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
- if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
- {
- MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
- uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
- uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
- uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
- uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- if (IsFindByIp)
- {
- if (CameraIp == ip)
- {
- ManufacturerName = stGigEDeviceInfo.chManufacturerName;
- ModelName = stGigEDeviceInfo.chModelName;
- SerialNumber = stGigEDeviceInfo.chSerialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- else
- {
- if (string.Equals(stGigEDeviceInfo.chSerialNumber, serialNumber))
- {
- ManufacturerName = stGigEDeviceInfo.chManufacturerName;
- ModelName = stGigEDeviceInfo.chModelName;
- SerialNumber = stGigEDeviceInfo.chSerialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
- {
- MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
- if (string.Equals(usbInfo.chSerialNumber, serialNumber))
- {
- ManufacturerName = usbInfo.chManufacturerName;
- ModelName = usbInfo.chModelName;
- SerialNumber = usbInfo.chSerialNumber;
- CameraType = CameraType.USB;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- IsConnected = false;
- }
- #region 方法
- /// <summary>
- /// 获取设备
- /// </summary>
- /// <returns></returns>
- public static CameraInfo[] GetDevices()
- {
- List<CameraInfo> cameras = new List<CameraInfo>();
- try
- {
- if (!CheckSoftwareInstalled().isInstalled)
- {
- LogHelper.WriteLogInfo("未安装MVS");
- return cameras.ToArray();
- }
- List<CCameraInfo> m_ltDeviceList = new List<CCameraInfo>();
- int nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref m_ltDeviceList);
- if (0 != nRet)
- {
- return cameras.ToArray();
- }
- for (int i = 0; i < m_ltDeviceList.Count; i++)
- {
- if (m_ltDeviceList[i].nTLayerType == CSystem.MV_GIGE_DEVICE)
- {
- CGigECameraInfo gigeInfo = (CGigECameraInfo)m_ltDeviceList[i];
- uint nIp1 = ((gigeInfo.nCurrentIp & 0xff000000) >> 24);
- uint nIp2 = ((gigeInfo.nCurrentIp & 0x00ff0000) >> 16);
- uint nIp3 = ((gigeInfo.nCurrentIp & 0x0000ff00) >> 8);
- uint nIp4 = (gigeInfo.nCurrentIp & 0x000000ff);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- cameras.Add(new CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = gigeInfo.UserDefinedName,
- CameraBrand = CameraBrand.HikRobot_MVS,
- CameraType = CameraType.GIGE,
- ManufacturerName = gigeInfo.chManufacturerName,
- Model = gigeInfo.chModelName,
- SerialNumber = gigeInfo.chSerialNumber,
- CameraIp = ip,
- IsFindByIp = true,
- });
- }
- else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_USB_DEVICE)
- {
- CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
- cameras.Add(new Models.CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = usbInfo.UserDefinedName,
- CameraBrand = CameraBrand.HikRobot_MVS,
- CameraType = CameraType.USB,
- ManufacturerName = usbInfo.chManufacturerName,
- Model = usbInfo.chModelName,
- SerialNumber = usbInfo.chSerialNumber,
- CameraIp = "",
- });
- }
- else if (m_ltDeviceList[i].nTLayerType == CSystem.MV_CAMERALINK_DEVICE)
- {
- CCamLCameraInfo Info = (CCamLCameraInfo)m_ltDeviceList[i];
- cameras.Add(new Models.CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = Info.chModelName,
- CameraBrand = CameraBrand.HikRobot_MVS,
- CameraType = CameraType.USB,
- ManufacturerName = Info.chManufacturerName,
- Model = Info.chModelName,
- SerialNumber = Info.chSerialNumber,
- CameraIp = "",
- });
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("搜索海康相机列表时出错!", ex);
- }
- return cameras.ToArray();
- }
- /// <summary>
- /// 检查相机软件是否安装
- /// </summary>
- /// <returns></returns>
- public static (bool isInstalled, string version) CheckSoftwareInstalled()
- {
- string softwareName = "MVS";
- string softwareVersion = "4.4.0";
- string[] registryPaths = new[]
- {
- @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
- @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
- };
- foreach (var path in registryPaths)
- {
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
- {
- if (key == null) continue;
- foreach (string subKeyName in key.GetSubKeyNames())
- {
- using (RegistryKey subKey = key.OpenSubKey(subKeyName))
- {
- string displayName = subKey.GetValue("DisplayName")?.ToString();
- if (displayName != null && displayName.ToUpper().Trim() == softwareName.ToUpper())
- {
- string version = subKey.GetValue("DisplayVersion")?.ToString();
- Version v1 = new Version(version);
- Version v2 = new Version(softwareVersion);
- if (v1 >= v2)
- {
- return (true, version);
- }
- else
- {
- return (false, version);
- }
- }
- }
- }
- }
- }
- return (false, "");
- }
- /// <summary>
- /// 打开相机
- /// </summary>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public bool OpenDevice()
- {
- _operationSemaphore.Wait();
- try
- {
- if (!IsHaveCamera)
- {
- mvCameraAcq = new MvCameraAcqTool.MvCameraAcqTool();
- MyCamera.MV_CC_DEVICE_INFO_LIST stDeviceList = default(MyCamera.MV_CC_DEVICE_INFO_LIST);
- mvCameraAcq.EnumDeivce(ref stDeviceList);
- MyCamera.MV_CC_DEVICE_INFO device = default(MyCamera.MV_CC_DEVICE_INFO);
- for (int i = 0; i < stDeviceList.nDeviceNum; i++)
- {
- device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
- if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
- {
- MV_GIGE_DEVICE_INFO stGigEDeviceInfo = (MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MV_GIGE_DEVICE_INFO));
- uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
- uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
- uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
- uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- if (IsFindByIp)
- {
- if (CameraIp == ip)
- {
- ManufacturerName = stGigEDeviceInfo.chManufacturerName;
- ModelName = stGigEDeviceInfo.chModelName;
- SerialNumber = stGigEDeviceInfo.chSerialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- else
- {
- if (string.Equals(stGigEDeviceInfo.chSerialNumber, SerialNumber))
- {
- ManufacturerName = stGigEDeviceInfo.chManufacturerName;
- ModelName = stGigEDeviceInfo.chModelName;
- SerialNumber = stGigEDeviceInfo.chSerialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- else if (device.nTLayerType == CSystem.MV_USB_DEVICE)
- {
- MV_USB3_DEVICE_INFO usbInfo = (MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MV_USB3_DEVICE_INFO));
- if (string.Equals(usbInfo.chSerialNumber, SerialNumber))
- {
- ManufacturerName = usbInfo.chManufacturerName;
- ModelName = usbInfo.chModelName;
- SerialNumber = usbInfo.chSerialNumber;
- CameraType = CameraType.USB;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- if (!IsHaveCamera)
- {
- throw new Exception("没有发现相机");
- }
- }
- mvCameraAcq.OpenDevice(CameraInfo);
- mvCameraAcq.AutoExposure = false;
- mvCameraAcq.TriggerMode = false;
- if (!IsConnected)
- {
- CameraConnectChangedEvent?.Invoke(ID, true);
- }
- IsConnected = mvCameraAcq.bIsOpened;
- return IsConnected;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 打开相机异步
- /// </summary>
- /// <returns></returns>
- public Task<bool> OpenDeviceAsync()
- {
- return Task.Run(() =>
- {
- return OpenDevice();
- });
- }
- /// <summary>
- /// 关闭相机
- /// </summary>
- public void CloseDevice()
- {
- // ch:关闭设备 | en:Close Device
- _operationSemaphore.Wait();
- try
- {
- mvCameraAcq.CloseDevice();
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 采集单张图片
- /// </summary>
- /// <param name="lastImageOnly">true:采集一张新图像,false:返回最后一张图像</param>
- /// <returns></returns>
- public ICogImage Grab(bool lastImageOnly = true)
- {
- _operationSemaphore.Wait();
- try
- {
- Stopwatch sw = Stopwatch.StartNew();
- for (int i = 0; i < 5; i++)
- {
- try
- {
- if (!mvCameraAcq.bIsOpened)
- {
- OpenDevice();
- }
- mvCameraAcq.Run();
- if (mvCameraAcq.RunStatus.Result == CogToolResultConstants.Accept)
- {
- ErrorMessage = "";
- Image = mvCameraAcq.OutputImage;
- if (!IsConnected)
- {
- IsConnected = true;
- CameraConnectChangedEvent?.Invoke(ID, true);
- }
- TotalTime = sw.Elapsed;
- return Image;
- }
- else
- {
- ErrorMessage = mvCameraAcq.RunStatus.Message;
- CloseDevice();
- OpenDevice();
- }
- }
- catch (Exception ex)
- {
- CloseDevice();
- OpenDevice();
- ErrorMessage = ex.Message;
- }
- }
- if (IsConnected)
- {
- IsConnected = false;
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- return null;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 开始采集图像
- /// </summary>
- public void StartGrabbing()
- {
- lock (_stateLock)
- {
- if (IsGrabbing)
- return;
- IsGrabbing = true;
- }
- m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
- m_hReceiveThread.Start();
- }
- /// <summary>
- /// 停止采集图像
- /// </summary>
- public void StopGrabbing()
- {
- try
- {
- lock (_stateLock)
- {
- IsGrabbing = false;
- }
- Thread.Sleep(1000);
- if (m_hReceiveThread != null)
- {
- m_hReceiveThread.Abort();
- m_hReceiveThread = null;
- }
- }
- catch (Exception)
- {
- }
- }
- /// <summary>
- /// 设置曝光时间
- /// </summary>
- /// <param name="ExposureTime"></param>
- /// <returns></returns>
- public bool SetExposureTime(float ExposureTime)
- {
- _operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.bIsOpened)
- return false;
- mvCameraAcq.ExposureTime = (double)ExposureTime;
- return true;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 获取曝光时间
- /// </summary>
- /// <returns></returns>
- public float GetExposureTime()
- {
- _operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.bIsOpened)
- return 0;
- return (float)mvCameraAcq.ExposureTime;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 设置增益
- /// </summary>
- /// <param name="Gain"></param>
- /// <returns></returns>
- public bool SetGain(float Gain)
- {
- _operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.bIsOpened)
- return false;
- mvCameraAcq.AnalogGain = (double)Gain;
- return true;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 获取增益
- /// </summary>
- /// <returns></returns>
- public float GetGain()
- {
- _operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.bIsOpened)
- return 0;
- return (float)mvCameraAcq.AnalogGain;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- private void GetStreamThreadProc()
- {
- while (IsGrabbing)
- {
- try
- {
- Grab();
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- catch (Exception)
- {
- }
- Thread.Sleep(10);
- }
- IsGrabbing = false;
- }
- #endregion
- #region 属性通知
- /// <summary>
- /// Occurs when a property value changes.
- /// </summary>
- public event PropertyChangedEventHandler PropertyChanged;
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <param name="onChanged">Action that is called after the property value has been changed.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- onChanged?.Invoke();
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers
- /// that support <see cref="CallerMemberNameAttribute"/>.</param>
- protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
- {
- OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="args">The PropertyChangedEventArgs</param>
- protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
- {
- PropertyChanged?.Invoke(this, args);
- }
- #endregion
- }
- }
|