MainThreadClass.cs 21 KB

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