MainThreadClass.cs 21 KB

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