MainThreadClass.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. using CCDCount.DLL.Tools;
  2. using CCDCount.MODEL.CameraClass;
  3. using CCDCount.MODEL.ConfigModel;
  4. using CCDCount.MODEL.ShuLiClass;
  5. using LogClass;
  6. using MvCameraControl;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Diagnostics;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. using System.Runtime.Remoting.Messaging;
  16. using System.Threading;
  17. namespace CCDCount.DLL
  18. {
  19. public class MainThreadClass
  20. {
  21. #region 变量与实例
  22. Thread SwitchIdentifyImageThread = null;
  23. private bool IsSwitch = false;
  24. public ShuLiClass shuLiClass = null;
  25. CameraClass cameraClass = new CameraClass();
  26. public ShuLiConfigClass shuLiConfig = null;
  27. public CameraConfig cameraConfig = null;
  28. public int ThisCamerNo = -1;
  29. public bool CameraStatic { get { return _CameraStatic; } }
  30. private bool _CameraStatic = false;
  31. // 返回交换线程状态
  32. public bool CameraRunStatic { get { return IsSwitch; } }
  33. public bool IsOpenLoadThread { get { return _IsOpenLoadThread; }}
  34. private bool _IsOpenLoadThread = false;
  35. public int HistoryActiveNum { get { return shuLiClass.GetHistoryActiveNum(); } }
  36. public int OkHistoryNum { get { return shuLiClass.GetOkHistoryNum(); } }
  37. public int NgHistoryNum { get { return shuLiClass.GetNgHistoryNum(); } }
  38. // 数粒信息发送线程
  39. Thread SendBottLogicMessageThread = null;
  40. bool IsSend = false;
  41. // Modbus客户端实例
  42. ModbusTcpClient modbusTcpClient = null;
  43. // 颗粒结果待发送队列
  44. ConcurrentQueue<ushort> SendQueue = new ConcurrentQueue<ushort>();
  45. /// <summary>
  46. /// 数粒状态计时器
  47. /// </summary>
  48. Stopwatch stopwatch = Stopwatch.StartNew();
  49. /// <summary>
  50. /// 数粒状态
  51. /// </summary>
  52. private bool _ShuLiState = true;
  53. public bool ShuLiState { get { return _ShuLiState; } }
  54. private bool IsDebug = false;
  55. #endregion
  56. #region 公共方法
  57. /// <summary>
  58. /// 设置ModbusTcpClient
  59. /// </summary>
  60. /// <param name="modbusTcpClient"></param>
  61. public void SetModbusClient(ModbusTcpClient modbusTcpClient)
  62. {
  63. this.modbusTcpClient = modbusTcpClient;
  64. if (!this.modbusTcpClient.IsTcpClientConnected())
  65. {
  66. LOG.error("ModbusTcpClient Connect Failed!");
  67. }
  68. else
  69. {
  70. StartSendBottLogicMessageThread();
  71. LOG.log("ModbusTcpClient Connect Success!", 6);
  72. }
  73. }
  74. /// <summary>
  75. /// 初始化构造方法
  76. /// </summary>
  77. /// <param name="configClass"></param>
  78. /// <param name="CameraConfig"></param>
  79. public MainThreadClass(ShuLiConfigClass configClass,CameraConfig CameraConfig)
  80. {
  81. shuLiConfig = configClass;
  82. cameraConfig = CameraConfig;
  83. // 数粒配置文件地址
  84. if (configClass!=null)
  85. {
  86. // 创建数粒对象(配置文件)
  87. shuLiClass = new ShuLiClass(shuLiConfig);
  88. }
  89. else
  90. {
  91. // 创建数粒对象(默认)
  92. shuLiClass = new ShuLiClass();
  93. }
  94. _IsOpenLoadThread = cameraConfig.IsOpenLoad;
  95. ThisCamerNo = cameraConfig.CamerNo;
  96. }
  97. public bool loadCamera()
  98. {
  99. bool result = false;
  100. // 相机列表
  101. List<CameraInfoClass> list = new List<CameraInfoClass>();
  102. try
  103. {
  104. // 获取相机列表
  105. cameraClass.GetCameraList(out list);
  106. if (list.Count == 0)
  107. {
  108. LOG.error(string.Format("{0}:没有相机", "MainThreadClass-StartMianThread"));
  109. // 如果没有相机,则退出
  110. return result;
  111. }
  112. // 加载相机
  113. // cameraClass.LoadCamereDevice(list.First().DeviceSN);
  114. if (!cameraClass.LoadCamereDevice(cameraConfig))
  115. {
  116. LOG.error(string.Format("{0}:相机加载失败", "MainThreadClass-StartMianThread"));
  117. return result;
  118. }
  119. }
  120. catch(Exception e)
  121. {
  122. }
  123. return result;
  124. }
  125. /// <summary>
  126. /// 开始主线程
  127. /// </summary>
  128. public bool StartMianThread()
  129. {
  130. bool result = false;
  131. try
  132. {
  133. // 取图线程开启
  134. cameraClass.StartCamera();
  135. _CameraStatic = true;
  136. // 数据交换线程开启
  137. StartSwitchThread();
  138. // 为数粒算法的识别成功一粒回调函数添加方法
  139. shuLiClass.WorkCompleted += Worker_OneGrainCompleted;
  140. // 开启识别线程
  141. shuLiClass.StartIdentifyFuntion(cameraClass.GetCamereImageSize().Width);
  142. result = true;
  143. }
  144. catch(Exception e)
  145. {
  146. }
  147. return result;
  148. }
  149. /// <summary>
  150. /// 停止主线程
  151. /// </summary>
  152. public bool StopMianThread()
  153. {
  154. bool result = false;
  155. try
  156. {
  157. shuLiClass.WorkCompleted -= Worker_OneGrainCompleted;
  158. // 相机取图关闭
  159. cameraClass.StopCamera();
  160. // 数据交换线程关闭
  161. StopSwitchThread();
  162. // 数粒识别线程关闭
  163. shuLiClass.StopIdentifyFuntion();
  164. StopSendBottLogicMessageThread();
  165. result = true;
  166. }
  167. catch (Exception ex)
  168. {
  169. }
  170. return result;
  171. }
  172. /// <summary>
  173. /// 释放相机资源
  174. /// </summary>
  175. public void DisposeCamera()
  176. {
  177. cameraClass.StopCamera();
  178. cameraClass.DisPoseCamera();
  179. }
  180. /// <summary>
  181. /// 重加载相机
  182. /// </summary>
  183. /// <param name="CameraSN"></param>
  184. /// <returns></returns>
  185. public bool ReLoadCamera(string CameraSN)
  186. {
  187. bool result = false;
  188. result = cameraClass.ReLoadCameraDevice(CameraSN);
  189. if (result)
  190. {
  191. cameraConfig = cameraClass.GetConfigValue();
  192. }
  193. return result;
  194. }
  195. /// <summary>
  196. /// 获取显示用的图片数据
  197. /// </summary>
  198. /// <param name="ImageHeight"></param>
  199. /// <param name="Data"></param>
  200. public void GetShowImage(int ImageHeight,out Bitmap ImageData)
  201. {
  202. List<RowStartEndCol> RowsShowList = new List<RowStartEndCol>();
  203. ActiveObjectClass NewActive = shuLiClass.GetLastActive();
  204. if (NewActive == null)
  205. {
  206. LOG.log(string.Format("{0}:没有获取到数粒数据", "MainThreadClass-GetShowImage"));
  207. ImageData = null;
  208. return;
  209. }
  210. List<ActiveObjectClass> Data = shuLiClass.GetHistoryActive().Where(o => o.LastSeenLine > NewActive.LastSeenLine - ImageHeight).ToList();
  211. Data.ForEach(o => o.RowsData.ForEach(p => RowsShowList.Add(p)));
  212. Bitmap BitmapImage = new Bitmap(NewActive.ImageWidth, ImageHeight);
  213. using (Graphics g = Graphics.FromImage(BitmapImage))
  214. {
  215. g.Clear(Color.White);
  216. using (Pen RedPan = new Pen(Color.Red, 5))
  217. {
  218. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  219. {
  220. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  221. }
  222. }
  223. using (Pen BlackPen = new Pen(Color.Black, 1))
  224. {
  225. List<RowStartEndCol> ShowList = RowsShowList.Where(o => o.RowsCol > NewActive.LastSeenLine - BitmapImage.Height).ToList();
  226. RowsShowList.Where(o => o.RowsCol < NewActive.LastSeenLine - BitmapImage.Height).ToList().ForEach(o => RowsShowList.Remove(o));
  227. RowsShowList.Clear();
  228. ShowList.ForEach(o => g.DrawLine(BlackPen, new Point(o.StartCol, (int)(NewActive.LastSeenLine - o.RowsCol)), new Point(o.EndCol, (int)(NewActive.LastSeenLine - o.RowsCol))));
  229. ShowList.Clear();
  230. }
  231. }
  232. ImageData = BitmapImage.Clone() as Bitmap;
  233. BitmapImage.Dispose();
  234. //GC.Collect();
  235. }
  236. /// <summary>
  237. /// 获取无数据的图片
  238. /// </summary>
  239. /// <param name="ImageWidth"></param>
  240. /// <param name="ImageHeight"></param>
  241. /// <param name="ImageData"></param>
  242. public void GetNullShowImage(int ImageWidth, int ImageHeight, out Bitmap ImageData)
  243. {
  244. Bitmap BitmapImage = new Bitmap(ImageWidth, ImageHeight);
  245. using (Graphics g = Graphics.FromImage(BitmapImage))
  246. {
  247. g.Clear(Color.White);
  248. using (Pen RedPan = new Pen(Color.Red, 8))
  249. {
  250. for (int i = 0; i < shuLiClass.ChannelsRoi.Count - 1; i++)
  251. {
  252. g.DrawLine(RedPan, new Point(shuLiClass.ChannelsRoi[i], 0), new Point(shuLiClass.ChannelsRoi[i], BitmapImage.Height));
  253. }
  254. }
  255. }
  256. ImageData = BitmapImage.Clone() as Bitmap;
  257. BitmapImage.Dispose();
  258. }
  259. /// <summary>
  260. /// 获取此刻的Config数据
  261. /// </summary>
  262. /// <param name="config"></param>
  263. public void GetAllConfigValue(out CameraConfig Camconfig,out ShuLiConfigClass shuLiConfig)
  264. {
  265. //判断是否加载了相机
  266. if(cameraClass.IsLoadCamera())
  267. {
  268. //获取已经加载的相机的配置
  269. cameraConfig = cameraClass.GetConfigValue();
  270. Camconfig = cameraConfig;
  271. }
  272. else
  273. {
  274. cameraConfig = new CameraConfig();
  275. Camconfig = cameraConfig;
  276. }
  277. //读取视觉配置
  278. shuLiConfig = shuLiClass.GetConfigValue();
  279. this.shuLiConfig = shuLiConfig;
  280. }
  281. /// <summary>
  282. /// 获取相机此刻的Config数据
  283. /// </summary>
  284. /// <param name="CameraConfig"></param>
  285. public CameraConfig GetCameraConfig()
  286. {
  287. CameraConfig result = null;
  288. //判断是否加载了相机
  289. if (cameraClass.IsLoadCamera())
  290. {
  291. //获取已经加载的相机的配置
  292. result = cameraClass.GetConfigValue();
  293. cameraConfig = result;
  294. }
  295. return result;
  296. }
  297. /// <summary>
  298. /// 保存所有Config
  299. /// </summary>
  300. public void SaveAllConfig()
  301. {
  302. shuLiClass.SaveConfig();
  303. }
  304. /// <summary>
  305. /// 获取相机连接状态
  306. /// </summary>
  307. /// <returns></returns>
  308. public bool GetCameraConnectStatic()
  309. {
  310. bool result = false;
  311. if(cameraClass != null)
  312. result = cameraClass.IsConnectCamera();
  313. return result;
  314. }
  315. /// <summary>
  316. /// 清除历史数据
  317. /// </summary>
  318. /// <returns></returns>
  319. public bool ClearHistoryActive()
  320. {
  321. bool result = false;
  322. if(shuLiClass != null)
  323. result = shuLiClass.ClearHistoryActive();
  324. return result;
  325. }
  326. /// <summary>
  327. /// 获取过去一秒内颗粒数量
  328. /// </summary>
  329. /// <returns></returns>
  330. public int GetOneSecondActiveNum()
  331. {
  332. int result = 0;
  333. if(shuLiClass != null)
  334. result = shuLiClass.GetHistoryActive().Where(o=>o.EndCheckTime>DateTime.Now-TimeSpan.FromSeconds(1)).Count();
  335. return result;
  336. }
  337. #endregion
  338. #region 私有方法
  339. //bool IsFill = false;
  340. //bool IsXuanZhuanCloseFaMen = false;
  341. /// <summary>
  342. /// 每数完一粒识别线程执行的事件
  343. /// </summary>
  344. /// <param name="sender"></param>
  345. /// <param name="e"></param>
  346. private void Worker_OneGrainCompleted(object sender, ActiveObjectEventArgsClass e)
  347. {
  348. LOG.log("有活跃物体转换为了历史物体,回调事件被触发!", 6);
  349. LOG.log(string.Format("图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum), 6);
  350. if (e.Actives.Where(o => o.StateCode == 7).Count() > 0)
  351. {
  352. stopwatch.Restart();
  353. _ShuLiState = false;
  354. }
  355. else if (stopwatch.ElapsedMilliseconds > 1000)
  356. {
  357. stopwatch.Stop();
  358. _ShuLiState = true;
  359. }
  360. //往数组中计数
  361. ushort result = new ushort();
  362. // 事件处理逻辑
  363. foreach (ActiveObjectClass oneActive in e.Actives)
  364. {
  365. Console.WriteLine(string.Format("输出当前颗粒信息,开始行:{0},结束行:{1},开始时间:{2}结束时间:{3},颗粒状态:{4},通道数:{5}",
  366. oneActive.StartLine, oneActive.LastSeenLine, oneActive.StartCheckTime.ToString("O"), oneActive.EndCheckTime.ToString("O"), oneActive.StateCode, oneActive.ChannelNO));
  367. LOG.log(string.Format("输出当前颗粒信息,开始行:{0},结束行:{1},开始时间:{2}结束时间:{3},颗粒状态:{4},通道数:{5}",
  368. oneActive.StartLine, oneActive.LastSeenLine, oneActive.StartCheckTime.ToString("O"), oneActive.EndCheckTime.ToString("O"), oneActive.StateCode, oneActive.ChannelNO), 6);
  369. if (oneActive.StateCode == 0 && oneActive.ChannelNO != -1)
  370. {
  371. //单通道合格计数
  372. result |= (ushort)(1 << (oneActive.ChannelNO));
  373. }
  374. else
  375. {
  376. //单通道不合格计数
  377. result |= (ushort)(1 << 8);
  378. }
  379. }
  380. LOG.log("当前待发送队列数量:" + SendQueue.Count, 6);
  381. if(IsSend)
  382. {
  383. SendQueue.Enqueue(result);
  384. }
  385. }
  386. #endregion
  387. #region 线程方法
  388. /// <summary>
  389. /// 开启交换线程
  390. /// </summary>
  391. private void StartSwitchThread()
  392. {
  393. IsSwitch = true;
  394. SwitchIdentifyImageThread = new Thread(SwitchIdentifyImageProcess);
  395. SwitchIdentifyImageThread.Start();
  396. }
  397. /// <summary>
  398. /// 关闭交换线程
  399. /// </summary>
  400. private void StopSwitchThread()
  401. {
  402. try
  403. {
  404. // 标志位设为false
  405. IsSwitch = false;
  406. if (SwitchIdentifyImageThread != null && SwitchIdentifyImageThread.IsAlive)
  407. SwitchIdentifyImageThread.Join();
  408. }
  409. catch (Exception ex)
  410. {
  411. LOG.error("Start thread failed!, " + ex.Message);
  412. throw;
  413. }
  414. }
  415. /// <summary>
  416. /// 交换线程
  417. /// </summary>
  418. private void SwitchIdentifyImageProcess()
  419. {
  420. IFrameOut IFramedata = null;
  421. Stopwatch stopwatch = Stopwatch.StartNew();
  422. stopwatch.Start();
  423. while (IsSwitch)
  424. {
  425. if (stopwatch.ElapsedMilliseconds > 1000)
  426. {
  427. //Console.WriteLine("交换线程-图像处理实例中的待识别图像缓存队列长度{0}", shuLiClass.ImageNum);
  428. GC.Collect();
  429. stopwatch.Restart();
  430. }
  431. //Thread.Sleep(5);
  432. bool result = cameraClass.GetOnceImage(out IFramedata);
  433. if (result)
  434. {
  435. //Debug模式,不进行图像处理
  436. if (IsDebug)
  437. {
  438. continue;
  439. }
  440. if (IFramedata == null)
  441. continue;
  442. shuLiClass.SetOnceIdentifyImageData(IFramedata.Image);
  443. }
  444. else
  445. continue;
  446. IFramedata.Dispose();
  447. }
  448. stopwatch.Stop();
  449. }
  450. /// <summary>
  451. /// 启动发送消息线程
  452. /// </summary>
  453. private void StartSendBottLogicMessageThread()
  454. {
  455. try
  456. {
  457. //zmcauxClass.OpenZmcauxCard();
  458. timeBeginPeriod(1); // 设置为1ms精度
  459. IsSend = true;
  460. SendBottLogicMessageThread = new Thread(SendBottLogicMessageProcess);
  461. SendBottLogicMessageThread.Start();
  462. }
  463. catch (Exception ex)
  464. {
  465. LOG.error("Start thread failed!, " + ex.Message);
  466. throw;
  467. }
  468. }
  469. /// <summary>
  470. /// 停止发送消息线程
  471. /// </summary>
  472. private void StopSendBottLogicMessageThread()
  473. {
  474. try
  475. {
  476. // 标志位设为false
  477. IsSend = false;
  478. if (SendBottLogicMessageThread != null && SendBottLogicMessageThread.IsAlive)
  479. SendBottLogicMessageThread.Join();
  480. if (modbusTcpClient != null) modbusTcpClient.Disconnect();
  481. }
  482. catch (Exception ex)
  483. {
  484. LOG.error("Start thread failed!, " + ex.Message);
  485. throw;
  486. }
  487. }
  488. /// <summary>
  489. /// 信息发送线程
  490. /// </summary>
  491. private void SendBottLogicMessageProcess()
  492. {
  493. //获取数据
  494. ushort sendMessage = 0;
  495. bool AllowTransfer = false;
  496. bool TransferDone = false;
  497. Stopwatch sw = Stopwatch.StartNew();
  498. while (IsSend)
  499. {
  500. //LOG.log("进入线程", 6);
  501. sw.Restart();
  502. sendMessage = new ushort();
  503. //读取装瓶状态
  504. AllowTransfer = false;
  505. TransferDone = false;
  506. bool[] ReadResult = modbusTcpClient.ReadCoilsRegister(slaveId: 1, startAddress: 11, numRegisters: 2);
  507. if (ReadResult == null)
  508. {
  509. continue;
  510. }
  511. AllowTransfer = ReadResult[1];
  512. TransferDone = ReadResult[0];
  513. //LOG.log(string.Format("读取值:AllowTransfer[0]:{0},TransferDone[1]:{1}", AllowTransfer, TransferDone), 6);
  514. //当允许写入且处于未写入的状态时
  515. if (AllowTransfer && !TransferDone)
  516. {
  517. if (SendQueue.Count() > 0)
  518. {
  519. if (!SendQueue.TryDequeue(out sendMessage))
  520. {
  521. LOG.error("MainThreadClass-SendBottLogicMessageProcess-SendQueue.TryDequeue failed!");
  522. }
  523. }
  524. if (sendMessage != 0)
  525. {
  526. //写入数据
  527. modbusTcpClient.WriteSingleRegister(slaveId: 1, registerAddress: 100, value: sendMessage);
  528. modbusTcpClient.WriteCoilsRegister(slaveId: 1, CoilsAddress: 11, values: true);
  529. }
  530. sw.Stop();
  531. LOG.log(string.Format("sendMessage[1]:{0},此次写值耗时:{1}", sendMessage, sw.Elapsed), 6);
  532. }
  533. Thread.Sleep(1);
  534. }
  535. }
  536. #endregion
  537. #region 外部函数
  538. [DllImport("winmm.dll")]
  539. static extern uint timeBeginPeriod(uint period);
  540. #endregion
  541. }
  542. }