CameraClass.cs 17 KB

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