MainThreadClass.cs 21 KB

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