CameraClass.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using CCDCount.MODEL.CameraClass;
  2. using CCDCount.MODEL.ConfigModel;
  3. using LogClass;
  4. using MvCameraControl;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. namespace CCDCount.DLL
  14. {
  15. public class CameraClass
  16. {
  17. #region 常量
  18. readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
  19. | DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice
  20. | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;
  21. #endregion
  22. #region 变量
  23. private List<IDeviceInfo> CamList; // 相机列表
  24. private IDevice device = null; // 相机实例
  25. private long lastframeNum = -1;
  26. public int CamereNo { get { return _cameraNo; } }
  27. private int _cameraNo = -1;
  28. #endregion
  29. #region 公共方法
  30. /// <summary>
  31. /// 获取相机列表
  32. /// </summary>
  33. /// <param name="CamList"></param>
  34. /// <returns></returns>
  35. public void GetCameraList(out List<CameraInfoClass> CameraInfoList)
  36. {
  37. CamList = new List<IDeviceInfo>();
  38. CameraInfoList = new List<CameraInfoClass>();
  39. int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out CamList);
  40. if (nRet != MvError.MV_OK)
  41. {
  42. return;
  43. }
  44. else
  45. {
  46. //输出相机名称及SN码以方便选择设备
  47. foreach (var item in CamList)
  48. {
  49. CameraInfoList.Add(new CameraInfoClass
  50. {
  51. //DeviceName = item.UserDefinedName == "" ? item.ModelName : item.UserDefinedName,
  52. DeviceName = item.ModelName,
  53. DeviceSN = item.SerialNumber,
  54. });
  55. }
  56. }
  57. return;
  58. }
  59. /// <summary>
  60. /// 更新相机列表
  61. /// </summary>
  62. public void UpdateCameraList()
  63. {
  64. CamList = new List<IDeviceInfo>();
  65. int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out CamList);
  66. if (nRet != MvError.MV_OK)
  67. {
  68. Console.WriteLine("相机列表更新失败");
  69. return;
  70. }
  71. }
  72. /// <summary>
  73. /// 加载指定相机
  74. /// </summary>
  75. /// <param name="DeviceSN"></param>
  76. public bool LoadCamereDevice(CameraConfig DeviceConfig)
  77. {
  78. bool Blresult = false;
  79. if (device != null && device.IsConnected)
  80. {
  81. device.Close();
  82. device.Dispose();
  83. }
  84. UpdateCameraList();
  85. List<IDeviceInfo> deviceInfos = CamList.Where(o => o.SerialNumber == DeviceConfig.CameraSNNum).ToList();
  86. if(deviceInfos.Count == 0) return Blresult;
  87. IDeviceInfo deviceInfo = deviceInfos.First();
  88. try
  89. {
  90. // 打开设备
  91. device = DeviceFactory.CreateDevice(deviceInfo);
  92. }
  93. catch (Exception ex)
  94. {
  95. FaultLog.RecordErrorMessage("Create Device fail!" + DeviceConfig.CameraSNNum + ":" + ex.Message);
  96. return Blresult;
  97. }
  98. int result = device.Open();
  99. if (result != MvError.MV_OK)
  100. {
  101. FaultLog.RecordErrorMessage("Open Device fail!" + DeviceConfig.CameraSNNum + ":" + result);
  102. return Blresult;
  103. }
  104. // 判断是否为gige设备
  105. if (device is IGigEDevice)
  106. {
  107. // 转换为gigE设备
  108. IGigEDevice gigEDevice = device as IGigEDevice;
  109. // 探测网络最佳包大小(只对GigE相机有效)
  110. result = gigEDevice.GetOptimalPacketSize(out int optionPacketSize);
  111. if (result != MvError.MV_OK)
  112. {
  113. //Log("Warning: Get Packet Size failed!", result);
  114. }
  115. else
  116. {
  117. result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
  118. if (result != MvError.MV_OK)
  119. {
  120. //Log("Warning: Set Packet Size failed!", result);
  121. }
  122. }
  123. }
  124. //判断是否从配置文件读取的参数,是则设置参数,否则加载相机默认参数
  125. if(DeviceConfig.IsLoadCanfig)
  126. {
  127. //设置从配置文件读取的参数
  128. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  129. _cameraNo = DeviceConfig.CamerNo;
  130. if (DeviceConfig.CameraName != deviceModelName.CurValue)
  131. device.Parameters.SetStringValue("DeviceUserID", DeviceConfig.CameraName);
  132. device.Parameters.SetFloatValue("ExposureTime", DeviceConfig.ExposureTimeValue);
  133. device.Parameters.SetIntValue("AcquisitionLineRate", DeviceConfig.AcquistionLineRateValue);
  134. device.Parameters.GetIntValue("Height", out IIntValue height);
  135. device.Parameters.SetIntValue("Height", height.Min);
  136. device.Parameters.SetIntValue("Width", DeviceConfig.Width);
  137. device.Parameters.SetIntValue("OffsetX", DeviceConfig.OffsetX);
  138. }
  139. // 设置采集连续模式
  140. device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
  141. device.Parameters.SetEnumValueByString("TriggerMode", "Off");
  142. Blresult = true;
  143. return Blresult;
  144. }
  145. /// <summary>
  146. /// 重新加载指定相机
  147. /// </summary>
  148. /// <param name="CameraSN"></param>
  149. /// <returns></returns>
  150. public bool ReLoadCameraDevice(string CameraSN)
  151. {
  152. bool Blresult = false;
  153. if(device!=null && device.IsConnected)
  154. {
  155. device.Close();
  156. device.Dispose();
  157. }
  158. UpdateCameraList();
  159. List<IDeviceInfo> deviceInfos = CamList.Where(o => o.SerialNumber == CameraSN).ToList();
  160. if (deviceInfos.Count == 0) return Blresult;
  161. IDeviceInfo deviceInfo = deviceInfos.First();
  162. try
  163. {
  164. // 打开设备
  165. device = DeviceFactory.CreateDevice(deviceInfo);
  166. Blresult = true;
  167. }
  168. catch (Exception ex)
  169. {
  170. FaultLog.RecordErrorMessage("Create Device fail!" + CameraSN + ":" + ex.Message);
  171. return Blresult;
  172. }
  173. int result = device.Open();
  174. if (result != MvError.MV_OK)
  175. {
  176. Blresult = false;
  177. FaultLog.RecordErrorMessage("Open Device fail!" + CameraSN + ":" + result);
  178. return Blresult;
  179. }
  180. // 判断是否为gige设备
  181. if (device is IGigEDevice)
  182. {
  183. // 转换为gigE设备
  184. IGigEDevice gigEDevice = device as IGigEDevice;
  185. // 探测网络最佳包大小(只对GigE相机有效)
  186. result = gigEDevice.GetOptimalPacketSize(out int optionPacketSize);
  187. if (result != MvError.MV_OK)
  188. {
  189. //Log("Warning: Get Packet Size failed!", result);
  190. }
  191. else
  192. {
  193. result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
  194. if (result != MvError.MV_OK)
  195. {
  196. //Log("Warning: Set Packet Size failed!", result);
  197. }
  198. }
  199. }
  200. return Blresult;
  201. }
  202. /// <summary>
  203. /// 重新加载相机参数
  204. /// </summary>
  205. /// <param name="RecameraConfig"></param>
  206. /// <returns></returns>
  207. public bool ReLoadCameraConfig(CameraConfig RecameraConfig)
  208. {
  209. bool Blresult = false;
  210. if (device != null && device.IsConnected)
  211. {
  212. //设置从配置文件读取的参数
  213. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  214. _cameraNo = RecameraConfig.CamerNo;
  215. if (RecameraConfig.CameraName != deviceModelName.CurValue)
  216. device.Parameters.SetStringValue("DeviceUserID", RecameraConfig.CameraName);
  217. device.Parameters.SetFloatValue("ExposureTime", RecameraConfig.ExposureTimeValue);
  218. device.Parameters.SetIntValue("AcquisitionLineRate", RecameraConfig.AcquistionLineRateValue);
  219. device.Parameters.GetIntValue("Height", out IIntValue height);
  220. device.Parameters.SetIntValue("Height", height.Min);
  221. device.Parameters.SetIntValue("Width", RecameraConfig.Width);
  222. device.Parameters.SetIntValue("OffsetX", RecameraConfig.OffsetX);
  223. // 设置采集连续模式
  224. device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
  225. device.Parameters.SetEnumValueByString("TriggerMode", "Off");
  226. Blresult = true;
  227. }
  228. return Blresult;
  229. }
  230. /// <summary>
  231. /// 开启相机采集
  232. /// </summary>
  233. public bool StartCamera()
  234. {
  235. return StartReceiveFuntion();
  236. }
  237. /// <summary>
  238. /// 关闭相机采集
  239. /// </summary>
  240. public void StopCamera()
  241. {
  242. StopReceiveFuntion();
  243. //StopEventGetImage();
  244. }
  245. /// <summary>
  246. /// 释放相机资源
  247. /// </summary>
  248. public void DisPoseCamera()
  249. {
  250. if (device != null)
  251. {
  252. int result = device.StreamGrabber.StopGrabbing();
  253. device.Close();
  254. device.Dispose();
  255. if (result != MvError.MV_OK)
  256. {
  257. LOG.log(("Stop Grabbing Fail!", result));
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// 获取一次图片
  263. /// </summary>
  264. /// <param name="IFrameData"></param>
  265. /// <returns></returns>
  266. public bool GetOnceImage(out IFrameOut IFrameData)
  267. {
  268. bool result = false;
  269. int BRet = device.StreamGrabber.GetImageBuffer(1000, out IFrameData);
  270. if (BRet == 0 && IFrameData != null) result = true;
  271. else return result;
  272. if (lastframeNum == -1)
  273. {
  274. lastframeNum = IFrameData.FrameNum;
  275. }
  276. else if (lastframeNum == IFrameData.FrameNum - 1)
  277. {
  278. lastframeNum = IFrameData.FrameNum;
  279. }
  280. else
  281. {
  282. //丢帧记录
  283. LOG.log(string.Format("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  284. IFrameData.Image.Width, IFrameData.Image.Height, IFrameData.FrameNum , lastframeNum), 6);
  285. Console.WriteLine("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  286. IFrameData.Image.Width, IFrameData.Image.Height, IFrameData.FrameNum , lastframeNum);
  287. lastframeNum = IFrameData.FrameNum;
  288. }
  289. return result;
  290. }
  291. /// <summary>
  292. /// 获取相机图像尺寸信息
  293. /// </summary>
  294. /// <returns></returns>
  295. public CameraImageSizeClass GetCamereImageSize()
  296. {
  297. CameraImageSizeClass cameraImageSize =new CameraImageSizeClass();
  298. if(device != null)
  299. {
  300. device.Parameters.GetIntValue("Width", out IIntValue PixWidth);
  301. device.Parameters.GetIntValue("Height", out IIntValue PixHeight);
  302. cameraImageSize.Height = (int)PixHeight.CurValue;
  303. cameraImageSize.Width = (int)PixWidth.CurValue;
  304. }
  305. return cameraImageSize;
  306. }
  307. /// <summary>
  308. /// 获取当前相机的参数生成Config信息
  309. /// </summary>
  310. /// <returns></returns>
  311. public CameraConfig GetConfigValue()
  312. {
  313. CameraConfig result;
  314. device.Parameters.GetFloatValue("ExposureTime", out IFloatValue exposureTime);
  315. device.Parameters.GetIntValue("AcquisitionLineRate", out IIntValue acquisitionLineRate);
  316. device.Parameters.GetIntValue("OffsetX", out IIntValue offsetX);
  317. device.Parameters.GetIntValue("Width", out IIntValue pixWidth);
  318. device.Parameters.GetStringValue("DeviceUserID", out IStringValue deviceUserID);
  319. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  320. device.Parameters.GetStringValue("DeviceSerialNumber", out IStringValue deviceSerialNumber);
  321. result = new CameraConfig()
  322. {
  323. CameraSNNum = deviceSerialNumber.CurValue,
  324. ExposureTimeValue = exposureTime.CurValue,
  325. AcquistionLineRateValue = (int)acquisitionLineRate.CurValue,
  326. Width = (int)pixWidth.CurValue,
  327. OffsetX = (int)offsetX.CurValue,
  328. CameraName = deviceUserID.CurValue,
  329. DeviceName = deviceModelName.CurValue,
  330. CamerNo = _cameraNo
  331. };
  332. return result;
  333. }
  334. /// <summary>
  335. /// 保存参数
  336. /// </summary>
  337. public void SaveConfig()
  338. {
  339. CameraConfig camerasConfig = null;
  340. if (!Directory.Exists(".\\Config\\")) Directory.CreateDirectory(".\\Config\\");
  341. XmlStorage.SerializeToXml(camerasConfig, ".\\Config\\CameraConfig.xml");
  342. }
  343. public bool IsLoadCamera()
  344. {
  345. return device != null;
  346. }
  347. public bool IsConnectCamera()
  348. {
  349. if (device == null) return false;
  350. else
  351. {
  352. return device.IsConnected;
  353. }
  354. }
  355. #endregion
  356. #region 私有方法
  357. /// <summary>
  358. /// 开启采集
  359. /// </summary>
  360. private bool StartReceiveFuntion()
  361. {
  362. bool result = false;
  363. try
  364. {
  365. if(device == null) return result;
  366. device.StreamGrabber.SetImageNodeNum(30);
  367. device.StreamGrabber.StartGrabbing();
  368. result = true;
  369. }
  370. catch (Exception ex)
  371. {
  372. FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  373. throw;
  374. }
  375. return result;
  376. }
  377. /// <summary>
  378. /// 关闭采集
  379. /// </summary>
  380. private void StopReceiveFuntion()
  381. {
  382. try
  383. {
  384. if (device == null) return;
  385. int ret = device.StreamGrabber.StopGrabbing();
  386. if (ret != MvError.MV_OK)
  387. {
  388. FaultLog.RecordErrorMessage($"Stop grabbing failed:{ret:x8}");
  389. return;
  390. }
  391. }
  392. catch (Exception ex)
  393. {
  394. FaultLog.RecordErrorMessage("Stop thread failed!, " + ex.Message);
  395. throw;
  396. }
  397. }
  398. #endregion
  399. }
  400. }